org.flywaydb.core.api.MigrationVersion Java Examples

The following examples show how to use org.flywaydb.core.api.MigrationVersion. 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: 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 #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: ShellMigrationResolver.java    From registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the migration info for this resource.
 *
 * @param resource The resource to analyse.
 * @return The migration info.
 */
private ResolvedMigrationImpl extractMigrationInfo(Resource resource) {
    ResolvedMigrationImpl migration = new ResolvedMigrationImpl();

    Pair<MigrationVersion, String> info =
            MigrationInfoHelper.extractVersionAndDescription(resource.getFilename(),
                    shellMigrationPrefix, shellMigrationSeparator, new String [] {shellMigrationSuffix}, false);
    migration.setVersion(info.getLeft());
    migration.setDescription(info.getRight());

    migration.setScript(extractScriptName(resource));

    byte [] migrationScriptAsBytes = null;
    try {
        migrationScriptAsBytes = IOUtils.toByteArray(new FileInputStream(resource.getLocation()));
    } catch (Exception e) {
        throw new ShellMigrationException(String.format("Failed to read the migration script : %s", resource.getLocation()), e);
    }

    migration.setChecksum(calculateChecksum(migrationScriptAsBytes));

    migration.setType(MigrationType.CUSTOM);
    return migration;
}
 
Example #4
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 #5
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 #6
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 #7
Source File: FlywayFunctionalityResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("migrate")
public String doMigrateAuto() {
    flyway.migrate();
    MigrationVersion version = Objects.requireNonNull(flyway.info().current().getVersion(),
            "Version is null! Migration was not applied");
    return version.toString();
}
 
Example #8
Source File: DatabaseJobHistoryStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static VersionedDatabaseJobHistoryStore findVersionedDatabaseJobHistoryStore(MigrationVersion requiredVersion)
    throws IllegalAccessException, InstantiationException, ClassNotFoundException {
  Class<?> foundClazz = null;
  Class<?> defaultClazz = null;
  MigrationVersion defaultVersion = MigrationVersion.EMPTY;
  for (Class<?> clazz : Sets.intersection(reflections.getTypesAnnotatedWith(SupportedDatabaseVersion.class),
          reflections.getSubTypesOf(VersionedDatabaseJobHistoryStore.class))) {
    SupportedDatabaseVersion annotation = clazz.getAnnotation(SupportedDatabaseVersion.class);
    String version = annotation.version();
    MigrationVersion actualVersion = MigrationVersion.fromVersion(Strings.isNullOrEmpty(version) ? null : version);
    if (annotation.isDefault() && actualVersion.compareTo(defaultVersion) > 0) {
      defaultClazz = clazz;
      defaultVersion = actualVersion;
    }
    if (actualVersion.compareTo(requiredVersion) == 0) {
      foundClazz = clazz;
    }
  }
  if (foundClazz == null) {
    foundClazz = defaultClazz;
  }
  if (foundClazz == null) {
    throw new ClassNotFoundException(
        String.format("Could not find an instance of %s which supports database " + "version %s.",
            VersionedDatabaseJobHistoryStore.class.getSimpleName(), requiredVersion.toString()));
  }
  return (VersionedDatabaseJobHistoryStore) foundClazz.newInstance();
}
 
Example #9
Source File: DatabaseJobHistoryStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static MigrationVersion getDatabaseVersion(DataSource dataSource) throws FlywayException {
  Flyway flyway = new Flyway();
  flyway.setDataSource(dataSource);
  MigrationInfoService info = flyway.info();
  MigrationVersion currentVersion = MigrationVersion.EMPTY;
  if (info.current() != null) {
    currentVersion = info.current().getVersion();
  }
  return currentVersion;
}
 
Example #10
Source File: DatabaseJobHistoryStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Inject
public DatabaseJobHistoryStore(DataSource dataSource)
    throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  MigrationVersion databaseVersion = getDatabaseVersion(dataSource);
  this.versionedStore = findVersionedDatabaseJobHistoryStore(databaseVersion);
  this.versionedStore.init(dataSource);
}
 
Example #11
Source File: VersionResolverTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(dataProvider = "validScripts")
public void resolvesVersion(String dir, String name, String expectedVersion) {
  final SqlScript script =
      new SqlScript(
          new FileSystemResource("sql/" + dir + "/" + name),
          new Location("filesystem:sql"),
          dir,
          null,
          name);

  assertEquals(resolver.resolve(script, flyway), MigrationVersion.fromVersion(expectedVersion));
}
 
Example #12
Source File: VersionResolver.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates migration version based on script data.
 *
 * @param script script for which to resolve the version
 * @param configuration flyway configuration used for resolution parameters
 */
MigrationVersion resolve(SqlScript script, FlywayConfiguration configuration) {
  String normalizedDir = normalizedDirs.get(script.dir);
  if (normalizedDir == null) {
    // 5.0.0-M1 -> 5.0.0.M1 -> 5.0.0.1
    normalizedDir =
        NOT_VERSION_CHARS_PATTERN.matcher(script.dir.replace("-", ".")).replaceAll("");
    normalizedDirs.put(script.dir, normalizedDir);
  }

  // separate version from the other part of the name
  final int sepIdx = script.name.indexOf(configuration.getSqlMigrationSeparator());
  if (sepIdx == -1) {
    throw new FlywayException(
        format(
            "sql script name '%s' is not valid, name must contain '%s'",
            script.name, configuration.getSqlMigrationSeparator()));
  }

  // check whether part before separator is not empty
  String version = script.name.substring(0, sepIdx);
  if (version.isEmpty()) {
    throw new FlywayException(
        format(
            "sql script name '%s' is not valid, name must provide version like "
                + "'%s4%smigration_description.sql",
            configuration.getSqlMigrationPrefix(),
            script.name,
            configuration.getSqlMigrationSeparator()));
  }

  // extract sql script version without prefix
  final String prefix = configuration.getSqlMigrationPrefix();
  if (!isNullOrEmpty(prefix) && script.name.startsWith(prefix)) {
    version = version.substring(prefix.length());
  }
  return MigrationVersion.fromVersion(normalizedDir + '.' + version);
}
 
