org.flywaydb.core.Flyway Java Examples

The following examples show how to use org.flywaydb.core.Flyway. 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: DDLMetaDataTest.java    From quark with 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 #2
Source File: DataSourceConfiguration.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: SchemaFlywayFactory.java    From registry with 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 #4
Source File: DbConnectionPool.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: MySQLDataSourceProvider.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.setDataSource(dataSource);
    flyway.setPlaceholderReplacement(false);
    flyway.migrate();
}
 
Example #6
Source File: FlywayMigrationServletContextListener.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: AbstractFlywayCommand.java    From dropwizard-flyway with 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 #9
Source File: ReaperApplication.java    From cassandra-reaper with 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 #10
Source File: DatabaseManager.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #11
Source File: FlywayEndpoint.java    From micronaut-flyway with 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 #12
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 #13
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 #14
Source File: DbMetaDataTest.java    From quark with 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 #15
Source File: FlywayIdolConfigUpdateHandler.java    From find with MIT License 5 votes vote down vote up
@Autowired
public FlywayIdolConfigUpdateHandler (
        final ProcessorFactory processorFactory,
        final Flyway flyway,
        final AciHttpClient aciHttpClient
) {
    this.processorFactory = processorFactory;
    this.flyway = flyway;

    aciService = new AciServiceImpl(aciHttpClient);
}
 
Example #16
Source File: UserSaltMigrationTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings(
  value = {
    "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE",
    "ODR_OPEN_DATABASE_RESOURCE",
  },
  justification = "Ignore that jdbcTemplate methods might return null or that the DB connection may be left open."
)
@Before
public void beforeEach() throws Exception {
  canaries = encryptionKeyCanaryRepository.findAll();

  databaseName = jdbcTemplate.getDataSource()
    .getConnection()
    .getMetaData()
    .getDatabaseProductName()
    .toLowerCase();

  Flyway flywayV40 = Flyway
    .configure()
    .target(MigrationVersion.fromVersion("40"))
    .dataSource(flyway.getConfiguration().getDataSource())
    .locations(flyway.getConfiguration().getLocations())
    .load();

  flywayV40.clean();
  flywayV40.migrate();
}
 
Example #17
Source File: MySQLDAOTestUtil.java    From conductor with Apache License 2.0 5 votes vote down vote up
private void flywayMigrate(DataSource dataSource) {

        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setPlaceholderReplacement(false);
        flyway.migrate();
    }
 
Example #18
Source File: RecommendationPersistenceVerticle.java    From istio-tutorial with Apache License 2.0 5 votes vote down vote up
private void populateData() {
    final Flyway flyway = Flyway
                            .configure()
                            .dataSource(URL, USER, PASSWORD)
                            .load();
    flyway.migrate();
}
 
Example #19
Source File: DatabaseClient.java    From datamill with ISC License 5 votes vote down vote up
public void migrate(Action1<Connection> migrationPreparation) {
    Flyway flyway = getFlyway();
    flyway.setCallbacks(new MigrationCallback(
            typeAdapter != null ? typeAdapter.createConnectionPreparer() : null,
            migrationPreparation));

    flyway.migrate();
}
 
Example #20
Source File: FlywayMigrationsTask.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void run() {

    checkNotNull(this.dataSource, "No datasource found for migrations");

    final Flyway flyway = Flyway.configure()
            .dataSource(this.dataSource)
            .locations("db/migrations")
            .baselineOnMigrate(true)
            .baselineVersion("0")
            .sqlMigrationPrefix("")
            .load();

    final MigrationInfo migrationInfo = flyway.info().current();

    if (migrationInfo == null) {
        this.logger.info("No existing database at the actual datasource");
    } else {
        this.logger.info("Current version: {}", migrationInfo.getVersion() + " : " + migrationInfo.getDescription());
    }

    try {
        flyway.migrate();
        this.logger.info("Successfully migrated to version: {}", flyway.info().current().getVersion());
    } catch (FlywayException ex) {
        this.logger.info("Flyway migrations failed!", ex);
    }
}
 
Example #21
Source File: FlywayFactoryTest.java    From dropwizard-flyway with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultConfigurationShouldBeValid() {
    final FlywayFactory factory = new FlywayFactory();
    final Flyway flyway = factory.build(mockDataSource);

    assertNotNull(flyway);
    assertSame(mockDataSource, flyway.getConfiguration().getDataSource());
    assertEquals(StandardCharsets.UTF_8, flyway.getConfiguration().getEncoding());
    assertEquals("flyway_schema_history", flyway.getConfiguration().getTable());
    assertEquals(0, flyway.getConfiguration().getSchemas().length);
}
 
