Java Code Examples for org.flywaydb.core.Flyway#setLocations()

The following examples show how to use org.flywaydb.core.Flyway#setLocations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatabaseMigrator.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void doMigrate(String table, String location) {
    logger.info("migrate : {}, {}", table, location);

    Flyway flyway = new Flyway();
    flyway.setPlaceholderPrefix("$${");
    // flyway.setInitOnMigrate(true);
    flyway.setBaselineOnMigrate(true);
    // flyway.setInitVersion("0");
    flyway.setBaselineVersionAsString("0");
    flyway.setDataSource(dataSource);
    flyway.setTable(table);
    flyway.setLocations(new String[] { location });

    try {
        flyway.repair();
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

    flyway.migrate();
}
 
Example 2
Source File: FlywayTestUtils.java    From embedded-database-spring-test with Apache License 2.0 6 votes vote down vote up
public static Flyway createFlyway(DataSource dataSource, String schema, List<String> locations, boolean validateOnMigrate) {
    int flywayVersion = FlywayClassUtils.getFlywayVersion();

    if (flywayVersion >= 60) {
        Object config = invokeStaticMethod(Flyway.class, "configure");
        invokeMethod(config, "dataSource", dataSource);
        invokeMethod(config, "schemas", (Object) new String[]{ schema });
        invokeMethod(config, "validateOnMigrate", validateOnMigrate);
        if (!CollectionUtils.isEmpty(locations)) {
            invokeMethod(config, "locations", (Object) locations.toArray(new String[0]));
        }
        return (Flyway) invokeMethod(config, "load");
    } else {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setSchemas(schema);
        flyway.setValidateOnMigrate(validateOnMigrate);
        if (!CollectionUtils.isEmpty(locations)) {
            flyway.setLocations(locations.toArray(new String[0]));
        }
        return flyway;
    }
}
 
Example 3
Source File: PostgresDataSourceProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void flywayMigrate(DataSource dataSource) {
    boolean enabled = configuration.isFlywayEnabled();
    if (!enabled) {
        logger.debug("Flyway migrations are disabled");
        return;
    }


    Flyway flyway = new Flyway();
    configuration.getFlywayTable().ifPresent(tableName -> {
        logger.debug("Using Flyway migration table '{}'", tableName);
        flyway.setTable(tableName);
    });

    flyway.setLocations(Paths.get("db","migration_postgres").toString());
    flyway.setDataSource(dataSource);
    flyway.setPlaceholderReplacement(false);
    flyway.migrate();
}
 
Example 4
Source File: JooqDBUnitTest.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void initMigration() throws SQLException {
    flyway = new Flyway();
    flyway.setDataSource(DB_URL, "sa", "");
    flyway.setLocations("filesystem:src/main/resources/db/migration");
    flyway.migrate();

    connection = flyway.getDataSource().getConnection();
    //add some data to test db cleanup
    try (Statement stmt = connection.createStatement()) {
        stmt.addBatch("INSERT INTO flyway_test.author(id, first_name, last_name, date_of_birth, year_of_birth, address) VALUES (1, 'Erich', 'Gamma','1903-06-25','1900',null)");
        stmt.addBatch("INSERT INTO flyway_test.author(id, first_name, last_name, date_of_birth, year_of_birth, address) VALUES (2, 'Richard', 'Helm','1903-06-25','1900',null)");
        int[] result = stmt.executeBatch();
        assertEquals(result.length, 2);
    }
}
 
