Search in sources :

Example 1 with PlaceholderReplacer

use of org.flywaydb.core.internal.util.PlaceholderReplacer in project che by eclipse.

the class CustomSqlMigrationResolver method resolveSqlMigrations.

private List<ResolvedMigration> resolveSqlMigrations() throws IOException, SQLException {
    LOG.info("Searching for sql scripts in locations {}", Arrays.toString(flywayConfiguration.getLocations()));
    final Map<Location, List<Resource>> allResources = finder.findResources(flywayConfiguration);
    LOG.debug("Found scripts: {}", allResources);
    final Map<String, Map<String, SqlScript>> scriptsInDir = new HashMap<>();
    for (Location location : allResources.keySet()) {
        final List<Resource> resources = allResources.get(location);
        for (Resource resource : resources) {
            final SqlScript newScript = scriptsCreator.createScript(location, resource);
            if (!scriptsInDir.containsKey(newScript.dir)) {
                scriptsInDir.put(newScript.dir, new HashMap<>(4));
            }
            final Map<String, SqlScript> existingScripts = scriptsInDir.get(newScript.dir);
            final SqlScript existingScript = existingScripts.get(newScript.name);
            if (existingScript == null) {
                existingScripts.put(newScript.name, newScript);
            } else if (Objects.equals(existingScript.vendor, newScript.vendor)) {
                throw new FlywayException(format("More than one script with name '%s' is registered for " + "database vendor '%s', script '%s' conflicts with '%s'", newScript.name, existingScript.vendor, newScript, existingScript));
            } else if (vendorName.equals(newScript.vendor)) {
                existingScripts.put(newScript.name, newScript);
            }
        }
    }
    final Map<MigrationVersion, ResolvedMigration> migrations = new HashMap<>();
    for (SqlScript script : scriptsInDir.values().stream().flatMap(scripts -> scripts.values().stream()).collect(toList())) {
        final ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
        migration.setVersion(versionResolver.resolve(script, flywayConfiguration));
        migration.setScript(script.resource.getLocation());
        migration.setPhysicalLocation(script.resource.getLocationOnDisk());
        migration.setType(MigrationType.SQL);
        migration.setDescription(script.name);
        migration.setChecksum(ByteSource.wrap(script.resource.loadAsBytes()).hash(Hashing.crc32()).asInt());
        migration.setExecutor(new SqlMigrationExecutor(dbSupport, script.resource, placeholderReplacer, flywayConfiguration.getEncoding()));
        if (migrations.put(migration.getVersion(), migration) != null) {
            throw new FlywayException("Two migrations with the same version detected");
        }
    }
    return new ArrayList<>(migrations.values());
}
Also used : Arrays(java.util.Arrays) FlywayException(org.flywaydb.core.api.FlywayException) LoggerFactory(org.slf4j.LoggerFactory) Hashing(com.google.common.hash.Hashing) Resource(org.flywaydb.core.internal.util.scanner.Resource) HashMap(java.util.HashMap) ResolvedMigrationImpl(org.flywaydb.core.internal.resolver.ResolvedMigrationImpl) BaseMigrationResolver(org.flywaydb.core.api.resolver.BaseMigrationResolver) ArrayList(java.util.ArrayList) Location(org.flywaydb.core.internal.util.Location) MigrationVersion(org.flywaydb.core.api.MigrationVersion) SQLException(java.sql.SQLException) Map(java.util.Map) ByteSource(com.google.common.io.ByteSource) Logger(org.slf4j.Logger) SqlMigrationExecutor(org.flywaydb.core.internal.resolver.sql.SqlMigrationExecutor) PlaceholderReplacer(org.flywaydb.core.internal.util.PlaceholderReplacer) Collection(java.util.Collection) IOException(java.io.IOException) MigrationType(org.flywaydb.core.api.MigrationType) ResolvedMigration(org.flywaydb.core.api.resolver.ResolvedMigration) String.format(java.lang.String.format) Objects(java.util.Objects) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) DbSupport(org.flywaydb.core.internal.dbsupport.DbSupport) FlywayException(org.flywaydb.core.api.FlywayException) HashMap(java.util.HashMap) Resource(org.flywaydb.core.internal.util.scanner.Resource) ArrayList(java.util.ArrayList) ResolvedMigrationImpl(org.flywaydb.core.internal.resolver.ResolvedMigrationImpl) SqlMigrationExecutor(org.flywaydb.core.internal.resolver.sql.SqlMigrationExecutor) MigrationVersion(org.flywaydb.core.api.MigrationVersion) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ResolvedMigration(org.flywaydb.core.api.resolver.ResolvedMigration) HashMap(java.util.HashMap) Map(java.util.Map) Location(org.flywaydb.core.internal.util.Location)

Example 2 with PlaceholderReplacer

use of org.flywaydb.core.internal.util.PlaceholderReplacer 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 PlaceholderReplacer

use of org.flywaydb.core.internal.util.PlaceholderReplacer in project che by eclipse.

