Java Code Examples for org.flywaydb.core.Flyway

The following examples show how to use org.flywaydb.core.Flyway. These examples are extracted from open source projects. 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 Project: registry   Source File: SchemaFlywayFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Flyway oracleFlyway(StorageProviderConfiguration conf,
                                   String scriptRootPath,
                                   boolean validateOnMigrate) {
    Flyway flyway = basicFlyway(conf, scriptRootPath, validateOnMigrate);
    Map<String, Object> connectionProperties = conf.getConnectionProperties();

    if (connectionProperties != null && !connectionProperties.isEmpty()) {
        Properties properties = new Properties();
        properties.putAll(connectionProperties);
        DriverDataSource dataSource = new DriverDataSource(flyway.getClassLoader(),
                null, conf.getUrl(), conf.getUser(), conf.getPassword(), properties);
        flyway.setDataSource(dataSource);
    } else {
        flyway.setDataSource(conf.getUrl(), conf.getUser(), conf.getPassword());
    }

    return flyway;
}
 
Example 2
Source Project: micronaut-flyway   Source File: FlywayEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return A list of Flyway migrations per active configuration
 */
@Read
public Publisher<FlywayReport> flywayMigrations() {

    return Flowable.fromIterable(flywayConfigurationProperties)
            .filter(FlywayConfigurationProperties::isEnabled)
            .map(c -> new Pair<>(c,
                    applicationContext
                            .findBean(Flyway.class, Qualifiers.byName(c.getNameQualifier()))
                            .orElse(null)))
            .filter(pair -> pair.getSecond() != null)
            .map(pair -> new FlywayReport(
                    pair.getFirst().getNameQualifier(),
                    Arrays.asList(pair.getSecond().info().all()))
            );
}
 
Example 3
public void migrate(String dbType, boolean withStartupVer) throws InitializationException
{
    setTransactionIsolation(dbType);

    if (withStartupVer)
    {
        checkMinVersion();
    }

    Flyway.configure()
        .schemas(DATABASE_SCHEMA_NAME)
        .dataSource(dataSource)
        .table(SCHEMA_HISTORY_TABLE_NAME)
        // When migrations are added in branches they can be applied in different orders
        .outOfOrder(true)
        // Pass the DB type to the migrations
        .placeholders(ImmutableMap.of(LinstorMigration.PLACEHOLDER_KEY_DB_TYPE, dbType))
        .locations(LinstorMigration.class.getPackage().getName())
        .ignoreFutureMigrations(false)
        .load()
        .migrate();
}
 
Example 4
Source Project: registry   Source File: SchemaFlywayFactory.java    License: 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 5
/**
 * Checks if test migrations are appendable to core migrations.
 */
protected static boolean isAppendable(Flyway flyway, FlywayTest annotation) throws ClassNotFoundException {
    if (annotation.overrideLocations()) {
        return false;
    }

    if (ArrayUtils.isEmpty(annotation.locationsForMigrate())) {
        return true;
    }

    MigrationVersion testVersion = findFirstVersion(flyway, annotation.locationsForMigrate());
    if (testVersion == MigrationVersion.EMPTY) {
        return true;
    }

    MigrationVersion coreVersion = findLastVersion(flyway, getFlywayLocations(flyway));
    return coreVersion.compareTo(testVersion) < 0;
}
 
Example 6
Source Project: quark   Source File: DbMetaDataTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
  MetaDataTest.setUpClass(h2Url);
  Flyway flyway = new Flyway();
  flyway.setDataSource(dbSchemaUrl, "sa", "");
  flyway.migrate();

  Properties connInfo = new Properties();
  connInfo.setProperty("url", dbSchemaUrl);
  connInfo.setProperty("user", "sa");
  connInfo.setProperty("password", "");

  dbConnection = DriverManager.getConnection(dbSchemaUrl, connInfo);

  Statement stmt = dbConnection.createStatement();
  String sql = "insert into data_sources(name, type, url, ds_set_id, datasource_type) values "
      + "('H2', 'H2', '" + h2Url + "', 1, 'JDBC'); insert into jdbc_sources (id, "
      + "username, password) values(1, 'sa', '');" +
      "update ds_sets set default_datasource_id = 1 where id = 1;";

  stmt.execute(sql);
  stmt.close();
}
 
