Search in sources :

Example 16 with FlywayException

use of org.flywaydb.core.api.FlywayException in project flyway by flyway.

the class AbstractFlywayMojo method loadCredentialsFromSettings.

/**
     * 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");
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) Server(org.apache.maven.settings.Server) SecDispatcher(org.sonatype.plexus.components.sec.dispatcher.SecDispatcher) DefaultSecDispatcher(org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher) DefaultPlexusCipher(org.sonatype.plexus.components.cipher.DefaultPlexusCipher) DefaultSecDispatcher(org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher) SecDispatcherException(org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException) PlexusCipherException(org.sonatype.plexus.components.cipher.PlexusCipherException)

Example 17 with FlywayException

use of org.flywaydb.core.api.FlywayException in project flyway by flyway.

the class Main method loadConfigurationFile.

/**
     * 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 (<install-dir>/conf/flyway.conf) 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(Properties properties, String file, String encoding, boolean failIfMissing) throws FlywayException {
    File configFile = new File(file);
    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 {
        String contents = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(configFile), encoding));
        properties.load(new StringReader(contents.replace("\\", "\\\\")));
        return true;
    } catch (IOException e) {
        throw new FlywayException(errorMessage, e);
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 18 with FlywayException

use of org.flywaydb.core.api.FlywayException in project flyway by flyway.

the class Main method main.

/**
     * Main method.
     *
     * @param args The command-line arguments.
     */
public static void main(String[] args) {
    Level logLevel = getLogLevel(args);
    initLogging(logLevel);
    try {
        printVersion();
        if (isPrintVersionAndExit(args)) {
            System.exit(0);
        }
        List<String> operations = determineOperations(args);
        if (operations.isEmpty()) {
            printUsage();
            return;
        }
        Properties properties = new Properties();
        initializeDefaults(properties);
        loadConfiguration(properties, args);
        overrideConfiguration(properties, args);
        if (!isSuppressPrompt(args)) {
            promptForCredentialsIfMissing(properties);
        }
        dumpConfiguration(properties);
        loadJdbcDrivers();
        loadJavaMigrationsFromJarDirs(properties);
        Flyway flyway = new Flyway();
        filterProperties(properties);
        flyway.configure(properties);
        for (String operation : operations) {
            executeOperation(flyway, operation);
        }
    } catch (Exception e) {
        if (logLevel == Level.DEBUG) {
            LOG.error("Unexpected error", e);
        } else {
            if (e instanceof FlywayException) {
                LOG.error(e.getMessage());
            } else {
                LOG.error(e.toString());
            }
        }
        System.exit(1);
    }
}
Also used : Flyway(org.flywaydb.core.Flyway) FlywayException(org.flywaydb.core.api.FlywayException) Level(org.flywaydb.core.internal.util.logging.console.ConsoleLog.Level) Properties(java.util.Properties) FlywayException(org.flywaydb.core.api.FlywayException) IOException(java.io.IOException)

Example 19 with FlywayException

use of org.flywaydb.core.api.FlywayException in project flyway by flyway.

the class Flyway method execute.

/**
     * Executes this command with proper resource handling and cleanup.
     *
     * @param command The command to execute.
     * @param <T>     The type of the result.
     * @return The result of the command.
     */
