Search in sources :

Example 1 with TransactionTemplate

use of org.flywaydb.core.internal.util.jdbc.TransactionTemplate in project killbill by killbill.

the class DbMigrateWithDryRun method dryRunMigrate.

public int dryRunMigrate() throws FlywayException {
    try {
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connectionUserObjects).execute(new TransactionCallback<Object>() {

                @Override
                public Object doInTransaction() throws SQLException {
                    dbSupportUserObjects.changeCurrentSchemaTo(schema);
                    callback.beforeMigrate(connectionUserObjects);
                    return null;
                }
            });
        }
        // PIERRE: perform a single query to the metadata table
        final MigrationInfoServiceImpl infoService = new MigrationInfoServiceImpl(migrationResolver, metaDataTableForDryRun, target, outOfOrder, true, true);
        infoService.refresh();
        final MigrationInfoImpl[] pendingMigrations = infoService.pending();
        new TransactionTemplate(connectionMetaDataTable, false).execute(new TransactionCallback<Boolean>() {

            public Boolean doInTransaction() {
                int i = 1;
                for (final MigrationInfoImpl migrationInfo : pendingMigrations) {
                    applyMigration(i, migrationInfo);
                    i++;
                }
                return true;
            }
        });
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connectionUserObjects).execute(new TransactionCallback<Object>() {

                @Override
                public Object doInTransaction() throws SQLException {
                    dbSupportUserObjects.changeCurrentSchemaTo(schema);
                    callback.afterMigrate(connectionUserObjects);
                    return null;
                }
            });
        }
        return pendingMigrations.length;
    } finally {
        dbSupportUserObjects.restoreCurrentSchema();
    }
}
Also used : MigrationInfoServiceImpl(org.flywaydb.core.internal.info.MigrationInfoServiceImpl) FlywayCallback(org.flywaydb.core.api.callback.FlywayCallback) SQLException(java.sql.SQLException) MigrationInfoImpl(org.flywaydb.core.internal.info.MigrationInfoImpl) TransactionTemplate(org.flywaydb.core.internal.util.jdbc.TransactionTemplate)

Example 2 with TransactionTemplate

use of org.flywaydb.core.internal.util.jdbc.TransactionTemplate in project flyway by flyway.

the class MetaDataTableImpl method upgradeIfNecessary.

@Override
public boolean upgradeIfNecessary() {
    if (table.exists() && table.hasColumn("version_rank")) {
        new TransactionTemplate(jdbcTemplate.getConnection()).execute(new Callable<Object>() {

            @Override
            public Void call() {
                lock(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                        LOG.info("Upgrading metadata table " + table + " to the Flyway 4.0 format ...");
                        String resourceName = "org/flywaydb/core/internal/dbsupport/" + dbSupport.getDbName() + "/upgradeMetaDataTable.sql";
                        String source = new ClassPathResource(resourceName, getClass().getClassLoader()).loadAsString("UTF-8");
                        Map<String, String> placeholders = new HashMap<String, String>();
                        placeholders.put("schema", table.getSchema().getName());
                        placeholders.put("table", table.getName());
                        String sourceNoPlaceholders = new PlaceholderReplacer(placeholders, "${", "}").replacePlaceholders(source);
                        SqlScript sqlScript = new SqlScript(sourceNoPlaceholders, dbSupport);
                        sqlScript.execute(jdbcTemplate);
                        return null;
                    }
                });
                return null;
            }
        });
        return true;
    }
    return false;
}
Also used : HashMap(java.util.HashMap) TransactionTemplate(org.flywaydb.core.internal.util.jdbc.TransactionTemplate) PlaceholderReplacer(org.flywaydb.core.internal.util.PlaceholderReplacer) SqlScript(org.flywaydb.core.internal.dbsupport.SqlScript) Callable(java.util.concurrent.Callable) ClassPathResource(org.flywaydb.core.internal.util.scanner.classpath.ClassPathResource)

Example 3 with TransactionTemplate

use of org.flywaydb.core.internal.util.jdbc.TransactionTemplate in project flyway by flyway.

the class DbMigrate method applyMigration.

/**
     * Applies this migration to the database. The migration state and the execution time are updated accordingly.
     *
     * @param migration    The migration to apply.
     * @param isOutOfOrder If this migration is being applied out of order.
     * @return The result of the migration.
     */
