1

Building upon the question How to build a WHERE-clause in a LiquiBase changeset, I would like to choose the default value of a column based on the value of a column from a different table.

For instance, I have two tables, order and order_history. Pls note that we maintain all our orders in both order in order_history as well. Once an order is completed, it is removed from order table.

order has a column 'status' but we missed it on order_history, you can call it a bad design. How do I add 'status' to order_history now, and copy the value from the corresponding order in order table for existing data at the time of upgrade? Is there a way to do this in liquibase?

user3616468
  • 79
  • 1
  • 8

1 Answers1

1

If order and order_history are connected with the foreign key, then you can just do the following:

<changeSet id="foo" author="bar">
    <preConditions onFail="MARK_RAN">
        <and>
            <columnExists tableName="order" columnName="status"/>
            <columnExists tableName="order_history" columnName="status"/>
        </and>
    </preConditions>
    <comment>Update order_history.status with values from order.status, where order.id = order_history.order_id</comment>
    <update tableName="order_history">
        <column name="status" valueComputed="SELECT o.status FROM order o WHERE o.id = order_id"/>
    </update>
</changeSet>

If these tables are not connected, then you may use defaultValueComputed when you're adding a new column:

    <addColumn tableName="order_history">
        <column name="status" type="varchar(255)" defaultValueComputed="some SQL query here"/>
    </addColumn>
Pimgd
  • 5,983
  • 1
  • 30
  • 45
htshame
  • 6,599
  • 5
  • 36
  • 56
  • Thanks @htshame. By the way, I do not see any necessity for the foreign-key relationship for the first code snippet to work. Correct me if I am wrong and let me know how the first code snippet is restricted to tables with foreign-key relation. – user3616468 May 17 '22 at 04:59
  • You’re right, it’s just for the sake of consistency – htshame May 17 '22 at 12:06