Search in sources :

Example 1 with Domain

use of org.jooq.Domain in project jOOQ by jOOQ.

the class JavaGenerator method generateDomainReferences.

/**
 * Generating central static domain access
 */
protected void generateDomainReferences(SchemaDefinition schema) {
    log.info("Generating DOMAIN references");
    JavaWriter out = newJavaWriter(getStrategy().getGlobalReferencesFile(schema, DomainDefinition.class));
    out.refConflicts(getStrategy().getJavaIdentifiers(database.getDomains(schema)));
    printGlobalReferencesPackage(out, schema, DomainDefinition.class);
    final String schemaId = out.ref(getStrategy().getFullJavaIdentifier(schema), 2);
    if (!kotlin) {
        printClassJavadoc(out, "Convenience access to all Domains in " + schemaNameOrDefault(schema) + ".");
        printClassAnnotations(out, schema, Mode.DOMAIN);
    }
    final String referencesClassName = getStrategy().getGlobalReferencesJavaClassName(schema, DomainDefinition.class);
    if (scala)
        out.println("%sobject %s {", visibility(), referencesClassName);
    else if (kotlin) {
    } else
        out.println("%sclass %s {", visibility(), referencesClassName);
    for (DomainDefinition domain : database.getDomains(schema)) {
        final String id = getStrategy().getJavaIdentifier(domain);
        final String domainTypeFull = getJavaType(domain.getType(resolver(out)), out);
        final String domainType = out.ref(domainTypeFull);
        final String domainTypeRef = getJavaTypeReference(domain.getDatabase(), domain.getType(resolver(out)), out);
        out.javadoc("The domain <code>%s</code>.", domain.getQualifiedOutputName());
        if (scala) {
            out.println("%sval %s: %s[%s] = %s.createDomain(", visibility(), scalaWhitespaceSuffix(id), Domain.class, domainType, Internal.class);
            out.println("  schema");
            out.println(", %s.name(\"%s\")", DSL.class, escapeString(domain.getOutputName()));
            out.println(", %s", domainTypeRef);
            for (String check : domain.getCheckClauses()) out.println(", %s.createCheck(null, null, \"%s\")", Internal.class, escapeString(check));
            out.println(")");
        } else if (kotlin) {
            out.println("%sval %s: %s<%s> = %s.createDomain(", visibility(), id, Domain.class, domainType, Internal.class);
            out.println("  schema()");
            out.println(", %s.name(\"%s\")", DSL.class, escapeString(domain.getOutputName()));
            out.println(", %s", domainTypeRef);
            for (String check : domain.getCheckClauses()) out.println(", %s.createCheck<%s>(null, null, \"%s\")", Internal.class, Record.class, escapeString(check));
            out.println(")");
        } else {
            out.println("%sstatic final %s<%s> %s = %s.createDomain(", visibility(), Domain.class, domainType, id, Internal.class);
            out.println("  schema()");
            out.println(", %s.name(\"%s\")", DSL.class, escapeString(domain.getOutputName()));
            out.println(", %s", domainTypeRef);
            for (String check : domain.getCheckClauses()) out.println(", %s.createCheck(null, null, \"%s\")", Internal.class, escapeString(check));
            out.println(");");
        }
    }
    if (scala) {
        out.println();
        out.println("private def schema: %s = new %s(%s.name(\"%s\"), %s.comment(\"\"), () => %s)", Schema.class, LazySchema.class, DSL.class, escapeString(schema.getOutputName()), DSL.class, schemaId);
    } else if (kotlin) {
        out.println();
        out.println("private fun schema(): %s = %s(%s.name(\"%s\"), %s.comment(\"\"), %s { %s })", Schema.class, LazySchema.class, DSL.class, escapeString(schema.getOutputName()), DSL.class, LazySupplier.class, schemaId);
    } else {
        out.println();
        out.println("private static final %s schema() {", Schema.class);
        out.println("return new %s(%s.name(\"%s\"), %s.comment(\"\"), () -> %s);", LazySchema.class, DSL.class, escapeString(schema.getOutputName()), DSL.class, schemaId);
        out.println("}");
    }
    generateDomainReferencesClassFooter(schema, out);
    if (!kotlin)
        out.println("}");
    closeJavaWriter(out);
    watch.splitInfo("DOMAIN references generated");
}
Also used : LazySupplier(org.jooq.impl.LazySupplier) DomainDefinition(org.jooq.meta.DomainDefinition) LazySchema(org.jooq.impl.LazySchema) Internal(org.jooq.impl.Internal) Schema(org.jooq.Schema) LazySchema(org.jooq.impl.LazySchema) Domain(org.jooq.Domain) DSL(org.jooq.impl.DSL)