private Boolean applyMigration(final MigrationInfoImpl migration, boolean isOutOfOrder) {
    MigrationVersion version = migration.getVersion();
    final MigrationExecutor migrationExecutor = migration.getResolvedMigration().getExecutor();
    final String migrationText;
    if (version != null) {
        migrationText = "schema " + schema + " to version " + version + " - " + migration.getDescription() + (isOutOfOrder ? " [out of order]" : "") + (migrationExecutor.executeInTransaction() ? "" : " [non-transactional]");
    } else {
        migrationText = "schema " + schema + " with repeatable migration " + migration.getDescription() + (migrationExecutor.executeInTransaction() ? "" : " [non-transactional]");
    }
    LOG.info("Migrating " + migrationText);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    try {
        if (migrationExecutor.executeInTransaction()) {
            new TransactionTemplate(connectionUserObjects).execute(new Callable<Object>() {

                @Override
                public Object call() throws SQLException {
                    doMigrate(migration, migrationExecutor, migrationText);
                    return null;
                }
            });
        } else {
            try {
                doMigrate(migration, migrationExecutor, migrationText);
            } catch (SQLException e) {
                throw new FlywaySqlException("Unable to apply migration", e);
            }
        }
    } catch (FlywayException e) {
        String failedMsg = "Migration of " + migrationText + " failed!";
        if (dbSupport.supportsDdlTransactions() && migrationExecutor.executeInTransaction()) {
            LOG.error(failedMsg + " Changes successfully rolled back.");
        } else {
            LOG.error(failedMsg + " Please restore backups and roll back database and code!");
            stopWatch.stop();
            int executionTime = (int) stopWatch.getTotalTimeMillis();
            AppliedMigration appliedMigration = new AppliedMigration(version, migration.getDescription(), migration.getType(), migration.getScript(), migration.getResolvedMigration().getChecksum(), executionTime, false);
            metaDataTable.addAppliedMigration(appliedMigration);
        }
        throw e;
    }
    stopWatch.stop();
    int executionTime = (int) stopWatch.getTotalTimeMillis();
    AppliedMigration appliedMigration = new AppliedMigration(version, migration.getDescription(), migration.getType(), migration.getScript(), migration.getResolvedMigration().getChecksum(), executionTime, true);
    metaDataTable.addAppliedMigration(appliedMigration);
    return false;
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) FlywaySqlException(org.flywaydb.core.internal.dbsupport.FlywaySqlException) SQLException(java.sql.SQLException) MigrationExecutor(org.flywaydb.core.api.resolver.MigrationExecutor) TransactionTemplate(org.flywaydb.core.internal.util.jdbc.TransactionTemplate) StopWatch(org.flywaydb.core.internal.util.StopWatch) MigrationVersion(org.flywaydb.core.api.MigrationVersion) AppliedMigration(org.flywaydb.core.internal.metadatatable.AppliedMigration)

Example 4 with TransactionTemplate

use of org.flywaydb.core.internal.util.jdbc.TransactionTemplate in project flyway by flyway.

the class DbBaseline method baseline.

/**
     * Baselines the database.
     */
public void baseline() {
    try {
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connection).execute(new Callable<Object>() {

                @Override
                public Object call() throws SQLException {
                    dbSupport.changeCurrentSchemaTo(schema);
                    callback.beforeBaseline(connection);
                    return null;
                }
            });
        }
        new TransactionTemplate(connection).execute(new Callable<Object>() {

            @Override
            public Void call() {
                dbSupport.changeCurrentSchemaTo(schema);
                if (metaDataTable.hasBaselineMarker()) {
                    AppliedMigration baselineMarker = metaDataTable.getBaselineMarker();
                    if (baselineVersion.equals(baselineMarker.getVersion()) && baselineDescription.equals(baselineMarker.getDescription())) {
                        LOG.info("Metadata table " + metaDataTable + " already initialized with (" + baselineVersion + "," + baselineDescription + "). Skipping.");
                        return null;
                    }
                    throw new FlywayException("Unable to baseline metadata table " + metaDataTable + " with (" + baselineVersion + "," + baselineDescription + ") as it has already been initialized with (" + baselineMarker.getVersion() + "," + baselineMarker.getDescription() + ")");
                }
                if (metaDataTable.hasSchemasMarker() && baselineVersion.equals(MigrationVersion.fromVersion("0"))) {
                    throw new FlywayException("Unable to baseline metadata table " + metaDataTable + " with version 0 as this version was used for schema creation");
                }
                if (metaDataTable.hasAppliedMigrations()) {
                    throw new FlywayException("Unable to baseline metadata table " + metaDataTable + " as it already contains migrations");
                }
                metaDataTable.addBaselineMarker(baselineVersion, baselineDescription);
                return null;
            }
        });
        LOG.info("Successfully baselined schema with version: " + baselineVersion);
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connection).execute(new Callable<Object>() {

                @Override
                public Object call() throws SQLException {
                    dbSupport.changeCurrentSchemaTo(schema);
                    callback.afterBaseline(connection);
                    return null;
                }
            });
        }
    } finally {
        dbSupport.restoreCurrentSchema();
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) FlywayCallback(org.flywaydb.core.api.callback.FlywayCallback) SQLException(java.sql.SQLException) AppliedMigration(org.flywaydb.core.internal.metadatatable.AppliedMigration) TransactionTemplate(org.flywaydb.core.internal.util.jdbc.TransactionTemplate)