/*private -> testing*/
<T> T execute(Command<T> command) {
    T result;
    VersionPrinter.printVersion();
    Connection connectionMetaDataTable = null;
    try {
        if (dataSource == null) {
            throw new FlywayException("Unable to connect to the database. Configure the url, user and password!");
        }
        connectionMetaDataTable = JdbcUtils.openConnection(dataSource);
        DbSupport dbSupport = DbSupportFactory.createDbSupport(connectionMetaDataTable, !dbConnectionInfoPrinted);
        dbConnectionInfoPrinted = true;
        LOG.debug("DDL Transactions Supported: " + dbSupport.supportsDdlTransactions());
        if (schemaNames.length == 0) {
            Schema currentSchema = dbSupport.getOriginalSchema();
            if (currentSchema == null) {
                throw new FlywayException("Unable to determine schema for the metadata table." + " Set a default schema for the connection or specify one using the schemas property!");
            }
            setSchemas(currentSchema.getName());
        }
        if (schemaNames.length == 1) {
            LOG.debug("Schema: " + schemaNames[0]);
        } else {
            LOG.debug("Schemas: " + StringUtils.arrayToCommaDelimitedString(schemaNames));
        }
        Schema[] schemas = new Schema[schemaNames.length];
        for (int i = 0; i < schemaNames.length; i++) {
            schemas[i] = dbSupport.getSchema(schemaNames[i]);
        }
        Scanner scanner = new Scanner(classLoader);
        MigrationResolver migrationResolver = createMigrationResolver(dbSupport, scanner);
        if (!skipDefaultCallbacks) {
            Set<FlywayCallback> flywayCallbacks = new LinkedHashSet<FlywayCallback>(Arrays.asList(callbacks));
            flywayCallbacks.add(new SqlScriptFlywayCallback(dbSupport, scanner, locations, createPlaceholderReplacer(), this));
            callbacks = flywayCallbacks.toArray(new FlywayCallback[flywayCallbacks.size()]);
        }
        for (FlywayCallback callback : callbacks) {
            ConfigurationInjectionUtils.injectFlywayConfiguration(callback, this);
        }
        MetaDataTable metaDataTable = new MetaDataTableImpl(dbSupport, schemas[0].getTable(table), installedBy);
        if (metaDataTable.upgradeIfNecessary()) {
            new DbRepair(dbSupport, connectionMetaDataTable, schemas[0], migrationResolver, metaDataTable, callbacks).repairChecksumsAndDescriptions();
            LOG.info("Metadata table " + table + " successfully upgraded to the Flyway 4.0 format.");
        }
        result = command.execute(connectionMetaDataTable, migrationResolver, metaDataTable, dbSupport, schemas, callbacks);
    } finally {
        JdbcUtils.closeConnection(connectionMetaDataTable);
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) FlywayException(org.flywaydb.core.api.FlywayException) Scanner(org.flywaydb.core.internal.util.scanner.Scanner) MetaDataTable(org.flywaydb.core.internal.metadatatable.MetaDataTable) Schema(org.flywaydb.core.internal.dbsupport.Schema) Connection(java.sql.Connection) DbRepair(org.flywaydb.core.internal.command.DbRepair) MetaDataTableImpl(org.flywaydb.core.internal.metadatatable.MetaDataTableImpl) SqlScriptFlywayCallback(org.flywaydb.core.internal.callback.SqlScriptFlywayCallback) FlywayCallback(org.flywaydb.core.api.callback.FlywayCallback) SqlScriptFlywayCallback(org.flywaydb.core.internal.callback.SqlScriptFlywayCallback) DbSupport(org.flywaydb.core.internal.dbsupport.DbSupport) MigrationResolver(org.flywaydb.core.api.resolver.MigrationResolver) CompositeMigrationResolver(org.flywaydb.core.internal.resolver.CompositeMigrationResolver)

Example 20 with FlywayException

use of org.flywaydb.core.api.FlywayException in project flyway by flyway.

the class OracleSchema method doClean.

@Override
protected void doClean() throws SQLException {
    if ("SYSTEM".equals(name.toUpperCase())) {
        throw new FlywayException("Clean not supported on Oracle for user 'SYSTEM'! You should NEVER add your own objects to the SYSTEM schema!");
    }
    String user = dbSupport.doGetCurrentSchemaName();
    boolean defaultSchemaForUser = user.equalsIgnoreCase(name);
    if (!defaultSchemaForUser) {
        LOG.warn("Cleaning schema " + name + " by a different user (" + user + "): " + "spatial extensions, queue tables, flashback tables and scheduled jobs will not be cleaned due to Oracle limitations");
    }
    for (String statement : generateDropStatementsForSpatialExtensions(defaultSchemaForUser)) {
        jdbcTemplate.execute(statement);
    }
    if (defaultSchemaForUser) {
        for (String statement : generateDropStatementsForQueueTables()) {
            try {
                jdbcTemplate.execute(statement);
            } catch (SQLException e) {
                if (e.getErrorCode() == 65040) {
                    //for dropping queue tables, a special grant is required:
                    //GRANT EXECUTE ON DBMS_AQADM TO flyway;
                    LOG.error("Missing required grant to clean queue tables: GRANT EXECUTE ON DBMS_AQADM");
                }
                throw e;
            }
        }
        if (flashbackAvailable()) {
            executeAlterStatementsForFlashbackTables();
        }
    }
    for (String statement : generateDropStatementsForScheduledJobs()) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("TRIGGER", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("SEQUENCE", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("FUNCTION", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("MATERIALIZED VIEW", "PRESERVE TABLE")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("PACKAGE", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("PROCEDURE", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("SYNONYM", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("VIEW", "CASCADE CONSTRAINTS")) {
        jdbcTemplate.execute(statement);
    }
    for (Table table : allTables()) {
        table.drop();
    }
    for (String statement : generateDropStatementsForXmlTables()) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("CLUSTER", "")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("TYPE", "FORCE")) {
        jdbcTemplate.execute(statement);
    }
    for (String statement : generateDropStatementsForObjectType("JAVA SOURCE", "")) {
        jdbcTemplate.execute(statement);
    }
    jdbcTemplate.execute("PURGE RECYCLEBIN");
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) Table(org.flywaydb.core.internal.dbsupport.Table) SQLException(java.sql.SQLException)

Aggregations

FlywayException (org.flywaydb.core.api.FlywayException)42 IOException (java.io.IOException)13 SQLException (java.sql.SQLException)11 ArrayList (java.util.ArrayList)6 MigrationVersion (org.flywaydb.core.api.MigrationVersion)6 Test (org.junit.Test)6 File (java.io.File)5 InputStreamReader (java.io.InputStreamReader)5 ResolvedMigrationImpl (org.flywaydb.core.internal.resolver.ResolvedMigrationImpl)5 FileInputStream (java.io.FileInputStream)4 ResolvedMigration (org.flywaydb.core.api.resolver.ResolvedMigration)4 StringReader (java.io.StringReader)3 Method (java.lang.reflect.Method)3 URL (java.net.URL)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 HashMap (java.util.HashMap)3 Properties (java.util.Properties)3 FlywayCallback (org.flywaydb.core.api.callback.FlywayCallback)3 DriverDataSource (org.flywaydb.core.internal.util.jdbc.DriverDataSource)3 TransactionTemplate (org.flywaydb.core.internal.util.jdbc.TransactionTemplate)3