Java Examples for org.flywaydb.core.Flyway

The following java examples will help you to understand the usage of org.flywaydb.core.Flyway. These source code samples are taken from different open source projects.

Example 1
Project: constellation-master  File: FlywaySpring.java View source code
@PostConstruct
public void migrate() throws ConfigurationRuntimeException {
    LOGGER.info("Start database migration check");
    boolean liquibaseInstalled = false;
    boolean liquibaseUpToDate = false;
    //search for previous installation using liquibase
    try (Connection conn = dataSource.getConnection()) {
        final DatabaseMetaData metaData = conn.getMetaData();
        try (ResultSet liquibaseTable = metaData.getTables(null, "public", "databasechangelog", null)) {
            if (liquibaseTable.next()) {
                liquibaseInstalled = true;
                final String lastLBVersion = "SELECT 1 FROM public.databasechangelog WHERE id='version_1.45';";
                try (Statement stmt = conn.createStatement();
                    ResultSet upToDate = stmt.executeQuery(lastLBVersion)) {
                    if (upToDate.next()) {
                        liquibaseUpToDate = true;
                    }
                }
            }
        }
    } catch (SQLException ex) {
        throw new ConfigurationRuntimeException("An error occurs during database analysis searching for " + "previous installations.", ex);
    }
    try {
        final Flyway flyway = FlywayUtils.createFlywayConfig(dataSource);
        //create schema_version table if not exist, even if database is not empty
        flyway.setBaselineOnMigrate(true);
        //previous liquibase installation found but not up to date
        if (liquibaseInstalled) {
            if (liquibaseUpToDate) {
                //start after 1.1.0.0
                flyway.setBaselineVersion(MigrationVersion.fromVersion("1.1.0.0"));
                LOGGER.info("Previous installation with Liquibase detected and up to date, start migration from 1.1.0.0 patch");
            } else {
                throw new ConfigurationRuntimeException("Previous database installation found but not up to date, " + "please update to 1.0.13 before applying this update.");
            }
        }
        flyway.migrate();
    } catch (SQLException ex) {
        throw new ConfigurationRuntimeException(ex.getMessage(), ex);
    }
    //clean old liquibase changelogs
    if (liquibaseInstalled) {
        LOGGER.info("Drop old liquibase changelogs tables");
        try (Connection conn = dataSource.getConnection();
            Statement stmt = conn.createStatement()) {
            stmt.execute("DROP TABLE IF EXISTS public.databasechangelog CASCADE;");
            stmt.execute("DROP TABLE IF EXISTS public.databasechangeloglock CASCADE;");
        } catch (SQLException ex) {
            throw new ConfigurationRuntimeException("Unable to delete old liquibase changelog tables", ex);
        }
    }
}
Example 2
Project: Eduardo-master  File: Bucket.java View source code
public void migrate() {
    Map<String, String> placeHolders = new HashMap<String, String>();
    placeHolders.put("tablePrefix", id + "_");
    Flyway flyway = new Flyway();
    flyway.setLocations("migrations/" + id);
    flyway.setClassLoader(getClass().getClassLoader());
    flyway.setDataSource(persistence.getDataSource());
    flyway.setTable(id + "_migrations");
    flyway.setPlaceholders(placeHolders);
    flyway.setValidateOnMigrate(false);
    flyway.migrate();
}
Example 3
Project: el-bombillo-master  File: ServiceRegistryApplication.java View source code
@Override
public void run(final ServiceRegistryConfiguration configuration, final Environment environment) throws Exception {
    final DataSourceFactory database = configuration.getDatabase();
    // execute DB migrations
    final Flyway flyway = new Flyway();
    flyway.setDataSource(database.getUrl(), database.getUser(), database.getPassword());
    log.debug("execute database migrations");
    flyway.migrate();
    log.info("database migrations successfully executed");
    // create DBI instance
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, database, "postgresql");
    environment.jersey().register(AuthFactory.binder(new BasicAuthFactory<>(new ServiceRegistryAuthenticator(configuration.getCredentials()), "Realm", ServiceRegistryCaller.class)));
    environment.jersey().register(new ServiceResource(jdbi.onDemand(ServiceDAO.class)));
}
Example 4
Project: flyway-master  File: AbstractFlywayMojo.java View source code
/**
     * Load username password from settings
     *
     * @throws FlywayException when the credentials could not be loaded.
     */
private void loadCredentialsFromSettings() throws FlywayException {
    final Server server = settings.getServer(serverId);
    if (user == null) {
        if (server != null) {
            user = server.getUsername();
            try {
                SecDispatcher secDispatcher = new DefaultSecDispatcher() {

                    {
                        _cipher = new DefaultPlexusCipher();
                    }
                };
                password = secDispatcher.decrypt(server.getPassword());
            } catch (SecDispatcherException e) {
                throw new FlywayException("Unable to decrypt password", e);
            } catch (PlexusCipherException e) {
                throw new FlywayException("Unable to initialize password decryption", e);
            }
        }
    } else if (server != null) {
        throw new FlywayException("You specified credentials both in the Flyway config and settings.xml. Use either one or the other");
    }
}
Example 5
Project: haikudepotserver-master  File: ManagedDatabase.java View source code
private void migrate() {
    if (null == migrate || migrate) {
        Preconditions.checkNotNull(getDataSource());
        Preconditions.checkState(!Strings.isNullOrEmpty(getSchema()));
        Flyway flyway = new Flyway();
        flyway.setSchemas(getSchema());
        flyway.setLocations(String.format("db/%s/migration", getSchema()));
        flyway.setValidateOnMigrate(null == validateOnMigrate || validateOnMigrate);
        flyway.setDataSource(dataSource);
        LOGGER.info("will migrate database to latest version...");
        flyway.migrate();
        LOGGER.info("did migrate database to latest version...");
    } else {
        LOGGER.warn("migration disabled");
    }
}
Example 6
Project: keywhiz-master  File: KeywhizService.java View source code
private void validateDatabase(KeywhizConfig config) {
    logger.debug("Validating database state");
    DataSource dataSource = config.getDataSourceFactory().build(new MetricRegistry(), "flyway-validation-datasource");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations(config.getMigrationsDir());
    flyway.validate();
}
Example 7
Project: lavagna-master  File: DatabaseMigrator.java View source code
private void doMigration(LavagnaEnvironment env, DataSource dataSource, MigrationVersion version) {
    String sqlDialect = env.getRequiredProperty("datasource.dialect");
    Flyway migration = new Flyway();
    migration.setDataSource(dataSource);
    // FIXME remove the validation = false when the schemas will be stable
    migration.setValidateOnMigrate(false);
    //
    migration.setTarget(version);
    migration.setLocations("io/lavagna/db/" + sqlDialect + "/");
    migration.migrate();
}
Example 8
Project: lemon-master  File: DatabaseMigrator.java View source code
@PostConstruct
public void init() {
    if (!enabled) {
        logger.info("skip dbmigrate");
        return;
    }
    long startTime = System.currentTimeMillis();
    if (clean) {
        logger.info("clean database");
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.clean();
    }
    Map<String, ModuleSpecification> map = applicationContext.getBeansOfType(ModuleSpecification.class);
    for (ModuleSpecification moduleSpecification : map.values()) {
        if (!moduleSpecification.isEnabled()) {
            logger.info("skip migrate : {}, {}", moduleSpecification.getSchemaTable(), moduleSpecification.getSchemaLocation());
            continue;
        }
        this.doMigrate(moduleSpecification.getSchemaTable(), moduleSpecification.getSchemaLocation());
        if (moduleSpecification.isInitData()) {
            this.doMigrate(moduleSpecification.getDataTable(), moduleSpecification.getDataLocation());
        }
    }
    long endTime = System.currentTimeMillis();
    logger.info("dbmigrate cost : {} ms", (endTime - startTime));
}
Example 9
Project: Nin-master  File: MigrationEngineFlyway.java View source code
@Override
public void migrate() {
    // Get the connection credentials from application.conf
    String connectionUrl = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_URL);
    String connectionUsername = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_USERNAME);
    String connectionPassword = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_PASSWORD);
    // We migrate automatically => if you do not want that (eg in production)
    // set ninja.migration.run=false in application.conf
    Flyway flyway = new Flyway();
    flyway.setDataSource(connectionUrl, connectionUsername, connectionPassword);
    // get a fresh database.
    if (ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_MIGRATION_DROP_SCHEMA, ninjaProperties.isTest() ? true : false)) {
        flyway.clean();
    }
    flyway.migrate();
}
Example 10
Project: Ninja-master  File: MigrationEngineFlyway.java View source code
@Override
public void migrate() {
    // Get the connection credentials from application.conf
    String connectionUrl = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_URL);
    String connectionUsername = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_USERNAME);
    String connectionPassword = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_PASSWORD);
    // We migrate automatically => if you do not want that (eg in production)
    // set ninja.migration.run=false in application.conf
    Flyway flyway = new Flyway();
    flyway.setDataSource(connectionUrl, connectionUsername, connectionPassword);
    // get a fresh database.
    if (ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_MIGRATION_DROP_SCHEMA, ninjaProperties.isTest() ? true : false)) {
        flyway.clean();
    }
    flyway.migrate();
}
Example 11
Project: oas-master  File: DatabaseMigrator.java View source code
/**
   * Migrate the database to the latest available migration.
   */