Example 5
Source File: ShellFlywayFactory.java    From registry with Apache License 2.0 6 votes vote down vote up
public static Flyway get(StorageProviderConfiguration conf, String scriptRootPath) {
    Flyway flyway = new Flyway();

    String location = "filesystem:" + scriptRootPath;
    flyway.setEncoding(encoding);
    flyway.setTable(metaDataTableName);
    flyway.setValidateOnMigrate(validateOnMigrate);
    flyway.setOutOfOrder(outOfOrder);
    flyway.setBaselineOnMigrate(baselineOnMigrate);
    flyway.setBaselineVersion(MigrationVersion.fromVersion(baselineVersion));
    flyway.setCleanOnValidationError(cleanOnValidationError);
    flyway.setLocations(location);
    flyway.setResolvers(new ShellMigrationResolver(flyway.getConfiguration(), location, shellMigrationPrefix, shellMigrationSeperator, shellMigrationSuffix));
    flyway.setDataSource(conf.getUrl(), conf.getUser(), conf.getPassword(), null);

    return flyway;
}
 
Example 6
Source File: SchemaFlywayFactory.java    From registry with Apache License 2.0 6 votes vote down vote up
private static Flyway basicFlyway(StorageProviderConfiguration conf,
                                  String scriptRootPath,
                                  boolean validateOnMigrate) {
    Flyway flyway = new Flyway();

    String location = "filesystem:" + scriptRootPath + File.separator + conf.getDbType();
    flyway.setEncoding(encoding);
    flyway.setTable(metaDataTableName);
    flyway.setSqlMigrationPrefix(sqlMigrationPrefix);
    flyway.setValidateOnMigrate(validateOnMigrate);
    flyway.setOutOfOrder(outOfOrder);
    flyway.setBaselineOnMigrate(baselineOnMigrate);
    flyway.setBaselineVersion(MigrationVersion.fromVersion(baselineVersion));
    flyway.setCleanOnValidationError(cleanOnValidationError);
    flyway.setLocations(location);

    return flyway;
}
 
Example 7
Source File: FlywayApplicationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void migrateWithNoCallbacks() {
    logTestBoundary("migrateWithNoCallbacks");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations("db/migration");
    flyway.migrate(); 
}
 
Example 8
Source File: TinkerTimeLauncher.java    From TinkerTime with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
	// Perform Database Migration
	Flyway flyway = new Flyway();
	flyway.setBaselineOnMigrate(true);
	flyway.setLocations("io/andrewohara/tinkertime/db/migration");
	flyway.setDataSource(connectionString.getUrl(), null, null);
	try {
		flyway.migrate();
	} catch (FlywayException e){
		flyway.repair();
		throw e;
	}
}
 
Example 9
Source File: FlywaySchemaInitializer.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Map<String, String> init() throws SchemaInitializationException {
  final Map<String, String> initResult = new HashMap<>();
  try (final Connection conn = dataSource.getConnection()) {
    final Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations(locations);
    flyway.setClassLoader(Thread.currentThread().getContextClassLoader());
    final DbSupport dbSupport = DbSupportFactory.createDbSupport(conn, true);
    final MetaDataTable mt =
        new MetaDataTableImpl(
            dbSupport,
            dbSupport.getOriginalSchema().getTable(flyway.getTable()),
            flyway.getInstalledBy());
    initResult.put(BARE_DB_INIT_PROPERTY_NAME, String.valueOf(!mt.hasAppliedMigrations()));
    final String productName = conn.getMetaData().getDatabaseProductName().toLowerCase();
    flyway.setResolvers(
        new CustomSqlMigrationResolver(productName, dbSupport, placeholderReplacer));
    flyway.setSkipDefaultResolvers(true);
    flyway.setBaselineOnMigrate(baselineOnMigrate);
    if (baselineOnMigrate) {
      flyway.setBaselineVersionAsString(baselineVersion);
    }
    flyway.setSqlMigrationSeparator(versionSeparator);
    flyway.setSqlMigrationSuffix(scriptsSuffix);
    flyway.setSqlMigrationPrefix(scriptsPrefix);
    flyway.migrate();
  } catch (SQLException | RuntimeException x) {
    throw new SchemaInitializationException(x.getLocalizedMessage(), x);
  }
  return initResult;
}
 
