Sobes.tech
Junior — Middle

How to correctly create and configure a script for managing database migrations using Liquibase?

sobes.tech AI

Answer from AI

To manage database migrations with Liquibase, you need to create a changelog file describing schema changes and configure a script to run migrations.

  1. Create a changelog file, e.g., db.changelog-master.xml, describing changes in XML, YAML, or JSON format. Example in XML:
<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-3.8.xsd">

    <changeSet id="1" author="user">
        <createTable tableName="person">
            <column name="id" type="int" autoIncrement="true">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="name" type="varchar(255)"/>
        </createTable>
    </changeSet>

</databaseChangeLog>
  1. Configure the script to run migrations. If using Maven, add the liquibase-maven-plugin in pom.xml:
<plugin>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-maven-plugin</artifactId>
    <version>4.15.0</version>
    <configuration>
        <changeLogFile>src/main/resources/db.changelog-master.xml</changeLogFile>
        <url>jdbc:postgresql://localhost:5432/mydb</url>
        <username>user</username>
        <password>password</password>
    </configuration>
</plugin>
  1. Run migrations with:
mvn liquibase:update

If using Gradle or standalone Liquibase, configure similarly: specify changelog, connection parameters, and run the update command.

Important: keep the changelog under version control, use unique ids for changeSets, and test migrations on a test database before production.

How to correctly create and configure a script for… - sobes.tech