public void migrate() {
    if (this.enabled) {
        final Flyway flyway = new Flyway();
        flyway.setDataSource(this.dataSource);
        if (this.testdata) {
            flyway.setLocations(masterDataPath, testDataPath);
        } else {
            flyway.setLocations(masterDataPath);
        }
        if (this.clean) {
            flyway.clean();
        }
        flyway.migrate();
    }
}
Example 12
Project: oasp4j-master  File: DatabaseMigrator.java View source code
/**
   * Migrate the database to the latest available migration.
   */
public void migrate() {
    if (this.enabled) {
        final Flyway flyway = new Flyway();
        flyway.setDataSource(this.dataSource);
        if (this.testdata) {
            flyway.setLocations(masterDataPath, testDataPath);
        } else {
            flyway.setLocations(masterDataPath);
        }
        if (this.clean) {
            flyway.clean();
        }
        flyway.migrate();
    }
}
Example 13
Project: dreampie-master  File: FlywayPlugin.java View source code
private Map<String, Flyway> flyways() {
    Map<String, Flyway> flywayMap = Maps.newHashMap();
    Map<String, DbSource> dbSourceMap = dbConfig.getAllDbSources();
    DbSource dbSource = null;
    String migrationFilesLocation = null;
    Flyway flyway = null;
    for (String dbName : dbSourceMap.keySet()) {
        migrationFilesLocation = flywayPrefixToMigrationScript + dbName;
        if (dbConfig.migrationFileDirectoryExists(migrationFilesLocation)) {
            dbSource = dbSourceMap.get(dbName);
            flyway = new Flyway();
            flyway.setDataSource(dbSource.url, dbSource.user, dbSource.password);
            flyway.setLocations(migrationFilesLocation);
            if (dbConfig.isClean(dbName)) {
                flyway.setCleanOnValidationError(true);
            }
            if (dbConfig.initOnMigrate(dbName)) {
                flyway.setInitOnMigrate(true);
            }
            flywayMap.put(dbName, flyway);
        }
    }
    return flywayMap;
}
Example 14
Project: uaa-master  File: BootstrapTests.java View source code
private static ConfigurableApplicationContext getServletContext(String profiles, boolean mergeProfiles, String[] yamlFiles, boolean cleandb, String... resources) {
    String[] resourcesToLoad = resources;
    if (!resources[0].endsWith(".xml")) {
        resourcesToLoad = new String[resources.length - 1];
        System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length);
    }
    final String[] configLocations = resourcesToLoad;
    AbstractRefreshableWebApplicationContext context = new AbstractRefreshableWebApplicationContext() {

        @Override
        protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
            XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
            // Configure the bean definition reader with this context's
            // resource loading environment.
            beanDefinitionReader.setEnvironment(this.getEnvironment());
            beanDefinitionReader.setResourceLoader(this);
            beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
            if (configLocations != null) {
                for (String configLocation : configLocations) {
                    beanDefinitionReader.loadBeanDefinitions(configLocation);
                }
            }
        }
    };
    if (profiles != null) {
        if (mergeProfiles) {
            String[] activeProfiles = context.getEnvironment().getActiveProfiles();
            HashSet<String> envProfiles = new HashSet<>(Arrays.asList(activeProfiles));
            envProfiles.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(profiles)));
            envProfiles.add("strict");
            context.getEnvironment().setActiveProfiles(envProfiles.toArray(new String[0]));
        } else {
            context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
        }
    }
    MockServletContext servletContext = new MockServletContext() {

        @Override
        public RequestDispatcher getNamedDispatcher(String path) {
            return new MockRequestDispatcher("/");
        }

        @Override
        public String getVirtualServerName() {
            return "localhost";
        }
    };
    context.setServletContext(servletContext);
    MockServletConfig servletConfig = new MockServletConfig(servletContext);
    servletConfig.addInitParameter("environmentConfigLocations", StringUtils.arrayToCommaDelimitedString(yamlFiles));
    context.setServletConfig(servletConfig);
    YamlServletProfileInitializer initializer = new YamlServletProfileInitializer();
    initializer.initialize(context);
    if (profiles != null) {
        context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }
    context.refresh();
    if (cleandb) {
        context.getBean(Flyway.class).clean();
        context.getBean(Flyway.class).migrate();
    }
    return context;
}
Example 15
Project: wildfly-swarm-master  File: FlywayMigrationServletContextListener.java View source code
@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);
            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);
    }
    flyway.migrate();
}
Example 16
Project: zookeeper-guides-master  File: Dao.java View source code
public void checkNCreate() {
    Flyway flyway = new Flyway();
    flyway.setDataSource(globalProps.getProperty("jdbcUrl"), globalProps.getProperty("jdbcUser"), globalProps.getProperty("jdbcPwd"));
    //Will wipe db each time. Avoid this in prod.
    if (globalProps.getProperty("env").equals("dev")) {
        flyway.clean();
    }
    //Remove the above line if deploying to prod.
    flyway.migrate();
}
Example 17
Project: ameba-master  File: MigrationResource.java View source code
/**
     * <p>info.</p>
     *
     * @param dbName   a {@link java.lang.String} object.
     * @param revision a {@link java.lang.String} object.
     * @return a {@link javax.ws.rs.core.Response} object.
     */