Example #22
Source File: FlywayMigrationsTask.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void run() {

    checkNotNull(this.dataSource, "No datasource found for migrations");

    final Flyway flyway = Flyway.configure()
            .dataSource(this.dataSource)
            .locations("db/migrations")
            .baselineOnMigrate(true)
            .baselineVersion("0")
            .sqlMigrationPrefix("")
            .load();

    final MigrationInfo migrationInfo = flyway.info().current();

    if (migrationInfo == null) {
        this.logger.info("No existing database at the actual datasource");
    } else {
        this.logger.info("Current version: {}", migrationInfo.getVersion() + " : " + migrationInfo.getDescription());
    }

    try {
        flyway.migrate();
        this.logger.info("Successfully migrated to version: {}", flyway.info().current().getVersion());
    } catch (FlywayException ex) {
        this.logger.info("Flyway migrations failed!", ex);
    }
}
 
Example #23
Source File: MigrationResource.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>listInfo.</p>
 *
 * @return a {@link java.util.Map} object.
 */
@GET
public Map<String, MigrationInfo[]> listInfo() {
    Map<String, MigrationInfo[]> infoMap = Maps.newLinkedHashMap();
    for (String dbName : DataSourceManager.getDataSourceNames()) {
        Flyway flyway = locator.getService(Flyway.class, dbName);
        infoMap.put(dbName, flyway.info().all());
    }
    return infoMap;
}
 
Example #24
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 #25
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected static String[] getFlywayLocations(Flyway flyway) {
    if (flywayVersion >= 51) {
        Object configuration = getField(flyway, "configuration");
        return Arrays.stream((Object[]) invokeMethod(configuration, "getLocations"))
                .map(location -> invokeMethod(location, "getDescriptor"))
                .toArray(String[]::new);
    } else {
        return flyway.getLocations();
    }
}
 
Example #26
Source File: MultipleFlywayBeansClassLevelIntegrationTest.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
@Primary
@DependsOn("flyway2")
@Bean
public Flyway flyway1(DataSource dataSource) throws Exception {
    List<String> locations = ImmutableList.of("db/migration", "db/test_migration/dependent");
    return createFlyway(dataSource, "test", locations);
}
 
Example #27
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected static MigrationVersion findFirstVersion(Flyway flyway, String... locations) throws ClassNotFoundException {
    Collection<ResolvedMigration> migrations = resolveMigrations(flyway, locations);
    return migrations.stream()
            .filter(migration -> migration.getVersion() != null)
            .findFirst()
            .map(ResolvedMigration::getVersion)
            .orElse(MigrationVersion.EMPTY);
}
 
Example #28
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 #29
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected synchronized void optimizedDbReset(TestContext testContext, AnnotatedElement element, FlywayTest annotation) throws Exception {
    try {
        if (annotation != null && annotation.invokeCleanDB() && annotation.invokeMigrateDB()
                && (!flywayBaselineAttributePresent || !annotation.invokeBaselineDB())) {

            ApplicationContext applicationContext = testContext.getApplicationContext();
            Flyway flywayBean = getFlywayBean(applicationContext, annotation);

            if (flywayBean != null) {
                FlywayDataSourceContext dataSourceContext = getDataSourceContext(applicationContext, flywayBean);

                if (dataSourceContext != null) {

                    dataSourceContext.getTarget(); // wait for completion of running flyway migration
                    DataSource dataSource = reloadDataSource(dataSourceContext, flywayBean, annotation);
                    EmbeddedDatabaseReporter.reportDataSource(dataSource, element);

                    FlywayTest adjustedAnnotation = copyAnnotation(annotation, false, false, true);
                    originalDbReset(testContext, adjustedAnnotation);

                    return;
                }
            }
        }

        originalDbReset(testContext, annotation);
    } catch (NoSuchMethodError e) {
        logger.error("\n\nHINT: Check that you are using compatible versions of org.flywaydb:flyway-core and org.flywaydb.flyway-test-extensions:flyway-spring-test dependencies!!!\n");
        throw e;
    }
}
 
Example #30
Source File: FlywayTestExecutionListener.java    From flyway-test-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Handling of the change of locations configuration of a flyway.
 *
 * @param annotation
 *            current annotation
 * @param flyWay
 *            bean
 * @param executionInfo
 *            current test context.
 */
private void locationsMigrationHandling(final FlywayTest annotation,
                                        final Flyway flyWay, final String executionInfo) {
    final String[] locations = annotation.locationsForMigrate();

    // now migration handling for locations support
    String[] oldLocations = convertLocationToString(flyWay);
    boolean override = annotation.overrideLocations();
    try {
        String[] useLocations = null;
        if (override) {

            useLocations = locations;
        } else {
            // Fill the locations
            useLocations = Arrays.copyOf(oldLocations, oldLocations.length
                    + locations.length);

            System.arraycopy(locations, 0, useLocations, oldLocations.length, locations.length);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(String
                    .format("******** Start migration from locations directories '%s'  for  '%s'.",
                            Arrays.asList(useLocations), executionInfo));

        }

        FluentConfiguration fluentConfiguration = new FluentConfiguration();
        fluentConfiguration.configuration(flyWay.getConfiguration())
        .locations(useLocations)
        .load()
        .migrate();
    } finally {
        // reset the flyway bean to original configuration.
        //flyWay.setLocations(oldLocations);
    }
}