Example 10
Source File: ReaperApplicationTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlywayOnH2() throws IOException {
  Flyway flyway = new Flyway();
  flyway.setLocations("/db/h2");
  JdbcDataSource ds = new JdbcDataSource();
  File db = File.createTempFile("cassandra-reaper", "h2");
  try {
    ds.setUrl("jdbc:h2:" + db.getAbsolutePath() + ";MODE=PostgreSQL");
    flyway.setDataSource(ds);
    flyway.migrate();
  } finally {
    db.delete();
  }
}
 
Example 11
Source File: FlywayApplicationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void migrateWithSqlAndJavaCallbacks() {
    logTestBoundary("migrateWithSqlAndJavaCallbacks");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations("db/migration", "db/callbacks");
    flyway.setCallbacks(new ExampleFlywayCallback());
    flyway.migrate(); 
}
 
Example 12
Source File: CMSMigrations.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void migrate() {
    Flyway flyway = new Flyway();
    flyway.setDataSource(CMSConnectionPools.processing());
    flyway.setBaselineOnMigrate(true);
    flyway.setLocations("db/cms/migration");
    flyway.setSqlMigrationPrefix("V_");
    flyway.setTable("_flyway");
    flyway.migrate();
}
 
Example 13
Source File: Migrate.java    From microtrader with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Config config = ConfigFactory.load();

    Flyway flyway = new Flyway();
    flyway.setBaselineOnMigrate(true);
    flyway.setLocations(config.getString("migrations.location"));
    flyway.setDataSource(
            config.getString("jdbc.url"), 
            config.getString("jdbc.user"), 
            config.getString("jdbc.password"));
    flyway.migrate();
}
 
Example 14
Source File: FlywayApplicationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void migrateWithSqlCallbacks() {
    logTestBoundary("migrateWithSqlCallbacks");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations("db/migration", "db/callbacks");
    flyway.migrate(); 
}
 
Example 15
Source File: PostgresDAOTestUtil.java    From conductor with Apache License 2.0 5 votes vote down vote up
private void flywayMigrate(DataSource dataSource) {

        Flyway flyway = new Flyway();
        flyway.setLocations(Paths.get("db","migration_postgres").toString());
        flyway.setDataSource(dataSource);
        flyway.setPlaceholderReplacement(false);
        flyway.migrate();
    }
 
Example 16
Source File: CMSMigrations.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void migrate() {
    Flyway flyway = new Flyway();
    flyway.setDataSource(CMSConnectionPools.processing());
    flyway.setBaselineOnMigrate(true);
    flyway.setLocations("db/cms/migration");
    flyway.setSqlMigrationPrefix("V_");
    flyway.setTable("_flyway");
    flyway.migrate();
}
 
Example 17
Source File: DeployerConfiguration.java    From oneops with Apache License 2.0 5 votes vote down vote up
private DataSource setDataSource(EmbeddedPostgres server) throws Exception {
  PGPoolingDataSource dataSource = new PGPoolingDataSource();
  dataSource.setUser("kloopzcm");
  dataSource.setPassword("testpwd");
  dataSource.setPortNumber(server.getPort());
  dataSource.setDatabaseName("kloopzdb");

  Flyway flyway = new Flyway();
  flyway.setPlaceholderReplacement(false);
  flyway.setLocations("classpath:deployer");
  flyway.setDataSource(dataSource);
  flyway.migrate();

  return dataSource;
}
 
Example 18
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected static void setFlywayLocations(Flyway flyway, String[] locations) {
    if (flywayVersion >= 51) {
        Object configuration = getField(flyway, "configuration");
        invokeMethod(configuration, "setLocationsAsStrings", (Object) locations);
    } else {
        flyway.setLocations(locations);
    }
}
 
Example 19
Source File: DataSourceAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return H2 pooled data source
 * @throws SQLException
 */
