liquibase.parser.ChangeLogParser Java Examples

The following examples show how to use liquibase.parser.ChangeLogParser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LiquibaseProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all resource files for the given change log file
 */
private Set<String> findAllChangeLogs(String file, ChangeLogParserFactory changeLogParserFactory,
        ClassLoaderResourceAccessor classLoaderResourceAccessor,
        ChangeLogParameters changeLogParameters) {
    try {
        ChangeLogParser parser = changeLogParserFactory.getParser(file, classLoaderResourceAccessor);
        DatabaseChangeLog changelog = parser.parse(file, changeLogParameters, classLoaderResourceAccessor);

        if (changelog != null) {
            Set<String> result = new LinkedHashSet<>();
            // get all changeSet files
            for (ChangeSet changeSet : changelog.getChangeSets()) {
                result.add(changeSet.getFilePath());

                // get all parents of the changeSet
                DatabaseChangeLog parent = changeSet.getChangeLog();
                while (parent != null) {
                    result.add(parent.getFilePath());
                    parent = parent.getParentChangeLog();
                }
            }
            result.add(changelog.getFilePath());
            return result;
        }
    } catch (LiquibaseException ex) {
        throw new IllegalStateException(ex);
    }
    return Collections.emptySet();
}
 
Example #2
Source File: LiquibaseProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * The default service loader is super slow
 *
 * As part of the extension build we index liquibase, then we use this index to find all implementations of services
 */
@BuildStep(onlyIfNot = NativeBuild.class)
@Record(STATIC_INIT)
public void fastServiceLoader(LiquibaseRecorder recorder,
        List<JdbcDataSourceBuildItem> jdbcDataSourceBuildItems) throws IOException {
    DotName liquibaseServiceName = DotName.createSimple(LiquibaseService.class.getName());
    try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/liquibase.idx")) {
        IndexReader reader = new IndexReader(in);
        Index index = reader.read();
        Map<String, List<String>> services = new HashMap<>();
        for (Class<?> c : Arrays.asList(liquibase.diff.compare.DatabaseObjectComparator.class,
                liquibase.parser.NamespaceDetails.class,
                liquibase.precondition.Precondition.class,
                liquibase.database.Database.class,
                liquibase.parser.ChangeLogParser.class,
                liquibase.change.Change.class,
                liquibase.snapshot.SnapshotGenerator.class,
                liquibase.changelog.ChangeLogHistoryService.class,
                liquibase.datatype.LiquibaseDataType.class,
                liquibase.executor.Executor.class,
                liquibase.lockservice.LockService.class,
                liquibase.sqlgenerator.SqlGenerator.class,
                liquibase.license.LicenseService.class)) {
            List<String> impls = new ArrayList<>();
            services.put(c.getName(), impls);
            Set<ClassInfo> classes = new HashSet<>();
            if (c.isInterface()) {
                classes.addAll(index.getAllKnownImplementors(DotName.createSimple(c.getName())));
            } else {
                classes.addAll(index.getAllKnownSubclasses(DotName.createSimple(c.getName())));
            }
            for (ClassInfo found : classes) {
                if (Modifier.isAbstract(found.flags()) ||
                        Modifier.isInterface(found.flags()) ||
                        !found.hasNoArgsConstructor() ||
                        !Modifier.isPublic(found.flags())) {
                    continue;
                }
                AnnotationInstance annotationInstance = found.classAnnotation(liquibaseServiceName);
                if (annotationInstance == null || !annotationInstance.value("skip").asBoolean()) {
                    impls.add(found.name().toString());
                }
            }
        }
        //if we know what DB types are in use we limit them
        //this gives a huge startup time boost
        //otherwise it generates SQL for every DB
        boolean allKnown = true;
        Set<String> databases = new HashSet<>();
        for (JdbcDataSourceBuildItem i : jdbcDataSourceBuildItems) {
            String known = KIND_TO_IMPL.get(i.getDbKind());
            if (known == null) {
                allKnown = false;
            } else {
                databases.add(known);
            }
        }
        if (allKnown) {
            services.put(Database.class.getName(), new ArrayList<>(databases));
        }
        recorder.setJvmServiceImplementations(services);
    }
}
 
