Search in sources :

Example 76 with FlywayException

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

the class MigrationInfoHelper method extractVersionAndDescription.

/**
 * Extracts the schema version and the description from a migration name formatted as 1_2__Description.
 *
 * @param migrationName The migration name to parse. Should not contain any folders or packages.
 * @param prefix The migration prefix.
 * @param separator The migration separator.
 * @param suffixes The migration suffixes.
 * @param repeatable Whether this is a repeatable migration.
 * @return The extracted schema version.
 * @throws FlywayException if the migration name does not follow the standard conventions.
 */
public static Pair<MigrationVersion, String> extractVersionAndDescription(String migrationName, String prefix, String separator, String[] suffixes, boolean repeatable) {
    // Only handles Java migrations now
    String cleanMigrationName = cleanMigrationName(migrationName, prefix, suffixes);
    int separatorPos = cleanMigrationName.indexOf(separator);
    String version;
    String description;
    if (separatorPos < 0) {
        version = cleanMigrationName;
        description = "";
    } else {
        version = cleanMigrationName.substring(0, separatorPos);
        description = cleanMigrationName.substring(separatorPos + separator.length()).replace("_", " ");
    }
    if (StringUtils.hasText(version)) {
        if (repeatable) {
            throw new FlywayException("Wrong repeatable migration name format: " + migrationName + " (It cannot contain a version and should look like this: " + prefix + separator + description + suffixes[0] + ")");
        }
        try {
            return Pair.of(MigrationVersion.fromVersion(version), description);
        } catch (Exception e) {
            throw new FlywayException("Wrong versioned migration name format: " + migrationName + " (could not recognise version number " + version + ")", e);
        }
    }
    if (!repeatable) {
        throw new FlywayException("Wrong versioned migration name format: " + migrationName + " (It must contain a version and should look like this: " + prefix + "1.2" + separator + description + suffixes[0] + ")");
    }
    return Pair.of(null, description);
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) FlywayException(org.flywaydb.core.api.FlywayException)

Example 77 with FlywayException

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

the class Migrator 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 (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);
    }
}
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 78 with FlywayException

use of org.flywaydb.core.api.FlywayException in project dhis2-core by dhis2.

the class V2_33_1__Job_configuration_job_type_column_to_varchar method migrate.

@Override
public void migrate(final Context context) throws Exception {
    // 1. Check whether migration is needed at all. Maybe it was already
    // applied. -> Achieves that script can be
    // run multiple times without worries
    boolean continueWithMigration = false;
    String sql = "SELECT data_type FROM information_schema.columns " + "WHERE table_name = 'jobconfiguration' AND column_name = 'jobtype';";
    try (Statement stmt = context.getConnection().createStatement();
        ResultSet rs = stmt.executeQuery(sql)) {
        if (rs.next() && rs.getString("data_type").equals("bytea")) {
            continueWithMigration = true;
        }
    }
    if (continueWithMigration) {
        // jobconfiguration table
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration ADD COLUMN IF NOT EXISTS jobtypevarchar VARCHAR(120)");
        }
        // 3. Move existing jobtype from bytearray column into varchar
        // column
        Map<Integer, byte[]> jobTypeByteMap = new HashMap<>();
        sql = "SELECT jobconfigurationid, jobtype FROM jobconfiguration WHERE jobtype IS NOT NULL";
        try (Statement stmt = context.getConnection().createStatement();
            ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                jobTypeByteMap.put(rs.getInt("jobconfigurationid"), rs.getBytes("jobtype"));
            }
        }
        jobTypeByteMap.forEach((id, jobTypeByteArray) -> {
            JobType jobType = (JobType) SerializationUtils.deserialize(jobTypeByteArray);
            if (jobType == null) {
                log.error("Flyway java migration error: Parsing JobType byte array failed.");
                throw new FlywayException("Parsing JobType byte array failed.");
            }
            try (PreparedStatement ps = context.getConnection().prepareStatement("UPDATE jobconfiguration SET jobtypevarchar = ? WHERE jobconfigurationid = ?")) {
                ps.setObject(1, jobType.name());
                ps.setInt(2, id);
                ps.execute();
            } catch (SQLException e) {
                log.error("Flyway java migration error:", e);
                throw new FlywayException(e);
            }
        });
        // table
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration DROP COLUMN jobtype");
        }
        // deleted column
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration RENAME COLUMN jobtypevarchar TO jobtype");
        }
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) JobType(org.hisp.dhis.scheduling.JobType) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 79 with FlywayException

use of org.flywaydb.core.api.FlywayException in project dhis2-core by dhis2.

the class V2_34_5__Convert_job_configuration_binary_columns_into_varchar_data_type method migrateLastExecutedStatusColumn.

