How to add new column with default value from existing column in Liquibase

后端 未结 2 1024
挽巷
挽巷 2020-12-30 08:40

I\'m using Postgres DB and for migration I\'m using Liquibase. I have an ORDERS table with the following columns:

ID | DATE | NAME | CREATOR | ...

相关标签:
2条回答
  • 2020-12-30 09:00

    You could use the defaultValueComputed attribute, which takes the name of a procedure or function. You would have to also create a changeset that creates the procedure.

    That might look something like this:

    <changeSet author="steve" id="createProcedureForDefaultValue">
        <createProcedure procedureName="myCoolProc">
        CREATE OR REPLACE PROCEDURE myCoolProc IS
        BEGIN
           -- actual logic here
        END;
        </createProcedure>
    </changeSet>
    
    <changeSet author="steve" id="addDefaultValueColumn">
        <addColumn tableName="ORDERS">
            <column name="LAST_MODIFIED_BY" type="VARCHAR" defaultValueComputed="myCoolProc">
                <constraints nullable="false"/>
            </column>
        </addColumn>
    </changeSet>
    

    Alternatively, you could do this using the <sql> tag.

    0 讨论(0)
  • 2020-12-30 09:07

    Since no one answered here I'm posting the way I handled it:

    <changeSet id="Add MODIFY_USER_ID to ORDERS" author="Noam">
            <addColumn tableName="ORDERS">
                <column name="MODIFY_USER_ID" type="BIGINT">
                    <constraints foreignKeyName="ORDERS_MODIFY_FK" referencedTableName="USERS" referencedColumnNames="ID"/>
                </column>
            </addColumn>
    </changeSet>
    
    <changeSet id="update the new MODIFY_USER_ID column to get the CREATOR" author="Noam">
        <sql>update ORDERS set MODIFY_USER_ID = CREATOR</sql>
    </changeSet>
    
    <changeSet id="Add not nullable constraint on MODIFY_USER_ID column" author="Noam">
        <addNotNullConstraint tableName="ORDERS" columnName="MODIFY_USER_ID" columnDataType="BIGINT"/>
    </changeSet>
    

    I've done this in three different change-sets as the documentation recommends

    0 讨论(0)
提交回复
热议问题