Search in sources :

Example 1 with FileSystemResourceAccessor

use of liquibase.resource.FileSystemResourceAccessor in project liquibase by liquibase.

the class ConvertCommand method run.

@Override
protected CommandResult run() throws Exception {
    List<ResourceAccessor> openers = new ArrayList<ResourceAccessor>();
    openers.add(new FileSystemResourceAccessor());
    openers.add(new ClassLoaderResourceAccessor());
    if (classpath != null) {
        openers.add(new FileSystemResourceAccessor(classpath));
    }
    ResourceAccessor resourceAccessor = new CompositeResourceAccessor(openers);
    ChangeLogParser sourceParser = ChangeLogParserFactory.getInstance().getParser(src, resourceAccessor);
    ChangeLogSerializer outSerializer = ChangeLogSerializerFactory.getInstance().getSerializer(out);
    DatabaseChangeLog changeLog = sourceParser.parse(src, new ChangeLogParameters(), resourceAccessor);
    File outFile = new File(out);
    if (!outFile.exists()) {
        outFile.getParentFile().mkdirs();
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    try {
        outSerializer.write(changeLog.getChangeSets(), outputStream);
    } finally {
        outputStream.flush();
        outputStream.close();
    }
    return new CommandResult("Converted successfully");
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ArrayList(java.util.ArrayList) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) CommandResult(liquibase.command.CommandResult) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ChangeLogParameters(liquibase.changelog.ChangeLogParameters) ChangeLogParser(liquibase.parser.ChangeLogParser) FileOutputStream(java.io.FileOutputStream) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) File(java.io.File)

Example 2 with FileSystemResourceAccessor

use of liquibase.resource.FileSystemResourceAccessor in project Singularity by HubSpot.

the class SingularityHistoryTest method createTestData.

@Before
public void createTestData() throws Exception {
    Handle handle = dbiProvider.get().open();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(handle.getConnection()));
    Liquibase liquibase = new Liquibase("singularity_test.sql", new FileSystemResourceAccessor(), database);
    liquibase.update((String) null);
    try {
        database.close();
    } catch (Throwable t) {
    }
    handle.close();
}
Also used : Liquibase(liquibase.Liquibase) Database(liquibase.database.Database) JdbcConnection(liquibase.database.jvm.JdbcConnection) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) Handle(org.skife.jdbi.v2.Handle) Before(org.junit.Before)

Example 3 with FileSystemResourceAccessor

use of liquibase.resource.FileSystemResourceAccessor in project openmrs-core by openmrs.

the class DatabaseUpdater method getLiquibase.

/**
 * Get a connection to the database through Liquibase. The calling method /must/ close the
 * database connection when finished with this Liquibase object.
 * liquibase.getDatabase().getConnection().close()
 *
 * @param changeLogFile the name of the file to look for the on classpath or filesystem
 * @param cl the {@link ClassLoader} to use to find the file (or null to use
 *            {@link OpenmrsClassLoader})
 * @return Liquibase object based on the current connection settings
 * @throws Exception
 */
private static Liquibase getLiquibase(String changeLogFile, ClassLoader cl) throws Exception {
    Connection connection;
    try {
        connection = getConnection();
    } catch (SQLException e) {
        throw new Exception("Unable to get a connection to the database.  Please check your openmrs runtime properties file and make sure you have the correct connection.username and connection.password set", e);
    }
    if (cl == null) {
        cl = OpenmrsClassLoader.getInstance();
    }
    try {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        database.setDatabaseChangeLogTableName("liquibasechangelog");
        database.setDatabaseChangeLogLockTableName("liquibasechangeloglock");
        if (connection.getMetaData().getDatabaseProductName().contains("HSQL Database Engine") || connection.getMetaData().getDatabaseProductName().contains("H2")) {
            // a hack because hsqldb and h2 seem to be checking table names in the metadata section case sensitively
            database.setDatabaseChangeLogTableName(database.getDatabaseChangeLogTableName().toUpperCase());
            database.setDatabaseChangeLogLockTableName(database.getDatabaseChangeLogLockTableName().toUpperCase());
        }
        ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl);
        ResourceAccessor fsFO = new FileSystemResourceAccessor();
        if (changeLogFile == null) {
            changeLogFile = CHANGE_LOG_FILE;
        }
        database.checkDatabaseChangeLogTable(false, null, null);
        return new Liquibase(changeLogFile, new CompositeResourceAccessor(openmrsFO, fsFO), database);
    } catch (Exception e) {
        // if an error occurs, close the connection
        if (connection != null) {
            connection.close();
        }
        throw e;
    }
}
Also used : Liquibase(liquibase.Liquibase) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) SQLException(java.sql.SQLException) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) Database(liquibase.database.Database) JdbcConnection(liquibase.database.jvm.JdbcConnection) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) LockException(liquibase.exception.LockException) SQLException(java.sql.SQLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 4 with FileSystemResourceAccessor

use of liquibase.resource.FileSystemResourceAccessor in project traccar by traccar.

the class DataManager method initDatabaseSchema.

private void initDatabaseSchema() throws SQLException, LiquibaseException {
    if (config.hasKey("database.changelog")) {
        ResourceAccessor resourceAccessor = new FileSystemResourceAccessor();
        Database database = DatabaseFactory.getInstance().openDatabase(config.getString("database.url"), config.getString("database.user"), config.getString("database.password"), null, resourceAccessor);
        Liquibase liquibase = new Liquibase(config.getString("database.changelog"), resourceAccessor, database);
        liquibase.clearCheckSums();
        liquibase.update(new Contexts());
    }
}
Also used : Liquibase(liquibase.Liquibase) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) Database(liquibase.database.Database) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) Contexts(liquibase.Contexts)