Example 5 with TransactionTemplate

use of org.flywaydb.core.internal.util.jdbc.TransactionTemplate in project flyway by flyway.

the class DbClean method clean.

/**
     * Cleans the schemas of all objects.
     *
     * @throws FlywayException when clean failed.
     */
public void clean() throws FlywayException {
    if (cleanDisabled) {
        throw new FlywayException("Unable to execute clean as it has been disabled with the \"flyway.cleanDisabled\" property.");
    }
    try {
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connection).execute(new Callable<Object>() {

                @Override
                public Object call() throws SQLException {
                    dbSupport.changeCurrentSchemaTo(schemas[0]);
                    callback.beforeClean(connection);
                    return null;
                }
            });
        }
        dbSupport.changeCurrentSchemaTo(schemas[0]);
        boolean dropSchemas = false;
        try {
            dropSchemas = metaDataTable.hasSchemasMarker();
        } catch (Exception e) {
            LOG.error("Error while checking whether the schemas should be dropped", e);
        }
        for (Schema schema : schemas) {
            if (!schema.exists()) {
                LOG.warn("Unable to clean unknown schema: " + schema);
                continue;
            }
            if (dropSchemas) {
                dropSchema(schema);
            } else {
                cleanSchema(schema);
            }
        }
        for (final FlywayCallback callback : callbacks) {
            new TransactionTemplate(connection).execute(new Callable<Object>() {

                @Override
                public Object call() throws SQLException {
                    dbSupport.changeCurrentSchemaTo(schemas[0]);
                    callback.afterClean(connection);
                    return null;
                }
            });
        }
    } finally {
        dbSupport.restoreCurrentSchema();
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) FlywayCallback(org.flywaydb.core.api.callback.FlywayCallback) SQLException(java.sql.SQLException) Schema(org.flywaydb.core.internal.dbsupport.Schema) TransactionTemplate(org.flywaydb.core.internal.util.jdbc.TransactionTemplate) FlywayException(org.flywaydb.core.api.FlywayException) SQLException(java.sql.SQLException)

Aggregations

TransactionTemplate (org.flywaydb.core.internal.util.jdbc.TransactionTemplate)11 SQLException (java.sql.SQLException)7 FlywayCallback (org.flywaydb.core.api.callback.FlywayCallback)7 StopWatch (org.flywaydb.core.internal.util.StopWatch)6 FlywayException (org.flywaydb.core.api.FlywayException)4 MigrationInfoServiceImpl (org.flywaydb.core.internal.info.MigrationInfoServiceImpl)4 Callable (java.util.concurrent.Callable)2 MigrationVersion (org.flywaydb.core.api.MigrationVersion)2 Schema (org.flywaydb.core.internal.dbsupport.Schema)2 AppliedMigration (org.flywaydb.core.internal.metadatatable.AppliedMigration)2 Connection (java.sql.Connection)1 HashMap (java.util.HashMap)1 MigrationInfoService (org.flywaydb.core.api.MigrationInfoService)1 MigrationExecutor (org.flywaydb.core.api.resolver.MigrationExecutor)1 MigrationResolver (org.flywaydb.core.api.resolver.MigrationResolver)1 SqlScriptFlywayCallback (org.flywaydb.core.internal.callback.SqlScriptFlywayCallback)1 DbSupport (org.flywaydb.core.internal.dbsupport.DbSupport)1 FlywaySqlException (org.flywaydb.core.internal.dbsupport.FlywaySqlException)1 SqlScript (org.flywaydb.core.internal.dbsupport.SqlScript)1 MigrationInfoImpl (org.flywaydb.core.internal.info.MigrationInfoImpl)1