Creating a Liquibase baseline

Published on - Updated on

This guide assumes that you already use Liquibase but don't yet have your full schema definition in source control.

Create a liquibase.properties file with the below content. Make sure to replace “<mydatabase>,” “<user>,” “<password>,” and “<home>” with the values appropriate for your environment.

url: jdbc:mysql://localhost:3306/<mydatabase>
username: <user>
password: <password>
classpath: <home>/.m2/repository/mysql/mysql-connector-java/8.0.23/mysql-connector-java-8.0.23.jar

Run liquibase --changeLogFile=changelog-1.0.xml generateChangeLog

Open “changelog-1.0.xml,“ and in every changeset in which a table is created, add the below precondition, replacing <tablename> with the appropriate name.

<preConditions onFail="MARK_RAN">
    <not>
        <tableExists tableName="<tablenam>"/>
    </not>
</preConditions>

If you already have a master changelog file, add the “include“ element below.

<include file="changelog-1.0.xml" relativeToChangelogFile="true"/>

The Liquibase CLI generates a separate changeset for tables and adds constraints/indexes. For every constraint/index, except for foreign keys, merge it with the respective “table creation changeset“. (This allows you to avoid having to set preconditions for each of these constraints independently.)

For foreign keys, add the below precondition. Replace <tablename> and <foreignKeyName> with the correct values.

<preConditions onFail="MARK_RAN">
    <not>
        <foreignKeyConstraintExists foreignKeyTableName="<tablename>" foreignKeyName="<foreignKeyName>"/>
    </not>
</preConditions>