Example #13
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 #14
Source File: FlywayFunctionalityResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("multiple-flyway-migratation")
public String doMigratationOfSecondDataSource() {
    flyway2.migrate();
    MigrationVersion version = Objects.requireNonNull(flyway2.info().current().getVersion(),
            "Version is null! Migration was not applied for second datasource");
    return version.toString();
}
 
Example #15
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected static MigrationVersion findLastVersion(Flyway flyway, String... locations) throws ClassNotFoundException {
    Collection<ResolvedMigration> migrations = resolveMigrations(flyway, locations);
    return migrations.stream()
            .filter(migration -> migration.getVersion() != null)
            .reduce((first, second) -> second) // finds last item
            .map(ResolvedMigration::getVersion)
            .orElse(MigrationVersion.EMPTY);
}
 
Example #16
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 #17
Source File: LinstorMigration.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public MigrationVersion getVersion()
{
    return MigrationVersion.fromVersion(getClass().getAnnotation(Migration.class).version());
}
 
Example #18
Source File: FlywayConfigSnapshot.java    From embedded-database-spring-test with Apache License 2.0 4 votes vote down vote up
public MigrationVersion getTarget() {
    return target;
}
 
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: CustomSqlMigrationResolver.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
private List<ResolvedMigration> resolveSqlMigrations() throws IOException, SQLException {
  LOG.info(
      "Searching for SQL scripts in locations {}",
      Arrays.toString(flywayConfiguration.getLocations()));
  final Map<Location, List<Resource>> allResources = finder.findResources(flywayConfiguration);
  LOG.debug("Found scripts: {}", allResources);

  final Map<String, Map<String, SqlScript>> scriptsInDir = new HashMap<>();
  for (Location location : allResources.keySet()) {
    final List<Resource> resources = allResources.get(location);
    for (Resource resource : resources) {
      final SqlScript newScript = scriptsCreator.createScript(location, resource);
      if (!scriptsInDir.containsKey(newScript.dir)) {
        scriptsInDir.put(newScript.dir, new HashMap<>(4));
      }
      final Map<String, SqlScript> existingScripts = scriptsInDir.get(newScript.dir);
      final SqlScript existingScript = existingScripts.get(newScript.name);
      if (existingScript == null) {
        existingScripts.put(newScript.name, newScript);
      } else if (Objects.equals(existingScript.vendor, newScript.vendor)) {
        throw new FlywayException(
            format(
                "More than one script with name '%s' is registered for "
                    + "database vendor '%s', script '%s' conflicts with '%s'",
                newScript.name, existingScript.vendor, newScript, existingScript));
      } else if (vendorName.equals(newScript.vendor)) {
        existingScripts.put(newScript.name, newScript);
      }
    }
  }

  final Map<MigrationVersion, ResolvedMigration> migrations = new HashMap<>();
  for (SqlScript script :
      scriptsInDir
          .values()
          .stream()
          .flatMap(scripts -> scripts.values().stream())
          .collect(toList())) {
    final ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
    migration.setVersion(versionResolver.resolve(script, flywayConfiguration));
    migration.setScript(script.resource.getLocation());
    migration.setPhysicalLocation(script.resource.getLocationOnDisk());
    migration.setType(MigrationType.SQL);
    migration.setDescription(script.name);
    migration.setChecksum(
        ByteSource.wrap(script.resource.loadAsBytes()).hash(Hashing.crc32()).asInt());
    migration.setExecutor(
        new SqlMigrationExecutor(
            dbSupport, script.resource, placeholderReplacer, flywayConfiguration));
    if (migrations.put(migration.getVersion(), migration) != null) {
      throw new FlywayException("Two migrations with the same version detected");
    }
  }
  return new ArrayList<>(migrations.values());
}
 
Example #21
Source File: FlywayExtensionCleanAndMigrateAtStartWithJavaMigrationTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public MigrationVersion getVersion() {
    return MigrationVersion.fromVersion("1.0.2");
}
 
Example #22
Source File: Event.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
private static boolean mustUseFirstAndLastName(Event event) {
    return event.getVersion() != null
        && MigrationVersion.fromVersion(event.getVersion()).compareTo(MigrationVersion.fromVersion(VERSION_FOR_FIRST_AND_LAST_NAME)) >= 0;
}
 
Example #23
Source File: FlywayConfigSnapshot.java    From embedded-database-spring-test with Apache License 2.0 4 votes vote down vote up
public MigrationVersion getBaselineVersion() {
    return baselineVersion;
}
 
Example #24
Source File: DbTestHelper.java    From jump-the-queue with Apache License 2.0 2 votes vote down vote up
/**
 * This method sets the internal value of the {@code migrationVersion}.
 *
 * @param migrationVersion new {@code String} value of {@code migrationVersion}. Must not be null
 */
public void setMigrationVersion(String migrationVersion) {

  this.migrationVersion = MigrationVersion.fromVersion(migrationVersion);
}