Example #3
Source File: LiquibaseProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep(onlyIf = NativeBuild.class)
@Record(STATIC_INIT)
void nativeImageConfiguration(
        LiquibaseRecorder recorder,
        LiquibaseBuildTimeConfig liquibaseBuildConfig,
        List<JdbcDataSourceBuildItem> jdbcDataSourceBuildItems,
        BuildProducer<ReflectiveClassBuildItem> reflective,
        BuildProducer<NativeImageResourceBuildItem> resource,
        BuildProducer<GeneratedResourceBuildItem> generatedResource,
        BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitialized,
        BuildProducer<NativeImageResourceBundleBuildItem> resourceBundle) {

    runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("liquibase.diff.compare.CompareControl"));

    reflective.produce(new ReflectiveClassBuildItem(false, true, false,
            "liquibase.change.AbstractSQLChange",
            "liquibase.database.jvm.JdbcConnection"));

    reflective.produce(new ReflectiveClassBuildItem(true, true, true,
            "liquibase.change.ColumnConfig",
            "liquibase.change.AddColumnConfig"));

    reflective.produce(new ReflectiveClassBuildItem(false, false, true,
            "liquibase.change.ConstraintsConfig"));

    addReflection(reflective, true, liquibase.change.Change.class);

    // add all implementation of these classes to the reflection process
    addReflection(reflective, false,
            liquibase.configuration.ConfigurationContainer.class,
            liquibase.parser.LiquibaseParser.class,
            liquibase.structure.DatabaseObject.class,
            liquibase.sql.visitor.SqlVisitor.class);

    // load the liquibase services
    Map<String, List<String>> serviceClassesImplementationRegistry = new HashMap<>();

    Stream.of(liquibase.diff.compare.DatabaseObjectComparator.class,
            liquibase.parser.NamespaceDetails.class,
            liquibase.precondition.Precondition.class,
            liquibase.database.Database.class,
            liquibase.parser.ChangeLogParser.class,
            liquibase.change.Change.class,
            liquibase.snapshot.SnapshotGenerator.class,
            liquibase.changelog.ChangeLogHistoryService.class,
            liquibase.datatype.LiquibaseDataType.class,
            liquibase.executor.Executor.class,
            liquibase.lockservice.LockService.class,
            liquibase.sqlgenerator.SqlGenerator.class,
            liquibase.command.LiquibaseCommand.class,
            liquibase.structure.DatabaseObject.class,
            liquibase.diff.output.changelog.ChangeGenerator.class,
            liquibase.diff.DiffGenerator.class)
            .forEach(t -> addService(reflective, t, true, serviceClassesImplementationRegistry));

    addService(reflective, liquibase.license.LicenseService.class, false, serviceClassesImplementationRegistry);

    recorder.setServicesImplementations(serviceClassesImplementationRegistry);

    Collection<String> dataSourceNames = jdbcDataSourceBuildItems.stream()
            .map(i -> i.getName())
            .collect(Collectors.toSet());

    resource.produce(
            new NativeImageResourceBuildItem(getChangeLogs(dataSourceNames, liquibaseBuildConfig).toArray(new String[0])));

    // liquibase XSD
    resource.produce(new NativeImageResourceBuildItem(
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd",
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.6.xsd",
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.7.xsd",
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd",
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.9.xsd",
            "www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd",
            "www.liquibase.org/xml/ns/pro/liquibase-pro-3.8.xsd",
            "liquibase.build.properties"));

    // liquibase resource bundles
    resourceBundle.produce(new NativeImageResourceBundleBuildItem("liquibase/i18n/liquibase-core"));
}
 
Example #4
Source File: ChangeLogParserTest.java    From liquibase-percona with Apache License 2.0 4 votes vote down vote up
private DatabaseChangeLog loadChangeLog(String filename) throws Exception {
    ChangeLogParserFactory parserFactory = ChangeLogParserFactory.getInstance();
    ChangeLogParser parser = parserFactory.getParser(filename, resourceAccessor);
    return parser.parse(filename, new ChangeLogParameters(), resourceAccessor);
}
 
