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

The following examples show how to use org.flywaydb.core.Flyway#setDataSource() . 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: 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 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: 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 4
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 5
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 6
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 7
Source File: Connection.java    From quark with Apache License 2.0 5 votes vote down vote up
public void runFlyWay() {
  Flyway flyway = new Flyway();
  flyway.setDataSource(
      info.getProperty("url"),
      info.getProperty("user"),
      info.getProperty("password"));
  flyway.migrate();
}
 
Example 8
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 9
Source File: DbUtility.java    From quark with 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 10
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 11
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 12
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 13
Source File: FlywayApplicationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void migrateWithJavaCallbacks() {
    logTestBoundary("migrateWithJavaCallbacks");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations("db/migration");
    flyway.setCallbacks(new ExampleFlywayCallback());
    flyway.migrate();
}
 
Example 14
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 15
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 16
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 17
Source File: DDLViewTest.java    From quark with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {

  setupTables(tpcdsUrl, "tpcds.sql");
  setupTables(tpcdsViewUrl, "tpcds_views.sql");
  // Inserting test-data in views
  String partitionData = "insert into warehouse_partition (w_warehouse_sk, w_warehouse_id, " +
      "w_warehouse_name,w_warehouse_sq_ft, w_street_number, w_street_name, w_street_type, " +
      "w_suite_number, w_city, w_county, w_state, w_zip, w_country,w_gmt_offset) values (1, 'ID', " +
      "'NAME', 400, '200', 'CHURCH STREET', 'BORAD', 'W3K', 'NEW YORK', 'US', 'IO', '333031', 'USA', 12);";

  partitionData = partitionData + " insert into customer_address_partition (ca_address_sk, " +
      "ca_address_id, ca_street_number, ca_street_name, ca_street_type, ca_suite_number, ca_city," +
      " ca_country, ca_state, ca_zip, ca_gmt_offset, ca_location_type) values ( 1, '12345', '24', " +
      "'commercialstreet', 'Broadway', '1A', 'NY', 'USA', 'NY', '333031', 10, 'UNKNOWN');";

  partitionData = partitionData + "insert into web_site_partition (web_site_sk, web_rec_start_date," +
      " web_county, web_tax_percentage) values (1, '2015-06-29', 'USA', 12);";

  Connection dbConnection = DriverManager.getConnection(tpcdsUrl, "sa", "");
  dbConnection = DriverManager.getConnection(tpcdsViewUrl, "sa", "");
  dbConnection.createStatement().executeUpdate(partitionData);
  dbConnection.close();

  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();
  // Sql statement default data-source and view datasource
  String sql = "insert into data_sources(name, type, url, ds_set_id, datasource_type) values "
      + "('CANONICAL', 'H2', '" + tpcdsUrl + "', 1, 'JDBC'); insert into jdbc_sources (id, "
      + "username, password) values(1, 'sa', '');"
      + "update ds_sets set default_datasource_id = 1 where id = 1;";

  sql = sql + "insert into data_sources(name, type, url, ds_set_id, datasource_type) values "
      + "('VIEWS', 'H2', '" + tpcdsViewUrl + "', 1, 'JDBC'); "
      + "insert into jdbc_sources (id, username, password) values(2, 'sa', '');";

  // Sql statement to add views, to be used for drop and alter view respectively.
  sql = sql + " insert into partitions(name, description, cost, query, ds_set_id, destination_id, "
      + "schema_name, table_name) values('web_site_part', 'Web Site Partitionn', 0, "
      + "'select web_site_sk, web_rec_start_date, web_county, web_tax_percentage from canonical.public.web_site where web_name = ''Quark''', "
      + "1, 2, 'PUBLIC', 'WEB_SITE_PARTITION'); ";

  sql = sql + " insert into partitions(name, description, cost, query, ds_set_id, destination_id, "
      + "schema_name, table_name) values('customer_address_part', 'Customer Address Partition', 0,"
      + "'select * from canonical.public.customer_address as c where c.ca_street_name=''commercialstreet''', "
      + "1, 2, 'PUBLIC', 'CUSTOMER_ADDRESS_PARTITION');";

  stmt.execute(sql);
  stmt.close();
}
 
Example 18
Source File: MsSqlTest.java    From kafka-connect-cdc-mssql with Apache License 2.0 4 votes vote down vote up
static void flywayMigrate(final String jdbcUrl) throws SQLException {
  Flyway flyway = new Flyway();
  flyway.setDataSource(jdbcUrl, MsSqlTestConstants.USERNAME, MsSqlTestConstants.PASSWORD);
  log.info("flyway locations. {}", Joiner.on(", ").join(flyway.getLocations()));
  flyway.migrate();
}
 
Example 19
Source File: DatabaseClient.java    From datamill with ISC License 4 votes vote down vote up
private Flyway getFlyway() {
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    return flyway;
}
 
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();
    }
}