Example 7
Source Project: quark   Source File: DDLMetaDataTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
  MetaDataTest.setUpClass(h2Url);
  MetaDataTest.setUpClass(inputUrl);
  Flyway flyway = new Flyway();
  flyway.setDataSource(dbSchemaUrl, "sa", "");
  flyway.migrate();

  Properties connInfo = new Properties();
  connInfo.setProperty("url", dbSchemaUrl);
  connInfo.setProperty("user", "sa");
  connInfo.setProperty("password", "");

  final Connection dbConnection = DriverManager.getConnection(dbSchemaUrl, connInfo);

  Statement stmt = dbConnection.createStatement();
  String sql = "insert into data_sources(name, type, url, ds_set_id, datasource_type) values "
      + "('SEEDED', 'H2', '" + h2Url + "', 1, 'JDBC'); insert into jdbc_sources (id, "
      + "username, password) values(1, 'sa', '');"
      + "update ds_sets set default_datasource_id = 1 where id = 1;";

  stmt.execute(sql);
  stmt.close();
}
 
Example 8
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    Flyway flyway = new Flyway();
    String dataSourceJndi = sc.getInitParameter(FLYWAY_JNDI_DATASOURCE);
    if (dataSourceJndi != null) {
        try {
            DataSource dataSource = (DataSource) new InitialContext().lookup(dataSourceJndi);
            flyway.setDataSource(dataSource);
        } catch (NamingException ex) {
            logger.log(Level.SEVERE, "Error while looking up DataSource", ex);
            // Do not proceed
            return;
        }
    } else {
        String url = sc.getInitParameter(FLYWAY_JDBC_URL);
        String user = sc.getInitParameter(FLYWAY_JDBC_USER);
        String password = sc.getInitParameter(FLYWAY_JDBC_PASSWORD);
        flyway.setDataSource(url, user, password);
    }
    // Configure with flyway.* system properties
    flyway.configure(System.getProperties());
    flyway.migrate();
}
 
Example 9
@Bean
public Flyway migrator(DataSource dataSource) {
    var configuration = Flyway.configure();
    var jdbcTemplate = new JdbcTemplate(dataSource);
    var matches = jdbcTemplate.queryForObject("select count(*) from information_schema.tables where table_name = 'schema_version'", Integer.class);
    var tableName = matches != null && matches > 0 ? "schema_version" : configuration.getTable();
    configuration.table(tableName)
        .dataSource(dataSource)
        .validateOnMigrate(false)
        .target(MigrationVersion.LATEST)
        .outOfOrder(true)
        .locations("alfio/db/PGSQL/");
    Flyway migration = new Flyway(configuration);
    migration.migrate();
    return migration;
}
 
Example 10
Source Project: conductor   Source File: MySQLDataSourceProvider.java    License: 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.setDataSource(dataSource);
    flyway.setPlaceholderReplacement(false);
    flyway.migrate();
}
 
Example 11
Source Project: dropwizard-flyway   Source File: AbstractFlywayCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void run(final Bootstrap<T> bootstrap, final Namespace namespace, final T configuration) throws Exception {
    final PooledDataSourceFactory datasourceFactory = databaseConfiguration.getDataSourceFactory(configuration);
    final FlywayFactory flywayFactory = flywayConfiguration.getFlywayFactory(configuration);

    // Give subclasses an option to set additional config flags for flyway.
    setAdditionalOptions(flywayFactory, namespace);
    
    final Flyway flyway = flywayFactory.build(datasourceFactory.build(bootstrap.getMetricRegistry(), "Flyway"));

    try {
        run(namespace, flyway);
    } catch (FlywayException e) {
        LOG.error("Error while running database command", e);
        throw e;
    }
}
 
