Different ways of using Liquibase in Grails

“You never develop code without version control, why do you develop your database without it? Liquibase is an open source, database-independent library for tracking, managing and applying database changes. It is built on a simple premise: All database changes are stored in a human readable yet trackable form and checked into source control.”

There are at least two “normal” ways to integrate Liquibase into a grails application:

For some reason we had to choice a special Liquibase version which is not integrated in any grails plugin. The Spring bean is not able to handle different Postgres-schemas which was an important requirement in our project. Therefore we decided to write our own Liquibase bootstrap code:

Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(dbConnection)
database.setDefaultSchemaName(SCHEMA_NAME)
Liquibase liquibase = new Liquibase(CHANGELOG_FILENAME, new SpringResourceOpener(resourceLoader: resourceLoader), database)
liquibase.update("test,production")

The SpringResourceOpener which is able to load the Liquibase changelog file from within the WAR-file looks as follows:

public class SpringResourceOpener implements liquibase.FileOpener {
	private ResourceLoader resourceLoader
	public InputStream getResourceAsStream(String file) throws IOException {
		Resource resource = resourceLoader.getResource("/WEB-INF/resources/changeLog/$file")
		return resource.getInputStream()
	}
	public ClassLoader toClassLoader() {
		return resourceLoader.getClassLoader()
	}
}

For testing purposes we clean the database with a simple drop and recreate of the complete database schema:

connection.createStatement().execute("DROP SCHEMA IF EXISTS ${SCHEMA_NAME} CASCADE")
connection.createStatement().execute("CREATE SCHEMA ${SCHEMA_NAME}")
This entry was posted in Groovy and Grails, Java Persistence, Spring Universe and tagged , , , , . Bookmark the permalink.