xampo
xampo

Reputation: 399

Liquibase - performs one operation and the other if there is an entry

I need to do some operations (update, delete) depending on whether there is a record with a given id. However, one operation must take place (update) regardless of whether there is a record or not. I will demonstrate this with a simple example in a backend language (Java):

if(simplyObject.getId().equals(1L){
 simplyObject.setFieldA(...);
 simplyObject.setFieldB(...);}
simplyObject.setFieldC(...);

I`m not proficient in liquibase. I know that there are preConditions, but I think they refer to all operations in a given migration, not to specific ones. Could you please give me a hint how to do this?

Upvotes: 1

Views: 584

Answers (1)

htshame
htshame

Reputation: 7330

You can write separate changesets and use preConditions for specific checks.

There's the sqlCheck preCondition for condition if record with ID = 1 exists:

<changeSet id="foo1" author="bar">
    <preConditions onFail="MARK_RAN" 
                   onFailMessage="Table 'my_table' is missing or record with ID = 1 does not exist">
        <tableExists tableName="my_table"/>
        <sqlCheck expectedResult="1">SELECT COUNT(id) FROM my_table WHERE id = 1</sqlCheck>
    </preConditions>
    <comment>Execute some logic because there is a record in 'my_table' with id = 1</comment>
    <sql>
        DELETE FROM my_table ... 
        (or whatever logic in plain SQL you need to execute if record with id = 1 exists);
    </sql>
</changeSet>

And for logic you need to execute regardless of whether record with ID = 1 exists you can simply do the following:

<changeSet id="foo2" author="bar">
    <preConditions onFail="MARK_RAN" 
                   onFailMessage="Table 'my_table' is missing">
        <tableExists tableName="my_table"/>
    </preConditions>
    <sql>
        some update logic regardless whether record with ID = 1 exists or not
    </sql>
    <!-- OR you can use the 'update' change -->
    <update tableName="my_table">
        <column name="my_column_name" value="my_value"/>
    </update>
</changeSet>

Upvotes: 1

Related Questions