Example 12
Source Project: cassandra-reaper   Source File: ReaperApplication.java    License: Apache License 2.0 6 votes vote down vote up
private void initDatabase(ReaperApplicationConfiguration config) throws ReaperException {
  Flyway flyway = new Flyway();
  DataSourceFactory dsfactory = config.getDataSourceFactory();
  flyway.setDataSource(
      dsfactory.getUrl(),
      dsfactory.getUser(),
      dsfactory.getPassword());

  if ("database".equals(config.getStorageType())) {
    LOG.warn("!!!!!!!!!!    USAGE 'database' AS STORAGE TYPE IS NOW DEPRECATED   !!!!!!!!!!!!!!");
    LOG.warn("!!!!!!!!!!    PLEASE USE EITHER 'postgres' OR 'h2' FROM NOW ON     !!!!!!!!!!!!!!");
    if (config.getDataSourceFactory().getUrl().contains("h2")) {
      flyway.setLocations("/db/h2");
    } else {
      flyway.setLocations("/db/postgres");
    }
  } else {
    flyway.setLocations("/db/".concat(config.getStorageType().toLowerCase()));
  }
  flyway.setBaselineOnMigrate(true);
  flyway.repair();
  flyway.migrate();
}
 
Example 13
public void handleMigrations() {
	Map<String, String> placeholders = new HashMap<>();
	placeholders.put("prefix", BotSettings.SQL_PREFIX.get());

	try {
		Flyway flyway = Flyway.configure()
			.dataSource(masterInfo.getSource())
			.cleanDisabled(true)
			.baselineOnMigrate(true)
			.table(BotSettings.SQL_PREFIX.get() + "schema_history")
			.placeholders(placeholders)
			.load();
		int sm = flyway.migrate();
		Logger.getLogger().debug("Migrations Successful, " + sm + " migrations applied!", true);
	} catch (Exception e) {
		Logger.getLogger().exception(null, "Migrations Failure", e, true, getClass());
		System.exit(2);
	}
}
 
Example 14
Source Project: database-rider   Source File: JooqDBUnitTest.java    License: 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 15
Source Project: sbp   Source File: FlywayClassLoaderConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public FlywayMigrationStrategy migrationStrategy() {
    return flyway -> {
        FluentConfiguration alterConf = Flyway.configure(plugin.getWrapper().getPluginClassLoader());
        alterConf.configuration(flyway.getConfiguration());
        new Flyway(alterConf).migrate();
    };
}
 
Example 16
@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 17
Source Project: keywhiz   Source File: MigrateCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected void run(Bootstrap<KeywhizConfig> bootstrap, Namespace namespace,
    KeywhizConfig config) throws Exception {
  DataSource dataSource = config.getDataSourceFactory()
      .build(new MetricRegistry(), "migration-datasource");

  Flyway flyway = Flyway.configure().dataSource(dataSource).locations(config.getMigrationsDir()).table(config.getFlywaySchemaTable()).load();
  flyway.migrate();
}
 
Example 18
Source Project: Jabit   Source File: JdbcConfig.java    License: Apache License 2.0 5 votes vote down vote up
public JdbcConfig(String dbUrl, String dbUser, String dbPassword) {
    this.dbUrl = dbUrl;
    this.dbUser = dbUser;
    this.dbPassword = dbPassword;
    this.flyway = new Flyway();
    flyway.setDataSource(dbUrl, dbUser, dbPassword);
    flyway.migrate();
}
 
Example 19
Source Project: quark   Source File: DbUtility.java    License: Apache License 2.0 5 votes vote down vote up
public static void setUpDb(String dbSchemaUrl,
                           String username,
                           String password,
                           String filename)
    throws ClassNotFoundException, SQLException, IOException, URISyntaxException {
  Flyway flyway = new Flyway();
  flyway.setDataSource(dbSchemaUrl, username, password);
  flyway.migrate();

  setupTables(dbSchemaUrl, username, password, filename);
}
 