Example 2 with Domain

use of org.jooq.Domain in project jOOQ by jOOQ.

the class InformationSchemaExport method exportDomain0.

private static final void exportDomain0(Configuration configuration, InformationSchema result, Domain<?> d) {
    org.jooq.util.xml.jaxb.Domain id = new org.jooq.util.xml.jaxb.Domain();
    String catalogName = catalogName(d);
    String schemaName = schemaName(d);
    String domainName = d.getName();
    if (!isBlank(catalogName))
        id.setDomainCatalog(catalogName);
    if (!isBlank(schemaName))
        id.setDomainSchema(schemaName);
    id.setDomainName(domainName);
    id.setDataType(d.getDataType().getTypeName(configuration));
    if (d.getDataType().lengthDefined())
        id.setCharacterMaximumLength(d.getDataType().length());
    if (d.getDataType().precisionDefined())
        id.setNumericPrecision(d.getDataType().precision());
    if (d.getDataType().scaleDefined())
        id.setNumericScale(d.getDataType().scale());
    result.getDomains().add(id);
    for (Check<?> c : d.getChecks()) {
        org.jooq.util.xml.jaxb.DomainConstraint idc = new org.jooq.util.xml.jaxb.DomainConstraint();
        org.jooq.util.xml.jaxb.CheckConstraint icc = new org.jooq.util.xml.jaxb.CheckConstraint();
        if (!isBlank(catalogName)) {
            idc.setDomainCatalog(catalogName);
            idc.setConstraintCatalog(catalogName);
            icc.setConstraintCatalog(catalogName);
        }
        if (!isBlank(schemaName)) {
            idc.setDomainSchema(schemaName);
            idc.setConstraintSchema(schemaName);
            icc.setConstraintSchema(schemaName);
        }
        idc.setDomainName(domainName);
        idc.setConstraintName(c.getName());
        icc.setConstraintName(c.getName());
        icc.setCheckClause(configuration.dsl().render(c.condition()));
        result.getDomainConstraints().add(idc);
        result.getCheckConstraints().add(icc);
    }
}
Also used : CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) Domain(org.jooq.Domain) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint)

Example 3 with Domain

use of org.jooq.Domain in project jOOQ by jOOQ.

the class JavaGenerator method generateSchema.