private void migrateLastExecutedStatusColumn(final Context context) throws Exception {
    // 1. Check whether migration is needed at all. Maybe it was already
    // applied. -> Achieves that script can be
    // run multiple times without worries
    boolean continueWithMigration = false;
    try (Statement stmt = context.getConnection().createStatement();
        ResultSet rs = stmt.executeQuery(CHECK_LAST_EXECUTED_STATUS_DATA_TYPE_SQL)) {
        if (rs.next() && rs.getString("data_type").equals("bytea")) {
            continueWithMigration = true;
        }
    }
    if (continueWithMigration) {
        // jobconfiguration table
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration ADD COLUMN IF NOT EXISTS lastexecutedstatusvarchar VARCHAR(120)");
        }
        // 3. Move existing lastexecutedstatus from bytearray column into
        // varchar column
        Map<Integer, byte[]> lastExecutedStatusByteMap = new HashMap<>();
        String sql = "SELECT jobconfigurationid, lastexecutedstatus FROM jobconfiguration " + "WHERE lastexecutedstatus IS NOT NULL";
        try (Statement stmt = context.getConnection().createStatement();
            ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                lastExecutedStatusByteMap.put(rs.getInt("jobconfigurationid"), rs.getBytes("lastexecutedstatus"));
            }
        }
        lastExecutedStatusByteMap.forEach((id, lastExecutedStatusByteArray) -> {
            JobStatus lastExecutedStatus = (JobStatus) SerializationUtils.deserialize(lastExecutedStatusByteArray);
            if (lastExecutedStatus == null) {
                log.error("Flyway java migration error: Parsing LastExecutedStatus byte array failed.");
                throw new FlywayException("Parsing LastExecutedStatus byte array failed.");
            }
            try (PreparedStatement ps = context.getConnection().prepareStatement("UPDATE jobconfiguration SET lastexecutedstatusvarchar = ? WHERE jobconfigurationid = ?")) {
                ps.setObject(1, lastExecutedStatus.name());
                ps.setInt(2, id);
                ps.execute();
            } catch (SQLException e) {
                log.error("Flyway java migration error:", e);
                throw new FlywayException(e);
            }
        });
        // jobconfiguration table
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration DROP COLUMN lastexecutedstatus");
        }
        // now deleted column
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("ALTER TABLE jobconfiguration RENAME COLUMN lastexecutedstatusvarchar TO lastexecutedstatus");
        }
        // 6. Set default values where NULL is present
        try (Statement stmt = context.getConnection().createStatement()) {
            stmt.executeUpdate("UPDATE jobconfiguration SET lastexecutedstatus = 'NOT_STARTED' WHERE lastexecutedstatus IS NULL");
        }
    }
}
Also used : JobStatus(org.hisp.dhis.scheduling.JobStatus) FlywayException(org.flywaydb.core.api.FlywayException) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 80 with FlywayException

use of org.flywaydb.core.api.FlywayException in project dhis2-core by dhis2.

the class V2_31_2__Job_configuration_param_to_jsonb method migrate.

public void migrate(Context context) throws Exception {
    ObjectMapper MAPPER = new ObjectMapper();
    MAPPER.enableDefaultTyping();
    MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    writer = MAPPER.writerFor(JobParameters.class);
    // 1. Create new jsonb column for jobparameters in jobconfiguration
    try (Statement stmt = context.getConnection().createStatement()) {
        stmt.executeUpdate("ALTER TABLE jobconfiguration ADD COLUMN IF NOT EXISTS jsonbjobparameters jsonb");
    }
    // 2. Move existing jobparameters from bytearray column into jsonb
    // column
    Map<Integer, byte[]> jobParamByteMap = new HashMap<>();
    Map<Integer, byte[]> jobTypeByteMap = new HashMap<>();
    try (Statement stmt = context.getConnection().createStatement()) {
        try (ResultSet rows = stmt.executeQuery("select jobconfigurationid,jobparameters,jobtype from jobconfiguration where jobparameters is not null")) {
            while (rows.next()) {
                jobParamByteMap.put(rows.getInt(1), rows.getBytes(2));
                jobTypeByteMap.put(rows.getInt(1), rows.getBytes(3));
            }
        }
    }
    jobParamByteMap.forEach((id, jobParamByteArray) -> {
        Object jParaB = null;
        JobType jobType = null;
        try {
            jParaB = toObject(jobParamByteArray);
            jobType = (JobType) toObject(jobTypeByteMap.get(id));
        } catch (IOException | ClassNotFoundException e) {
            log.error("Flyway java migration error:", e);
            throw new FlywayException(e);
        }
        try (PreparedStatement ps = context.getConnection().prepareStatement("Update jobconfiguration set jsonbjobparameters =? where  jobconfigurationid = ?")) {
            PGobject pg = new PGobject();
            pg.setType("jsonb");
            pg.setValue(convertObjectToJson(jobType.getJobParameters().cast(jParaB)));
            ps.setObject(1, pg);
            ps.setInt(2, id);
            ps.execute();
        } catch (SQLException e) {
            log.error("Flyway java migration error:", e);
            throw new FlywayException(e);
        }
    });
    // 3. Delete old byte array column for jobparameters in jobconfiguration
    try (Statement stmt = context.getConnection().createStatement()) {
        stmt.executeUpdate("ALTER TABLE jobconfiguration DROP COLUMN IF EXISTS jobparameters");
    }
}
Also used : FlywayException(org.flywaydb.core.api.FlywayException) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) PGobject(org.postgresql.util.PGobject) JobType(org.hisp.dhis.scheduling.JobType) ResultSet(java.sql.ResultSet) JobParameters(org.hisp.dhis.scheduling.JobParameters) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

FlywayException (org.flywaydb.core.api.FlywayException)82 SQLException (java.sql.SQLException)22 IOException (java.io.IOException)17 ArrayList (java.util.ArrayList)14 PreparedStatement (java.sql.PreparedStatement)8 HashMap (java.util.HashMap)8 URL (java.net.URL)7 ResultSet (java.sql.ResultSet)7 Statement (java.sql.Statement)7 File (java.io.File)6 MigrationVersion (org.flywaydb.core.api.MigrationVersion)6 ResolvedMigrationImpl (org.flywaydb.core.internal.resolver.ResolvedMigrationImpl)6 Test (org.junit.Test)6 InputStreamReader (java.io.InputStreamReader)5 Method (java.lang.reflect.Method)5 BufferedReader (java.io.BufferedReader)4 FileInputStream (java.io.FileInputStream)4 Reader (java.io.Reader)4 StringReader (java.io.StringReader)4 URLClassLoader (java.net.URLClassLoader)4