Search in sources :

Example 1 with Schema

use of org.flywaydb.core.internal.database.base.Schema in project flyway by flyway.

the class ParsingContext method populate.

public void populate(Database database, Configuration configuration) {
    setDatabase(database);
    String defaultSchemaName = configuration.getDefaultSchema();
    String[] schemaNames = configuration.getSchemas();
    Schema currentSchema = getCurrentSchema(database);
    String catalog = database.getCatalog();
    String currentUser = getCurrentUser(database);
    // cf. Flyway.prepareSchemas()
    if (defaultSchemaName == null) {
        if (schemaNames.length > 0) {
            defaultSchemaName = schemaNames[0];
        } else {
            defaultSchemaName = currentSchema.getName();
        }
    }
    if (defaultSchemaName != null) {
        placeholders.put(DEFAULT_SCHEMA_PLACEHOLDER, defaultSchemaName);
    }
    if (catalog != null) {
        placeholders.put(DATABASE_PLACEHOLDER, catalog);
    }
    placeholders.put(USER_PLACEHOLDER, currentUser);
    placeholders.put(TIMESTAMP_PLACEHOLDER, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    placeholders.put(WORKING_DIRECTORY_PLACEHOLDER, System.getProperty("user.dir"));
    placeholders.put(TABLE_PLACEHOLDER, configuration.getTable());
}
Also used : Schema(org.flywaydb.core.internal.database.base.Schema) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 2 with Schema

use of org.flywaydb.core.internal.database.base.Schema in project flyway by flyway.

the class SchemaHistoryFactory method prepareSchemas.

public static Pair<Schema, List<Schema>> prepareSchemas(Configuration configuration, Database database) {
    String[] schemaNames = configuration.getSchemas();
    String defaultSchemaName = configuration.getDefaultSchema();
    LOG.debug("Schemas: " + StringUtils.arrayToCommaDelimitedString(schemaNames));
    LOG.debug("Default schema: " + defaultSchemaName);
    List<Schema> schemas = new ArrayList<>();
    for (String schemaName : schemaNames) {
        schemas.add(database.getMainConnection().getSchema(schemaName));
    }
    if (defaultSchemaName == null) {
        if (schemaNames.length == 0) {
            Schema currentSchema = database.getMainConnection().getCurrentSchema();
            if (currentSchema == null || currentSchema.getName() == null) {
                throw new FlywayException("Unable to determine schema for the schema history table. Set a default schema for the connection or specify one using the 'defaultSchema' property");
            }
            defaultSchemaName = currentSchema.getName();
        } else {
            defaultSchemaName = schemaNames[0];
        }
    }
    Schema defaultSchema = database.getMainConnection().getSchema(defaultSchemaName);
    if (!schemas.contains(defaultSchema)) {
        schemas.add(0, defaultSchema);
    }
    return Pair.of(defaultSchema, schemas);
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) Schema(org.flywaydb.core.internal.database.base.Schema) ArrayList(java.util.ArrayList)

Example 3 with Schema

use of org.flywaydb.core.internal.database.base.Schema in project flyway by flyway.

the class DbClean method clean.

protected void clean(Schema[] schemas, CleanResult cleanResult, List<String> dropSchemas) {
    dropDatabaseObjectsPreSchemas();
    List<Schema> schemaList = new ArrayList<>(Arrays.asList(schemas));
    for (int i = 0; i < schemaList.size(); ) {
        Schema schema = schemaList.get(i);
        if (!schema.exists()) {
            String unknownSchemaWarning = "Unable to clean unknown schema: " + schema;
            cleanResult.addWarning(unknownSchemaWarning);
            LOG.warn(unknownSchemaWarning);
            schemaList.remove(i);
        } else {
            i++;
        }
    }
    cleanSchemas(schemaList.toArray(new Schema[0]), dropSchemas, cleanResult);
    Collections.reverse(schemaList);
    cleanSchemas(schemaList.toArray(new Schema[0]), dropSchemas, null);
    dropDatabaseObjectsPostSchemas();
    for (Schema schema : schemas) {
        if (dropSchemas.contains(schema.getName())) {
            dropSchema(schema, cleanResult);
        }
    }
}
Also used : Schema(org.flywaydb.core.internal.database.base.Schema) ArrayList(java.util.ArrayList)

Example 4 with Schema

use of org.flywaydb.core.internal.database.base.Schema in project flyway by flyway.

the class DbSchemas method create.

/**
 * Creates the schemas.
 *
 * @param baseline Whether to include the creation of a baseline marker.
 */
public void create(final boolean baseline) {
    callbackExecutor.onEvent(Event.CREATE_SCHEMA);
    int retries = 0;
    while (true) {
        try {
            ExecutionTemplateFactory.createExecutionTemplate(connection.getJdbcConnection(), database).execute(() -> {
                List<Schema> createdSchemas = new ArrayList<>();
                for (Schema schema : schemas) {
                    if (!schema.exists()) {
                        if (schema.getName() == null) {
                            throw new FlywayException("Unable to determine schema for the schema history table." + " Set a default schema for the connection or specify one using the defaultSchema property!");
                        }
                        LOG.debug("Creating schema: " + schema);
                        schema.create();
                        createdSchemas.add(schema);
                    } else {
                        LOG.debug("Skipping creation of existing schema: " + schema);
                    }
                }
                if (!createdSchemas.isEmpty()) {
                    schemaHistory.create(baseline);
                    schemaHistory.addSchemasMarker(createdSchemas.toArray(new Schema[0]));
                }
                return null;
            });
            return;
        } catch (RuntimeException e) {
            if (++retries >= 10) {
                throw e;
            }
            try {
                LOG.debug("Schema creation failed. Retrying in 1 sec ...");
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
            // Ignore
            }
        }
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) Schema(org.flywaydb.core.internal.database.base.Schema) ArrayList(java.util.ArrayList)

Example 5 with Schema

use of org.flywaydb.core.internal.database.base.Schema in project flyway by flyway.

the class FlywayExecutor 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.
 */
public <T> T execute(Command<T> command, boolean scannerRequired) {
    T result;
    configurationValidator.validate(configuration);
    StatementInterceptor statementInterceptor = null;
    final Pair<ResourceProvider, ClassProvider<JavaMigration>> resourceProviderClassProviderPair = createResourceAndClassProviders(scannerRequired);
    final ResourceProvider resourceProvider = resourceProviderClassProviderPair.getLeft();
    final ClassProvider<JavaMigration> classProvider = resourceProviderClassProviderPair.getRight();
    final ParsingContext parsingContext = new ParsingContext();
    resourceNameValidator.validateSQLMigrationNaming(resourceProvider, configuration);
    JdbcConnectionFactory jdbcConnectionFactory = new JdbcConnectionFactory(configuration.getDataSource(), configuration, statementInterceptor);
    final DatabaseType databaseType = jdbcConnectionFactory.getDatabaseType();
    final SqlScriptFactory sqlScriptFactory = databaseType.createSqlScriptFactory(configuration, parsingContext);
    RetryStrategy.setNumberOfRetries(configuration.getLockRetryCount());
    final SqlScriptExecutorFactory noCallbackSqlScriptExecutorFactory = databaseType.createSqlScriptExecutorFactory(jdbcConnectionFactory, NoopCallbackExecutor.INSTANCE, null);
    jdbcConnectionFactory.setConnectionInitializer((jdbcConnectionFactory1, connection) -> {
        if (configuration.getInitSql() == null) {
            return;
        }
        StringResource resource = new StringResource(configuration.getInitSql());
        SqlScript sqlScript = sqlScriptFactory.createSqlScript(resource, true, resourceProvider);
        boolean outputQueryResults = false;
        noCallbackSqlScriptExecutorFactory.createSqlScriptExecutor(connection, false, false, outputQueryResults).execute(sqlScript);
    });
    Database database = null;
    try {
        VersionPrinter.printVersion();
        database = databaseType.createDatabase(configuration, !dbConnectionInfoPrinted, jdbcConnectionFactory, statementInterceptor);
        databaseType.printMessages();
        dbConnectionInfoPrinted = true;
        LOG.debug("DDL Transactions Supported: " + database.supportsDdlTransactions());
        Pair<Schema, List<Schema>> schemas = SchemaHistoryFactory.prepareSchemas(configuration, database);
        Schema defaultSchema = schemas.getLeft();
        parsingContext.populate(database, configuration);
        database.ensureSupported();
        DefaultCallbackExecutor callbackExecutor = new DefaultCallbackExecutor(configuration, database, defaultSchema, prepareCallbacks(database, resourceProvider, jdbcConnectionFactory, sqlScriptFactory, statementInterceptor, defaultSchema, parsingContext));
        SqlScriptExecutorFactory sqlScriptExecutorFactory = databaseType.createSqlScriptExecutorFactory(jdbcConnectionFactory, callbackExecutor, statementInterceptor);
        SchemaHistory schemaHistory = SchemaHistoryFactory.getSchemaHistory(configuration, noCallbackSqlScriptExecutorFactory, sqlScriptFactory, database, defaultSchema, statementInterceptor);
        result = command.execute(createMigrationResolver(resourceProvider, classProvider, sqlScriptExecutorFactory, sqlScriptFactory, parsingContext), schemaHistory, database, defaultSchema, schemas.getRight().toArray(new Schema[0]), callbackExecutor, statementInterceptor);
    } finally {
        IOUtils.close(database);
        showMemoryUsage();
    }
    return result;
}
Also used : JdbcConnectionFactory(org.flywaydb.core.internal.jdbc.JdbcConnectionFactory) SqlScriptExecutorFactory(org.flywaydb.core.internal.sqlscript.SqlScriptExecutorFactory) ParsingContext(org.flywaydb.core.internal.parser.ParsingContext) DatabaseType(org.flywaydb.core.internal.database.DatabaseType) SqlScriptFactory(org.flywaydb.core.internal.sqlscript.SqlScriptFactory) Schema(org.flywaydb.core.internal.database.base.Schema) SchemaHistory(org.flywaydb.core.internal.schemahistory.SchemaHistory) StringResource(org.flywaydb.core.internal.resource.StringResource) ResourceProvider(org.flywaydb.core.api.ResourceProvider) NoopResourceProvider(org.flywaydb.core.internal.resource.NoopResourceProvider) ClassProvider(org.flywaydb.core.api.ClassProvider) NoopClassProvider(org.flywaydb.core.internal.clazz.NoopClassProvider) Database(org.flywaydb.core.internal.database.base.Database) SqlScript(org.flywaydb.core.internal.sqlscript.SqlScript) JavaMigration(org.flywaydb.core.api.migration.JavaMigration) ArrayList(java.util.ArrayList) List(java.util.List) StatementInterceptor(org.flywaydb.core.internal.jdbc.StatementInterceptor)

Aggregations

Schema (org.flywaydb.core.internal.database.base.Schema)5 ArrayList (java.util.ArrayList)4 FlywayException (org.flywaydb.core.api.FlywayException)2 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 List (java.util.List)1 ClassProvider (org.flywaydb.core.api.ClassProvider)1 ResourceProvider (org.flywaydb.core.api.ResourceProvider)1 JavaMigration (org.flywaydb.core.api.migration.JavaMigration)1 NoopClassProvider (org.flywaydb.core.internal.clazz.NoopClassProvider)1 DatabaseType (org.flywaydb.core.internal.database.DatabaseType)1 Database (org.flywaydb.core.internal.database.base.Database)1 JdbcConnectionFactory (org.flywaydb.core.internal.jdbc.JdbcConnectionFactory)1 StatementInterceptor (org.flywaydb.core.internal.jdbc.StatementInterceptor)1 ParsingContext (org.flywaydb.core.internal.parser.ParsingContext)1 NoopResourceProvider (org.flywaydb.core.internal.resource.NoopResourceProvider)1 StringResource (org.flywaydb.core.internal.resource.StringResource)1 SchemaHistory (org.flywaydb.core.internal.schemahistory.SchemaHistory)1 SqlScript (org.flywaydb.core.internal.sqlscript.SqlScript)1 SqlScriptExecutorFactory (org.flywaydb.core.internal.sqlscript.SqlScriptExecutorFactory)1