Liquibase: Do I really need to add a rollback section for one-row insert?

Viewed 1743

Assume, that we have the following changeset:

   <changeSet id="add_ACME_code_to_tbl_acme" author="developer">
        <sql>
            INSERT INTO tbl_acme(identifier, description, code)
            VALUES (nextval('seq_acme'), 'acme description', 'ACME');
        </sql>
        <rollback>
            <delete tableName="tbl_acme">
                <where>code = 'ACME'</where>
            </delete>
        </rollback>
    </changeSet>

where I am just trying to insert one row to the table.

The discussion that was started during the code review:

Do we really need to have a rollback section for a simple one-row insert and what exactly we need to do here? (in the case when insert failed, does it make any sense try to remove something that we tried to insert without success?) and what exactly can go wrong with an insert?

1 Answers

Unfortunately, Liquibase rollbacks are a bit confusing. They are designed to roll already executed changeSets back.

Check out this article about Rollling back changes

“Roll Back To” Modes

You can specify what changes to rollback in three ways:

Tag

Specifying a tag to rollback to will roll back all change-sets that were executed against the target database after the given tag was applied. See the command line documentation for how to tag your database.

E.g. iquibase:rollback -Dliquibase.rollbackTag=your-database-tag - It'll rollback all the changeSets after the your-database-tag was created. (you can create a tag via liquibase tag command).

Number of Change Sets

You can specify the number of change-sets to rollback.

E.g. liquibase:rollbackCountSQL 5 - It'll rollback the last 5 executed changeSets.

Date

You can specify the date to roll back to.

E.g. liquibase rollbackToDate 2020-05-01T08:36:17 - It'll roll back all the changeSets which were executed after the provided date.

By the way, it's not always necessary to write rollback statements. Most of the time Liquibase generates rollback statements itself. For example, the generated rollback statement for <createTable tableName="new_table"> will be:

<rollback>
    <dropTable tableName="new_table"/>
</rollback>

But if you want to override it, you can always create your own <rollback>.


About failed changeSets:

Liquibase executes the changeSets in transaction. And if the changeSet fails, then the transaction's rollback it invoked and no changes will be made.

<rollback> has nothing to do with error handling.

Related