Liquibase add a new column and populates the new one with the value of another existing column, operation to be done only if the column does not exist

Viewed 3576

In the same table I have to migrate the values of a column to a new one; I want to create a new column, populate it with the values of the other column and remove the old column already migrated, this must only happen if the new column has not already been created.

<changeSet author="xxxx" id="00021">
        <preConditions onFail="MARK_RAN">
            <not>
                <columnExists schemaName="schema" tableName="talbee" columnName="new_table"/>
            </not>
        </preConditions>
        <addColumn schemaName="schema" tableName="new_table">
            <column name="new_column" type="text"/>
        </addColumn>

        <sql>UPDATE table_name SET new_column = old_column</sql>

        <dropColumn  
          catalogName="cat"  
          columnName="old_column"
          schemaName="schema"  
          tableName="table_name">  
        <column  name="old_column"/>  

    </dropColumn> 
 
    </changeSet>

Is the way I delete the old column correct?

Is it better just to rename the column?

1 Answers

Yes, it's more rational to just rename the existing column. You can use <columnExists> preConditions and then <renameColumn> change.

<changeSet author="xxxx" id="00021">
    <preConditions onFail="MARK_RAN">
        <tableExists tableName="table_name"/>
        <columnExists tableName="table_name" columnName="old_column"/>
        <not>
            <columnExists tableName="table_name" columnName="new_column"/>
        </not>
    </preConditions>
    <renameColumn tableName="table_name" oldColumnName="old_column" newColumnName="new_column" 
                  columnDataType="text"/>
</changeSet>
Related