the class FlywaySchemaInitializerTest method replacesVariablesWhenPlaceholderReplacerIsConfigured.

@Test
public void replacesVariablesWhenPlaceholderReplacerIsConfigured() throws Exception {
    createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));" + "INSERT INTO test VALUES(1, '${variable}');");
    FlywayInitializerBuilder.from(dataSource).setReplacer(new PlaceholderReplacer(ImmutableMap.of("variable", "test"), "${", "}")).build().init();
    assertEquals(queryEntities(), Sets.newHashSet(new TestEntity(1, "test")));
}
Also used : PlaceholderReplacer(org.flywaydb.core.internal.util.PlaceholderReplacer) Test(org.testng.annotations.Test)

Example 4 with PlaceholderReplacer

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

the class MetaDataTableImpl method createIfNotExists.

/**
     * Creates the metatable if it doesn't exist, upgrades it if it does.
     */
private void createIfNotExists() {
    int retries = 0;
    while (!table.exists()) {
        if (retries == 0) {
            LOG.info("Creating Metadata table: " + table);
        }
        try {
            String resourceName = "org/flywaydb/core/internal/dbsupport/" + dbSupport.getDbName() + "/createMetaDataTable.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);
            final SqlScript sqlScript = new SqlScript(sourceNoPlaceholders, dbSupport);
            sqlScript.execute(jdbcTemplate);
            LOG.debug("Metadata table " + table + " created.");
        } catch (FlywayException e) {
            if (++retries >= 10) {
                throw e;
            }
            try {
                LOG.debug("Metadata table creation failed. Retrying in 1 sec ...");
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
            // Ignore
            }
        }
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) HashMap(java.util.HashMap) PlaceholderReplacer(org.flywaydb.core.internal.util.PlaceholderReplacer) SqlScript(org.flywaydb.core.internal.dbsupport.SqlScript) ClassPathResource(org.flywaydb.core.internal.util.scanner.classpath.ClassPathResource)

Example 5 with PlaceholderReplacer

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

the class MetaDataTableImpl method update.

@Override
public void update(MigrationVersion version, String description, Integer checksum) {
    clearCache();
    LOG.info("Repairing metadata for version " + version + " (Description: " + description + ", Checksum: " + checksum + ")  ...");
    // Try load an update.sql file if it exists
    String resourceName = "org/flywaydb/core/internal/dbsupport/" + dbSupport.getDbName() + "/update.sql";
    ClassPathResource resource = new ClassPathResource(resourceName, getClass().getClassLoader());
    if (resource.exists()) {
        String source = resource.loadAsString("UTF-8");
        Map<String, String> placeholders = new HashMap<String, String>();
        // Placeholders for column names
        placeholders.put("schema", table.getSchema().getName());
        placeholders.put("table", table.getName());
        // Placeholders for column values
        placeholders.put("version_val", version.toString());
        placeholders.put("description_val", description);
        placeholders.put("checksum_val", String.valueOf(checksum));
        String sourceNoPlaceholders = new PlaceholderReplacer(placeholders, "${", "}").replacePlaceholders(source);
        new SqlScript(sourceNoPlaceholders, dbSupport).execute(jdbcTemplate);
    } else {
        try {
            jdbcTemplate.update("UPDATE " + table + " SET " + dbSupport.quote("description") + "='" + description + "' , " + dbSupport.quote("checksum") + "=" + checksum + " WHERE " + dbSupport.quote("version") + "='" + version + "'");
        } catch (SQLException e) {
            throw new FlywaySqlException("Unable to repair metadata table " + table + " for version " + version, e);
        }
    }
}
Also used : FlywaySqlException(org.flywaydb.core.internal.dbsupport.FlywaySqlException) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) PlaceholderReplacer(org.flywaydb.core.internal.util.PlaceholderReplacer) SqlScript(org.flywaydb.core.internal.dbsupport.SqlScript) ClassPathResource(org.flywaydb.core.internal.util.scanner.classpath.ClassPathResource)

Aggregations

PlaceholderReplacer (org.flywaydb.core.internal.util.PlaceholderReplacer)8 HashMap (java.util.HashMap)6 SqlScript (org.flywaydb.core.internal.dbsupport.SqlScript)4 ClassPathResource (org.flywaydb.core.internal.util.scanner.classpath.ClassPathResource)4 SQLException (java.sql.SQLException)3 FlywayException (org.flywaydb.core.api.FlywayException)2 MigrationVersion (org.flywaydb.core.api.MigrationVersion)2 ResolvedMigration (org.flywaydb.core.api.resolver.ResolvedMigration)2 FlywaySqlException (org.flywaydb.core.internal.dbsupport.FlywaySqlException)2 Test (org.junit.Test)2 Hashing (com.google.common.hash.Hashing)1 ByteSource (com.google.common.io.ByteSource)1 IOException (java.io.IOException)1 String.format (java.lang.String.format)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1