protected void generateSchema(SchemaDefinition schema, JavaWriter out) {
    final String catalogId = out.ref(getStrategy().getFullJavaIdentifier(schema.getCatalog()), 2);
    final String schemaId = getStrategy().getJavaIdentifier(schema);
    final String schemaName = !schema.getQualifiedOutputName().isEmpty() ? schema.getQualifiedOutputName() : schemaId;
    final String className = getStrategy().getJavaClassName(schema);
    final List<String> interfaces = out.ref(getStrategy().getJavaClassImplements(schema, Mode.DEFAULT));
    printPackage(out, schema);
    if (scala) {
        out.println("object %s {", className);
        out.javadoc("The reference instance of <code>%s</code>", schemaName);
        out.println("val %s = new %s", schemaId, className);
        out.println("}");
        out.println();
    }
    generateSchemaClassJavadoc(schema, out);
    printClassAnnotations(out, schema, Mode.DEFAULT);
    if (scala) {
        out.println("%sclass %s extends %s(\"%s\", %s)[[before= with ][separator= with ][%s]] {", visibility(), className, SchemaImpl.class, escapeString(schema.getOutputName()), catalogId, interfaces);
    } else if (kotlin) {
        out.println("%sopen class %s : %s(\"%s\", %s)[[before=, ][%s]] {", visibility(), className, SchemaImpl.class, escapeString(schema.getOutputName()), catalogId, interfaces);
        out.println("public companion object {");
        out.javadoc("The reference instance of <code>%s</code>", schemaName);
        out.println("%sval %s: %s = %s()", visibility(), scalaWhitespaceSuffix(schemaId), className, className);
        out.println("}");
    } else {
        out.println("%sclass %s extends %s[[before= implements ][%s]] {", visibility(), className, SchemaImpl.class, interfaces);
        out.printSerial();
        out.javadoc("The reference instance of <code>%s</code>", schemaName);
        out.println("%sstatic final %s %s = new %s();", visibility(), className, schemaId, className);
    }
    if (generateGlobalTableReferences()) {
        Set<String> memberNames = getMemberNames(schema);
        for (TableDefinition table : schema.getTables()) {
            // reference in the schema, and the function call
            if (scala && table.isTableValuedFunction() && table.getParameters().isEmpty())
                continue;
            final String tableClassName = out.ref(getStrategy().getFullJavaClassName(table));
            final String tableId = getStrategy().getJavaIdentifier(table);
            final String tableShortId = getShortId(out, memberNames, table);
            final String tableComment = escapeEntities(comment(table));
            out.javadoc(isBlank(tableComment) ? "The table <code>" + table.getQualifiedOutputName() + "</code>." : tableComment);
            if (scala)
                out.println("%sdef %s = %s", visibility(), tableId, tableShortId);
            else if (kotlin)
                out.println("%sval %s: %s get() = %s", visibility(), scalaWhitespaceSuffix(tableId), tableClassName, tableShortId);
            else
                out.println("%sfinal %s %s = %s;", visibility(), tableClassName, tableId, tableShortId);
            // globalObjectReferences
            if (table.isTableValuedFunction())
                printTableValuedFunction(out, table, getStrategy().getJavaIdentifier(table));
        }
    }
    if (!scala && !kotlin) {
        out.javadoc(NO_FURTHER_INSTANCES_ALLOWED);
        out.println("private %s() {", className);
        out.println("super(\"%s\", null);", escapeString(schema.getOutputName()));
        out.println("}");
    }
    out.println();
    if (scala) {
        out.println("%soverride def getCatalog: %s = %s", visibilityPublic(), Catalog.class, catalogId);
    } else if (kotlin) {
        out.println("%soverride fun getCatalog(): %s = %s", visibilityPublic(), Catalog.class, catalogId);
    } else {
        out.overrideInherit();
        printNonnullAnnotation(out);
        out.println("%s%s getCatalog() {", visibilityPublic(), Catalog.class);
        out.println("return %s;", catalogId);
        out.println("}");
    }
    // [#2255] Avoid referencing sequence literals, if they're not generated
    if (generateGlobalSequenceReferences())
        printReferences(out, database.getSequences(schema), Sequence.class, true);
    // [#681] Avoid referencing domain literals, if they're not generated
    if (generateGlobalDomainReferences())
        printReferences(out, database.getDomains(schema), Domain.class, true);
    // [#9685] Avoid referencing table literals if they're not generated
    if (generateTables())
        printReferences(out, database.getTables(schema), Table.class, true);
    // [#9685] Avoid referencing UDT literals if they're not generated
    if (generateUDTs())
        printReferences(out, database.getUDTs(schema), UDT.class, true);
    generateSchemaClassFooter(schema, out);
    out.println("}");
}
Also used : SchemaImpl(org.jooq.impl.SchemaImpl) Table(org.jooq.Table) UDT(org.jooq.UDT) TableDefinition(org.jooq.meta.TableDefinition) Sequence(org.jooq.Sequence) Domain(org.jooq.Domain) Catalog(org.jooq.Catalog)

Example 4 with Domain

use of org.jooq.Domain in project jOOQ by jOOQ.

the class InformationSchemaMetaImpl method init.

