Search in sources :

Example 16 with FileSystemResourceAccessor

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

the class AbstractLiquibaseMojoTest method loadPropertiesFileIfPresent.

protected void loadPropertiesFileIfPresent(AbstractLiquibaseMojo mojo) throws MojoExecutionException, MojoFailureException {
    File rootDir = new File(getBasedir(), "target/test-classes");
    ResourceAccessor fo = new FileSystemResourceAccessor(rootDir.getAbsolutePath());
    mojo.configureFieldsAndValues(fo);
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) File(java.io.File)

Example 17 with FileSystemResourceAccessor

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

the class LiquibaseMain method init.

public void init(String logLevel, String logFile) throws Exception {
    changeLogLevel(logLevel, logFile);
    FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
    ClassLoader classLoader = getClass().getClassLoader();
    ResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader);
    String defaultSchemaName = dbConf.getSchema();
    this.database = // resourceAccessor
    CommandLineUtils.createDatabaseObject(// resourceAccessor
    clOpener, dbConf.getUrl(), dbConf.getUsername(), dbConf.getPassword(), dbConf.getDriver(), // defaultCatalogName
    (String) null, // defaultSchemaName
    defaultSchemaName, // outputDefaultCatalog
    false, // outputDefaultSchema
    false, // databaseClass
    (String) null, // driverPropertiesFile
    (String) null, // propertyProviderClass
    (String) null, // liquibaseCatalogName
    (String) null, // liquibaseSchemaName
    (String) null, // databaseChangeLogTableName
    (String) null, // databaseChangeLogLockTableName
    (String) null);
    try {
        CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener);
        DiffOutputControl diffOutputControl = new // includeCatalog
        DiffOutputControl(// includeCatalog
        false, // includeSchema
        false, // includeTablespace
        false, // schemaComparisons
        null);
        CompareControl.SchemaComparison[] finalSchemaComparisons;
        finalSchemaComparisons = new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(new CatalogAndSchema(null, defaultSchemaName), new CatalogAndSchema(null, defaultSchemaName)) };
        for (CompareControl.SchemaComparison schema : finalSchemaComparisons) {
            diffOutputControl.addIncludedSchema(schema.getReferenceSchema());
            diffOutputControl.addIncludedSchema(schema.getComparisonSchema());
        }
        this.liquibase = new Liquibase(changeLogFile, fileOpener, database);
    } catch (Exception ex) {
        try {
            database.rollback();
            database.close();
        } catch (Exception ex2) {
            LogFactory.getInstance().getLog().warning("problem closing connection", ex2);
        }
        throw ex;
    }
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) CommandLineResourceAccessor(liquibase.integration.commandline.CommandLineResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) DiffOutputControl(liquibase.diff.output.DiffOutputControl) CatalogAndSchema(liquibase.CatalogAndSchema) CommandLineParsingException(liquibase.exception.CommandLineParsingException) DatabaseException(liquibase.exception.DatabaseException) CommandLineResourceAccessor(liquibase.integration.commandline.CommandLineResourceAccessor) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) Liquibase(liquibase.Liquibase) CompareControl(liquibase.diff.compare.CompareControl) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor)

Example 18 with FileSystemResourceAccessor

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

the class LiquibaseHelperTest method testEndToEnd.