@GET
@Path("{dbName}/{revision}")
public Response info(@PathParam("dbName") String dbName, @PathParam("revision") String revision) {
    Flyway flyway = locator.getService(Flyway.class, dbName);
    if (flyway == null)
        throw new NotFoundException();
    Object entity = null;
    switch(revision) {
        case "current":
            entity = flyway.info().current();
            break;
        case "pending":
            entity = flyway.info().pending();
            break;
        case "applied":
            entity = flyway.info().applied();
            break;
        case "first":
            {
                MigrationInfo[] migrationInfos = flyway.info().all();
                if (migrationInfos.length == 0)
                    throw new NotFoundException();
                entity = migrationInfos[0];
                break;
            }
        case "resolved":
            entity = resolved(flyway.info().all());
            break;
        case "failed":
            entity = failed(flyway.info().all());
            break;
        case "future":
            entity = future(flyway.info().all());
            break;
        case "latest":
            {
                MigrationInfo[] migrationInfos = flyway.info().all();
                if (migrationInfos.length == 0)
                    throw new NotFoundException();
                entity = migrationInfos[migrationInfos.length - 1];
                break;
            }
        default:
            for (MigrationInfo info : flyway.info().all()) {
                if (revision.equalsIgnoreCase(info.getVersion().getVersion())) {
                    entity = info;
                    break;
                }
            }
    }
    if (entity == null)
        throw new NotFoundException();
    return Response.ok(entity).build();
}
Example 18
Project: flyway-test-extensions-master  File: FlywayTestExecutionListener.java View source code
/**
	 * Test the annotation an reset the database.
	 *
	 * @param testContext
	 *            default test context filled from spring
	 * @param annotation
	 *            founded
	 */
