Search code examples
sqlpostgresqlliquibase

Add one column in existing table and load values for the required column only from csv file on the basis of ID in Liquibase


I have a table table1 with these columns and sample data:

Id Column1
1 abc
2 def

I need to add a column and output will be like this after using below

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog     http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.3.xsd">

    <changeSet id="add-date-column" author="gwylimwilliams">

        <addColumn tableName="table1">
             <column name="column2" type="date">
             </column>
        </addColumn>
    </changeSet>
</databaseChangeLog>

After using above schema, the new column will be added like this:

Id Column1 Column2
1 abc
2 def

You can see column 2 is empty, now I want to load this column value from a .csv file on the basis of id. I do not want to touch column1 value. I know how to load data and uploadLoadData is there and we may use skip but how can we insert the condition or do we have any best way to implement this, we have all the column data in csv file and just want to insert column2 data on the basis of id

<changeset author="gwylimwilliams" id="update-column">
   <loadData
     file="abc.csv"
     seperator=","
     tableName = "table1" >
     <column name="column1" type="skip"/>
     <column name="column2" type="datetime"/>
   </loadData>
</changeset> 

Solution

  • Assuming the id column is present in the table, then you can use loadUpdateData. Using skip works for me using Liquibase 3.10

    <changeset author="gwylimwilliams" id="update-column">
       <loadUpdateData file="abc.csv" separator="," 
                       tableName = "table1" primaryKey="id">
         <column name="id"/>
         <column name="column1" type="skip"/>
         <column name="column2"/>
       </loadUpdateData>
    </changeset>