@Test
public void testEndToEnd() throws Exception {
    final File targetFile = File.createTempFile("target", null);
    final File referenceFile = File.createTempFile("reference", null);
    final String targetUrl = "jdbc:h2:" + targetFile.getAbsolutePath();
    final String referenceUrl = "jdbc:h2:" + referenceFile.getAbsolutePath();
    final String masterChangeLogResourceName = "changes-" + System.currentTimeMillis() + ".xml";
    final File migrationsDir = new File(TEST_RESOURCES, "migrations");
    final File masterChangeLogFile = new File(migrationsDir, masterChangeLogResourceName);
    final Map<String, String> props = new HashMap<>();
    props.put(MinijaxProperties.PERSISTENCE_UNIT_NAME, "testdb");
    props.put(MinijaxProperties.DB_DRIVER, "org.h2.jdbcx.JdbcDataSource");
    props.put(MinijaxProperties.DB_URL, targetUrl);
    props.put(MinijaxProperties.DB_REFERENCE_URL, referenceUrl);
    props.put(MinijaxProperties.DB_USERNAME, "");
    props.put(MinijaxProperties.DB_PASSWORD, "");
    // Verify that both databases are empty and that the changelog does not exist
    assertTrue(getTables(targetUrl).isEmpty());
    assertTrue(getTables(referenceUrl).isEmpty());
    assertFalse(masterChangeLogFile.exists());
    final FileSystemResourceAccessor accessor = new FileSystemResourceAccessor(TEST_RESOURCES.getAbsolutePath()) {

        @Override
        protected void init() {
            try {
                addRootPath(TEST_RESOURCES.getAbsoluteFile().toURI().toURL());
                addRootPath(masterChangeLogFile.getAbsoluteFile().toURI().toURL());
            } catch (final MalformedURLException ex) {
                ex.printStackTrace();
            }
        }
    };
    final LiquibaseHelper m = new LiquibaseHelper(props, accessor, TEST_RESOURCES, masterChangeLogResourceName);
    // Generate the migration
    final File firstGeneratedChangeLog = m.generateMigrations();
    assertTrue(firstGeneratedChangeLog.exists());
    // Verify that the "target" database is still empty
    assertTrue(getTables(targetUrl).isEmpty());
    // Verify that the "reference" database now has the "WIDGET" table
    assertEquals(Arrays.asList("WIDGET"), getTables(referenceUrl));
    // Verify that the changelog file now exists
    assertTrue(masterChangeLogFile.exists());
    // Run the migration
    m.migrate();
    // Verify that the "target" database now has Liquibase tables and the "WIDGET" table
    assertEquals(Arrays.asList("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "WIDGET"), getTables(targetUrl));
    // Generate the migration again (should be no-op)
    final File secondGeneratedChangeLog = m.generateMigrations();
    assertNull(secondGeneratedChangeLog);
    // Verify that the "reference" database is still only the "WIDGET" table
    assertEquals(Arrays.asList("WIDGET"), getTables(referenceUrl));
    // Run the migration again (should be no-op)
    m.migrate();
    // Verify that the "target" database still has only Liquibase tables and the "WIDGET" table
    assertEquals(Arrays.asList("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "WIDGET"), getTables(targetUrl));
    // Cleanup
    deleteDatabase(targetFile);
    deleteDatabase(referenceFile);
    masterChangeLogFile.delete();
    firstGeneratedChangeLog.delete();
    migrationsDir.delete();
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) File(java.io.File) Test(org.junit.Test)

Example 19 with FileSystemResourceAccessor

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

the class DatabaseUpdater method executeChangelog.

/**
 * This code was borrowed from the liquibase jar so that we can call the given callback
 * function.
 *
 * @param changeLogFile the file to execute
 * @param contexts the liquibase changeset context
 * @param userInput answers given by the user
 * @param callback the function to call after every changeset
 * @param cl {@link ClassLoader} to use to find the changeLogFile (or null to use
 *            {@link OpenmrsClassLoader})
 * @return A list of messages or warnings generated by the executed changesets
 * @throws Exception
 */
public static List<String> executeChangelog(String changeLogFile, String contexts, Map<String, Object> userInput, ChangeSetExecutorCallback callback, ClassLoader cl) throws Exception {
    final class OpenmrsUpdateVisitor extends UpdateVisitor {

        private ChangeSetExecutorCallback callback;

        private int numChangeSetsToRun;

        public OpenmrsUpdateVisitor(Database database, ChangeSetExecutorCallback callback, int numChangeSetsToRun) {
            super(database);
            this.callback = callback;
            this.numChangeSetsToRun = numChangeSetsToRun;
        }

        @Override
        public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException {
            if (callback != null) {
                callback.executing(changeSet, numChangeSetsToRun);
            }
            super.visit(changeSet, databaseChangeLog, database);
        }
    }
    if (cl == null) {
        cl = OpenmrsClassLoader.getInstance();
    }
    log.debug("Setting up liquibase object to run changelog: " + changeLogFile);
    Liquibase liquibase = getLiquibase(changeLogFile, cl);
    int numChangeSetsToRun = liquibase.listUnrunChangeSets(contexts).size();
    Database database = null;
    LockService lockHandler = null;
    try {
        database = liquibase.getDatabase();
        lockHandler = LockService.getInstance(database);
        lockHandler.waitForLock();
        ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl);
        ResourceAccessor fsFO = new FileSystemResourceAccessor();
        DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(changeLogFile, new ChangeLogParameters(), new CompositeResourceAccessor(openmrsFO, fsFO));
        changeLog.setChangeLogParameters(liquibase.getChangeLogParameters());
        changeLog.validate(database);
        ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new DbmsChangeSetFilter(database));
        database.checkDatabaseChangeLogTable(true, changeLog, new String[] { contexts });
        logIterator.run(new OpenmrsUpdateVisitor(database, callback, numChangeSetsToRun), database);
    } catch (LiquibaseException e) {
        throw e;
    } finally {
        try {
            lockHandler.releaseLock();
        } catch (Exception e) {
            log.error("Could not release lock", e);
        }
        try {
            database.getConnection().close();
        } catch (Exception e) {
        // pass
        }
    }
    return updateWarnings;
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) ShouldRunChangeSetFilter(liquibase.changelog.filter.ShouldRunChangeSetFilter) UpdateVisitor(liquibase.changelog.visitor.UpdateVisitor) LockService(liquibase.lockservice.LockService) ContextChangeSetFilter(liquibase.changelog.filter.ContextChangeSetFilter) XMLChangeLogSAXParser(liquibase.parser.core.xml.XMLChangeLogSAXParser) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) LockException(liquibase.exception.LockException) SQLException(java.sql.SQLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) LiquibaseException(liquibase.exception.LiquibaseException) Liquibase(liquibase.Liquibase) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ChangeLogIterator(liquibase.changelog.ChangeLogIterator) ChangeLogParameters(liquibase.changelog.ChangeLogParameters) Database(liquibase.database.Database) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) LiquibaseException(liquibase.exception.LiquibaseException) DbmsChangeSetFilter(liquibase.changelog.filter.DbmsChangeSetFilter) ChangeSet(liquibase.changelog.ChangeSet)