Example 5 with FileSystemResourceAccessor

use of liquibase.resource.FileSystemResourceAccessor in project stdlib by petergeneric.

the class LiquibaseCore method executeAction.

/**
 * Executes the Liquibase update.
 */
private static void executeAction(InitialContext jndi, GuiceApplicationValueContainer config, Map<String, String> parameters, LiquibaseAction action) throws NamingException, SQLException, LiquibaseException, IOException, ParserConfigurationException {
    // N.B. liquibase may create a databasechangeloglock / databasechangelog table if one does not already exist
    if (action.isWriteAction() && StringUtils.equalsIgnoreCase("true", config.getValue(HIBERNATE_IS_READONLY))) {
        log.info("Changing liquibase action from " + action + " to ASSERT_UPDATED because hibernate is set to read only mode");
        action = LiquibaseAction.ASSERT_UPDATED;
    }
    // Fail if hbm2ddl is enabled (Hibernate should not be involved in schema management)
    if (StringUtils.isNotEmpty(config.getValue(HIBERNATE_SCHEMA_MANAGEMENT)) && action != LiquibaseAction.GENERATE_CHANGELOG) {
        throw new RuntimeException("Liquibase is enabled but so is " + HIBERNATE_SCHEMA_MANAGEMENT + ". Only one of these schema management methods may be used at a time.");
    }
    final String dataSourceName = config.getDataSource();
    final String changeLogFile = config.getValue(GuiceProperties.LIQUIBASE_CHANGELOG);
    final String contexts = config.getValue(GuiceProperties.LIQUIBASE_CONTEXTS);
    final String labels = config.getValue(GuiceProperties.LIQUIBASE_LABELS);
    final String defaultSchema = config.getDefaultSchema();
    final String jdbcUrl = config.getValue(AvailableSettings.URL);
    final String jdbcUsername = config.getValue(AvailableSettings.USER);
    final String jdbcPassword = config.getValue(AvailableSettings.PASS);
    if (StringUtils.isEmpty(dataSourceName) && StringUtils.isEmpty(jdbcUrl))
        throw new RuntimeException("Cannot run Liquibase: no JNDI datasource or JDBC URL set");
    else if (changeLogFile == null)
        throw new RuntimeException("Cannot run Liquibase: " + GuiceProperties.LIQUIBASE_CHANGELOG + " is not set");
    int storedTransactionIsolation = Integer.MIN_VALUE;
    Connection connection = null;
    Database database = null;
    try {
        // Set up the resource accessor
        final ResourceAccessor resourceAccessor;
        {
            final CompositeResourceAccessor composite;
            {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                ResourceAccessor threadClFO = new ClassLoaderResourceAccessor(contextClassLoader);
                ResourceAccessor clFO = new ClassLoaderResourceAccessor();
                ResourceAccessor fsFO = new FileSystemResourceAccessor();
                composite = new CompositeResourceAccessor(clFO, fsFO, threadClFO);
            }
            // If loading a resource with an absolute path fails, re-try it as a path relative to /
            // This is for unit tests where /liquibase/changelog.xml needs to be accessed as liquibase/changelog.xml
            final ResourceAccessor fallback = new RetryAbsoluteAsRelativeResourceAccessor(composite);
            // Wrap the resource accessor in a filter that interprets ./ as the changeLogFile folder
            resourceAccessor = new RelativePathFilteringResourceAccessor(fallback, changeLogFile);
        }
        // Set up the database
        {
            if (StringUtils.isNotEmpty(dataSourceName)) {
                if (log.isDebugEnabled())
                    log.debug("Look up datasource for liquibase: " + dataSourceName);
                final DataSource dataSource = (DataSource) jndi.lookup(dataSourceName);
                connection = dataSource.getConnection();
            } else {
                if (log.isDebugEnabled())
                    log.debug("Create JDBC Connection directly: " + jdbcUrl);
                // N.B. do we need to call Class.forName on the JDBC Driver URL?
                // JDBC drivers should expose themselves using the service provider interface nowadays so this shouldn't be necessary
                connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
            }
            // Allow changing the transaction isolation away from the default for liquibase
            // This is a hack inserted for SQL Server where the SNAPSHOT isolation is being used
            // because in this mode it refuses to execute certain DDL statements because of metadata not being versioned
            {
                storedTransactionIsolation = connection.getTransactionIsolation();
                // In this case we change to READ UNCOMMITTED for the duration of the liquibase run
                if (storedTransactionIsolation == 4096) {
                    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                }
            }
            database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            database.setDefaultSchemaName(defaultSchema);
        }
        Liquibase liquibase = new Liquibase(changeLogFile, resourceAccessor, database);
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            liquibase.setChangeLogParameter(param.getKey(), param.getValue());
        }
        if (log.isDebugEnabled())
            log.debug("Execute liquibase action: " + action);
        switch(action) {
            case ASSERT_UPDATED:
                // Figure out which changesets need to be run
                List<ChangeSet> unrun = liquibase.listUnrunChangeSets(new Contexts(contexts), new LabelExpression(labels));
                if (log.isDebugEnabled())
                    log.debug("Pending changesets: " + unrun);
                // If any need to be run, fail
                if (unrun.size() > 0)
                    throw new LiquibaseChangesetsPending(unrun);
                else
                    return;
            case UPDATE:
                // Perform a schema update
                liquibase.update(new Contexts(contexts), new LabelExpression(labels));
                return;
            case MARK_UPDATED:
                // Mark all pending changesets as run
                liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels));
                return;
            case GENERATE_CHANGELOG:
                CatalogAndSchema catalogueAndSchema = CatalogAndSchema.DEFAULT;
                DiffToChangeLog writer = new DiffToChangeLog(new DiffOutputControl(false, false, false, new CompareControl.SchemaComparison[0]));
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                PrintStream pw = new PrintStream(bos);
                liquibase.generateChangeLog(catalogueAndSchema, writer, pw);
                System.out.println("********** GENERATED CHANGELOG START **********");
                System.out.println(new String(bos.toByteArray()));
                System.out.println("********** GENERATED CHANGELOG END **********");
                break;
            default:
                throw new RuntimeException("Unknown liquibase action: " + action);
        }
    } finally {
        // N.B. we don't return to isolations < 0 (isolation at db defaults)
        if (connection != null && connection.getTransactionIsolation() != storedTransactionIsolation && storedTransactionIsolation >= 0) {
            connection.setTransactionIsolation(storedTransactionIsolation);
        }
        if (database != null)
            database.close();
        else if (connection != null)
            connection.close();
    }
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) JdbcConnection(liquibase.database.jvm.JdbcConnection) Contexts(liquibase.Contexts) Database(liquibase.database.Database) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) ChangeSet(liquibase.changelog.ChangeSet) PrintStream(java.io.PrintStream) LiquibaseChangesetsPending(com.peterphi.std.guice.liquibase.exception.LiquibaseChangesetsPending) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) DiffOutputControl(liquibase.diff.output.DiffOutputControl) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CatalogAndSchema(liquibase.CatalogAndSchema) DataSource(javax.sql.DataSource) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) Liquibase(liquibase.Liquibase) LabelExpression(liquibase.LabelExpression) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

FileSystemResourceAccessor (liquibase.resource.FileSystemResourceAccessor)24 ResourceAccessor (liquibase.resource.ResourceAccessor)17 CompositeResourceAccessor (liquibase.resource.CompositeResourceAccessor)16 Database (liquibase.database.Database)11 Liquibase (liquibase.Liquibase)10 File (java.io.File)9 ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)8 JdbcConnection (liquibase.database.jvm.JdbcConnection)6 FileOutputStream (java.io.FileOutputStream)3 IOException (java.io.IOException)3 Connection (java.sql.Connection)3 SQLException (java.sql.SQLException)3 ArrayList (java.util.ArrayList)3 Contexts (liquibase.Contexts)3 ChangeLogParameters (liquibase.changelog.ChangeLogParameters)3 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)3 DiffOutputControl (liquibase.diff.output.DiffOutputControl)3 FileNotFoundException (java.io.FileNotFoundException)2 PrintStream (java.io.PrintStream)2 HashMap (java.util.HashMap)2