private void dbResetWithAnotation(final TestContext testContext, final FlywayTest annotation) {
    if (annotation != null) {
        Flyway flyWay = null;
        final ApplicationContext appContext = testContext.getApplicationContext();
        final String executionInfo = ExecutionListenerHelper.getExecutionInformation(testContext);
        if (appContext != null) {
            flyWay = getBean(appContext, Flyway.class, annotation.flywayName());
            if (flyWay != null) {
                // we have a fly way configuration no lets try
                if (logger.isInfoEnabled()) {
                    logger.info("---> Start reset database for  '" + executionInfo + "'.");
                }
                if (annotation.invokeCleanDB()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("******** Clean database for  '" + executionInfo + "'.");
                    }
                    flyWay.clean();
                }
                if (annotation.invokeBaselineDB()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("******** Baseline database  for  '" + executionInfo + "'.");
                    }
                    flyWay.baseline();
                }
                if (annotation.invokeMigrateDB()) {
                    String[] locations = annotation.locationsForMigrate();
                    if ((locations == null || locations.length == 0)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("******** Default migrate database for  '" + executionInfo + "'.");
                        }
                        flyWay.migrate();
                    } else {
                        locationsMigrationHandling(annotation, flyWay, executionInfo);
                    }
                }
                if (logger.isInfoEnabled()) {
                    logger.info("<--- Finished reset database  for  '" + executionInfo + "'.");
                }
                return;
            }
            throw new IllegalArgumentException("Annotation " + annotation.getClass() + " was set, but no Flyway configuration was given.");
        }
        throw new IllegalArgumentException("Annotation " + annotation.getClass() + " was set, but no configuration was given.");
    }
}
Example 19
Project: spring-boot-master  File: FlywayAutoConfigurationTests.java View source code
@Test
public void createDataSource() throws Exception {
    EnvironmentTestUtils.addEnvironment(this.context, "flyway.url:jdbc:hsqldb:mem:flywaytest", "flyway.user:sa");
    registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    Flyway flyway = this.context.getBean(Flyway.class);
    assertThat(flyway.getDataSource()).isNotNull();
}
Example 20
Project: auth-server-master  File: AuthServer.java View source code
@Bean(initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    flyway.setBaselineOnMigrate(true);
    flyway.setDataSource(hikariDataSource());
    flyway.setLocations("db/migration/" + databaseVendor);
    flyway.setTable("auth_server_schema_version");
    MigrationVersion version = MigrationVersion.fromVersion("0");
    flyway.setBaselineVersion(version);
    return flyway;
}
Example 21
Project: che-master  File: FlywaySchemaInitializer.java View source code
@Override
public void init() throws SchemaInitializationException {
    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 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 (SQLExceptionRuntimeException |  x) {
        throw new SchemaInitializationException(x.getLocalizedMessage(), x);
    }
}
Example 22
Project: DevTools-master  File: FlywaySchemaInitializer.java View source code
@Override
public void init() throws SchemaInitializationException {
    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 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 (SQLExceptionRuntimeException |  x) {
        throw new SchemaInitializationException(x.getLocalizedMessage(), x);
    }
}
Example 23
Project: eGov-master  File: DBMigrationConfiguration.java View source code
@Bean
@DependsOn("dataSource")
public Flyway flyway(DataSource dataSource, @Qualifier("cities") List<String> cities) {
    if (applicationProperties.isMasterServer()) {
        boolean devMode = applicationProperties.devMode();
        cities.parallelStream().forEach( schema -> {
            if (devMode)
                migrateDatabase(schema, dataSource, MAIN_MIGRATION_FILE_PATH, SAMPLE_MIGRATION_FILE_PATH, format(TENANT_MIGRATION_FILE_PATH, schema));
            else
                migrateDatabase(schema, dataSource, MAIN_MIGRATION_FILE_PATH, format(TENANT_MIGRATION_FILE_PATH, schema));
        });
        if (applicationProperties.statewideMigrationRequired() && !devMode)
            migrateDatabase(PUBLIC_SCHEMA, dataSource, MAIN_MIGRATION_FILE_PATH, STATEWIDE_MIGRATION_FILE_PATH, format(TENANT_MIGRATION_FILE_PATH, PUBLIC_SCHEMA));
        else if (!devMode)
            migrateDatabase(PUBLIC_SCHEMA, dataSource, MAIN_MIGRATION_FILE_PATH, format(TENANT_MIGRATION_FILE_PATH, PUBLIC_SCHEMA));
    }
    return new Flyway();
}
Example 24
Project: gobblin-master  File: DatabaseJobHistoryStore.java View source code
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 25
Project: resource-server-master  File: ResourceServer.java View source code
@Bean(initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    flyway.setBaselineOnMigrate(true);
    flyway.setDataSource(dataSource());
    flyway.setLocations("db/migration/" + databaseVendor);
    flyway.setTable("resource_server_schema_version");
    MigrationVersion version = MigrationVersion.fromVersion("0");
    flyway.setBaselineVersion(version);
    return flyway;
}
Example 26
Project: categolj2-backend-master  File: InfraConfig.java View source code
@Bean
BeanPostProcessor flywayBeanPostProcessor() {
    return new BeanPostProcessor() {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof Flyway) {
                ((Flyway) bean).setValidateOnMigrate(false);
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    };
}
Example 27
Project: jooby-master  File: Flywaydb.java View source code
@Override
public void configure(final Env env, final Config conf, final Binder binder) {
    Config $flyway = conf.getConfig(name).withFallback(conf.getConfig("flyway"));
    Flyway flyway = new Flyway();
    flyway.configure(props($flyway));
    // bind
    env.serviceKey().generate(Flyway.class, name,  key -> binder.bind(key).toInstance(flyway));
    // run
    Iterable<Command> cmds = commands($flyway);
    env.onStart(() -> {
        cmds.forEach( cmd -> cmd.run(flyway));
    });
}
Example 28
Project: mycontroller-master  File: DataBaseUtils.java View source code
public static synchronized void loadDatabase() throws SQLException, ClassNotFoundException {
    if (!isDbLoaded) {
        // Class.forName("org.sqlite.JDBC");
        /*
             * // create a connection source to our database connectionSource =
             * new JdbcConnectionSource(databaseUrl);
             */
        //Update Database url
        DB_URL = DB_URL_PREFIX + AppProperties.getInstance().getDbH2DbLocation();
        // pooled connection source
        connectionPooledSource = new JdbcPooledConnectionSource(DB_URL, DB_USERNAME, DB_PASSWORD);
        // only keep the connections open for 5 minutes
        connectionPooledSource.setMaxConnectionAgeMillis(McUtils.FIVE_MINUTES);
        // change the check-every milliseconds from 30 seconds to 60
        connectionPooledSource.setCheckConnectionsEveryMillis(McUtils.THREE_MINUTES);
        // for extra protection, enable the testing of connections
        // right before they are handed to the user
        connectionPooledSource.setTestBeforeGet(true);
        isDbLoaded = true;
        _logger.debug("Database ConnectionSource loaded. Database Url:[{}]", DB_URL);
        //Steps to migrate database
        // Create the Flyway instance
        Flyway flyway = new Flyway();
        // Point it to the database
        flyway.setDataSource(DB_URL, DB_USERNAME, DB_PASSWORD);
        flyway.setLocations(DB_MIGRATION_LOCATION);
        // Start the migration
        int migrationsCount = 0;
        try {
            migrationsCount = flyway.migrate();
        } catch (FlywayException fEx) {
            _logger.error("Migration exception, ", fEx);
            if (fEx.getMessage().contains("contains a failed migration")) {
                flyway.repair();
                migrationsCount = flyway.migrate();
            }
        }
        //Load Dao's if not loaded already
        if (!DaoUtils.isDaoInitialized()) {
            DaoUtils.loadAllDao();
        }
        //set recent migration version to application table.
        //load/reload settings
        AppProperties.getInstance().loadPropertiesFromDb();
        McAbout mcAbout = new McAbout();
        if (migrationsCount > 0) {
            MyControllerSettings.builder().version(mcAbout.getGitVersion()).dbVersion(flyway.info().current().getVersion() + " - " + flyway.info().current().getDescription()).build().updateInternal();
        } else {
            MyControllerSettings.builder().version(mcAbout.getGitVersion()).build().updateInternal();
        }
        //After executed migration, reload settings again
        AppProperties.getInstance().loadPropertiesFromDb();
        if (migrationsCount > 0) {
            _logger.info("Number of migrations done:{}", migrationsCount);
        } else {
            _logger.debug("Number of migrations done:{}", migrationsCount);
        }
        _logger.info("Application information: [Version:{}, Database version:{}]", AppProperties.getInstance().getControllerSettings().getVersion(), AppProperties.getInstance().getControllerSettings().getDbVersion());
    } else {
        _logger.warn("Database ConnectionSource already created. Nothing to do. Database Url:[{}]", DB_URL);
    }
}
Example 29
Project: TinkerTime-master  File: TinkerTimeLauncher.java View source code
@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 30
Project: WorldGuard-master  File: SQLDriver.java View source code
/**
     * Attempt to migrate the tables to the latest version.
     *
     * @throws StorageException thrown if migration fails
     * @throws SQLException thrown on SQL error
     */