@SuppressWarnings({ "unchecked", "rawtypes" })
private final void init(InformationSchema meta) {
    List<String> errors = new ArrayList<>();
    // Catalogs
    // -------------------------------------------------------------------------------------------------------------
    boolean hasCatalogs = false;
    for (org.jooq.util.xml.jaxb.Catalog xc : meta.getCatalogs()) {
        InformationSchemaCatalog ic = new InformationSchemaCatalog(xc.getCatalogName(), xc.getComment());
        catalogs.add(ic);
        catalogsByName.put(name(xc.getCatalogName()), ic);
        hasCatalogs = true;
    }
    // -------------------------------------------------------------------------------------------------------------
    schemaLoop: for (org.jooq.util.xml.jaxb.Schema xs : meta.getSchemata()) {
        // [#6662] This is kept for backwards compatibility reasons
        if (!hasCatalogs) {
            InformationSchemaCatalog ic = new InformationSchemaCatalog(xs.getCatalogName(), null);
            if (!catalogs.contains(ic)) {
                catalogs.add(ic);
                catalogsByName.put(name(xs.getCatalogName()), ic);
            }
        }
        Name catalogName = name(xs.getCatalogName());
        Catalog catalog = catalogsByName.get(catalogName);
        if (catalog == null) {
            errors.add("Catalog " + catalogName + " not defined for schema " + xs.getSchemaName());
            continue schemaLoop;
        }
        InformationSchemaSchema is = new InformationSchemaSchema(xs.getSchemaName(), catalog, xs.getComment());
        schemas.add(is);
        schemasByName.put(name(xs.getCatalogName(), xs.getSchemaName()), is);
    }
    // -------------------------------------------------------------------------------------------------------------
    domainLoop: for (org.jooq.util.xml.jaxb.Domain d : meta.getDomains()) {
        Name schemaName = name(d.getDomainCatalog(), d.getDomainSchema());
        Schema schema = schemasByName.get(schemaName);
        if (schema == null) {
            errors.add("Schema " + schemaName + " not defined for domain " + d.getDomainName());
            continue domainLoop;
        }
        Name domainName = name(d.getDomainCatalog(), d.getDomainSchema(), d.getDomainName());
        int length = d.getCharacterMaximumLength() == null ? 0 : d.getCharacterMaximumLength();
        int precision = d.getNumericPrecision() == null ? 0 : d.getNumericPrecision();
        int scale = d.getNumericScale() == null ? 0 : d.getNumericScale();
        // TODO [#10239] Support NOT NULL constraints
        boolean nullable = true;
        List<Check<?>> checks = new ArrayList<>();
        for (org.jooq.util.xml.jaxb.DomainConstraint dc : meta.getDomainConstraints()) {
            if (domainName.equals(name(dc.getDomainCatalog(), dc.getDomainSchema(), dc.getDomainName()))) {
                Name constraintName = name(dc.getConstraintCatalog(), dc.getConstraintSchema(), dc.getConstraintName());
                for (org.jooq.util.xml.jaxb.CheckConstraint cc : meta.getCheckConstraints()) if (constraintName.equals(name(cc.getConstraintCatalog(), cc.getConstraintSchema(), cc.getConstraintName())))
                    checks.add(new CheckImpl<>(null, constraintName, DSL.condition(cc.getCheckClause()), true));
            }
        }
        InformationSchemaDomain<?> id = new InformationSchemaDomain<Object>(schema, name(d.getDomainName()), (DataType) type(d.getDataType(), length, precision, scale, nullable, false, null, null), checks.toArray(EMPTY_CHECK));
        domains.add(id);
        domainsByName.put(domainName, id);
    }
    // -------------------------------------------------------------------------------------------------------------
    tableLoop: for (org.jooq.util.xml.jaxb.Table xt : meta.getTables()) {
        Name schemaName = name(xt.getTableCatalog(), xt.getTableSchema());
        Schema schema = schemasByName.get(schemaName);
        if (schema == null) {
            errors.add("Schema " + schemaName + " not defined for table " + xt.getTableName());
            continue tableLoop;
        }
        TableType tableType;
        switch(xt.getTableType()) {
            case GLOBAL_TEMPORARY:
                tableType = TableType.TEMPORARY;
                break;
            case VIEW:
                tableType = TableType.VIEW;
                break;
            case BASE_TABLE:
            default:
                tableType = TableType.TABLE;
                break;
        }
        String sql = null;
        if (tableType == TableType.VIEW) {
            viewLoop: for (org.jooq.util.xml.jaxb.View vt : meta.getViews()) {
                if (StringUtils.equals(defaultIfNull(xt.getTableCatalog(), ""), defaultIfNull(vt.getTableCatalog(), "")) && StringUtils.equals(defaultIfNull(xt.getTableSchema(), ""), defaultIfNull(vt.getTableSchema(), "")) && StringUtils.equals(defaultIfNull(xt.getTableName(), ""), defaultIfNull(vt.getTableName(), ""))) {
                    sql = vt.getViewDefinition();
                    break viewLoop;
                }
            }
        }
        InformationSchemaTable it = new InformationSchemaTable(xt.getTableName(), schema, xt.getComment(), tableType, sql);
        tables.add(it);
        tablesByName.put(name(xt.getTableCatalog(), xt.getTableSchema(), xt.getTableName()), it);
    }
    // Columns
    // -------------------------------------------------------------------------------------------------------------
    List<Column> columns = new ArrayList<>(meta.getColumns());
    columns.sort((o1, o2) -> {
        Integer p1 = o1.getOrdinalPosition();
        Integer p2 = o2.getOrdinalPosition();
        if (Objects.equals(p1, p2))
            return 0;
        if (p1 == null)
            return -1;
        if (p2 == null)
            return 1;
        return p1.compareTo(p2);
    });
    columnLoop: for (Column xc : columns) {
        String typeName = xc.getDataType();
        int length = xc.getCharacterMaximumLength() == null ? 0 : xc.getCharacterMaximumLength();
        int precision = xc.getNumericPrecision() == null ? 0 : xc.getNumericPrecision();
        int scale = xc.getNumericScale() == null ? 0 : xc.getNumericScale();
        boolean nullable = !FALSE.equals(xc.isIsNullable());
        boolean readonly = TRUE.equals(xc.isReadonly());
        Field<?> generatedAlwaysAs = TRUE.equals(xc.isIsGenerated()) ? DSL.field(xc.getGenerationExpression()) : null;
        GenerationOption generationOption = TRUE.equals(xc.isIsGenerated()) ? "STORED".equalsIgnoreCase(xc.getGenerationOption()) ? STORED : "VIRTUAL".equalsIgnoreCase(xc.getGenerationOption()) ? VIRTUAL : null : null;
        // TODO: Exception handling should be moved inside SQLDataType
        Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
        InformationSchemaTable table = tablesByName.get(tableName);
        if (table == null) {
            errors.add("Table " + tableName + " not defined for column " + xc.getColumnName());
            continue columnLoop;
        }
        AbstractTable.createField(name(xc.getColumnName()), type(typeName, length, precision, scale, nullable, readonly, generatedAlwaysAs, generationOption), table, xc.getComment());
    }
    // Indexes
    // -------------------------------------------------------------------------------------------------------------
    Map<Name, List<SortField<?>>> columnsByIndex = new HashMap<>();
    List<IndexColumnUsage> indexColumnUsages = new ArrayList<>(meta.getIndexColumnUsages());
    indexColumnUsages.sort(comparingInt(IndexColumnUsage::getOrdinalPosition));
    indexColumnLoop: for (IndexColumnUsage ic : indexColumnUsages) {
        Name indexName = name(ic.getIndexCatalog(), ic.getIndexSchema(), ic.getTableName(), ic.getIndexName());
        List<SortField<?>> fields = columnsByIndex.computeIfAbsent(indexName, k -> new ArrayList<>());
        Name tableName = name(ic.getTableCatalog(), ic.getTableSchema(), ic.getTableName());
        InformationSchemaTable table = tablesByName.get(tableName);
        if (table == null) {
            errors.add("Table " + tableName + " not defined for index " + indexName);
            continue indexColumnLoop;
        }
        TableField<Record, ?> field = (TableField<Record, ?>) table.field(ic.getColumnName());
        if (field == null) {
            errors.add("Column " + ic.getColumnName() + " not defined for table " + tableName);
            continue indexColumnLoop;
        }
        fields.add(Boolean.TRUE.equals(ic.isIsDescending()) ? field.desc() : field.asc());
    }
    indexLoop: for (org.jooq.util.xml.jaxb.Index i : meta.getIndexes()) {
        Name tableName = name(i.getTableCatalog(), i.getTableSchema(), i.getTableName());
        Name indexName = name(i.getIndexCatalog(), i.getIndexSchema(), i.getTableName(), i.getIndexName());
        InformationSchemaTable table = tablesByName.get(tableName);
        if (table == null) {
            errors.add("Table " + tableName + " not defined for index " + indexName);
            continue indexLoop;
        }
        List<SortField<?>> c = columnsByIndex.get(indexName);
        if (c == null || c.isEmpty()) {
            errors.add("No columns defined for index " + indexName);
            continue indexLoop;
        }
        IndexImpl index = (IndexImpl) Internal.createIndex(i.getIndexName(), table, c.toArray(EMPTY_SORTFIELD), Boolean.TRUE.equals(i.isIsUnique()));
        table.indexes.add(index);
        indexesByName.put(indexName, index);
    }
    // Constraints
    // -------------------------------------------------------------------------------------------------------------
    Map<Name, List<TableField<Record, ?>>> columnsByConstraint = new HashMap<>();
    List<KeyColumnUsage> keyColumnUsages = new ArrayList<>(meta.getKeyColumnUsages());
    keyColumnUsages.sort(comparing(KeyColumnUsage::getOrdinalPosition));
    keyColumnLoop: for (KeyColumnUsage xc : keyColumnUsages) {
        Name constraintName = name(xc.getConstraintCatalog(), xc.getConstraintSchema(), xc.getConstraintName());
        List<TableField<Record, ?>> fields = columnsByConstraint.computeIfAbsent(constraintName, k -> new ArrayList<>());
        Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
        InformationSchemaTable table = tablesByName.get(tableName);
        if (table == null) {
            errors.add("Table " + tableName + " not defined for constraint " + constraintName);
            continue keyColumnLoop;
        }
        TableField<Record, ?> field = (TableField<Record, ?>) table.field(xc.getColumnName());
        if (field == null) {
            errors.add("Column " + xc.getColumnName() + " not defined for table " + tableName);
            continue keyColumnLoop;
        }
        fields.add(field);
    }
    tableConstraintLoop: for (TableConstraint xc : meta.getTableConstraints()) {
        switch(xc.getConstraintType()) {
            case PRIMARY_KEY:
            case UNIQUE:
                {
                    Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
                    Name constraintName = name(xc.getConstraintCatalog(), xc.getConstraintSchema(), xc.getConstraintName());
                    InformationSchemaTable table = tablesByName.get(tableName);
                    if (table == null) {
                        errors.add("Table " + tableName + " not defined for constraint " + constraintName);
                        continue tableConstraintLoop;
                    }
                    List<TableField<Record, ?>> c = columnsByConstraint.get(constraintName);
                    if (c == null || c.isEmpty()) {
                        errors.add("No columns defined for constraint " + constraintName);
                        continue tableConstraintLoop;
                    }
                    UniqueKeyImpl<Record> key = (UniqueKeyImpl<Record>) Internal.createUniqueKey(table, xc.getConstraintName(), c.toArray(new TableField[0]));
                    if (xc.getConstraintType() == PRIMARY_KEY) {
                        table.primaryKey = key;
                        primaryKeys.add(key);
                    } else
                        table.uniqueKeys.add(key);
                    keysByName.put(constraintName, key);
                    break;
                }
        }
    }
    for (ReferentialConstraint xr : meta.getReferentialConstraints()) {
        referentialKeys.put(name(xr.getConstraintCatalog(), xr.getConstraintSchema(), xr.getConstraintName()), name(xr.getUniqueConstraintCatalog(), xr.getUniqueConstraintSchema(), xr.getUniqueConstraintName()));
    }
    tableConstraintLoop: for (TableConstraint xc : meta.getTableConstraints()) {
        switch(xc.getConstraintType()) {
            case FOREIGN_KEY:
                {
                    Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
                    Name constraintName = name(xc.getConstraintCatalog(), xc.getConstraintSchema(), xc.getConstraintName());
                    InformationSchemaTable table = tablesByName.get(tableName);
                    if (table == null) {
                        errors.add("Table " + tableName + " not defined for constraint " + constraintName);
                        continue tableConstraintLoop;
                    }
                    List<TableField<Record, ?>> c = columnsByConstraint.get(constraintName);
                    if (c == null || c.isEmpty()) {
                        errors.add("No columns defined for constraint " + constraintName);
                        continue tableConstraintLoop;
                    }
                    UniqueKeyImpl<Record> uniqueKey = keysByName.get(referentialKeys.get(constraintName));
                    if (uniqueKey == null) {
                        errors.add("No unique key defined for foreign key " + constraintName);
                        continue tableConstraintLoop;
                    }
                    ForeignKey<Record, Record> key = Internal.createForeignKey(uniqueKey, table, xc.getConstraintName(), c.toArray(new TableField[0]));
                    table.foreignKeys.add(key);
                    break;
                }
        }
    }
    tableConstraintLoop: for (TableConstraint xc : meta.getTableConstraints()) {
        switch(xc.getConstraintType()) {
            case CHECK:
                {
                    Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
                    Name constraintName = name(xc.getConstraintCatalog(), xc.getConstraintSchema(), xc.getConstraintName());
                    InformationSchemaTable table = tablesByName.get(tableName);
                    if (table == null) {
                        errors.add("Table " + tableName + " not defined for constraint " + constraintName);
                        continue tableConstraintLoop;
                    }
                    for (CheckConstraint cc : meta.getCheckConstraints()) {
                        if (constraintName.equals(name(cc.getConstraintCatalog(), cc.getConstraintSchema(), cc.getConstraintName()))) {
                            table.checks.add(new CheckImpl<>(table, constraintName, DSL.condition(cc.getCheckClause()), true));
                            continue tableConstraintLoop;
                        }
                    }
                    errors.add("No check clause found for check constraint " + constraintName);
                    continue tableConstraintLoop;
                }
        }
    }
    // -------------------------------------------------------------------------------------------------------------
    sequenceLoop: for (org.jooq.util.xml.jaxb.Sequence xs : meta.getSequences()) {
        Name schemaName = name(xs.getSequenceCatalog(), xs.getSequenceSchema());
        Schema schema = schemasByName.get(schemaName);
        if (schema == null) {
            errors.add("Schema " + schemaName + " not defined for sequence " + xs.getSequenceName());
            continue sequenceLoop;
        }
        String typeName = xs.getDataType();
        int length = xs.getCharacterMaximumLength() == null ? 0 : xs.getCharacterMaximumLength();
        int precision = xs.getNumericPrecision() == null ? 0 : xs.getNumericPrecision();
        int scale = xs.getNumericScale() == null ? 0 : xs.getNumericScale();
        boolean nullable = true;
        BigInteger startWith = xs.getStartValue();
        BigInteger incrementBy = xs.getIncrement();
        BigInteger minvalue = xs.getMinimumValue();
        BigInteger maxvalue = xs.getMaximumValue();
        Boolean cycle = xs.isCycleOption();
        BigInteger cache = xs.getCache();
        InformationSchemaSequence is = new InformationSchemaSequence(xs.getSequenceName(), schema, type(typeName, length, precision, scale, nullable, false, null, null), startWith, incrementBy, minvalue, maxvalue, cycle, cache);
        sequences.add(is);
    }
    // -------------------------------------------------------------------------------------------------------------
    for (Schema s : schemas) initLookup(schemasPerCatalog, s.getCatalog(), s);
    for (InformationSchemaDomain<?> d : domains) initLookup(domainsPerSchema, d.getSchema(), d);
    for (InformationSchemaTable t : tables) initLookup(tablesPerSchema, t.getSchema(), t);
    for (Sequence<?> q : sequences) initLookup(sequencesPerSchema, q.getSchema(), q);
    if (!errors.isEmpty())
        throw new IllegalArgumentException(errors.toString());
}
Also used : UniqueKey(org.jooq.UniqueKey) EMPTY_SORTFIELD(org.jooq.impl.Tools.EMPTY_SORTFIELD) Table(org.jooq.Table) HashMap(java.util.HashMap) STORED(org.jooq.impl.QOM.GenerationOption.STORED) ForeignKey(org.jooq.ForeignKey) Sequence(org.jooq.Sequence) ArrayList(java.util.ArrayList) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Index(org.jooq.Index) Map(java.util.Map) Schema(org.jooq.Schema) BigInteger(java.math.BigInteger) Comparator.comparing(java.util.Comparator.comparing) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) EMPTY_CHECK(org.jooq.impl.Tools.EMPTY_CHECK) Domain(org.jooq.Domain) FALSE(java.lang.Boolean.FALSE) Record(org.jooq.Record) Comparator.comparingInt(java.util.Comparator.comparingInt) DataType(org.jooq.DataType) DSL.name(org.jooq.impl.DSL.name) SQLDialectNotSupportedException(org.jooq.exception.SQLDialectNotSupportedException) Collections.emptyList(java.util.Collections.emptyList) Name(org.jooq.Name) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) Check(org.jooq.Check) Field(org.jooq.Field) StringUtils(org.jooq.tools.StringUtils) PRIMARY_KEY(org.jooq.util.xml.jaxb.TableConstraintType.PRIMARY_KEY) GenerationOption(org.jooq.impl.QOM.GenerationOption) Objects(java.util.Objects) TableType(org.jooq.TableOptions.TableType) Configuration(org.jooq.Configuration) List(java.util.List) Catalog(org.jooq.Catalog) SortField(org.jooq.SortField) VIRTUAL(org.jooq.impl.QOM.GenerationOption.VIRTUAL) TableField(org.jooq.TableField) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint) TableOptions(org.jooq.TableOptions) StringUtils.defaultIfNull(org.jooq.tools.StringUtils.defaultIfNull) IndexColumnUsage(org.jooq.util.xml.jaxb.IndexColumnUsage) TRUE(java.lang.Boolean.TRUE) Collections(java.util.Collections) Column(org.jooq.util.xml.jaxb.Column) HashMap(java.util.HashMap) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Schema(org.jooq.Schema) ArrayList(java.util.ArrayList) Index(org.jooq.Index) Name(org.jooq.Name) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) GenerationOption(org.jooq.impl.QOM.GenerationOption) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) Sequence(org.jooq.Sequence) TableField(org.jooq.TableField) Catalog(org.jooq.Catalog) BigInteger(java.math.BigInteger) Domain(org.jooq.Domain) IndexColumnUsage(org.jooq.util.xml.jaxb.IndexColumnUsage) Field(org.jooq.Field) SortField(org.jooq.SortField) TableField(org.jooq.TableField) Column(org.jooq.util.xml.jaxb.Column) DataType(org.jooq.DataType) Record(org.jooq.Record) Table(org.jooq.Table) TableType(org.jooq.TableOptions.TableType) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) BigInteger(java.math.BigInteger) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint)