Example 20
Source Project: OpenCue   Source File: TestDatabaseSetupPostgres.java    License: Apache License 2.0 5 votes vote down vote up
public void create() throws Exception {
    if (!setupComplete.compareAndSet(false, true)) {
        return;
    }

    postgres = EmbeddedPostgres.start();
    Flyway flyway = Flyway.configure()
        .dataSource(postgres.getPostgresDatabase())
        .locations("classpath:conf/ddl/postgres/migrations")
        .load();
    flyway.migrate();

    populateTestData();
}
 
Example 21
Source Project: halo   Source File: StartedListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Migrate database.
 */
private void migrate() throws SQLException {
    log.info("Starting migrate database...");

    Flyway flyway = Flyway
        .configure()
        .locations("classpath:/migration")
        .baselineVersion("1")
        .baselineOnMigrate(true)
        .dataSource(url, username, password)
        .load();
    flyway.repair();
    flyway.migrate();

    // Gets database connection
    Connection connection = flyway.getConfiguration().getDataSource().getConnection();

    // Gets database metadata
    DatabaseMetaData databaseMetaData = JdbcUtils.getDatabaseMetaData(connection);

    // Gets database product name
    HaloConst.DATABASE_PRODUCT_NAME = databaseMetaData.getDatabaseProductName() + " " + databaseMetaData.getDatabaseProductVersion();

    // Close connection.
    connection.close();

    log.info("Migrate database succeed.");
}
 
Example 22
Source Project: quarkus   Source File: FlywayExtensionConfigFixture.java    License: Apache License 2.0 5 votes vote down vote up
public void assertDefaultConfigurationSettings(Configuration configuration) {
    FluentConfiguration defaultConfiguration = Flyway.configure();
    assertEquals(locations(configuration), locations(defaultConfiguration));
    assertEquals(sqlMigrationPrefix(configuration), sqlMigrationPrefix(defaultConfiguration));
    assertEquals(repeatableSqlMigrationPrefix(configuration), repeatableSqlMigrationPrefix(defaultConfiguration));
    assertEquals(tableName(configuration), tableName(defaultConfiguration));
    assertEquals(schemaNames(configuration), schemaNames(defaultConfiguration));

    assertEquals(connectRetries(configuration), connectRetries(defaultConfiguration));

    assertEquals(baselineOnMigrate(configuration), baselineOnMigrate(defaultConfiguration));
    assertEquals(baselineVersion(configuration), baselineVersion(defaultConfiguration));
    assertEquals(baselineDescription(configuration), baselineDescription(defaultConfiguration));
}
 
Example 23
Source Project: quarkus   Source File: FlywayRecorder.java    License: Apache License 2.0 5 votes vote down vote up
public Supplier<Flyway> flywaySupplier(String dataSourceName) {
    DataSource dataSource = DataSources.fromName(dataSourceName);
    FlywayContainerProducer flywayProducer = Arc.container().instance(FlywayContainerProducer.class).get();
    FlywayContainer flywayContainer = flywayProducer.createFlyway(dataSource, dataSourceName);
    flywayContainers.add(flywayContainer);
    return new Supplier<Flyway>() {
        @Override
        public Flyway get() {
            return flywayContainer.getFlyway();
        }
    };
}
 
