Search in sources :

Example 1 with SchemaMappingType

use of org.jooq.meta.jaxb.SchemaMappingType in project jOOQ by jOOQ.

the class AbstractDatabase method getInputSchemata.

@Override
public final List<String> getInputSchemata() {
    if (inputSchemataPerCatalog == null) {
        inputSchemata = new ArrayList<>();
        inputSchemataPerCatalog = new LinkedHashMap<>();
        // [#1312] Allow for omitting inputSchema configuration. Generate all schemata instead.
        if (configuredSchemata.size() == 1 && StringUtils.isBlank(configuredSchemata.get(0).getInputSchema())) {
            initAllSchemata();
        } else if (configuredCatalogs.size() == 1 && StringUtils.isBlank(configuredCatalogs.get(0).getInputCatalog()) && configuredCatalogs.get(0).getSchemata().size() == 1 && StringUtils.isBlank(configuredCatalogs.get(0).getSchemata().get(0).getInputSchema())) {
            initAllSchemata();
        } else if (configuredCatalogs.isEmpty()) {
            inputSchemataPerCatalog.put("", inputSchemata);
            for (SchemaMappingType schema : configuredSchemata) {
                {
                    inputSchemata.add(schema.getInputSchema());
                }
            }
        } else {
            for (CatalogMappingType catalog : configuredCatalogs) {
                for (SchemaMappingType schema : catalog.getSchemata()) {
                    String inputSchema;
                    {
                        inputSchema = schema.getInputSchema();
                    }
                    inputSchemata.add(inputSchema);
                    // [#6064] If no input catalogs were configured, we need to register the input schema for each catalog
                    for (String inputCatalog : (configuredCatalogs.size() == 1 && StringUtils.isBlank(configuredCatalogs.get(0).getInputCatalog())) ? getInputCatalogs() : Collections.singletonList(catalog.getInputCatalog())) {
                        inputSchemataPerCatalog.computeIfAbsent(inputCatalog, c -> new ArrayList<>()).add(inputSchema);
                    }
                }
            }
        }
    }
    return inputSchemata;
}
Also used : ForcedTypeObjectType(org.jooq.meta.jaxb.ForcedTypeObjectType) Arrays(java.util.Arrays) Connection(java.sql.Connection) DSL(org.jooq.impl.DSL) StringUtils.isBlank(org.jooq.tools.StringUtils.isBlank) ParseWithMetaLookups(org.jooq.conf.ParseWithMetaLookups) OnError(org.jooq.meta.jaxb.OnError) Table(org.jooq.Table) DSL.rowNumber(org.jooq.impl.DSL.rowNumber) DSL.when(org.jooq.impl.DSL.when) Condition(org.jooq.Condition) SyntheticViewType(org.jooq.meta.jaxb.SyntheticViewType) Matcher(java.util.regex.Matcher) CatalogMappingType(org.jooq.meta.jaxb.CatalogMappingType) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Log(org.jooq.Log) DSLContext(org.jooq.DSLContext) BigInteger(java.math.BigInteger) CustomType(org.jooq.meta.jaxb.CustomType) SQLDialect(org.jooq.SQLDialect) Select(org.jooq.Select) AbstractTypedElementDefinition.customType(org.jooq.meta.AbstractTypedElementDefinition.customType) SyntheticIdentityType(org.jooq.meta.jaxb.SyntheticIdentityType) Nullability(org.jooq.meta.jaxb.Nullability) JooqLogger(org.jooq.tools.JooqLogger) Collections.emptyList(java.util.Collections.emptyList) Name(org.jooq.Name) CommentType(org.jooq.meta.jaxb.CommentType) DSL.falseCondition(org.jooq.impl.DSL.falseCondition) Collection(java.util.Collection) DSL.partitionBy(org.jooq.impl.DSL.partitionBy) Set(java.util.Set) ExecuteListener(org.jooq.ExecuteListener) Field(org.jooq.Field) CUBRID(org.jooq.SQLDialect.CUBRID) Meta(org.jooq.Meta) JDBCUtils(org.jooq.tools.jdbc.JDBCUtils) TableType(org.jooq.TableOptions.TableType) List(java.util.List) Stream(java.util.stream.Stream) TableField(org.jooq.TableField) SQLDataType(org.jooq.impl.SQLDataType) EmbeddableField(org.jooq.meta.jaxb.EmbeddableField) StringUtils.defaultIfNull(org.jooq.tools.StringUtils.defaultIfNull) Pattern(java.util.regex.Pattern) SchemaMappingType(org.jooq.meta.jaxb.SchemaMappingType) SyntheticObjectsType(org.jooq.meta.jaxb.SyntheticObjectsType) Query(org.jooq.Query) TRUE(java.lang.Boolean.TRUE) DetachedException(org.jooq.exception.DetachedException) DSL.count(org.jooq.impl.DSL.count) EnumType(org.jooq.meta.jaxb.EnumType) HashMap(java.util.HashMap) SyntheticReadonlyRowidType(org.jooq.meta.jaxb.SyntheticReadonlyRowidType) Supplier(java.util.function.Supplier) SyntheticReadonlyColumnType(org.jooq.meta.jaxb.SyntheticReadonlyColumnType) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) SyntheticForeignKeyType(org.jooq.meta.jaxb.SyntheticForeignKeyType) StringUtils.defaultIfEmpty(org.jooq.tools.StringUtils.defaultIfEmpty) SQLException(java.sql.SQLException) SQLITE(org.jooq.SQLDialect.SQLITE) Schema(org.jooq.Schema) Comparator.comparing(java.util.Comparator.comparing) SyntheticPrimaryKeyType(org.jooq.meta.jaxb.SyntheticPrimaryKeyType) Record(org.jooq.Record) DataAccessException(org.jooq.exception.DataAccessException) RegexFlag(org.jooq.meta.jaxb.RegexFlag) Properties(java.util.Properties) Iterator(java.util.Iterator) StringUtils.defaultIfBlank(org.jooq.tools.StringUtils.defaultIfBlank) IOException(java.io.IOException) ForcedType(org.jooq.meta.jaxb.ForcedType) FIREBIRD(org.jooq.SQLDialect.FIREBIRD) StringUtils(org.jooq.tools.StringUtils) SyntheticUniqueKeyType(org.jooq.meta.jaxb.SyntheticUniqueKeyType) File(java.io.File) ERROR(org.jooq.Log.Level.ERROR) DSL.one(org.jooq.impl.DSL.one) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Param(org.jooq.Param) RenderQuotedNames(org.jooq.conf.RenderQuotedNames) Configuration(org.jooq.Configuration) ExecuteContext(org.jooq.ExecuteContext) DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) StringReader(java.io.StringReader) EmbeddableDefinitionType(org.jooq.meta.jaxb.EmbeddableDefinitionType) StopWatch(org.jooq.tools.StopWatch) CSVReader(org.jooq.tools.csv.CSVReader) Comparator(java.util.Comparator) Collections(java.util.Collections) MetaProvider(org.jooq.MetaProvider) CatalogMappingType(org.jooq.meta.jaxb.CatalogMappingType) SchemaMappingType(org.jooq.meta.jaxb.SchemaMappingType) ArrayList(java.util.ArrayList)

