Java.DBMigrationTools.How rollback is implemented ? Give example

rollback support is one of the biggest advantages of using migration tools like Liquibase. It shows you’re thinking about safe deployments, disaster recovery, and controlled rollbacks — all critical in production.

Let’s break it down:


Short Answer

In Liquibase, rollback is implemented using:

  • Explicit <rollback> blocks inside a changeset
  • Automatically generated rollback (for supported operations)
  • Or separate rollback scripts

Flyway, by contrast, does not support automatic rollback — you must write manual “undo” scripts or handle rollback through external version control/database backups.

🔎 Liquibase Rollback — Full Example (XML)

<changeSet id="1" author="alice">
  <createTable tableName="users">
    <column name="id" type="bigint" autoIncrement="true"/>
    <column name="username" type="varchar(255)"/>
  </createTable>

  <rollback>
    <dropTable tableName="users"/>
  </rollback>
</changeSet>

✅ This says:

  • On migration → create users table
  • On rollback → drop users table

You can run rollback like:

liquibase rollbackCount 1

🔎 YAML version

- changeSet:
    id: 2
    author: bob
    changes:
      - addColumn:
          tableName: users
          columns:
            - column:
                name: email
                type: varchar(255)
    rollback:
      - dropColumn:
          columnName: email
          tableName: users

🔎 Automatic rollback (when possible)

For certain standard changes (like createTable, addColumn), Liquibase can auto-generate rollback if you don’t define it explicitly.

<changeSet id="3" author="carol" runOnChange="true">
  <addColumn tableName="users">
    <column name="last_login" type="timestamp"/>
  </addColumn>
</changeSet>

✅ You can run:

liquibase rollbackCount 1

And Liquibase automatically knows to drop the column.

🔎 SQL rollback (formatted SQL)

--liquibase formatted sql
--changeset alice:4
CREATE TABLE logs (
  id SERIAL PRIMARY KEY,
  message TEXT
);

--rollback DROP TABLE logs;

🔎 Flyway Rollback (manual only)

Flyway doesn’t support rollback natively.
You’d need to:

  • Write a separate undo script (e.g. U1__undo_create_users.sql)
  • Or handle rollback via database backups or manual SQL

📌 Key Takeaways

Liquibase offers powerful, flexible rollback support: rollback tags, auto rollback, SQL or Java-based.
Flyway requires manual undo scripts — no built-in rollback logic.
✅ Always test rollback in staging before applying to production.

This entry was posted in Без рубрики. Bookmark the permalink.