Example #5
Source File: LiquibaseProcessor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Record(ExecutionTime.STATIC_INIT)
@BuildStep
void configure(KeycloakRecorder recorder) {
    DotName liquibaseServiceName = DotName.createSimple(LiquibaseService.class.getName());
    Map<String, List<String>> services = new HashMap<>();

    try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/liquibase.idx")) {
        IndexReader reader = new IndexReader(in);
        Index index = reader.read();
        for (Class<?> c : Arrays.asList(liquibase.diff.compare.DatabaseObjectComparator.class,
                liquibase.parser.NamespaceDetails.class,
                liquibase.precondition.Precondition.class,
                Database.class,
                ChangeLogParser.class,
                liquibase.change.Change.class,
                liquibase.snapshot.SnapshotGenerator.class,
                liquibase.changelog.ChangeLogHistoryService.class,
                liquibase.datatype.LiquibaseDataType.class,
                liquibase.executor.Executor.class,
                LockService.class,
                SqlGenerator.class)) {
            List<String> impls = new ArrayList<>();
            services.put(c.getName(), impls);
            Set<ClassInfo> classes = new HashSet<>();
            if (c.isInterface()) {
                classes.addAll(index.getAllKnownImplementors(DotName.createSimple(c.getName())));
            } else {
                classes.addAll(index.getAllKnownSubclasses(DotName.createSimple(c.getName())));
            }
            for (ClassInfo found : classes) {
                if (Modifier.isAbstract(found.flags()) ||
                        Modifier.isInterface(found.flags()) ||
                        !found.hasNoArgsConstructor() ||
                        !Modifier.isPublic(found.flags())) {
                    continue;
                }
                AnnotationInstance annotationInstance = found.classAnnotation(liquibaseServiceName);
                if (annotationInstance == null || !annotationInstance.value("skip").asBoolean()) {
                    impls.add(found.name().toString());
                }
            }
        }
    } catch (IOException cause) {
        throw new RuntimeException("Failed to get liquibase jandex index", cause);
    }

    services.put(Logger.class.getName(), Arrays.asList(KeycloakLogger.class.getName()));
    services.put(LockService.class.getName(), Arrays.asList(DummyLockService.class.getName()));
    services.put(ChangeLogParser.class.getName(), Arrays.asList(XMLChangeLogSAXParser.class.getName()));
    services.get(SqlGenerator.class.getName()).add(CustomInsertLockRecordGenerator.class.getName());
    services.get(SqlGenerator.class.getName()).add(CustomLockDatabaseChangeLogGenerator.class.getName());

    recorder.configureLiquibase(services);
}
 
Example #6
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization(KeycloakSession session) {
    resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
    FastServiceLocator locator = (FastServiceLocator) ServiceLocator.getInstance();

    JpaConnectionProviderFactory jpaConnectionProvider = (JpaConnectionProviderFactory) session
            .getKeycloakSessionFactory().getProviderFactory(JpaConnectionProvider.class);

    // register our custom databases
    locator.register(new PostgresPlusDatabase());
    locator.register(new UpdatedMySqlDatabase());
    locator.register(new UpdatedMariaDBDatabase());
    
    // registers only the database we are using
    try (Connection connection = jpaConnectionProvider.getConnection()) {
        Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
        if (database.getDatabaseProductName().equals(MySQLDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        } else if (database.getDatabaseProductName().equals(MariaDBDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        }

        DatabaseFactory.getInstance().clearRegistry();
        locator.register(database);
    } catch (Exception cause) {
        throw new RuntimeException("Failed to configure Liquibase database", cause);
    }

    // disables XML validation
    for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
        if (parser instanceof XMLChangeLogSAXParser) {
            Method getSaxParserFactory = null;
            try {
                getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
                getSaxParserFactory.setAccessible(true);
                SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
                saxParserFactory.setValidating(false);
                saxParserFactory.setSchema(null);
            } catch (Exception e) {
                logger.warnf("Failed to disable liquibase XML validations");
            } finally {
                if (getSaxParserFactory != null) {
                    getSaxParserFactory.setAccessible(false);
                }
            }
        }
    }
}