Search code examples
liquibase

When does Liquibase rollback statement come into play


Let's say we have the following liquibase .sql file:

--liquibase formatted sql    
--changeset Jack:create_session_id_index rollbackSplitStatements:true runInTransaction:false
CREATE INDEX CONCURRENTLY ORDERS_IDX_SESSION_ID ON orders((orders_counter->>'sessionId'));
--rollback DROP INDEX ORDERS_IDX_SESSION_ID;

Here we create an index on json-field in orders table. My question is about the commented statement: DROP INDEX ORDERS_IDX_SESSION_ID; Is it executed by liquibase automatically when something goes wrong? Ot is it just a prompt for developers? Which rollback statement should I write if at this moment I am not creating an index, but instead what to drop it?


Solution

  • Liquibase has a feature called rollback. Not to be confused with database transaction rollback.

    To answer your questions:

    Is it executed by liquibase automatically when something goes wrong?

    No. If something goes wrong, the transaction rolls back. --rollback statement from the changeSet is not being executed.

    Ot is it just a prompt for developers?

    No. If you want a prompt for developers, you may use the <comment> tag. Or I guess in SQL notation it'll be --comment. When you're writing --rollback in the changeSet, you refer to Liquibase "rollback" feature.

    Which rollback statement should I write if at this moment I am not creating an index, but instead what to drop it?

    That depends on the business logic. I guess the opposite of dropping an index will be createIndex.

    Some explanation:

    When Liquibase executes a changeSet, it does it within a database transaction. If the change in the changeSet fails, then transaction rollback kicks in and rolls everything back. It has nothing to do with --rollback do-something part of the changeSet.

    Now if we're talking about Liquibase feature named rollback, then there's a pretty good piece of documentation. It describes the "types" of rollback and how it works.

    rollback

    The rollback command rolls back changes made to the database based on the specified tag.

    Uses

    The rollback command is typically used to revert all changes that were made to the database after the tag you specify.

    When you run rollback, Liquibase will roll back sequentially all the deployed changes until it reaches the tag row in the DATABASECHANGELOG table. For example, you can use the rollback command when you want to undo a series of changes made to your database related to a specific tag such as a numbered release. If you have tags for release 1, release 2, and release 3, and need to make a correction in release 2, the rollback command will rollback release 3 first.

    Also there's a nice Baeldung article with explanation and examples of how to use the rollback feature.