@Bean(destroyMethod = "dispose")
public DataSource dataSource() throws SQLException {
	final JdbcConnectionPool pool = JdbcConnectionPool.create(url, user, password);
	pool.setMaxConnections(maxPoolConnections);
	Connection con = null;
	con = pool.getConnection();

	final Flyway flyway = new Flyway();
	flyway.setLocations("classpath:sql/migration");
	flyway.setDataSource(pool);
	flyway.setSqlMigrationPrefix("VOS-");
	flyway.setIgnoreFailedFutureMigration(true);

	final JdbcTemplate tpl = new JdbcTemplate(pool);
	if (tpl.queryForObject("select count(*) from information_schema.tables where table_name = 'LOG_SOURCES'",
			int.class) == 0) {
		logger.info("H2 database not found, creating new schema and populate with default data");
		flyway.setBaselineVersion(MigrationVersion.fromVersion(DB_SETUP_VERSION));
		flyway.setBaselineOnMigrate(true);
		try {
			final ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
			dbPopulator.addScript(new ClassPathResource("/sql/quartz/tables_h2.sql"));
			dbPopulator.addScript(new ClassPathResource("/sql/model/schema_h2.sql"));
			dbPopulator.populate(con);
			newSchema = true;
			logger.info("Established H2 connection pool with new database");
		} finally {
			if (con != null) {
				con.close();
			}
		}
	} else {
		logger.info("Established H2 connection pool with existing database");
		if (tpl.queryForObject("select count(*) from information_schema.tables where table_name = 'schema_version'",
				int.class) == 0) {
			logger.info("Flyway's DB migration not setup in this version, set baseline version to 0.5.0");
			flyway.setBaselineVersion(MigrationVersion.fromVersion("0.5.0"));
			flyway.setBaselineOnMigrate(true);
		}
	}

	logger.debug("Migrating database, base version is: {}", flyway.getBaselineVersion());
	flyway.migrate();
	logger.debug("Database migrated from base version: {}", flyway.getBaselineVersion());

	return pool;
}
 
Example 20
Source File: StatisticsFlywayWrapper.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
public void init(HibernateStorageSettings settings) {
    try {
        readWriteLock.writeLock().lock();
        migrationRequired = false;

        sfUpdateRequired = false;

        flyway = new Flyway();

        flyway.getPlaceholders().put("db_name", settings.getDbName());

        String[] initSqls = new String[0];

        if (settings.getDbms().equals(DbmsType.PostgreSQL.getValue())) {
            flyway.setLocations(PSQL_SCRIPT_LOCATION);
        }

        if (settings.getDbms().equals(DbmsType.MySql.getValue())) {
            flyway.setLocations(MYSQL_SCRIPT_LOCATION);
            initSqls = MYSQL_INIT_SQL;
        }

        flyway.setDataSource(settings.buildConnectionUrl(), settings.getUsername(), settings.getPassword(), initSqls);

        flyway.setBaselineOnMigrate(false);

        // Get info about migrations

        MigrationInfoService info = flyway.info();

        currentDbVersionInfo = info.current();

        pendingMigrationsInfo = info.pending();

        MigrationInfo[] all = info.all();

        // Checks

        if (currentDbVersionInfo == null) {
            migrationRequired = true;

            throw new OlderSchemaException("DB initialization is required");

        }

        if (pendingMigrationsInfo.length != 0) {
            migrationRequired = true;

            throw new OlderSchemaException("Migration to version "
                    + pendingMigrationsInfo[pendingMigrationsInfo.length - 1].getVersion().getVersion()
                    + " is required");

        }

        if (all.length != 0) {
            MigrationInfo lastKnown = all[all.length - 1];

            if(lastKnown.getState() == MigrationState.FUTURE_SUCCESS) {

                sfUpdateRequired = true;

                throw new NewerSchemaException("DB schema has newer version " + lastKnown.getVersion().getVersion()
                        + ". Upgrade this Sailfish instance to use it.");
            }
        }
    } finally {
        readWriteLock.writeLock().unlock();
    }
}