private void migrate() throws SQLException, StorageException {
    Closer closer = Closer.create();
    Connection conn = closer.register(getConnection());
    try {
        // Check some tables
        boolean tablesExist;
        boolean isRecent;
        boolean isBeforeMigrations;
        boolean hasMigrations;
        try {
            tablesExist = tryQuery(conn, "SELECT * FROM " + config.getTablePrefix() + "region_cuboid LIMIT 1");
            isRecent = tryQuery(conn, "SELECT world_id FROM " + config.getTablePrefix() + "region_cuboid LIMIT 1");
            isBeforeMigrations = !tryQuery(conn, "SELECT uuid FROM " + config.getTablePrefix() + "user LIMIT 1");
            hasMigrations = tryQuery(conn, "SELECT * FROM " + config.getTablePrefix() + "migrations LIMIT 1");
        } finally {
            closer.closeQuietly();
        }
        // We don't bother with migrating really old tables
        if (tablesExist && !isRecent) {
            throw new StorageException("Sorry, your tables are too old for the region SQL auto-migration system. " + "Please run region_manual_update_20110325.sql on your database, which comes " + "with WorldGuard or can be found in http://github.com/sk89q/worldguard");
        }
        // Our placeholders
        Map<String, String> placeHolders = new HashMap<String, String>();
        placeHolders.put("tablePrefix", config.getTablePrefix());
        Flyway flyway = new Flyway();
        // checks and issue messages appropriately
        if (!hasMigrations) {
            flyway.setInitOnMigrate(true);
            if (tablesExist) {
                // Detect if this is before migrations
                if (isBeforeMigrations) {
                    flyway.setInitVersion(MigrationVersion.fromVersion("1"));
                }
                log.log(Level.INFO, "The SQL region tables exist but the migrations table seems to not exist yet. Creating the migrations table...");
            } else {
                // By default, if Flyway sees any tables at all in the schema, it
                // will assume that we are up to date, so we have to manually
                // check ourselves and then ask Flyway to start from the beginning
                // if our test table doesn't exist
                flyway.setInitVersion(MigrationVersion.fromVersion("0"));
                log.log(Level.INFO, "SQL region tables do not exist: creating...");
            }
        }
        flyway.setClassLoader(getClass().getClassLoader());
        flyway.setLocations("migrations/region/" + getMigrationFolderName());
        flyway.setDataSource(config.getDsn(), config.getUsername(), config.getPassword());
        flyway.setTable(config.getTablePrefix() + "migrations");
        flyway.setPlaceholders(placeHolders);
        flyway.setValidateOnMigrate(false);
        flyway.migrate();
    } catch (FlywayException e) {
        throw new StorageException("Failed to migrate tables", e);
    } finally {
        closer.closeQuietly();
    }
}
Example 31
Project: alf.io-master  File: DataSourceConfiguration.java View source code
@Bean
public Flyway migrator(Environment env, PlatformProvider platform, DataSource dataSource) {
    String sqlDialect = platform.getDialect(env);
    Flyway migration = new Flyway();
    migration.setDataSource(dataSource);
    migration.setValidateOnMigrate(false);
    migration.setTarget(MigrationVersion.LATEST);
    migration.setOutOfOrder(true);
    migration.setLocations("alfio/db/" + sqlDialect + "/");
    migration.migrate();
    return migration;
}
Example 32
Project: WaveTact-master  File: LoadUtils.java View source code
public static void initiateDatabaseConnection() throws Exception {
    Flyway flyway = new Flyway();
    flyway.setDataSource("jdbc:sqlite:./db.sqlite", null, null);
    flyway.setValidateOnMigrate(false);
    flyway.migrate();
    System.err.println("Getting connection...");
    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:./db.sqlite");
    System.err.println("Creating DSLContext...");
    Registry.wavetactDB = DSL.using(conn, SQLDialect.SQLITE);
}
Example 33
Project: dlibrary-master  File: DatabaseUtils.java View source code
/**
     * Commandline tools for managing database changes, etc.
     * @param argv
     */