Example 20 with FileSystemResourceAccessor

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

the class LiquibaseDatabase method export.

@Override
protected void export() throws Exception {
    String rootPath = getProperties().getProperty("rootPath");
    String scripts = getProperties().getProperty("scripts");
    includeLiquibaseTables = Boolean.parseBoolean(getProperties().getProperty("includeLiquibaseTables", "false"));
    if (isBlank(scripts)) {
        scripts = "";
        log.warn("No scripts defined", "It is recommended that you provide an explicit script directory to scan");
    }
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection()));
    String contexts = "";
    // Database.setXyz() configuration setter calls
    for (Entry<Object, Object> entry : getProperties().entrySet()) {
        String key = "" + entry.getKey();
        if (key.startsWith("database.")) {
            String property = key.substring("database.".length());
            Method setter = SETTERS.get("set" + Character.toUpperCase(property.charAt(0)) + property.substring(1));
            try {
                if (setter != null)
                    setter.invoke(database, Convert.convert(entry.getValue(), setter.getParameterTypes()[0]));
            } catch (Exception e) {
                log.warn("Configuration error", e.getMessage(), e);
            }
        } else // [#9872] Some changeLogParameters can also be passed along
        if (key.startsWith("changeLogParameters.")) {
            String property = key.substring("changeLogParameters.".length());
            if ("contexts".equals(property))
                contexts = "" + entry.getValue();
        }
    }
    // Retrieve changeLog table names as they might be overridden by configuration setters
    databaseChangeLogTableName = database.getDatabaseChangeLogTableName();
    databaseChangeLogLockTableName = database.getDatabaseChangeLogLockTableName();
    // [#9866] Allow for loading included files from the classpath or using absolute paths.
    // [#12872] [#13021] The decision is made based on the presence of the rootPath property
    ResourceAccessor ra = StringUtils.isBlank(rootPath) ? new CompositeResourceAccessor(new ClassLoaderResourceAccessor(), new ClassLoaderResourceAccessor(Thread.currentThread().getContextClassLoader())) : new FileSystemResourceAccessor(new File(rootPath));
    Liquibase liquibase = new Liquibase(scripts, ra, database);
    liquibase.update(contexts);
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) JdbcConnection(liquibase.database.jvm.JdbcConnection) Method(java.lang.reflect.Method) SQLException(java.sql.SQLException) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) Liquibase(liquibase.Liquibase) Database(liquibase.database.Database) AbstractInterpretingDatabase(org.jooq.meta.extensions.AbstractInterpretingDatabase) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) File(java.io.File)

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