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

The following examples show how to use org.flywaydb.core.Flyway#migrate() . 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: CleanSchemaConfiguration.java    From sbp with Apache License 2.0 6 votes vote down vote up
@Override
public void migrate(Flyway flyway) {
    try (Statement stat = flyway.getConfiguration().getDataSource().getConnection().createStatement()) {
        for (String schema : flyway.getConfiguration().getSchemas()) {
            stat.execute("DROP SCHEMA IF EXISTS "+schema + " CASCADE");
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (plugin != null) {
        FluentConfiguration alterConf = Flyway.configure(plugin.getWrapper().getPluginClassLoader());
        alterConf.configuration(flyway.getConfiguration());
        new Flyway(alterConf).migrate();
    } else {
        flyway.migrate();
    }
}
 
Example 2
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 3
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 4
Source File: EndToEndTest.java    From quark with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws SQLException, IOException, URISyntaxException,
    ClassNotFoundException {

  String[] args = new String [1];
  args[0] = EndToEndTest.class.getResource("/dbCatalog.json").getPath();
  main = new Main(args);

  new Thread(main).start();

  Flyway flyway = new Flyway();
  flyway.setDataSource(dbUrl, "sa", "");
  flyway.migrate();

  setupTables(dbUrl, "tpcds_db.sql");
  setupTables(h2Url, "tpcds.sql");
  setupTables(cubeUrl, "tpcds_cubes.sql");
  setupTables(viewUrl, "tpcds_views.sql");
}
 
Example 5
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 6
Source File: DumpGoldenSchemaCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
void runCommand() throws IOException, InterruptedException {
  Flyway flyway =
      Flyway.configure()
          .locations("sql/flyway")
          .dataSource(
              postgresContainer.getJdbcUrl(),
              postgresContainer.getUsername(),
              postgresContainer.getPassword())
          .load();
  flyway.migrate();

  String userName = postgresContainer.getUsername();
  String databaseName = postgresContainer.getDatabaseName();
  Container.ExecResult result =
      postgresContainer.execInContainer(getSchemaDumpCommand(userName, databaseName));
  if (result.getExitCode() != 0) {
    throw new RuntimeException(result.toString());
  }
  result =
      postgresContainer.execInContainer("cp", CONTAINER_MOUNT_POINT_TMP, CONTAINER_MOUNT_POINT);
  if (result.getExitCode() != 0) {
    throw new RuntimeException(result.toString());
  }
}
 
Example 7
Source File: DbSelectTest.java    From quark with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpDb() throws Exception {
  SelectTest.setUpClass(dbUrl);
  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', '" + dbUrl + "', 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
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 9
Source File: App.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // Create the Flyway instance and point it to the database
    Flyway flyway = Flyway.configure().dataSource(
            "jdbc:mysql://localhost:3306/application?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8",
            "root", "root").load();

    // Start the migration
    // 默认 flyway.locations=classpath:/db/migration
    flyway.migrate();
}
 
Example 10
Source File: FlywayIt.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void initDB(){
    flyway = new Flyway();
    flyway.setDataSource("jdbc:hsqldb:mem:flyway;DB_CLOSE_DELAY=-1", "sa", "");
    flyway.setLocations("filesystem:src/test/resources/migration");
    flyway.migrate();

}
 
Example 11
Source File: EarlyCredentialMigrationTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
  public void beforeEach() {
      canaries = encryptionKeyCanaryRepository.findAll();

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

  flywayV4.clean();
  flywayV4.migrate();
}
 
Example 12
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 13
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 14
Source File: App.java    From maven-framework-project with MIT License 5 votes vote down vote up
public static void main( String[] args )
{
	// Create the Flyway instance
    Flyway flyway = new Flyway();

    // Point it to the database
    flyway.setDataSource("jdbc:h2:file:target/flyway", "sa", null);

    // Start the migration
    flyway.migrate();
}
 
Example 15
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 16
Source File: AbstractFlywayMigration.java    From micronaut-flyway with Apache License 2.0 5 votes vote down vote up
private void runFlyway(FlywayConfigurationProperties config, Flyway flyway) {
    if (config.isCleanSchema()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Cleaning schema for database with qualifier [{}]", config.getNameQualifier());
        }
        flyway.clean();
        eventPublisher.publishEvent(new SchemaCleanedEvent(config));
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("Running migrations for database with qualifier [{}]", config.getNameQualifier());
    }
    flyway.migrate();
    eventPublisher.publishEvent(new MigrationFinishedEvent(config));
}
 
Example 17
Source File: MigrationsRule.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile());
      Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
      ObjectMapper objectMapper = KeywhizService.customizeObjectMapper(Jackson.newObjectMapper());
      KeywhizConfig config = new YamlConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw")
          .build(yamlFile);

      DataSource dataSource = config.getDataSourceFactory()
          .build(new MetricRegistry(), "db-migrations");

      Flyway flyway = Flyway.configure().dataSource(dataSource).locations(config.getMigrationsDir()).table(config.getFlywaySchemaTable()).load();
      flyway.clean();
      flyway.migrate();

      DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource);
      DbSeedCommand.doImport(dslContext);

      base.evaluate();
    }
  };
}
 
Example 18
Source File: FlywayExtension.java    From tutorials with MIT License 4 votes vote down vote up
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
    Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
    flyway.migrate();
}
 
Example 19
Source File: FlywayConfiguration.java    From freeacs with MIT License 4 votes vote down vote up
@PostConstruct
public void runFlyway() {
  Flyway flyway = new Flyway();
  flyway.setDataSource(mainDataSource);
  flyway.migrate();
}
 
Example 20
Source File: FlywayMigration.java    From leo-im-server with Apache License 2.0 2 votes vote down vote up
/**
 * 数据库迁移
 * @param url JDBC URL
 * @param user 数据库用户
 * @param password 数据库口令
 */
public void migrate(String url, String user, String password) {
	Flyway flyway = new Flyway();
	flyway.setDataSource(url, user, password);
	flyway.migrate();
}