public static void main(String[] argv) {
    // Usage checks
    if (argv.length < 1) {
        System.out.println("\nDatabase action argument is missing.");
        System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
        System.out.println("\nOr, type 'database help' for more information.\n");
        System.exit(1);
    }
    try {
        // Call initDataSource to JUST initialize the dataSource WITHOUT fully
        // initializing the DatabaseManager itself. This ensures we do NOT
        // immediately run our Flyway DB migrations on this database
        DataSource dataSource = DatabaseManager.initDataSource();
        // Get configured DB URL for reporting below
        String url = ConfigurationManager.getProperty("db.url");
        // Point Flyway API to our database
        Flyway flyway = setupFlyway(dataSource);
        // "test" = Test Database Connection
        if (argv[0].equalsIgnoreCase("test")) {
            // Try to connect to the database
            System.out.println("\nAttempting to connect to database using these configurations: ");
            System.out.println(" - URL: " + url);
            System.out.println(" - Driver: " + ConfigurationManager.getProperty("db.driver"));
            System.out.println(" - Username: " + ConfigurationManager.getProperty("db.username"));
            System.out.println(" - Password: [hidden]");
            System.out.println(" - Schema: " + ConfigurationManager.getProperty("db.schema"));
            System.out.println("\nTesting connection...");
            try {
                // Just do a high level test by getting our configured DataSource and attempting to connect to it
                // NOTE: We specifically do NOT call DatabaseManager.getConnection() because that will attempt
                // a full initialization of DatabaseManager & also cause database migrations/upgrades to occur
                Connection connection = dataSource.getConnection();
                connection.close();
            } catch (SQLException sqle) {
                System.err.println("\nError: ");
                System.err.println(" - " + sqle);
                System.err.println("\nPlease see the DSpace documentation for assistance.\n");
                System.exit(1);
            }
            System.out.println("Connected successfully!\n");
        } else // "info" = Basic Database Information
        if (argv[0].equalsIgnoreCase("info")) {
            // Get basic Database info
            Connection connection = dataSource.getConnection();
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println("\nDatabase URL: " + url);
            System.out.println("Database Schema: " + getSchemaName(connection));
            System.out.println("Database Software: " + meta.getDatabaseProductName() + " version " + meta.getDatabaseProductVersion());
            System.out.println("Database Driver: " + meta.getDriverName() + " version " + meta.getDriverVersion());
            // Get info table from Flyway
            System.out.println("\n" + MigrationInfoDumper.dumpToAsciiTable(flyway.info().all()));
            // See: http://flywaydb.org/documentation/faq.html#case-sensitive
            if (!tableExists(connection, flyway.getTable(), true)) {
                System.out.println("\nNOTE: This database is NOT yet initialized for auto-migrations (via Flyway).");
                // Determine which version of DSpace this looks like
                String dbVersion = determineDBVersion(connection);
                if (dbVersion != null) {
                    System.out.println("\nYour database looks to be compatible with DSpace version " + dbVersion);
                    System.out.println("All upgrades *after* version " + dbVersion + " will be run during the next migration.");
                    System.out.println("\nIf you'd like to upgrade now, simply run 'dspace database migrate'.");
                }
            }
            connection.close();
        } else // "migrate" = Manually run any outstanding Database migrations (if any)
        if (argv[0].equalsIgnoreCase("migrate")) {
            System.out.println("\nDatabase URL: " + url);
            //    - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING)
            if (argv.length == 2) {
                if (argv[1].equalsIgnoreCase("ignored")) {
                    System.out.println("Migrating database to latest version AND running previously \"Ignored\" migrations... (Check logs for details)");
                    Connection connection = dataSource.getConnection();
                    // Update the database to latest version, but set "outOfOrder=true"
                    // This will ensure any old migrations in the "ignored" state are now run
                    updateDatabase(dataSource, connection, null, true);
                    connection.close();
                } else {
                    // Otherwise, we assume "argv[1]" is a valid migration version number
                    // This is only for testing! Never specify for Production!
                    System.out.println("Migrating database ONLY to version " + argv[1] + " ... (Check logs for details)");
                    System.out.println("\nWARNING: It is highly likely you will see errors in your logs when the Metadata");
                    System.out.println("or Bitstream Format Registry auto-update. This is because you are attempting to");
                    System.out.println("use an OLD version " + argv[1] + " Database with a newer DSpace API. NEVER do this in a");
                    System.out.println("PRODUCTION scenario. The resulting old DB is only useful for migration testing.\n");
                    Connection connection = dataSource.getConnection();
                    // Update the database, to the version specified.
                    updateDatabase(dataSource, connection, argv[1], false);
                    connection.close();
                }
            } else {
                System.out.println("Migrating database to latest version... (Check logs for details)");
                // NOTE: This looks odd, but all we really need to do is ensure the
                // DatabaseManager auto-initializes. It'll take care of the migration itself.
                // Asking for our DB Name will ensure DatabaseManager.initialize() is called.
                DatabaseManager.getDbName();
            }
            System.out.println("Done.");
        } else // "repair" = Run Flyway repair script
        if (argv[0].equalsIgnoreCase("repair")) {
            System.out.println("\nDatabase URL: " + url);
            System.out.println("Attempting to repair any previously failed migrations via FlywayDB... (Check logs for details)");
            flyway.repair();
            System.out.println("Done.");
        } else // "clean" = Run Flyway clean script
        if (argv[0].equalsIgnoreCase("clean")) {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\nDatabase URL: " + url);
            System.out.println("\nWARNING: ALL DATA AND TABLES IN YOUR DATABASE WILL BE PERMANENTLY DELETED.\n");
            System.out.println("There is NO turning back from this action. Backup your DB before continuing.");
            System.out.println("If you are using Oracle, your RECYCLEBIN will also be PURGED.\n");
            System.out.print("Do you want to PERMANENTLY DELETE everything from your database? [y/n]: ");
            String choiceString = input.readLine();
            input.close();
            if (choiceString.equalsIgnoreCase("y")) {
                System.out.println("Scrubbing database clean... (Check logs for details)");
                cleanDatabase(flyway, dataSource);
                System.out.println("Done.");
            }
        } else {
            System.out.println("\nUsage: database [action]");
            System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
            System.out.println(" - test    = Test database connection is OK");
            System.out.println(" - info    = Describe basic info about database, including migrations run");
            System.out.println(" - migrate = Migrate the Database to the latest version");
            System.out.println("             Optionally, specify \"ignored\" to also run \"Ignored\" migrations");
            System.out.println(" - repair  = Attempt to repair any previously failed database migrations");
            System.out.println(" - clean   = DESTROY all data and tables in Database (WARNING there is no going back!)");
            System.out.println("");
        }
        System.exit(0);
    } catch (Exception e) {
        System.err.println("Caught exception:");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 34
Project: vtechworks-master  File: DatabaseUtils.java View source code
/**
     * Commandline tools for managing database changes, etc.
     * @param argv
     */
public static void main(String[] argv) {
    // Usage checks
    if (argv.length < 1) {
        System.out.println("\nDatabase action argument is missing.");
        System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
        System.out.println("\nOr, type 'database help' for more information.\n");
        System.exit(1);
    }
    try {
        // Call initDataSource to JUST initialize the dataSource WITHOUT fully
        // initializing the DatabaseManager itself. This ensures we do NOT
        // immediately run our Flyway DB migrations on this database
        DataSource dataSource = DatabaseManager.initDataSource();
        // Get configured DB URL for reporting below
        String url = ConfigurationManager.getProperty("db.url");
        // Point Flyway API to our database
        Flyway flyway = setupFlyway(dataSource);
        // "test" = Test Database Connection
        if (argv[0].equalsIgnoreCase("test")) {
            // Try to connect to the database
            System.out.println("\nAttempting to connect to database using these configurations: ");
            System.out.println(" - URL: " + url);
            System.out.println(" - Driver: " + ConfigurationManager.getProperty("db.driver"));
            System.out.println(" - Username: " + ConfigurationManager.getProperty("db.username"));
            System.out.println(" - Password: [hidden]");
            System.out.println(" - Schema: " + ConfigurationManager.getProperty("db.schema"));
            System.out.println("\nTesting connection...");
            try {
                // Just do a high level test by getting our configured DataSource and attempting to connect to it
                // NOTE: We specifically do NOT call DatabaseManager.getConnection() because that will attempt
                // a full initialization of DatabaseManager & also cause database migrations/upgrades to occur
                Connection connection = dataSource.getConnection();
                connection.close();
            } catch (SQLException sqle) {
                System.err.println("\nError: ");
                System.err.println(" - " + sqle);
                System.err.println("\nPlease see the DSpace documentation for assistance.\n");
                System.exit(1);
            }
            System.out.println("Connected successfully!\n");
        } else // "info" = Basic Database Information
        if (argv[0].equalsIgnoreCase("info")) {
            // Get basic Database info
            Connection connection = dataSource.getConnection();
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println("\nDatabase URL: " + url);
            System.out.println("Database Schema: " + getSchemaName(connection));
            System.out.println("Database Software: " + meta.getDatabaseProductName() + " version " + meta.getDatabaseProductVersion());
            System.out.println("Database Driver: " + meta.getDriverName() + " version " + meta.getDriverVersion());
            // Get info table from Flyway
            System.out.println("\n" + MigrationInfoDumper.dumpToAsciiTable(flyway.info().all()));
            // See: http://flywaydb.org/documentation/faq.html#case-sensitive
            if (!tableExists(connection, flyway.getTable(), true)) {
                System.out.println("\nNOTE: This database is NOT yet initialized for auto-migrations (via Flyway).");
                // Determine which version of DSpace this looks like
                String dbVersion = determineDBVersion(connection);
                if (dbVersion != null) {
                    System.out.println("\nYour database looks to be compatible with DSpace version " + dbVersion);
                    System.out.println("All upgrades *after* version " + dbVersion + " will be run during the next migration.");
                    System.out.println("\nIf you'd like to upgrade now, simply run 'dspace database migrate'.");
                }
            }
            connection.close();
        } else // "migrate" = Manually run any outstanding Database migrations (if any)
        if (argv[0].equalsIgnoreCase("migrate")) {
            System.out.println("\nDatabase URL: " + url);
            //    - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING)
            if (argv.length == 2) {
                if (argv[1].equalsIgnoreCase("ignored")) {
                    System.out.println("Migrating database to latest version AND running previously \"Ignored\" migrations... (Check logs for details)");
                    Connection connection = dataSource.getConnection();
                    // Update the database to latest version, but set "outOfOrder=true"
                    // This will ensure any old migrations in the "ignored" state are now run
                    updateDatabase(dataSource, connection, null, true);
                    connection.close();
                } else {
                    // Otherwise, we assume "argv[1]" is a valid migration version number
                    // This is only for testing! Never specify for Production!
                    System.out.println("Migrating database ONLY to version " + argv[1] + " ... (Check logs for details)");
                    System.out.println("\nWARNING: It is highly likely you will see errors in your logs when the Metadata");
                    System.out.println("or Bitstream Format Registry auto-update. This is because you are attempting to");
                    System.out.println("use an OLD version " + argv[1] + " Database with a newer DSpace API. NEVER do this in a");
                    System.out.println("PRODUCTION scenario. The resulting old DB is only useful for migration testing.\n");
                    Connection connection = dataSource.getConnection();
                    // Update the database, to the version specified.
                    updateDatabase(dataSource, connection, argv[1], false);
                    connection.close();
                }
            } else {
                System.out.println("Migrating database to latest version... (Check logs for details)");
                // NOTE: This looks odd, but all we really need to do is ensure the
                // DatabaseManager auto-initializes. It'll take care of the migration itself.
                // Asking for our DB Name will ensure DatabaseManager.initialize() is called.
                DatabaseManager.getDbName();
            }
            System.out.println("Done.");
        } else // "repair" = Run Flyway repair script
        if (argv[0].equalsIgnoreCase("repair")) {
            System.out.println("\nDatabase URL: " + url);
            System.out.println("Attempting to repair any previously failed migrations via FlywayDB... (Check logs for details)");
            flyway.repair();
            System.out.println("Done.");
        } else // "clean" = Run Flyway clean script
        if (argv[0].equalsIgnoreCase("clean")) {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("\nDatabase URL: " + url);
            System.out.println("\nWARNING: ALL DATA AND TABLES IN YOUR DATABASE WILL BE PERMANENTLY DELETED.\n");
            System.out.println("There is NO turning back from this action. Backup your DB before continuing.");
            System.out.println("If you are using Oracle, your RECYCLEBIN will also be PURGED.\n");
            System.out.print("Do you want to PERMANENTLY DELETE everything from your database? [y/n]: ");
            String choiceString = input.readLine();
            input.close();
            if (choiceString.equalsIgnoreCase("y")) {
                System.out.println("Scrubbing database clean... (Check logs for details)");
                cleanDatabase(flyway, dataSource);
                System.out.println("Done.");
            }
        } else {
            System.out.println("\nUsage: database [action]");
            System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
            System.out.println(" - test    = Test database connection is OK");
            System.out.println(" - info    = Describe basic info about database, including migrations run");
            System.out.println(" - migrate = Migrate the Database to the latest version");
            System.out.println("             Optionally, specify \"ignored\" to also run \"Ignored\" migrations");
            System.out.println(" - repair  = Attempt to repair any previously failed database migrations");
            System.out.println(" - clean   = DESTROY all data and tables in Database (WARNING there is no going back!)");
            System.out.println("");
        }
        System.exit(0);
    } catch (Exception e) {
        System.err.println("Caught exception:");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 35
Project: DSpace-master  File: DatabaseUtils.java View source code
/**
     * Commandline tools for managing database changes, etc.
     * @param argv the command line arguments given
     */
public static void main(String[] argv) {
    // Usage checks
    if (argv.length < 1) {
        System.out.println("\nDatabase action argument is missing.");
        System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair', 'validate' or 'clean'");
        System.out.println("\nOr, type 'database help' for more information.\n");
        System.exit(1);
    }
    try {
        // Get a reference to our configured DataSource
        DataSource dataSource = getDataSource();
        // Point Flyway API to our database
        Flyway flyway = setupFlyway(dataSource);
        // "test" = Test Database Connection
        if (argv[0].equalsIgnoreCase("test")) {
            // Try to connect to the database
            System.out.println("\nAttempting to connect to database");
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("Connected successfully!");
                // Print basic database connection information
                printDBInfo(connection);
                // Print any database warnings/errors found (if any)
                boolean issueFound = printDBIssues(connection);
                // If issues found, exit with an error status (even if connection succeeded).
                if (issueFound)
                    System.exit(1);
                else
                    System.exit(0);
            } catch (SQLException sqle) {
                System.err.println("\nError running 'test': ");
                System.err.println(" - " + sqle);
                System.err.println("\nPlease see the DSpace documentation for assistance.\n");
                sqle.printStackTrace();
                System.exit(1);
            }
        } else if (argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) {
            try (Connection connection = dataSource.getConnection()) {
                // Print basic Database info
                printDBInfo(connection);
                // Get info table from Flyway
                System.out.println("\n" + MigrationInfoDumper.dumpToAsciiTable(flyway.info().all()));
                // See: http://flywaydb.org/documentation/faq.html#case-sensitive
                if (!tableExists(connection, flyway.getTable(), true)) {
                    System.out.println("\nNOTE: This database is NOT yet initialized for auto-migrations (via Flyway).");
                    // Determine which version of DSpace this looks like
                    String dbVersion = determineDBVersion(connection);
                    if (dbVersion != null) {
                        System.out.println("\nYour database looks to be compatible with DSpace version " + dbVersion);
                        System.out.println("All upgrades *after* version " + dbVersion + " will be run during the next migration.");
                        System.out.println("\nIf you'd like to upgrade now, simply run 'dspace database migrate'.");
                    }
                }
                // Print any database warnings/errors found (if any)
                boolean issueFound = printDBIssues(connection);
                // If issues found, exit with an error status
                if (issueFound)
                    System.exit(1);
                else
                    System.exit(0);
            } catch (SQLException e) {
                System.err.println("Info exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else if (argv[0].equalsIgnoreCase("migrate")) {
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                //    - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING)
                if (argv.length == 2) {
                    if (argv[1].equalsIgnoreCase("ignored")) {
                        System.out.println("Migrating database to latest version AND running previously \"Ignored\" migrations... (Check logs for details)");
                        // Update the database to latest version, but set "outOfOrder=true"
                        // This will ensure any old migrations in the "ignored" state are now run
                        updateDatabase(dataSource, connection, null, true);
                    } else {
                        // Otherwise, we assume "argv[1]" is a valid migration version number
                        // This is only for testing! Never specify for Production!
                        String migrationVersion = argv[1];
                        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                        System.out.println("You've specified to migrate your database ONLY to version " + migrationVersion + " ...");
                        System.out.println("\nWARNING: It is highly likely you will see errors in your logs when the Metadata");
                        System.out.println("or Bitstream Format Registry auto-update. This is because you are attempting to");
                        System.out.println("use an OLD version " + migrationVersion + " Database with a newer DSpace API. NEVER do this in a");
                        System.out.println("PRODUCTION scenario. The resulting old DB is only useful for migration testing.\n");
                        System.out.print("Are you SURE you only want to migrate your database to version " + migrationVersion + "? [y/n]: ");
                        String choiceString = input.readLine();
                        input.close();
                        if (choiceString.equalsIgnoreCase("y")) {
                            System.out.println("Migrating database ONLY to version " + migrationVersion + " ... (Check logs for details)");
                            // Update the database, to the version specified.
                            updateDatabase(dataSource, connection, migrationVersion, false);
                        } else {
                            System.out.println("No action performed.");
                        }
                    }
                } else {
                    System.out.println("Migrating database to latest version... (Check dspace logs for details)");
                    updateDatabase(dataSource, connection);
                }
                System.out.println("Done.");
                System.exit(0);
            } catch (SQLException e) {
                System.err.println("Migration exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else // "repair" = Run Flyway repair script
        if (argv[0].equalsIgnoreCase("repair")) {
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println("Attempting to repair any previously failed migrations (or mismatched checksums) via FlywayDB... (Check dspace logs for details)");
                flyway.repair();
                System.out.println("Done.");
                System.exit(0);
            } catch (SQLExceptionFlywayException |  e) {
                System.err.println("Repair exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else // "validate" = Run Flyway validation to check for database errors/issues
        if (argv[0].equalsIgnoreCase("validate")) {
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println("Attempting to validate database status (and migration checksums) via FlywayDB...");
                flyway.validate();
                System.out.println("No errors thrown. Validation succeeded. (Check dspace logs for more details)");
                System.exit(0);
            } catch (SQLExceptionFlywayException |  e) {
                System.err.println("Validation exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else // "clean" = Run Flyway clean script
        if (argv[0].equalsIgnoreCase("clean")) {
            // If clean is disabled, return immediately
            if (flyway.isCleanDisabled()) {
                System.out.println("\nWARNING: 'clean' command is currently disabled, as it is dangerous to run in Production scenarios!");
                System.out.println("\nIn order to run a 'clean' you first must enable it in your DSpace config by specifying 'db.cleanDisabled=false'.\n");
                System.exit(1);
            }
            try (Connection connection = dataSource.getConnection()) {
                String dbType = getDbType(connection);
                // as only 'superuser' accounts can remove the 'pgcrypto' extension.
                if (dbType.equals(DBMS_POSTGRES)) {
                    // Check if database user has permissions suitable to run a clean
                    if (!PostgresUtils.checkCleanPermissions(connection)) {
                        String username = connection.getMetaData().getUserName();
                        // Exit immediately, providing a descriptive error message
                        System.out.println("\nERROR: The database user '" + username + "' does not have sufficient privileges to run a 'database clean' (via Flyway).");
                        System.out.println("\nIn order to run a 'clean', the database user MUST have 'superuser' privileges");
                        System.out.println("OR the '" + PostgresUtils.PGCRYPTO + "' extension must be installed in a separate schema (see documentation).");
                        System.out.println("\nOptionally, you could also manually remove the '" + PostgresUtils.PGCRYPTO + "' extension first (DROP EXTENSION " + PostgresUtils.PGCRYPTO + " CASCADE;), then rerun the 'clean'");
                        System.exit(1);
                    }
                }
                BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println("\nWARNING: ALL DATA AND TABLES IN YOUR DATABASE WILL BE PERMANENTLY DELETED.\n");
                System.out.println("There is NO turning back from this action. Backup your DB before continuing.");
                if (dbType.equals(DBMS_ORACLE)) {
                    System.out.println("\nORACLE WARNING: your RECYCLEBIN will also be PURGED.\n");
                } else if (dbType.equals(DBMS_POSTGRES)) {
                    System.out.println("\nPOSTGRES WARNING: the '" + PostgresUtils.PGCRYPTO + "' extension will be dropped if it is in the same schema as the DSpace database.\n");
                }
                System.out.print("Do you want to PERMANENTLY DELETE everything from your database? [y/n]: ");
                String choiceString = input.readLine();
                input.close();
                if (choiceString.equalsIgnoreCase("y")) {
                    System.out.println("Scrubbing database clean... (Check dspace logs for details)");
                    cleanDatabase(flyway, dataSource);
                    System.out.println("Done.");
                    System.exit(0);
                } else {
                    System.out.println("No action performed.");
                }
            } catch (SQLException e) {
                System.err.println("Clean exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else {
            System.out.println("\nUsage: database [action]");
            System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
            System.out.println(" - test          = Performs a test connection to database to validate connection settings");
            System.out.println(" - info / status = Describe basic info/status about database, including validating the compatibility of this database");
            System.out.println(" - migrate       = Migrate the database to the latest version");
            System.out.println(" - repair        = Attempt to repair any previously failed database migrations or checksum mismatches (via Flyway repair)");
            System.out.println(" - validate      = Validate current database's migration status (via Flyway validate), validating all migration checksums.");
            System.out.println(" - clean         = DESTROY all data and tables in database (WARNING there is no going back!). Requires 'db.cleanDisabled=false' setting in config.");
            System.out.println("");
            System.exit(0);
        }
    } catch (Exception e) {
        System.err.println("Caught exception:");
        e.printStackTrace();
        System.exit(1);
    }
}
Example 36
Project: catwatch-master  File: FlywayConfiguration.java View source code
@Bean
public FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
    return new OptionalFlywayMigrationInitializer(flyway, this.migrationStrategy);
}
Example 37
Project: report-cockpit-birt-web-master  File: MigrationDatabaseIT.java View source code
@Test
public void test() {
    // Create the Flyway instance
    Flyway flyway = new Flyway();
    // Point it to the database
    flyway.setDataSource("jdbc:hsqldb:mem:testdb;sql.syntax_ora=true", "sa", null);
    flyway.setBaselineOnMigrate(true);
    // Start the migration
    flyway.migrate();
}
Example 38
Project: reference-java-spa-webapp-master  File: DatabaseConfig.java View source code
@Bean(initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource());
    return flyway;
}
Example 39
Project: webofneeds-master  File: FlywayWrapper.java View source code
@Override
public void afterPropertiesSet() throws Exception {
    if ("validate".equals(ddlStrategy.trim())) {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.migrate();
    } else {
        logger.info("Flyway DB Migration ommitted due to non-validate DDL-Strategy: " + ddlStrategy);
    }
}
Example 40
Project: hammock-master  File: FlywayExtension.java View source code
public void findFlywayBean(@Observes ProcessBean<Flyway> flywayProcessBean) {
    this.foundFlywayBean = true;
}
Example 41
Project: ja-micro-master  File: SchemaMigratorIntegrationTest.java View source code
@Before
public void setup() {
    props = new ServiceProperties();
    healthcheck = new DatabaseMigrationContributor(props);
    connectionVerifier = mock(ConnectionVerifier.class);
    migrator = new SchemaMigrator(props, healthcheck, connectionVerifier, new Flyway());
}
Example 42
Project: OTj-master  File: FlywayPreparer.java View source code
public static FlywayPreparer forClasspathLocation(String... locations) {
    Flyway f = new Flyway();
    f.setLocations(locations);
    return new FlywayPreparer(f, Arrays.asList(locations));
}
Example 43
Project: otj-pg-embedded-master  File: FlywayPreparer.java View source code
public static FlywayPreparer forClasspathLocation(String... locations) {
    Flyway f = new Flyway();
    f.setLocations(locations);
    return new FlywayPreparer(f, Arrays.asList(locations));
}
Example 44
Project: Consent2Share-master  File: DataAccessConfig.java View source code
@Bean(name = "flyway", initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    flyway.setBaselineVersion(baselineVersion());
    flyway.setBaselineOnMigrate(true);
    flyway.setDataSource(dataSource());
    return flyway;
}
Example 45
Project: HotSUploader-master  File: DataSourceFactoryBean.java View source code
private static void migrateDataSource(DataSource dataSource) {
    final Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setValidateOnMigrate(false);
    flyway.migrate();
}