Example 2 with SchemaMappingType

use of org.jooq.meta.jaxb.SchemaMappingType in project jOOQ by jOOQ.

the class GenerationTool method run0.

@SuppressWarnings({ "unchecked", "unused" })
private void run0(Configuration configuration) throws Exception {
    // Trigger logging of jOOQ logo eagerly already here
    selectOne().toString();
    if (configuration.getLogging() != null) {
        setGlobalLoggingThreshold(configuration);
    } else {
        String property = System.getProperty("jooq.codegen.logging");
        if (property != null) {
            try {
                Logging.valueOf(property);
            } catch (IllegalArgumentException e) {
                log.error("Unsupported property", "Unsupported value for system property jooq.codegen.logging: " + property + ". Supported values include: " + Arrays.asList(Logging.values()));
            }
        }
    }
    if (Boolean.getBoolean("jooq.codegen.skip")) {
        log.info("Skipping jOOQ code generation");
        return;
    }
    if (log.isDebugEnabled())
        log.debug("Input configuration", "" + configuration);
    // Standalone code generation should use the JVM's working dir as basedir, by default.
    if (configuration.getBasedir() == null)
        configuration.setBasedir(new File(".").getAbsolutePath());
    Jdbc j = configuration.getJdbc();
    org.jooq.meta.jaxb.Generator g = configuration.getGenerator();
    if (g == null)
        throw new GeneratorException("The <generator/> tag is mandatory. For details, see " + Constants.NS_CODEGEN);
    // [#3669] Optional Database element
    if (g.getDatabase() == null)
        g.setDatabase(new org.jooq.meta.jaxb.Database());
    org.jooq.meta.jaxb.Database d = g.getDatabase();
    String databaseName = trim(d.getName());
    // [#1394] The <generate/> element and some others should be optional
    if (g.getGenerate() == null)
        g.setGenerate(new Generate());
    if (g.getStrategy() == null)
        g.setStrategy(new Strategy());
    if (g.getTarget() == null)
        g.setTarget(new Target());
    // [#9744] The <locale/> is also needed in GenerationTool:
    Locale locale = Locale.getDefault();
    if (!StringUtils.isBlank(g.getTarget().getLocale()))
        locale = Locale.forLanguageTag(g.getTarget().getLocale());
    Database database = null;
    try {
        // ---------------------
        if (connection == null) {
            close = true;
            if (dataSource != null) {
                setConnection(dataSource.getConnection());
            } else {
                String url = System.getProperty("jooq.codegen.jdbc.url");
                if (url != null) {
                    j = defaultIfNull(j, new Jdbc());
                    if (j.getDriver() == null)
                        j.setDriver(System.getProperty("jooq.codegen.jdbc.driver"));
                    if (j.getUrl() == null)
                        j.setUrl(url);
                    if (j.getUser() == null)
                        j.setUser(System.getProperty("jooq.codegen.jdbc.user"));
                    if (j.getUsername() == null)
                        j.setUsername(System.getProperty("jooq.codegen.jdbc.username"));
                    if (j.getPassword() == null)
                        j.setPassword(System.getProperty("jooq.codegen.jdbc.password"));
                    if (j.isAutoCommit() == null) {
                        String a = System.getProperty("jooq.codegen.jdbc.autoCommit");
                        if (a != null)
                            j.setAutoCommit(Boolean.valueOf(a));
                    }
                    if (j.getInitScript() == null)
                        j.setInitScript(System.getProperty("jooq.codegen.jdbc.initScript"));
                    if (j.getInitSeparator() == null)
                        j.setInitSeparator(System.getProperty("jooq.codegen.jdbc.initSeparator"));
                }
                if (j != null && !StringUtils.isBlank(j.getUrl())) {
                    try {
                        Class<? extends Driver> driver = (Class<? extends Driver>) loadClass(driverClass(j));
                        Properties properties = properties(j.getProperties());
                        if (!properties.containsKey("user"))
                            properties.put("user", defaultString(defaultString(j.getUser(), j.getUsername())));
                        if (!properties.containsKey("password"))
                            properties.put("password", defaultString(j.getPassword()));
                        Connection c = driver.newInstance().connect(defaultString(j.getUrl()), properties);
                        // [#12951] Some drivers may (illegally) return null if the URL is incorrect?
                        if (c == null)
                            throw new SQLException("Cannot connect to database using JDBC URL: " + j.getUrl() + ". Please review your JDBC configuration in the code generator configuration.");
                        setConnection(c);
                        if (j.getInitScript() != null)
                            for (String sql : j.getInitScript().split(defaultIfBlank(j.getInitSeparator(), ";"))) if (!StringUtils.isBlank(sql))
                                ctx.execute(sql);
                    } catch (Exception e) {
                        if (databaseName != null)
                            if (databaseName.contains("DDLDatabase") || databaseName.contains("XMLDatabase") || databaseName.contains("JPADatabase"))
                                log.warn("Error while connecting to database. Note that file based database implementations do not need a <jdbc/> configuration in the code generator.", e);
                        throw e;
                    }
                }
            }
        }
        j = defaultIfNull(j, new Jdbc());
        if (connection != null && j.isAutoCommit() != null) {
            autoCommit = connection.getAutoCommit();
            connection.setAutoCommit(j.isAutoCommit());
        }
        // Initialise generator
        // --------------------
        Class<Generator> generatorClass = (Class<Generator>) (!isBlank(g.getName()) ? loadClass(trim(g.getName())) : JavaGenerator.class);
        Generator generator = generatorClass.newInstance();
        GeneratorStrategy strategy;
        Matchers matchers = g.getStrategy().getMatchers();
        if (matchers != null) {
            strategy = new MatcherStrategy(matchers);
            if (g.getStrategy().getName() != null) {
                // the XSD's default value might apply, which we can safely ignore.
                if (!DefaultGeneratorStrategy.class.getName().equals(g.getStrategy().getName()))
                    log.warn("WARNING: Matchers take precedence over custom strategy. Strategy ignored: " + g.getStrategy().getName());
                g.getStrategy().setName(null);
            }
        } else {
            Class<GeneratorStrategy> strategyClass = (Class<GeneratorStrategy>) (!isBlank(g.getStrategy().getName()) ? loadClass(trim(g.getStrategy().getName())) : DefaultGeneratorStrategy.class);
            strategy = strategyClass.newInstance();
        }
        generator.setStrategy(strategy);
        Class<? extends Database> databaseClass = !isBlank(databaseName) ? (Class<? extends Database>) loadClass(databaseName) : connection != null ? databaseClass(connection) : databaseClass(j);
        database = databaseClass.newInstance();
        database.setBasedir(configuration.getBasedir());
        database.setProperties(properties(d.getProperties()));
        database.setOnError(configuration.getOnError());
        List<CatalogMappingType> catalogs = d.getCatalogs();
        List<SchemaMappingType> schemata = d.getSchemata();
        boolean catalogsEmpty = catalogs.isEmpty();
        boolean schemataEmpty = schemata.isEmpty();
        // For convenience, the catalog configuration can be set also directly in the <database/> element
        if (catalogsEmpty) {
            if (isBlank(d.getInputCatalog()) && !isBlank(d.getOutputCatalog()))
                log.warn("WARNING: /configuration/generator/database/outputCatalog must be paired with /configuration/generator/database/inputCatalog");
            CatalogMappingType catalog = new CatalogMappingType();
            catalog.setInputCatalog(trim(d.getInputCatalog()));
            catalog.setOutputCatalog(trim(d.getOutputCatalog()));
            catalog.setOutputCatalogToDefault(d.isOutputCatalogToDefault());
            catalogs.add(catalog);
            if (!isBlank(catalog.getInputCatalog()))
                catalogsEmpty = false;
            // in the <database/> element
            if (schemataEmpty) {
                if (isBlank(d.getInputSchema()) && !isBlank(d.getOutputSchema()))
                    log.warn("WARNING: /configuration/generator/database/outputSchema must be paired with /configuration/generator/database/inputSchema");
                SchemaMappingType schema = new SchemaMappingType();
                schema.setInputSchema(trim(d.getInputSchema()));
                schema.setOutputSchema(trim(d.getOutputSchema()));
                schema.setOutputSchemaToDefault(d.isOutputSchemaToDefault());
                catalog.getSchemata().add(schema);
                if (!isBlank(schema.getInputSchema()))
                    schemataEmpty = false;
            } else {
                catalog.getSchemata().addAll(schemata);
                if (!isBlank(d.getInputSchema()))
                    log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/inputSchema and /configuration/generator/database/schemata");
                if (!isBlank(d.getOutputSchema()))
                    log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/outputSchema and /configuration/generator/database/schemata");
            }
        } else {
            if (!isBlank(d.getInputCatalog()))
                log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/inputCatalog and /configuration/generator/database/catalogs");
            if (!isBlank(d.getOutputCatalog()))
                log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/outputCatalog and /configuration/generator/database/catalogs");
            if (!isBlank(d.getInputSchema()))
                log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/inputSchema and /configuration/generator/database/catalogs");
            if (!isBlank(d.getOutputSchema()))
                log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/outputSchema and /configuration/generator/database/catalogs");
            if (!schemataEmpty)
                log.warn("WARNING: Cannot combine configuration properties /configuration/generator/database/catalogs and /configuration/generator/database/schemata");
        }
        for (CatalogMappingType catalog : catalogs) {
            if ("".equals(catalog.getOutputCatalog()))
                log.warn("WARNING: Empty <outputCatalog/> should not be used to model default outputCatalogs. Use <outputCatalogToDefault>true</outputCatalogToDefault>, instead. See also: https://github.com/jOOQ/jOOQ/issues/3018");
            // [#3018] If users want the output catalog to be "" then, ignore the actual <outputCatalog/> configuration
            if (TRUE.equals(catalog.isOutputCatalogToDefault()))
                catalog.setOutputCatalog("");
            else if (catalog.getOutputCatalog() == null)
                catalog.setOutputCatalog(trim(catalog.getInputCatalog()));
            for (SchemaMappingType schema : catalog.getSchemata()) {
                if (catalogsEmpty && schemataEmpty && isBlank(schema.getInputSchema())) {
                    if (!isBlank(j.getSchema()))
                        log.warn("WARNING: The configuration property jdbc.Schema is deprecated and will be removed in the future. Use /configuration/generator/database/inputSchema instead");
                    schema.setInputSchema(trim(j.getSchema()));
                }
                // work when Maven parses the XML configurations.
                if ("".equals(schema.getOutputSchema()))
                    log.warn("WARNING: Empty <outputSchema/> should not be used to model default outputSchemas. Use <outputSchemaToDefault>true</outputSchemaToDefault>, instead. See also: https://github.com/jOOQ/jOOQ/issues/3018");
                // [#3018] If users want the output schema to be "" then, ignore the actual <outputSchema/> configuration
                if (TRUE.equals(schema.isOutputSchemaToDefault()))
                    schema.setOutputSchema("");
                else if (schema.getOutputSchema() == null)
                    schema.setOutputSchema(trim(schema.getInputSchema()));
            }
        }
        if (catalogsEmpty)
            log.info("No <inputCatalog/> was provided. Generating ALL available catalogs instead.");
        if (catalogsEmpty && schemataEmpty)
            log.info("No <inputSchema/> was provided. Generating ALL available schemata instead.");
        database.setConnection(connection);
        database.setConfiguredCatalogs(catalogs);
        database.setConfiguredSchemata(schemata);
        database.setIncludes(new String[] { defaultString(d.getIncludes()) });
        database.setExcludes(new String[] { defaultString(d.getExcludes()) });
        database.setIncludeExcludeColumns(TRUE.equals(d.isIncludeExcludeColumns()));
        database.setIncludeExcludePackageRoutines(TRUE.equals(d.isIncludeExcludePackageRoutines()));
        database.setIncludeForeignKeys(!FALSE.equals(d.isIncludeForeignKeys()));
        database.setIncludePackages(!FALSE.equals(d.isIncludePackages()));
        database.setIncludePackageRoutines(!FALSE.equals(d.isIncludePackageRoutines()));
        database.setIncludePackageUDTs(!FALSE.equals(d.isIncludePackageUDTs()));
        database.setIncludePackageConstants(!FALSE.equals(d.isIncludePackageConstants()));
        database.setIncludeIndexes(!FALSE.equals(d.isIncludeIndexes()));
        database.setIncludeCheckConstraints(!FALSE.equals(d.isIncludeCheckConstraints()));
        database.setIncludeSystemTables(TRUE.equals(d.isIncludeSystemTables()));
        database.setIncludeSystemIndexes(TRUE.equals(d.isIncludeSystemIndexes()));
        database.setIncludeSystemCheckConstraints(TRUE.equals(d.isIncludeSystemCheckConstraints()));
        database.setIncludeSystemSequences(TRUE.equals(d.isIncludeSystemSequences()));
        database.setIncludeSystemUDTs(TRUE.equals(d.isIncludeSystemUDTs()));
        database.setIncludeInvisibleColumns(!FALSE.equals(d.isIncludeInvisibleColumns()));
        database.setIncludePrimaryKeys(!FALSE.equals(d.isIncludePrimaryKeys()));
        database.setIncludeRoutines(!FALSE.equals(d.isIncludeRoutines()));
        database.setIncludeDomains(!FALSE.equals(d.isIncludeDomains()));
        database.setIncludeSequences(!FALSE.equals(d.isIncludeSequences()));
        database.setIncludeTables(!FALSE.equals(d.isIncludeTables()));
        database.setIncludeEmbeddables(!FALSE.equals(d.isIncludeEmbeddables()));
        database.setIncludeTriggerRoutines(TRUE.equals(d.isIncludeTriggerRoutines()));
        database.setIncludeUDTs(!FALSE.equals(d.isIncludeUDTs()));
        database.setIncludeUniqueKeys(!FALSE.equals(d.isIncludeUniqueKeys()));
        database.setForceIntegerTypesOnZeroScaleDecimals(!FALSE.equals(d.isForceIntegerTypesOnZeroScaleDecimals()));
        database.setRecordVersionFields(new String[] { defaultString(d.getRecordVersionFields()) });
        database.setRecordTimestampFields(new String[] { defaultString(d.getRecordTimestampFields()) });
        database.setSyntheticPrimaryKeys(new String[] { defaultString(d.getSyntheticPrimaryKeys()) });
        database.setOverridePrimaryKeys(new String[] { defaultString(d.getOverridePrimaryKeys()) });
        database.setSyntheticIdentities(new String[] { defaultString(d.getSyntheticIdentities()) });
        database.setConfiguredCustomTypes(d.getCustomTypes());
        database.setConfiguredEnumTypes(d.getEnumTypes());
        database.setConfiguredForcedTypes(d.getForcedTypes());
        database.setForcedTypesForBuiltinDataTypeExtensions(d.isForcedTypesForBuiltinDataTypeExtensions());
        database.setConfiguredEmbeddables(d.getEmbeddables());
        database.setConfiguredComments(d.getComments());
        database.setConfiguredSyntheticObjects(d.getSyntheticObjects());
        database.setEmbeddablePrimaryKeys(d.getEmbeddablePrimaryKeys());
        database.setEmbeddableUniqueKeys(d.getEmbeddableUniqueKeys());
        database.setEmbeddableDomains(d.getEmbeddableDomains());
        database.setReadonlyIdentities(TRUE.equals(d.isReadonlyIdentities()));
        database.setReadonlyComputedColumns(!FALSE.equals(d.isReadonlyComputedColumns()));
        database.setReadonlyNonUpdatableColumns(!FALSE.equals(d.isReadonlyNonUpdatableColumns()));
        database.setLogSlowQueriesAfterSeconds(defaultIfNull(d.getLogSlowQueriesAfterSeconds(), 5));
        database.setLogSlowResultsAfterSeconds(defaultIfNull(d.getLogSlowResultsAfterSeconds(), 5));
        if (d.getRegexFlags() != null) {
            database.setRegexFlags(d.getRegexFlags());
            if (strategy instanceof MatcherStrategy)
                ((MatcherStrategy) strategy).getPatterns().setRegexFlags(d.getRegexFlags());
        }
        database.setRegexMatchesPartialQualification(!FALSE.equals(d.isRegexMatchesPartialQualification()));
        database.setSqlMatchesPartialQualification(!FALSE.equals(d.isSqlMatchesPartialQualification()));
        SchemaVersionProvider svp = null;
        CatalogVersionProvider cvp = null;
        if (!isBlank(d.getSchemaVersionProvider())) {
            try {
                svp = (SchemaVersionProvider) Class.forName(d.getSchemaVersionProvider()).newInstance();
                log.info("Using custom schema version provider : " + svp);
            } catch (Exception ignore) {
                if (d.getSchemaVersionProvider().toLowerCase(locale).startsWith("select")) {
                    svp = new SQLSchemaVersionProvider(connection, d.getSchemaVersionProvider());
                    log.info("Using SQL schema version provider : " + d.getSchemaVersionProvider());
                } else {
                    svp = new ConstantSchemaVersionProvider(d.getSchemaVersionProvider());
                }
            }
        }
        if (!isBlank(d.getCatalogVersionProvider())) {
            try {
                cvp = (CatalogVersionProvider) Class.forName(d.getCatalogVersionProvider()).newInstance();
                log.info("Using custom catalog version provider : " + cvp);
            } catch (Exception ignore) {
                if (d.getCatalogVersionProvider().toLowerCase(locale).startsWith("select")) {
                    cvp = new SQLCatalogVersionProvider(connection, d.getCatalogVersionProvider());
                    log.info("Using SQL catalog version provider : " + d.getCatalogVersionProvider());
                } else {
                    cvp = new ConstantCatalogVersionProvider(d.getCatalogVersionProvider());
                }
            }
        }
        if (svp == null)
            svp = new ConstantSchemaVersionProvider(null);
        if (cvp == null)
            cvp = new ConstantCatalogVersionProvider(null);
        database.setSchemaVersionProvider(svp);
        database.setCatalogVersionProvider(cvp);
        if (!isBlank(d.getOrderProvider())) {
            Class<?> orderProvider = Class.forName(d.getOrderProvider());
            if (Comparator.class.isAssignableFrom(orderProvider))
                database.setOrderProvider((Comparator<Definition>) orderProvider.newInstance());
            else
                log.warn("Order provider must be of type java.util.Comparator: " + orderProvider);
        }
        if (d.getEnumTypes().size() > 0)
            log.warn("DEPRECATED", "The configuration property /configuration/generator/database/enumTypes is experimental and deprecated and will be removed in the future.");
        if (Boolean.TRUE.equals(d.isDateAsTimestamp()))
            log.warn("DEPRECATED", "The configuration property /configuration/generator/database/dateAsTimestamp is deprecated as it is superseded by custom bindings and converters. It will thus be removed in the future.");
        if (d.isDateAsTimestamp() != null)
            database.setDateAsTimestamp(d.isDateAsTimestamp());
        if (g.getGenerate().isJavaTimeTypes() != null)
            database.setJavaTimeTypes(g.getGenerate().isJavaTimeTypes());
        if (d.isUnsignedTypes() != null)
            database.setSupportsUnsignedTypes(d.isUnsignedTypes());
        if (d.isIntegerDisplayWidths() != null)
            database.setIntegerDisplayWidths(d.isIntegerDisplayWidths());
        if (d.isIgnoreProcedureReturnValues() != null)
            database.setIgnoreProcedureReturnValues(d.isIgnoreProcedureReturnValues());
        if (Boolean.TRUE.equals(d.isIgnoreProcedureReturnValues()))
            log.warn("DEPRECATED", "The <ignoreProcedureReturnValues/> flag is deprecated and used for backwards-compatibility only. It will be removed in the future.");
        if (isBlank(g.getTarget().getPackageName()))
            g.getTarget().setPackageName(DEFAULT_TARGET_PACKAGENAME);
        if (isBlank(g.getTarget().getDirectory()))
            g.getTarget().setDirectory(DEFAULT_TARGET_DIRECTORY);
        if (isBlank(g.getTarget().getEncoding()))
            g.getTarget().setEncoding(DEFAULT_TARGET_ENCODING);
        // [#2887] [#9727] Patch relative paths to take plugin execution basedir into account
        if (!new File(g.getTarget().getDirectory()).isAbsolute())
            g.getTarget().setDirectory(new File(configuration.getBasedir(), g.getTarget().getDirectory()).getCanonicalPath());
        generator.setTargetPackage(g.getTarget().getPackageName());
        generator.setTargetDirectory(g.getTarget().getDirectory());
        generator.setTargetEncoding(g.getTarget().getEncoding());
        if (g.getTarget().isClean() != null)
            generator.setTargetClean(g.getTarget().isClean());
        generator.setTargetLocale(locale);
        if (g.getGenerate().isIndexes() != null)
            generator.setGenerateIndexes(g.getGenerate().isIndexes());
        if (g.getGenerate().isRelations() != null)
            generator.setGenerateRelations(g.getGenerate().isRelations());
        if (g.getGenerate().isImplicitJoinPathsToOne() != null)
            generator.setGenerateImplicitJoinPathsToOne(g.getGenerate().isImplicitJoinPathsToOne());
        if (g.getGenerate().isRowConvenienceToOne() != null)
            generator.setGenerateRowConvenienceToOne(g.getGenerate().isRowConvenienceToOne());
        if (g.getGenerate().isMultisetConvenienceOneToMany() != null)
            generator.setGenerateMultisetConvenienceOneToMany(g.getGenerate().isMultisetConvenienceOneToMany());
        if (g.getGenerate().isMultisetConvenienceManyToMany() != null)
            generator.setGenerateMultisetConvenienceManyToMany(g.getGenerate().isMultisetConvenienceManyToMany());
        if (g.getGenerate().isDeprecated() != null)
            generator.setGenerateDeprecated(g.getGenerate().isDeprecated());
        if (g.getGenerate().isDeprecationOnUnknownTypes() != null)
            generator.setGenerateDeprecationOnUnknownTypes(g.getGenerate().isDeprecationOnUnknownTypes());
        if (g.getGenerate().isInstanceFields() != null)
            generator.setGenerateInstanceFields(g.getGenerate().isInstanceFields());
        if (g.getGenerate().getVisibilityModifier() != null)
            generator.setGenerateVisibilityModifier(g.getGenerate().getVisibilityModifier());
        if (g.getGenerate().isGeneratedAnnotation() != null)
            generator.setGenerateGeneratedAnnotation(g.getGenerate().isGeneratedAnnotation());
        if (g.getGenerate().getGeneratedAnnotationType() != null)
            generator.setGenerateGeneratedAnnotationType(g.getGenerate().getGeneratedAnnotationType());
        if (g.getGenerate().isGeneratedAnnotationDate() != null)
            generator.setGenerateGeneratedAnnotationDate(g.getGenerate().isGeneratedAnnotationDate());
        if (g.getGenerate().isNonnullAnnotation() != null)
            generator.setGenerateNonnullAnnotation(g.getGenerate().isNonnullAnnotation());
        if (g.getGenerate().getNonnullAnnotationType() != null)
            generator.setGeneratedNonnullAnnotationType(g.getGenerate().getNonnullAnnotationType());
        if (g.getGenerate().isNullableAnnotation() != null)
            generator.setGenerateNullableAnnotation(g.getGenerate().isNullableAnnotation());
        if (g.getGenerate().getNullableAnnotationType() != null)
            generator.setGeneratedNullableAnnotationType(g.getGenerate().getNullableAnnotationType());
        if (g.getGenerate().isConstructorPropertiesAnnotation() != null)
            generator.setGenerateConstructorPropertiesAnnotation(g.getGenerate().isConstructorPropertiesAnnotation());
        if (g.getGenerate().isConstructorPropertiesAnnotationOnPojos() != null)
            generator.setGenerateConstructorPropertiesAnnotationOnPojos(g.getGenerate().isConstructorPropertiesAnnotationOnPojos());
        if (g.getGenerate().isConstructorPropertiesAnnotationOnRecords() != null)
            generator.setGenerateConstructorPropertiesAnnotationOnRecords(g.getGenerate().isConstructorPropertiesAnnotationOnRecords());
        if (g.getGenerate().isRoutines() != null)
            generator.setGenerateRoutines(g.getGenerate().isRoutines());
        if (g.getGenerate().isSequences() != null)
            generator.setGenerateSequences(g.getGenerate().isSequences());
        if (g.getGenerate().isSequenceFlags() != null)
            generator.setGenerateSequenceFlags(g.getGenerate().isSequenceFlags());
        if (g.getGenerate().isUdts() != null)
            generator.setGenerateUDTs(g.getGenerate().isUdts());
        if (g.getGenerate().isTables() != null)
            generator.setGenerateTables(g.getGenerate().isTables());
        if (g.getGenerate().isEmbeddables() != null)
            generator.setGenerateEmbeddables(g.getGenerate().isEmbeddables());
        if (g.getGenerate().isRecords() != null)
            generator.setGenerateRecords(g.getGenerate().isRecords());
        if (g.getGenerate().isRecordsImplementingRecordN() != null)
            generator.setGenerateRecordsImplementingRecordN(g.getGenerate().isRecordsImplementingRecordN());
        if (g.getGenerate().isEnumsAsScalaSealedTraits() != null)
            generator.setGenerateEnumsAsScalaSealedTraits(g.getGenerate().isEnumsAsScalaSealedTraits());
        if (g.getGenerate().isPojos() != null)
            generator.setGeneratePojos(g.getGenerate().isPojos());
        if (g.getGenerate().isPojosAsJavaRecordClasses() != null)
            generator.setGeneratePojosAsJavaRecordClasses(g.getGenerate().isPojosAsJavaRecordClasses());
        if (g.getGenerate().isPojosAsScalaCaseClasses() != null)
            generator.setGeneratePojosAsScalaCaseClasses(g.getGenerate().isPojosAsScalaCaseClasses());
        if (g.getGenerate().isPojosAsKotlinDataClasses() != null)
            generator.setGeneratePojosAsKotlinDataClasses(g.getGenerate().isPojosAsKotlinDataClasses());
        if (g.getGenerate().isImmutablePojos() != null)
            generator.setGenerateImmutablePojos(g.getGenerate().isImmutablePojos());
        if (g.getGenerate().isSerializablePojos() != null)
            generator.setGenerateSerializablePojos(g.getGenerate().isSerializablePojos());
        if (g.getGenerate().isInterfaces() != null)
            generator.setGenerateInterfaces(g.getGenerate().isInterfaces());
        if (g.getGenerate().isImmutableInterfaces() != null)
            generator.setGenerateImmutableInterfaces(g.getGenerate().isImmutableInterfaces());
        if (g.getGenerate().isSerializableInterfaces() != null)
            generator.setGenerateSerializableInterfaces(g.getGenerate().isSerializableInterfaces());
        if (g.getGenerate().isDaos() != null)
            generator.setGenerateDaos(g.getGenerate().isDaos());
        if (g.getGenerate().isJooqVersionReference() != null)
            generator.setGenerateJooqVersionReference(g.getGenerate().isJooqVersionReference());
        if (g.getGenerate().isJpaAnnotations() != null)
            generator.setGenerateJPAAnnotations(g.getGenerate().isJpaAnnotations());
        if (g.getGenerate().getJpaVersion() != null)
            generator.setGenerateJPAVersion(g.getGenerate().getJpaVersion());
        if (g.getGenerate().isValidationAnnotations() != null)
            generator.setGenerateValidationAnnotations(g.getGenerate().isValidationAnnotations());
        if (g.getGenerate().isSpringAnnotations() != null)
            generator.setGenerateSpringAnnotations(g.getGenerate().isSpringAnnotations());
        if (g.getGenerate().isKotlinSetterJvmNameAnnotationsOnIsPrefix() != null)
            generator.setGenerateKotlinSetterJvmNameAnnotationsOnIsPrefix(g.getGenerate().isKotlinSetterJvmNameAnnotationsOnIsPrefix());
        if (g.getGenerate().getGeneratedSerialVersionUID() != null)
            generator.setGenerateGeneratedSerialVersionUID(g.getGenerate().getGeneratedSerialVersionUID());
        if (g.getGenerate().getMaxMembersPerInitialiser() != null)
            generator.setMaxMembersPerInitialiser(g.getGenerate().getMaxMembersPerInitialiser());
        if (g.getGenerate().isQueues() != null)
            generator.setGenerateQueues(g.getGenerate().isQueues());
        if (g.getGenerate().isLinks() != null)
            generator.setGenerateLinks(g.getGenerate().isLinks());
        if (g.getGenerate().isKeys() != null)
            generator.setGenerateKeys(g.getGenerate().isKeys());
        if (g.getGenerate().isGlobalObjectReferences() != null)
            generator.setGenerateGlobalObjectReferences(g.getGenerate().isGlobalObjectReferences());
        if (g.getGenerate().isGlobalCatalogReferences() != null)
            generator.setGenerateGlobalCatalogReferences(g.getGenerate().isGlobalCatalogReferences());
        if (g.getGenerate().isGlobalDomainReferences() != null)
            generator.setGenerateGlobalDomainReferences(g.getGenerate().isGlobalDomainReferences());
        if (g.getGenerate().isGlobalSchemaReferences() != null)
            generator.setGenerateGlobalSchemaReferences(g.getGenerate().isGlobalSchemaReferences());
        if (g.getGenerate().isGlobalRoutineReferences() != null)
            generator.setGenerateGlobalRoutineReferences(g.getGenerate().isGlobalRoutineReferences());
        if (g.getGenerate().isGlobalSequenceReferences() != null)
            generator.setGenerateGlobalSequenceReferences(g.getGenerate().isGlobalSequenceReferences());
        if (g.getGenerate().isGlobalTableReferences() != null)
            generator.setGenerateGlobalTableReferences(g.getGenerate().isGlobalTableReferences());
        if (g.getGenerate().isGlobalUDTReferences() != null)
            generator.setGenerateGlobalUDTReferences(g.getGenerate().isGlobalUDTReferences());
        if (g.getGenerate().isGlobalQueueReferences() != null)
            generator.setGenerateGlobalQueueReferences(g.getGenerate().isGlobalQueueReferences());
        if (g.getGenerate().isGlobalLinkReferences() != null)
            generator.setGenerateGlobalLinkReferences(g.getGenerate().isGlobalLinkReferences());
        if (g.getGenerate().isGlobalKeyReferences() != null)
            generator.setGenerateGlobalKeyReferences(g.getGenerate().isGlobalKeyReferences());
        if (g.getGenerate().isGlobalIndexReferences() != null)
            generator.setGenerateGlobalIndexReferences(g.getGenerate().isGlobalIndexReferences());
        if (g.getGenerate().isJavadoc() != null)
            generator.setGenerateJavadoc(g.getGenerate().isJavadoc());
        if (g.getGenerate().isComments() != null)
            generator.setGenerateComments(g.getGenerate().isComments());
        if (g.getGenerate().isCommentsOnAttributes() != null)
            generator.setGenerateCommentsOnAttributes(g.getGenerate().isCommentsOnAttributes());
        if (g.getGenerate().isCommentsOnCatalogs() != null)
            generator.setGenerateCommentsOnCatalogs(g.getGenerate().isCommentsOnCatalogs());
        if (g.getGenerate().isCommentsOnColumns() != null)
            generator.setGenerateCommentsOnColumns(g.getGenerate().isCommentsOnColumns());
        if (g.getGenerate().isCommentsOnKeys() != null)
            generator.setGenerateCommentsOnKeys(g.getGenerate().isCommentsOnKeys());
        if (g.getGenerate().isCommentsOnLinks() != null)
            generator.setGenerateCommentsOnLinks(g.getGenerate().isCommentsOnLinks());
        if (g.getGenerate().isCommentsOnPackages() != null)
            generator.setGenerateCommentsOnPackages(g.getGenerate().isCommentsOnPackages());
        if (g.getGenerate().isCommentsOnParameters() != null)
            generator.setGenerateCommentsOnParameters(g.getGenerate().isCommentsOnParameters());
        if (g.getGenerate().isCommentsOnQueues() != null)
            generator.setGenerateCommentsOnQueues(g.getGenerate().isCommentsOnQueues());
        if (g.getGenerate().isCommentsOnRoutines() != null)
            generator.setGenerateCommentsOnRoutines(g.getGenerate().isCommentsOnRoutines());
        if (g.getGenerate().isCommentsOnSchemas() != null)
            generator.setGenerateCommentsOnSchemas(g.getGenerate().isCommentsOnSchemas());
        if (g.getGenerate().isCommentsOnSequences() != null)
            generator.setGenerateCommentsOnSequences(g.getGenerate().isCommentsOnSequences());
        if (g.getGenerate().isCommentsOnTables() != null)
            generator.setGenerateCommentsOnTables(g.getGenerate().isCommentsOnTables());
        if (g.getGenerate().isCommentsOnEmbeddables() != null)
            generator.setGenerateCommentsOnEmbeddables(g.getGenerate().isCommentsOnEmbeddables());
        if (g.getGenerate().isCommentsOnUDTs() != null)
            generator.setGenerateCommentsOnUDTs(g.getGenerate().isCommentsOnUDTs());
        if (g.getGenerate().isSources() != null)
            generator.setGenerateSources(g.getGenerate().isSources());
        if (g.getGenerate().isSourcesOnViews() != null)
            generator.setGenerateSourcesOnViews(g.getGenerate().isSourcesOnViews());
        if (g.getGenerate().isFluentSetters() != null)
            generator.setGenerateFluentSetters(g.getGenerate().isFluentSetters());
        if (g.getGenerate().isJavaBeansGettersAndSetters() != null)
            generator.setGenerateJavaBeansGettersAndSetters(g.getGenerate().isJavaBeansGettersAndSetters());
        if (g.getGenerate().isVarargSetters() != null)
            generator.setGenerateVarargsSetters(g.getGenerate().isVarargSetters());
        if (g.getGenerate().isPojosEqualsAndHashCode() != null)
            generator.setGeneratePojosEqualsAndHashCode(g.getGenerate().isPojosEqualsAndHashCode());
        if (g.getGenerate().isPojosToString() != null)
            generator.setGeneratePojosToString(g.getGenerate().isPojosToString());
        if (g.getGenerate().getFullyQualifiedTypes() != null)
            generator.setGenerateFullyQualifiedTypes(g.getGenerate().getFullyQualifiedTypes());
        if (g.getGenerate().isJavaTimeTypes() != null)
            generator.setGenerateJavaTimeTypes(g.getGenerate().isJavaTimeTypes());
        if (g.getGenerate().isEmptyCatalogs() != null)
            generator.setGenerateEmptyCatalogs(g.getGenerate().isEmptyCatalogs());
        if (g.getGenerate().isEmptySchemas() != null)
            generator.setGenerateEmptySchemas(g.getGenerate().isEmptySchemas());
        if (g.getGenerate().getNewline() != null)
            generator.setGenerateNewline(g.getGenerate().getNewline());
        if (g.getGenerate().getIndentation() != null)
            generator.setGenerateIndentation(g.getGenerate().getIndentation());
        if (g.getGenerate().getPrintMarginForBlockComment() != null)
            generator.setGeneratePrintMarginForBlockComment(g.getGenerate().getPrintMarginForBlockComment());
        if (!isBlank(d.getSchemaVersionProvider()))
            generator.setUseSchemaVersionProvider(true);
        if (!isBlank(d.getCatalogVersionProvider()))
            generator.setUseCatalogVersionProvider(true);
        if (d.isTableValuedFunctions() != null)
            generator.setGenerateTableValuedFunctions(d.isTableValuedFunctions());
        else {
            generator.setGenerateTableValuedFunctions(true);
        }
        // Generator properties that should in fact be strategy properties
        strategy.setInstanceFields(generator.generateInstanceFields());
        strategy.setJavaBeansGettersAndSetters(generator.generateJavaBeansGettersAndSetters());
        verifyVersions();
        generator.generate(database);
        logUnused("forced type", "forced types", database.getUnusedForcedTypes());
        logUnused("embeddable", "embeddables", database.getUnusedEmbeddables());
        logUnused("comment", "comments", database.getUnusedComments());
        logUnused("synthetic identity", "synthetic identities", database.getUnusedSyntheticIdentities());
        logUnused("synthetic primary key", "synthetic primary keys", database.getUnusedSyntheticPrimaryKeys());
        logUnused("synthetic unique key", "synthetic unique keys", database.getUnusedSyntheticUniqueKeys());
        logUnused("synthetic foreign key", "synthetic foreign keys", database.getUnusedSyntheticForeignKeys());
        logUnused("synthetic view", "synthetic views", database.getUnusedSyntheticViews());
    } finally {
        if (database != null)
            try {
                database.close();
            } catch (Exception e) {
                log.error("Error while closing database", e);
            }
        // Close connection only if it was created by the GenerationTool
        if (connection != null) {
            if (close) {
                // [#11105] In case of misconfiguration, the ctx reference could be null as a side effect
                if (ctx != null && ctx.family() == HSQLDB && dataSource == null)
                    ctx.execute("shutdown");
                connection.close();
            } else if (autoCommit != null) {
                connection.setAutoCommit(autoCommit);
            }
        }
    }
}
Also used : Locale(java.util.Locale) SQLException(java.sql.SQLException) CatalogMappingType(org.jooq.meta.jaxb.CatalogMappingType) Driver(java.sql.Driver) StringUtils.defaultString(org.jooq.tools.StringUtils.defaultString) Properties(java.util.Properties) Comparator(java.util.Comparator) Target(org.jooq.meta.jaxb.Target) CatalogVersionProvider(org.jooq.meta.CatalogVersionProvider) Generate(org.jooq.meta.jaxb.Generate) Database(org.jooq.meta.Database) SchemaVersionProvider(org.jooq.meta.SchemaVersionProvider) SchemaMappingType(org.jooq.meta.jaxb.SchemaMappingType) Connection(java.sql.Connection) Matchers(org.jooq.meta.jaxb.Matchers) SQLException(java.sql.SQLException) IOException(java.io.IOException) Jdbc(org.jooq.meta.jaxb.Jdbc) Strategy(org.jooq.meta.jaxb.Strategy) File(java.io.File)

Aggregations

File (java.io.File)2 IOException (java.io.IOException)2 Connection (java.sql.Connection)2 SQLException (java.sql.SQLException)2 Comparator (java.util.Comparator)2 Properties (java.util.Properties)2 StringReader (java.io.StringReader)1 TRUE (java.lang.Boolean.TRUE)1 BigInteger (java.math.BigInteger)1 Driver (java.sql.Driver)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Arrays.asList (java.util.Arrays.asList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Collections.emptyList (java.util.Collections.emptyList)1 Comparator.comparing (java.util.Comparator.comparing)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1