Example 5 with Domain

use of org.jooq.Domain in project jOOQ by jOOQ.

the class DDL method createDomain.

@SuppressWarnings({ "rawtypes", "unchecked" })
final Query createDomain(Domain<?> domain) {
    CreateDomainAsStep s1 = configuration.createDomainIfNotExists() ? ctx.createDomainIfNotExists(domain) : ctx.createDomain(domain);
    CreateDomainDefaultStep s2 = s1.as(domain.getDataType());
    CreateDomainConstraintStep s3 = domain.getDataType().defaulted() ? s2.default_(domain.getDataType().default_()) : s2;
    if (domain.getChecks().isEmpty())
        return s3;
    return s3.constraints(map(domain.getChecks(), c -> c.constraint()));
}
Also used : UniqueKey(org.jooq.UniqueKey) Arrays(java.util.Arrays) Tools.map(org.jooq.impl.Tools.map) KEY_COMP(org.jooq.impl.Comparators.KEY_COMP) Table(org.jooq.Table) SCHEMA(org.jooq.DDLFlag.SCHEMA) SEQUENCE(org.jooq.DDLFlag.SEQUENCE) CreateTableOnCommitStep(org.jooq.CreateTableOnCommitStep) Arrays.asList(java.util.Arrays.asList) Index(org.jooq.Index) DSLContext(org.jooq.DSLContext) Domain(org.jooq.Domain) COMMENT(org.jooq.DDLFlag.COMMENT) DSL.constraint(org.jooq.impl.DSL.constraint) CHECK(org.jooq.DDLFlag.CHECK) Collection(java.util.Collection) Check(org.jooq.Check) Field(org.jooq.Field) Meta(org.jooq.Meta) DOMAIN(org.jooq.DDLFlag.DOMAIN) TableType(org.jooq.TableOptions.TableType) List(java.util.List) Queries(org.jooq.Queries) CreateIndexIncludeStep(org.jooq.CreateIndexIncludeStep) Query(org.jooq.Query) TABLE(org.jooq.DDLFlag.TABLE) ForeignKey(org.jooq.ForeignKey) VIEW(org.jooq.TableOptions.TableType.VIEW) UNIQUE(org.jooq.DDLFlag.UNIQUE) Sequence(org.jooq.Sequence) ArrayList(java.util.ArrayList) CreateViewAsStep(org.jooq.CreateViewAsStep) INDEX(org.jooq.DDLFlag.INDEX) Comment(org.jooq.Comment) Schema(org.jooq.Schema) PRIMARY_KEY(org.jooq.DDLFlag.PRIMARY_KEY) FOREIGN_KEY(org.jooq.DDLFlag.FOREIGN_KEY) NAMED_COMP(org.jooq.impl.Comparators.NAMED_COMP) CreateDomainAsStep(org.jooq.CreateDomainAsStep) DDLFlag(org.jooq.DDLFlag) DDLExportConfiguration(org.jooq.DDLExportConfiguration) OnCommit(org.jooq.TableOptions.OnCommit) CreateSequenceFlagsStep(org.jooq.CreateSequenceFlagsStep) StringUtils(org.jooq.tools.StringUtils) Constraint(org.jooq.Constraint) ConstraintEnforcementStep(org.jooq.ConstraintEnforcementStep) CreateDomainConstraintStep(org.jooq.CreateDomainConstraintStep) Named(org.jooq.Named) TableOptions(org.jooq.TableOptions) CreateDomainDefaultStep(org.jooq.CreateDomainDefaultStep) Key(org.jooq.Key) CreateDomainConstraintStep(org.jooq.CreateDomainConstraintStep) CreateDomainDefaultStep(org.jooq.CreateDomainDefaultStep) CreateDomainAsStep(org.jooq.CreateDomainAsStep)

Aggregations

Domain (org.jooq.Domain)5 Schema (org.jooq.Schema)3 Sequence (org.jooq.Sequence)3 Table (org.jooq.Table)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Catalog (org.jooq.Catalog)2 Check (org.jooq.Check)2 Field (org.jooq.Field)2 ForeignKey (org.jooq.ForeignKey)2 Index (org.jooq.Index)2 TableOptions (org.jooq.TableOptions)2 TableType (org.jooq.TableOptions.TableType)2 UniqueKey (org.jooq.UniqueKey)2 StringUtils (org.jooq.tools.StringUtils)2 FALSE (java.lang.Boolean.FALSE)1 TRUE (java.lang.Boolean.TRUE)1 BigInteger (java.math.BigInteger)1 Arrays (java.util.Arrays)1 Arrays.asList (java.util.Arrays.asList)1