ProgrammableLiquibase.java

/*
 * Copyright 2022 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.custom.liquibase;

import liquibase.Liquibase;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.exception.LiquibaseException;
import liquibase.integration.spring.SpringLiquibase;
import liquibase.integration.spring.SpringResourceAccessor;

import java.sql.Connection;

public class ProgrammableLiquibase extends SpringLiquibase {
	
	private final DatabaseChangeLog databaseChangeLog;

	public ProgrammableLiquibase(DatabaseChangeLog databaseChangeLog) {
		this.databaseChangeLog = databaseChangeLog;
	}
	
	@Override
	public void afterPropertiesSet() {
		// Do nothing
	}

	// Our upgrades
	public void doUpgrades() throws Exception {
		Connection c = null;
		Liquibase liquibase = null;
		try {
			c = getDataSource().getConnection();
			liquibase = createLiquibase(c);
			performUpdate(liquibase);
		} finally {
			if (liquibase != null) {
				liquibase.close();
			}
		}
	}

	@Override
	protected Liquibase createLiquibase(Connection c) throws LiquibaseException {
		SpringResourceAccessor resourceAccessor = createResourceOpener();

		return new Liquibase(databaseChangeLog, resourceAccessor, createDatabase(c, resourceAccessor));
	}
}