AdmMono/src/com/rjconsultores/ventaboletos/FlyWay.java

127 lines
3.1 KiB
Java

package com.rjconsultores.ventaboletos;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.flywaydb.core.Flyway;
import javax.sql.DataSource;
public class FlyWay {
private static Logger log = Logger.getLogger(FlyWay.class);
private static final FlyWay INSTANCE = new FlyWay();
private DataSource dataSource = null;
private String location = "db.migration";
public static FlyWay getInstance() {
return INSTANCE;
}
public void defineLocation(final String location) {
this.location = location;
}
public void defineDataSource(final DataSource dataSource) {
this.dataSource = dataSource;
fixFiles(dataSource);
}
private void fixFiles(final DataSource ds) {
try {
Connection c = dataSource.getConnection();
Statement s = c.createStatement();
fixVersion(s, "20161710.1833", "20161017.1833", "V20161017_1833__mantis8112.sql");
fixVersion(s, "20161910.0934", "20161019.0934", "V20161019_0934__mantis7907.sql");
fixVersion(s, "20162410.1119", "20161024.1119", "V20161024_1119__mantis7904.sql");
s.close();
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
}
private void fixVersion(final Statement s, final String oldVersion, final String newVersion, final String newScript) throws SQLException {
ResultSet rs = s.executeQuery("select count(*) as total from \"schema_version\" where \"version\" like '" + oldVersion + "'");
int total = 0;
while (rs.next()) {
total = rs.getInt("total");
}
rs.close();
if (total > 0) {
log.info("Fix version " + oldVersion + " to new version " + newVersion + " and new script " + newScript);
StringBuilder sql = new StringBuilder("");
sql.append(" update \"schema_version\"");
sql.append(" set \"version\" = '" + newVersion + "', \"script\" = '" + newScript + "'");
sql.append(" where \"version\" like '" + oldVersion + "'");
s.executeUpdate(sql.toString());
}
}
public boolean start() {
log.info("Executando Flyway...");
try{
final Flyway flyway = new Flyway();
flyway.setLocations(this.location);
flyway.setDataSource(dataSource);
execute(flyway);
}catch(Throwable t){
log.error("Erro ao executar o flyway",t);
return false;
}
log.info("Flyway executado.");
return true;
}
public boolean start(String url, String user, String password) {
log.info("Executando Flyway...");
try{
final Flyway flyway = new Flyway();
flyway.setLocations("classpath: " + this.location);
flyway.setDataSource(url, user, password);
execute(flyway);
}catch(Throwable t){
log.error("Erro ao executar o flyway",t);
return false;
}
log.info("Flyway executado.");
return true;
}
public void execute(final Flyway flyway) {
flyway.setValidateOnMigrate(false);
flyway.setIgnoreFutureMigrations(true);
flyway.setOutOfOrder(true);
flyway.setBaselineOnMigrate(true);
flyway.migrate();
}
}