Liquibase Database Migrations
Overview
Section titled “Overview”Liquibase manages versioned database schema changes using changelogs and changesets. It supports multiple formats (XML, YAML, JSON), rollbacks, and contexts/labels for targeted deployments.
- Works with many databases (PostgreSQL, SQL Server, MySQL, Oracle)
- Strong diff and rollback capabilities
- Great fit for database DevOps and CI/CD
Key concepts
Section titled “Key concepts”- Changelog: entry point that includes or lists changesets
- Changeset: atomic change with id, author, and operations
- Contexts/Labels: filter which changes to run
- Rollback: define how to undo a changeset
Changelog (XML) example
Section titled “Changelog (XML) example”<?xml version="1.0" encoding="UTF-8"?><databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.20.xsd"> <changeSet id="001-create-users" author="banky"> <createTable tableName="users"> <column name="id" type="BIGINT" autoIncrement="true"> <constraints primaryKey="true"/> </column> <column name="email" type="VARCHAR(255)"> <constraints nullable="false" unique="true"/> </column> <column name="created_at" type="TIMESTAMP"/> </createTable> <rollback> <dropTable tableName="users"/> </rollback> </changeSet></databaseChangeLog>
Changelog (YAML) example
Section titled “Changelog (YAML) example”databaseChangeLog: - changeSet: id: 002-add-index author: banky changes: - createIndex: tableName: users columns: - column: name: email
GitLab CI integration
Section titled “GitLab CI integration”liquibase_update: stage: deploy image: liquibase/liquibase:4.27 script: - liquibase --url=$DB_URL --username=$DB_USER --password=$DB_PASS \ --changelog-file=changelog.xml update rules: - if: "$CI_COMMIT_BRANCH == 'main'"
Rollbacks
Section titled “Rollbacks”liquibase --url=$DB_URL --username=$DB_USER --password=$DB_PASS \ --changelog-file=changelog.xml rollbackCount 1
See more: ./liquibase/introduction, ./liquibase/changelogs, ./liquibase/rollbacks, ./liquibase/gitlab-ci-integration
Best practices
Section titled “Best practices”- Keep small, atomic changesets with clear ids
- Always define rollbacks where feasible
- Use contexts/labels per environment
- Validate on CI using
liquibase validate