Search code examples
database-migrationliquibase

Liquibase database migration with empty and preexisting database


I'm developing a Java web application with Spring, JPA/Hibernate and MS SQL Server/PostgreSQL. To make migration of the database for installed systems easier I want to integrate Liquibase to do the update automatically when the application is started. Currently I'm always creating update scripts which I have to execute manually in the right order.

I tested the integration with Spring and I got it working very quickly. The meta tables of Liquibase are getting created with the first changeset and it performs the changes. The problem is that there exist already some installed systems, but there may be other installations coming in the future.

Is it possible with Liquibase to detect if the database is empty and execute a DDL automatically in a freshly installed system? Otherwise I would have to manually execute the DDL and than start the application.

What I want is that the database gets initialized automatically when it is empty or gets updated if it already exists. Is there a possiblity to do that with Liquibase or are there any tricks to get this working?


Solution

  • When you are starting to use liquibase on an existing system with an existing schema, there are basically two options:

    1. Assume all databases will start at a known start point. Do whatever you need outside liquibase to get them to this point (restore from snapshot, manually build, etc.)

    2. Use the liquibase generateChangeLog command to create a changeSet for the existing database. You will only want to run this on new databases, so you can control this either with a custom liquibase spring integration call, or collapsing the generated changeLog down to one changeSet with a <preConditions onFail="MARK_RAN"><not><tableExists tableName="table name here"/></not></preConditions> block at the start.