Example 24
Source Project: quarkus   Source File: FlywayCreator.java    License: Apache License 2.0 5 votes vote down vote up
public Flyway createFlyway(DataSource dataSource) {
    FluentConfiguration configure = Flyway.configure();
    configure.dataSource(dataSource);
    if (flywayRuntimeConfig.connectRetries.isPresent()) {
        configure.connectRetries(flywayRuntimeConfig.connectRetries.getAsInt());
    }
    if (flywayRuntimeConfig.schemas.isPresent()) {
        configure.schemas(flywayRuntimeConfig.schemas.get().toArray(EMPTY_ARRAY));
    }
    if (flywayRuntimeConfig.table.isPresent()) {
        configure.table(flywayRuntimeConfig.table.get());
    }
    configure.locations(flywayBuildTimeConfig.locations.toArray(EMPTY_ARRAY));
    if (flywayRuntimeConfig.sqlMigrationPrefix.isPresent()) {
        configure.sqlMigrationPrefix(flywayRuntimeConfig.sqlMigrationPrefix.get());
    }
    if (flywayRuntimeConfig.repeatableSqlMigrationPrefix.isPresent()) {
        configure.repeatableSqlMigrationPrefix(flywayRuntimeConfig.repeatableSqlMigrationPrefix.get());
    }
    configure.baselineOnMigrate(flywayRuntimeConfig.baselineOnMigrate);
    configure.validateOnMigrate(flywayRuntimeConfig.validateOnMigrate);
    configure.outOfOrder(flywayRuntimeConfig.outOfOrder);
    if (flywayRuntimeConfig.baselineVersion.isPresent()) {
        configure.baselineVersion(flywayRuntimeConfig.baselineVersion.get());
    }
    if (flywayRuntimeConfig.baselineDescription.isPresent()) {
        configure.baselineDescription(flywayRuntimeConfig.baselineDescription.get());
    }
    configure.placeholders(flywayRuntimeConfig.placeholders);
    return configure.load();
}
 
Example 25
Source Project: flyway-test-extensions   Source File: SpringConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Second flyway configuration use "flyway.locations" hard coded value.
 */
@Bean(name = "flywaySecond")
public Flyway flywaySecond(DataSource dataSource) {
    return Flyway.configure()
            .dataSource(dataSource)
            .locations(flywaySecondLocation)
            .load();
}
 
Example 26
@PostConstruct
public void migrate() {
  Flyway flyway = Flyway.configure()
  		.dataSource(dataSource)
  		.encoding(encoding)
  		.baselineDescription(baselineDescription)
  		.baselineOnMigrate(baselineOnMigrate)
  		.baselineVersion(baselineVersion)
  		.validateOnMigrate(validateOnMigrate)
  		.outOfOrder(outOfOrder)
  		.ignoreFutureMigrations(ignoreFutureMigrations)
  		.initSql(initSql)
  		.load();
  flyway.migrate();
}
 
Example 27
@Override
public void migrate(Flyway flyway) {
	MigrationInfo current = flyway.info().current();
	if (current != null && current.getVersion().equals(INITIAL) && current.getType() == MigrationType.SQL) {
		logger.info("Detected initial version based on SQL scripts, doing repair to switch to Java based migrations.");
		flyway.repair();
	}
	flyway.migrate();
}
 
Example 28
Source Project: avro-schema-generator   Source File: PgsqlIntegrationTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    Flyway.configure()
        .dataSource(PGSQL.getJdbcUrl(), PGSQL.getUsername(), PGSQL.getPassword())
        .locations("classpath:pgsql/db/migration")
        .load().migrate();
}
 
Example 29
Source Project: ja-micro   Source File: SchemaMigrator.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public SchemaMigrator(ServiceProperties props, DatabaseMigrationContributor hc,
                      ConnectionVerifier verifier, Flyway flyway) {
    this.serviceProps = props;
    this.healthCheck = hc;
    this.connectionVerifier = verifier;
    this.flyway = flyway;
}
 
Example 30
Source Project: ja-micro   Source File: SchemaMigratorIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void sleepAfterFailedMigration() {
    props.addProperty("databaseServer", "foo");
    Flyway flyway = mock(Flyway.class);
    when(flyway.migrate()).thenThrow(new FlywayException());
    migrator.flyway = flyway;
    migrator.flywayFailedSemaphore.release();
    migrator.migrate();
}