如何从 Liquibase 中的现有列添加具有默认值的新列

2022-09-03 09:05:00

我正在使用Postgres DB,对于迁移,我正在使用Liquibase。我有一个包含以下列的订单表:

ID | DATE | NAME | CREATOR | ...

我需要添加一个新列,该列将保存上次修改订单的用户 - 此列应该是不可为空的,并且应该具有默认值,即CREATOR。对于新订单,我可以解决业务逻辑的默认值部分,问题是我已经有一个现有的订单,我需要在创建新列时设置默认值。现在,我知道我可以在Liquibase中设置一个硬编码的默认值 - 但是有没有办法根据该表的其他列(对于每个实体)添加默认值。


答案 1

由于没有人在这里回答,我以我处理它的方式发布:

<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>

我已经按照文档的建议在三个不同的更改集中完成了此操作


答案 2

可以使用该属性,该属性采用过程或函数的名称。您还必须创建创建过程的变更集。defaultValueComputed

这可能看起来像这样

<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>

或者,您可以使用标记执行此操作。<sql>


推荐