/** * Adds a jar or a directory with this name to the classpath. * * @param name The name of the jar or directory to add. * @throws IOException when the jar or directory could not be found. */ private static void addJarOrDirectoryToClasspath(final String name) throws IOException { LOG.debug("Adding location to classpath: " + name); try { final URL url = new File(name).toURI().toURL(); final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); final Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysloader, url); } catch (final Exception e) { throw new FlywayException("Unable to load " + name, e); } }
@Override public void migrate(Flyway flyway) { try { flyway.migrate(); } catch (FlywayException e) { if (e.getMessage().contains("1.15")) { logger.info("Found failed database migration. Attempting repair"); flyway.repair(); try { flyway.getConfiguration().getDataSource().getConnection().createStatement().executeUpdate("delete from PUBLIC.\"schema_version\" where \"version\" = '1.15' or \"version\" = '1.16'"); } catch (SQLException e1) { logger.error("Error while deleting old migration steps", e); } flyway.migrate(); } else { logger.error("Unable to migrate", e); throw e; } } } };
protected void originalDbReset(TestContext testContext, FlywayTest annotation) { try { String dbResetMethodName = repeatableAnnotationPresent ? "dbResetWithAnnotation" : "dbResetWithAnotation"; invokeMethod(this, dbResetMethodName, testContext, annotation); } catch (FlywayException e) { if (e.getCause() instanceof SQLException) { String errorCode = ((SQLException) e.getCause()).getSQLState(); if (errorCode != null && errorCode.matches("(42723|42P06|42P07|42712|42710)")) { logger.error("\n\nHINT: Check that you have correctly set org.flywaydb.core.Flyway#schemaNames property!!!\n"); } } throw e; } }
public void check() { logger.info("Start database migration"); final InitialContext cxt; final DataSource dataSource; try { cxt = new InitialContext(); dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic"); } catch (final NamingException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } final Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setTable("schema_version"); flyway.setEncoding("UTF-8"); try { flyway.migrate(); } catch (final FlywayException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } logger.info("Database migration successful"); } }
/** * Loads the configuration from the configuration file. If a configuration file is specified using the -configfile * argument it will be used, otherwise the default config file (conf/flyway.properties) will be loaded. * * @param properties The properties object to load to configuration into. * @param file The configuration file to load. * @param encoding The encoding of the configuration file. * @param failIfMissing Whether to fail if the file is missing. * @return Whether the file was loaded successfully. * @throws FlywayException when the configuration file could not be loaded. */ private static boolean loadConfigurationFile(final Properties properties, final String file, final String encoding, final boolean failIfMissing) throws FlywayException { final File configFile = new File(file); final String errorMessage = "Unable to load config file: " + configFile.getAbsolutePath(); if (!configFile.isFile() || !configFile.canRead()) { if (!failIfMissing) { LOG.debug(errorMessage); return false; } throw new FlywayException(errorMessage); } LOG.debug("Loading config file: " + configFile.getAbsolutePath()); try { final String contents = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(configFile), encoding)); properties.load(new StringReader(contents.replace("\\", "\\\\"))); return true; } catch (final IOException e) { throw new FlywayException(errorMessage, e); } }
private void migrateDbOrError(@NonNull MarquezConfig config) { final Flyway flyway = new Flyway(); final DataSourceFactory database = config.getDataSourceFactory(); flyway.setDataSource(database.getUrl(), database.getUser(), database.getPassword()); // Attempt to perform a database migration. An exception is thrown on failed migration attempts // requiring we handle the throwable and apply a repair on the database to fix any // issues before terminating. try { flyway.migrate(); } catch (FlywayException e) { log.error("Failed to apply migration to database.", e.getMessage()); log.info("Repairing failed database migration...", e.getMessage()); flyway.repair(); log.info("Successfully repaired database, stopping app..."); // The throwable is not propagating up the stack. onFatalError(); // Signal app termination. } }
doMigrate(migration, migrationExecutor, migrationText); } catch (final SQLException e) { throw new FlywayException("Unable to apply migration", e);
} catch (FlywayException fEx) { _logger.error("Migration exception, ", fEx); if (fEx.getMessage().contains("contains a failed migration")) { flyway.repair(); migrationsCount = flyway.migrate();
@Test public void sleepAfterFailedMigration() { props.addProperty("databaseServer", "foo"); Flyway flyway = mock(Flyway.class); when(flyway.migrate()).thenThrow(new FlywayException()); migrator.flyway = flyway; migrator.flywayFailedSemaphore.release(); migrator.migrate(); } }
} catch (FlywayException fEx) { _logger.error("Migration exception, ", fEx); if (fEx.getMessage().contains("contains a failed migration")) { flyway.repair(); migrationsCount = flyway.migrate();
/** * Serializes an object to JSON. * * @param object the object to convert. * @return JSON content. */ private String convertObjectToJson( Object object ) { try { return writer.writeValueAsString( object ); } catch ( IOException e ) { log.error( "Flyway java migration error:", e ); throw new FlywayException( e ); } }
/** * Determines if the database represented by this data source is being initialized for the first time based on * whether or not the table named 'BUCKET' or 'bucket' already exists. * * @param dataSource the data source * @return true if the database has never been initialized before, false otherwise */ private boolean isNewDatabase(final DataSource dataSource) { try (final Connection connection = dataSource.getConnection(); final ResultSet rsUpper = connection.getMetaData().getTables(null, null, "BUCKET", null); final ResultSet rsLower = connection.getMetaData().getTables(null, null, "bucket", null)) { return !rsUpper.next() && !rsLower.next(); } catch (SQLException e) { LOGGER.error(e.getMessage(), e); throw new FlywayException("Unable to obtain connection from Flyway DataSource", e); } }
/** * Get version of pgcrypto extension available. The extension is "available" * if it's been installed via operating system tools/packages. It also * MUST be installed in the DSpace database (see getPgcryptoInstalled()). * <P> * The pgcrypto extension is required for Postgres databases * * @param connection database connection * @return version number or null if not available */ protected static Double getPgcryptoAvailableVersion(Connection connection) { Double version = null; String checkPgCryptoAvailable = "SELECT default_version AS version FROM pg_available_extensions WHERE name=?"; // Run the query to obtain the version of 'pgcrypto' available try (PreparedStatement statement = connection.prepareStatement(checkPgCryptoAvailable)) { statement.setString(1, PGCRYPTO); try (ResultSet results = statement.executeQuery()) { if (results.next()) { version = results.getDouble("version"); } } } catch (SQLException e) { throw new FlywayException("Unable to determine whether 'pgcrypto' extension is available.", e); } return version; }
/** * Get version of pgcrypto extension installed in the DSpace database. * <P> * The pgcrypto extension is required for Postgres databases to support * UUIDs. * * @param connection database connection * @return version number or null if not installed */ protected static Double getPgcryptoInstalledVersion(Connection connection) { Double version = null; String checkPgCryptoInstalled = "SELECT extversion AS version FROM pg_extension WHERE extname=?"; // Run the query to obtain the version of 'pgcrypto' installed on this database try (PreparedStatement statement = connection.prepareStatement(checkPgCryptoInstalled)) { statement.setString(1, PGCRYPTO); try (ResultSet results = statement.executeQuery()) { if (results.next()) { version = results.getDouble("version"); } } } catch (SQLException e) { throw new FlywayException("Unable to determine whether 'pgcrypto' extension is installed.", e); } return version; }
/** * Check for pgcrypto (if needed). Throws an exception if pgcrypto is * not installed or needs an upgrade. * * @param connection database connection */ public void checkPgCrypto(Connection connection) { String dbType; try { dbType = DatabaseUtils.getDbType(connection); } catch (SQLException se) { throw new FlywayException("Unable to determine database type.", se); } // ONLY Check if this is a PostgreSQL database if (dbType != null && dbType.equals(DatabaseUtils.DBMS_POSTGRES)) { // If this is a PostgreSQL database, then a supported version // of the 'pgcrypto' extension MUST be installed to continue. // Check if pgcrypto is both installed & a supported version if (!PostgresUtils.isPgcryptoUpToDate()) { throw new FlywayException( "This PostgreSQL Database is INCOMPATIBLE with DSpace. The upgrade will NOT proceed. " + "A supported version (>=" + PostgresUtils.PGCRYPTO_VERSION + ") of the '" + PostgresUtils .PGCRYPTO + "' extension must be installed! " + "Please run 'dspace database info' for additional info/tips."); } } }
static int calculateChecksum(String str) { Hasher hasher = Hashing.murmur3_32().newHasher(); BufferedReader bufferedReader = new BufferedReader(new StringReader(str)); try { String line; while ((line = bufferedReader.readLine()) != null) { hasher.putString(line.trim(), Charsets.UTF_8); } } catch (IOException e) { String message = "Unable to calculate checksum"; throw new FlywayException(message, e); } return hasher.hash().asInt(); }
@Override public void execute(Connection connection) throws SQLException { String scriptLocation = this.shellScriptResource.getLocationOnDisk(); try { List<String> args = new ArrayList<String>(); args.add(scriptLocation); ProcessBuilder builder = new ProcessBuilder(args); builder.redirectErrorStream(true); Process process = builder.start(); Scanner in = new Scanner(process.getInputStream()); System.out.println(StringUtils.repeat("+",200)); while (in.hasNextLine()) { System.out.println(in.nextLine()); } int returnCode = process.waitFor(); System.out.println(StringUtils.repeat("+",200)); if (returnCode != 0) { throw new FlywayException("script exited with value : " + returnCode); } } catch (Exception e) { LOG.error(e.toString()); // Only if SQLException or FlywaySqlScriptException is thrown flyway will mark the migration as failed in the metadata table throw new SQLException(String.format("Failed to run script \"%s\", %s", scriptLocation, e.getMessage()), e); } }
@Override public void execute(Connection connection) throws SQLException { String scriptLocation = this.shellScriptResource.getLocationOnDisk(); try { List<String> args = new ArrayList<String>(); args.add(scriptLocation); ProcessBuilder builder = new ProcessBuilder(args); builder.redirectErrorStream(true); Process process = builder.start(); Scanner in = new Scanner(process.getInputStream()); System.out.println(StringUtils.repeat("+",200)); while (in.hasNextLine()) { System.out.println(in.nextLine()); } int returnCode = process.waitFor(); System.out.println(StringUtils.repeat("+",200)); if (returnCode != 0) { throw new FlywayException("script exited with value : " + returnCode); } } catch (Exception e) { LOG.error(e.toString()); // Only if SQLException or FlywaySqlScriptException is thrown flyway will mark the migration as failed in the metadata table throw new SQLException(String.format("Failed to run script \"%s\", %s", scriptLocation, e.getMessage()), e); } }
@Override public void execute(Connection connection) throws SQLException { try { getSpincastFlywayMigration().migrate(connection); } catch (SQLException e) { throw e; } catch (Exception e) { throw new FlywayException("Migration failed !", e); } }
/** * Check if the pgcrypto extension is BOTH installed AND up-to-date. * <P> * This requirement is only needed for PostgreSQL databases. * It doesn't matter what schema pgcrypto is installed in, as long as it exists. * * @return true if everything is installed and up-to-date. False otherwise. */ public static boolean isPgcryptoUpToDate() { // Get our configured dataSource DataSource dataSource = DatabaseUtils.getDataSource(); try (Connection connection = dataSource.getConnection()) { Double pgcryptoInstalled = getPgcryptoInstalledVersion(connection); // Check if installed & up-to-date in this DSpace database if (pgcryptoInstalled != null && pgcryptoInstalled.compareTo(PGCRYPTO_VERSION) >= 0) { return true; } return false; } catch (SQLException e) { throw new FlywayException("Unable to determine whether 'pgcrypto' extension is up-to-date.", e); } }