Search in sources :

Example 6 with RoutineDefinition

use of org.jooq.meta.RoutineDefinition in project jOOQ by jOOQ.

the class XMLDatabase method getRoutines0.

@Override
protected List<RoutineDefinition> getRoutines0() {
    List<RoutineDefinition> result = new ArrayList<>();
    for (Routine routine : info().getRoutines()) {
        if (isBlank(routine.getSpecificPackage()) && isBlank(routine.getRoutinePackage())) {
            String schemaName = defaultIfBlank(routine.getSpecificSchema(), routine.getRoutineSchema());
            if (getInputSchemata().contains(schemaName)) {
                SchemaDefinition schema = getSchema(schemaName);
                result.add(new XMLRoutineDefinition(schema, null, info(), routine, routine.getComment()));
            }
        }
    }
    return result;
}
Also used : RoutineDefinition(org.jooq.meta.RoutineDefinition) SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) Routine(org.jooq.util.xml.jaxb.Routine)

Example 7 with RoutineDefinition

use of org.jooq.meta.RoutineDefinition in project jOOQ by jOOQ.

the class MySQLDatabase method getRoutines0.

@Override
protected List<RoutineDefinition> getRoutines0() throws SQLException {
    List<RoutineDefinition> result = new ArrayList<>();
    Result<Record6<String, String, String, byte[], byte[], ProcType>> records = is8() ? create().select(ROUTINES.ROUTINE_SCHEMA, ROUTINES.ROUTINE_NAME, ROUTINES.ROUTINE_COMMENT, inline(new byte[0]).as(PROC.PARAM_LIST), inline(new byte[0]).as(PROC.RETURNS), ROUTINES.ROUTINE_TYPE.coerce(PROC.TYPE).as(ROUTINES.ROUTINE_TYPE)).from(ROUTINES).where(ROUTINES.ROUTINE_SCHEMA.in(getInputSchemata())).orderBy(1, 2, 6).fetch() : create().select(PROC.DB.as(ROUTINES.ROUTINE_SCHEMA), PROC.NAME.as(ROUTINES.ROUTINE_NAME), PROC.COMMENT.as(ROUTINES.ROUTINE_COMMENT), PROC.PARAM_LIST, PROC.RETURNS, PROC.TYPE.as(ROUTINES.ROUTINE_TYPE)).from(PROC).where(PROC.DB.in(getInputSchemata())).orderBy(1, 2, 6).fetch();
    Map<Record, Result<Record6<String, String, String, byte[], byte[], ProcType>>> groups = records.intoGroups(new Field[] { ROUTINES.ROUTINE_SCHEMA, ROUTINES.ROUTINE_NAME });
    // [#1908] This indirection is necessary as MySQL allows for overloading
    // procedures and functions with the same signature.
    groups.forEach((k, overloads) -> {
        overloads.forEach(record -> {
            SchemaDefinition schema = getSchema(record.get(ROUTINES.ROUTINE_SCHEMA));
            String name = record.get(ROUTINES.ROUTINE_NAME);
            String comment = record.get(ROUTINES.ROUTINE_COMMENT);
            String params = is8() ? "" : new String(record.get(PROC.PARAM_LIST));
            String returns = is8() ? "" : new String(record.get(PROC.RETURNS));
            ProcType type = record.get(ROUTINES.ROUTINE_TYPE.coerce(PROC.TYPE).as(ROUTINES.ROUTINE_TYPE));
            if (overloads.size() > 1)
                result.add(new MySQLRoutineDefinition(schema, name, comment, params, returns, type, "_" + type.name()));
            else
                result.add(new MySQLRoutineDefinition(schema, name, comment, params, returns, type, null));
        });
    });
    return result;
}
Also used : RoutineDefinition(org.jooq.meta.RoutineDefinition) SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) ProcType(org.jooq.meta.mysql.mysql.enums.ProcType) Record6(org.jooq.Record6) Record(org.jooq.Record) Result(org.jooq.Result)

Example 8 with RoutineDefinition

use of org.jooq.meta.RoutineDefinition in project jOOQ by jOOQ.

the class JavaGenerator method generateRecord0.

private final void generateRecord0(Definition tableUdtOrEmbeddable, JavaWriter out) {
    final UniqueKeyDefinition key = (tableUdtOrEmbeddable instanceof TableDefinition) ? ((TableDefinition) tableUdtOrEmbeddable).getPrimaryKey() : null;
    final String className = getStrategy().getJavaClassName(tableUdtOrEmbeddable, Mode.RECORD);
    final String tableIdentifier = !(tableUdtOrEmbeddable instanceof EmbeddableDefinition) ? out.ref(getStrategy().getFullJavaIdentifier(tableUdtOrEmbeddable), 2) : null;
    final List<String> interfaces = out.ref(getStrategy().getJavaClassImplements(tableUdtOrEmbeddable, Mode.RECORD));
    printPackage(out, tableUdtOrEmbeddable, Mode.RECORD);
    if (tableUdtOrEmbeddable instanceof TableDefinition)
        generateRecordClassJavadoc((TableDefinition) tableUdtOrEmbeddable, out);
    else if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
        generateEmbeddableClassJavadoc((EmbeddableDefinition) tableUdtOrEmbeddable, out);
    else
        generateUDTRecordClassJavadoc((UDTDefinition) tableUdtOrEmbeddable, out);
    printClassAnnotations(out, tableUdtOrEmbeddable, Mode.RECORD);
    if (tableUdtOrEmbeddable instanceof TableDefinition)
        printTableJPAAnnotation(out, (TableDefinition) tableUdtOrEmbeddable);
    Class<?> baseClass;
    if (tableUdtOrEmbeddable instanceof UDTDefinition)
        baseClass = UDTRecordImpl.class;
    else if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
        baseClass = EmbeddableRecordImpl.class;
    else if (generateRelations() && key != null)
        baseClass = UpdatableRecordImpl.class;
    else
        baseClass = TableRecordImpl.class;
    // [#10481] Use the types from replaced embeddables if applicable
    List<Definition> embeddablesAndColumns = embeddablesAndColumns(tableUdtOrEmbeddable);
    List<Definition> embeddablesAndUnreplacedColumns = embeddablesAndUnreplacedColumns(tableUdtOrEmbeddable);
    List<Definition> replacingEmbeddablesAndUnreplacedColumns = replacingEmbeddablesAndUnreplacedColumns(tableUdtOrEmbeddable);
    List<Definition> embeddablesOrColumns = embeddablesOrColumns(tableUdtOrEmbeddable);
    int degree = replacingEmbeddablesAndUnreplacedColumns.size();
    String rowType = null;
    String rowTypeRecord = null;
    // [#6072] Generate these super types only if configured to do so
    if (generateRecordsImplementingRecordN() && degree > 0 && degree <= Constants.MAX_ROW_DEGREE) {
        rowType = refRowType(out, replacingEmbeddablesAndUnreplacedColumns);
        if (scala)
            rowTypeRecord = out.ref(Record.class.getName() + degree) + "[" + rowType + "]";
        else
            rowTypeRecord = out.ref(Record.class.getName() + degree) + "<" + rowType + ">";
        interfaces.add(rowTypeRecord);
    }
    if (generateInterfaces())
        interfaces.add(out.ref(getStrategy().getFullJavaClassName(tableUdtOrEmbeddable, Mode.INTERFACE)));
    if (scala)
        if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
            out.println("%sclass %s extends %s[%s](%s.%s.getDataType.getRow)[[before= with ][separator= with ][%s]] {", visibility(), className, baseClass, className, out.ref(getStrategy().getFullJavaIdentifier(((EmbeddableDefinition) tableUdtOrEmbeddable).getTable()), 2), getStrategy().getJavaIdentifier(tableUdtOrEmbeddable), interfaces);
        else
            out.println("%sclass %s extends %s[%s](%s)[[before= with ][separator= with ][%s]] {", visibility(), className, baseClass, className, tableIdentifier, interfaces);
    else if (kotlin)
        if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
            out.println("%sopen class %s() : %s<%s>(%s.%s.dataType.row)[[before=, ][%s]] {", visibility(), className, baseClass, className, out.ref(getStrategy().getFullJavaIdentifier(((EmbeddableDefinition) tableUdtOrEmbeddable).getTable()), 2), getStrategy().getJavaIdentifier(tableUdtOrEmbeddable), interfaces);
        else
            out.println("%sopen class %s() : %s<%s>(%s)[[before=, ][%s]] {", visibility(), className, baseClass, className, tableIdentifier, interfaces);
    else
        out.println("%sclass %s extends %s<%s>[[before= implements ][%s]] {", visibility(), className, baseClass, className, interfaces);
    out.printSerial();
    for (Definition column : embeddablesAndUnreplacedColumns) {
        final int index = replacingEmbeddablesAndUnreplacedColumns.indexOf(column);
        if (column instanceof EmbeddableDefinition) {
            final EmbeddableDefinition embeddable = (EmbeddableDefinition) column;
            generateEmbeddableRecordSetter(embeddable, index, out);
            generateEmbeddableRecordGetter(embeddable, index, out);
        } else {
            final TypedElementDefinition<?> c = (TypedElementDefinition<?>) column;
            if (tableUdtOrEmbeddable instanceof TableDefinition) {
                generateRecordSetter(c, index, out);
                generateRecordGetter(c, index, out);
            } else if (tableUdtOrEmbeddable instanceof EmbeddableDefinition) {
                generateEmbeddableSetter(c, index, out);
                generateEmbeddableGetter(c, index, out);
            } else {
                generateUDTRecordSetter(c, index, out);
                generateUDTRecordGetter(c, index, out);
            }
        }
    }
    if (generateRelations() && key != null) {
        int keyDegree = key.getKeyColumns().size();
        if (keyDegree <= Constants.MAX_ROW_DEGREE) {
            final String recordNType = out.ref(Record.class.getName() + keyDegree);
            final String keyType = refRowType(out, key.getKeyColumns());
            out.header("Primary key information");
            if (scala) {
                out.println();
                out.println("%soverride def key: %s[%s] = super.key.asInstanceOf[ %s[%s] ]", visibilityPublic(), recordNType, keyType, recordNType, keyType);
            } else if (kotlin) {
                out.println();
                out.println("%soverride fun key(): %s<%s> = super.key() as %s<%s>", visibilityPublic(), recordNType, keyType, recordNType, keyType);
            } else {
                out.overrideInherit();
                printNonnullAnnotation(out);
                out.println("%s%s<%s> key() {", visibilityPublic(), recordNType, keyType);
                out.println("return (%s) super.key();", recordNType);
                out.println("}");
            }
        }
    }
    if (tableUdtOrEmbeddable instanceof UDTDefinition) {
        // [#799] Oracle UDT's can have member procedures
        for (RoutineDefinition routine : ((UDTDefinition) tableUdtOrEmbeddable).getRoutines()) {
            // Instance methods ship with a SELF parameter at the first position
            // [#1584] Static methods don't have that
            boolean instance = routine.getInParameters().size() > 0 && routine.getInParameters().get(0).getInputName().toUpperCase(getStrategy().getTargetLocale()).equals("SELF");
            try {
                if (!routine.isSQLUsable()) {
                    // Instance execute() convenience method
                    printConvenienceMethodProcedure(out, routine, instance);
                } else {
                    // Instance execute() convenience method
                    if (!routine.isAggregate()) {
                        printConvenienceMethodFunction(out, routine, instance);
                    }
                }
            } catch (Exception e) {
                log.error("Error while generating routine " + routine, e);
            }
        }
    }
    // [#3130] Invalid UDTs may have a degree of 0
    if (generateRecordsImplementingRecordN() && degree > 0 && degree <= Constants.MAX_ROW_DEGREE) {
        final String recordNType = out.ref(Row.class.getName() + degree);
        out.header("Record%s type implementation", degree);
        // fieldsRow()
        if (scala) {
            out.println();
            out.println("%soverride def fieldsRow: %s[%s] = super.fieldsRow.asInstanceOf[ %s[%s] ]", visibilityPublic(), recordNType, rowType, recordNType, rowType);
        } else if (kotlin) {
            out.println();
            out.println("%soverride fun fieldsRow(): %s<%s> = super.fieldsRow() as %s<%s>", visibilityPublic(), recordNType, rowType, recordNType, rowType);
        } else {
            out.overrideInherit();
            printNonnullAnnotation(out);
            out.println("%s%s<%s> fieldsRow() {", visibilityPublic(), recordNType, rowType);
            out.println("return (%s) super.fieldsRow();", recordNType);
            out.println("}");
        }
        // valuesRow()
        if (scala) {
            out.println();
            out.println("%soverride def valuesRow: %s[%s] = super.valuesRow.asInstanceOf[ %s[%s] ]", visibilityPublic(), recordNType, rowType, recordNType, rowType);
        } else if (kotlin) {
            out.println("%soverride fun valuesRow(): %s<%s> = super.valuesRow() as %s<%s>", visibilityPublic(), recordNType, rowType, recordNType, rowType);
        } else {
            out.overrideInherit();
            printNonnullAnnotation(out);
            out.println("%s%s<%s> valuesRow() {", visibilityPublic(), recordNType, rowType);
            out.println("return (%s) super.valuesRow();", recordNType);
            out.println("}");
        }
        // field[N]()
        for (int i = 1; i <= degree; i++) {
            Definition column = replacingEmbeddablesAndUnreplacedColumns.get(i - 1);
            if (column instanceof EmbeddableColumnDefinition)
                column = ((EmbeddableColumnDefinition) column).getReferencingColumn();
            final String colTypeFull = getJavaType(column, out);
            final String colType = out.ref(colTypeFull);
            final String colIdentifierFull = out.ref(getStrategy().getFullJavaIdentifier(column), colRefSegments(column));
            final String colIdentifier = getStrategy().getJavaIdentifier(column);
            if (scala) {
                printDeprecationIfUnknownType(out, colTypeFull);
                if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
                    out.println("%soverride def field%s: %s[%s] = field(%s).asInstanceOf[%s [%s] ]", visibilityPublic(), i, Field.class, colType, i - 1, Field.class, colType);
                else
                    out.println("%soverride def field%s: %s[%s] = %s", visibilityPublic(), i, Field.class, colType, colIdentifierFull);
            } else if (kotlin) {
                printDeprecationIfUnknownType(out, colTypeFull);
                if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
                    out.println("%soverride fun field%s(): %s<%s?> = field(%s) as %s<%s?>", visibilityPublic(), i, Field.class, colType, i - 1, Field.class, colType);
                else if (tableUdtOrEmbeddable instanceof UDTDefinition)
                    out.println("%soverride fun field%s(): %s<%s%s> = %s.%s", visibilityPublic(), i, Field.class, colType, column instanceof EmbeddableDefinition ? "" : "?", out.ref(getStrategy().getFullJavaIdentifier(((AttributeDefinition) column).getContainer()), 2), colIdentifier);
                else
                    out.println("%soverride fun field%s(): %s<%s%s> = %s", visibilityPublic(), i, Field.class, colType, column instanceof EmbeddableDefinition ? "" : "?", colIdentifierFull);
            } else {
                if (printDeprecationIfUnknownType(out, colTypeFull))
                    out.override();
                else
                    out.overrideInherit();
                printNonnullAnnotation(out);
                out.println("%s%s<%s> field%s() {", visibilityPublic(), Field.class, colType, i);
                if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
                    out.println("return (%s<%s>) field(%s);", Field.class, colType, i - 1);
                else
                    out.println("return %s;", colIdentifierFull);
                out.println("}");
            }
        }
        // component[N]()
        for (int i = 1; i <= degree; i++) {
            Definition column = replacingEmbeddablesAndUnreplacedColumns.get(i - 1);
            final String colTypeFull = getJavaType(column, out);
            final String colType = out.ref(colTypeFull);
            final String colGetter = getStrategy().getJavaGetterName(column, Mode.RECORD);
            final String colMember = getStrategy().getJavaMemberName(column, Mode.POJO);
            if (scala) {
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride def component%s: %s = %s", visibilityPublic(), i, colType, colGetter);
            } else if (kotlin) {
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride fun component%s(): %s? = %s", visibilityPublic(), i, colType, colMember);
            } else {
                if (printDeprecationIfUnknownType(out, colTypeFull))
                    out.override();
                else
                    out.overrideInherit();
                printNullableOrNonnullAnnotation(out, column);
                out.println("%s%s component%s() {", visibilityPublic(), colType, i);
                out.println("return %s();", colGetter);
                out.println("}");
            }
        }
        // value[N]()
        for (int i = 1; i <= degree; i++) {
            Definition column = replacingEmbeddablesAndUnreplacedColumns.get(i - 1);
            final String colTypeFull = getJavaType(column, out);
            final String colType = out.ref(colTypeFull);
            final String colGetter = getStrategy().getJavaGetterName(column, Mode.RECORD);
            final String colMember = getStrategy().getJavaMemberName(column, Mode.POJO);
            if (scala) {
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride def value%s: %s = %s", visibilityPublic(), i, colType, colGetter);
            } else if (kotlin) {
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride fun value%s(): %s? = %s", visibilityPublic(), i, colType, colMember);
            } else {
                if (printDeprecationIfUnknownType(out, colTypeFull))
                    out.override();
                else
                    out.overrideInherit();
                printNullableOrNonnullAnnotation(out, column);
                out.println("%s%s value%s() {", visibilityPublic(), colType, i);
                out.println("return %s();", colGetter);
                out.println("}");
            }
        }
        // value[N](T[N])
        for (int i = 1; i <= degree; i++) {
            Definition column = replacingEmbeddablesAndUnreplacedColumns.get(i - 1);
            final String colTypeFull = getJavaType(column, out);
            final String colType = out.ref(colTypeFull);
            final String colSetter = getStrategy().getJavaSetterName(column, Mode.RECORD);
            final String colMember = getStrategy().getJavaMemberName(column, Mode.POJO);
            if (scala) {
                out.println();
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride def value%s(value: %s): %s = {", visibilityPublic(), i, colType, className);
                out.println("%s(value)", colSetter);
                out.println("this");
                out.println("}");
            } else if (kotlin) {
                out.println();
                printDeprecationIfUnknownType(out, colTypeFull);
                out.println("%soverride fun value%s(value: %s%s): %s {", visibilityPublic(), i, colType, column instanceof EmbeddableDefinition ? "" : "?", className);
                out.println("this.%s = value", colMember);
                out.println("return this");
                out.println("}");
            } else {
                final String nullableAnnotation = nullableOrNonnullAnnotation(out, column);
                if (printDeprecationIfUnknownType(out, colTypeFull))
                    out.override();
                else
                    out.overrideInherit();
                printNonnullAnnotation(out);
                out.println("%s%s value%s([[before=@][after= ][%s]]%s value) {", visibilityPublic(), className, i, list(nullableAnnotation), varargsIfArray(colType));
                out.println("%s(value);", colSetter);
                out.println("return this;");
                out.println("}");
            }
        }
        List<String> arguments = new ArrayList<>(degree);
        List<String> calls = new ArrayList<>(degree);
        for (int i = 1; i <= degree; i++) {
            final Definition column = replacingEmbeddablesAndUnreplacedColumns.get(i - 1);
            final String colType = getJavaTypeRef(column, out);
            if (scala) {
                arguments.add("value" + i + " : " + colType);
                calls.add("this.value" + i + "(value" + i + ")");
            } else if (kotlin) {
                arguments.add("value" + i + ": " + colType + (column instanceof EmbeddableDefinition ? "" : "?"));
                calls.add("this.value" + i + "(value" + i + ")");
            } else {
                final String nullableAnnotation = nullableOrNonnullAnnotation(out, column);
                arguments.add((nullableAnnotation == null ? "" : "@" + nullableAnnotation + " ") + colType + " value" + i);
                calls.add("value" + i + "(value" + i + ");");
            }
        }
        if (scala) {
            out.println();
            out.println("%soverride def values([[%s]]): %s = {", visibilityPublic(), arguments, className);
            for (String call : calls) out.println(call);
            out.println("this");
            out.println("}");
        } else if (kotlin) {
            out.println();
            out.println("%soverride fun values([[%s]]): %s {", visibilityPublic(), arguments, className);
            for (String call : calls) out.println(call);
            out.println("return this");
            out.println("}");
        } else {
            out.overrideInherit();
            printNonnullAnnotation(out);
            out.println("%s%s values([[%s]]) {", visibilityPublic(), className, arguments);
            for (String call : calls) out.println(call);
            out.println("return this;");
            out.println("}");
        }
    }
    if (generateInterfaces())
        printFromAndInto(out, tableUdtOrEmbeddable, Mode.RECORD);
    if (scala || kotlin) {
    } else {
        out.header("Constructors");
        out.javadoc("Create a detached %s", className);
        out.println("%s%s() {", visibility(), className);
        if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
            out.println("super(%s.%s.getDataType().getRow());", out.ref(getStrategy().getFullJavaIdentifier(((EmbeddableDefinition) tableUdtOrEmbeddable).getTable()), 2), getStrategy().getJavaIdentifier(tableUdtOrEmbeddable));
        else
            out.println("super(%s);", tableIdentifier);
        out.println("}");
    }
    // [#3130] Invalid UDTs may have a degree of 0
    // [#3176] Avoid generating constructors for tables with more than 255 columns (Java's method argument limit)
    generateRecordConstructor(tableUdtOrEmbeddable, out, replacingEmbeddablesAndUnreplacedColumns, false);
    if (!replacingEmbeddablesAndUnreplacedColumns.equals(embeddablesOrColumns))
        generateRecordConstructor(tableUdtOrEmbeddable, out, embeddablesOrColumns, false);
    if (generatePojos())
        generateRecordConstructor(tableUdtOrEmbeddable, out, replacingEmbeddablesAndUnreplacedColumns, true);
    if (tableUdtOrEmbeddable instanceof TableDefinition)
        generateRecordClassFooter((TableDefinition) tableUdtOrEmbeddable, out);
    else if (tableUdtOrEmbeddable instanceof EmbeddableDefinition)
        generateEmbeddableClassFooter((EmbeddableDefinition) tableUdtOrEmbeddable, out);
    else
        generateUDTRecordClassFooter((UDTDefinition) tableUdtOrEmbeddable, out);
    out.println("}");
}
Also used : UDTRecordImpl(org.jooq.impl.UDTRecordImpl) RoutineDefinition(org.jooq.meta.RoutineDefinition) PostgresRoutineDefinition(org.jooq.meta.postgres.PostgresRoutineDefinition) TypedElementDefinition(org.jooq.meta.TypedElementDefinition) AbstractTypedElementDefinition(org.jooq.meta.AbstractTypedElementDefinition) EmbeddableColumnDefinition(org.jooq.meta.EmbeddableColumnDefinition) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) EmbeddableDefinition(org.jooq.meta.EmbeddableDefinition) TableRecordImpl(org.jooq.impl.TableRecordImpl) AttributeDefinition(org.jooq.meta.AttributeDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) RoutineDefinition(org.jooq.meta.RoutineDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) IdentityDefinition(org.jooq.meta.IdentityDefinition) EmbeddableColumnDefinition(org.jooq.meta.EmbeddableColumnDefinition) CheckConstraintDefinition(org.jooq.meta.CheckConstraintDefinition) SequenceDefinition(org.jooq.meta.SequenceDefinition) TableDefinition(org.jooq.meta.TableDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) SchemaDefinition(org.jooq.meta.SchemaDefinition) CatalogDefinition(org.jooq.meta.CatalogDefinition) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) PackageDefinition(org.jooq.meta.PackageDefinition) PostgresRoutineDefinition(org.jooq.meta.postgres.PostgresRoutineDefinition) TypedElementDefinition(org.jooq.meta.TypedElementDefinition) DomainDefinition(org.jooq.meta.DomainDefinition) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) Definition(org.jooq.meta.Definition) EmbeddableDefinition(org.jooq.meta.EmbeddableDefinition) ArrayDefinition(org.jooq.meta.ArrayDefinition) UDTDefinition(org.jooq.meta.UDTDefinition) ParameterDefinition(org.jooq.meta.ParameterDefinition) ConstraintDefinition(org.jooq.meta.ConstraintDefinition) AbstractTypedElementDefinition(org.jooq.meta.AbstractTypedElementDefinition) EnumDefinition(org.jooq.meta.EnumDefinition) ForeignKeyDefinition(org.jooq.meta.ForeignKeyDefinition) ArrayList(java.util.ArrayList) AttributeDefinition(org.jooq.meta.AttributeDefinition) UpdatableRecordImpl(org.jooq.impl.UpdatableRecordImpl) UDTDefinition(org.jooq.meta.UDTDefinition) IOException(java.io.IOException) SQLDialectNotSupportedException(org.jooq.exception.SQLDialectNotSupportedException) ReflectException(org.jooq.tools.reflect.ReflectException) SelectField(org.jooq.SelectField) TableField(org.jooq.TableField) Field(org.jooq.Field) UDTField(org.jooq.UDTField) OrderField(org.jooq.OrderField) TableDefinition(org.jooq.meta.TableDefinition) Record(org.jooq.Record)

Example 9 with RoutineDefinition

use of org.jooq.meta.RoutineDefinition in project jOOQ by jOOQ.

the class XMLGenerator method generate0.

@Override
public void generate0(Database db) {
    logDatabaseParameters(db);
    log.info("");
    logGenerationRemarks(db);
    log.info("");
    log.info("----------------------------------------------------------");
    TextWriter out = new TextWriter(getStrategy().getFile("information_schema.xml"), targetEncoding);
    log.info("");
    log.info("Generating XML", out.file().getName());
    log.info("==========================================================");
    InformationSchema is = new InformationSchema();
    boolean hasNonDefaultCatalogs = false;
    for (CatalogDefinition c : db.getCatalogs()) {
        if (!StringUtils.isBlank(c.getName())) {
            hasNonDefaultCatalogs = true;
            break;
        }
    }
    for (CatalogDefinition c : db.getCatalogs()) {
        String catalogName = c.getOutputName();
        if (hasNonDefaultCatalogs)
            is.getCatalogs().add(new Catalog().withCatalogName(catalogName).withComment(generateCommentsOnCatalogs() ? c.getComment() : null));
        for (SchemaDefinition s : c.getSchemata()) {
            String schemaName = s.getOutputName();
            Schema schema = new Schema();
            schema.setCatalogName(catalogName);
            schema.setSchemaName(schemaName);
            if (generateCommentsOnSchemas())
                schema.setComment(s.getComment());
            is.getSchemata().add(schema);
            for (TableDefinition t : s.getTables()) {
                String tableName = t.getOutputName();
                Table table = new Table();
                table.setTableCatalog(catalogName);
                table.setTableSchema(schemaName);
                table.setTableName(tableName);
                table.setTableType(t.isView() ? TableType.VIEW : t.isTemporary() ? TableType.GLOBAL_TEMPORARY : TableType.BASE_TABLE);
                if (generateCommentsOnTables())
                    table.setComment(t.getComment());
                is.getTables().add(table);
                if (t.isView()) {
                    View view = new View();
                    view.setTableCatalog(catalogName);
                    view.setTableSchema(schemaName);
                    view.setTableName(tableName);
                    if (generateSourcesOnViews())
                        view.setViewDefinition(t.getSource());
                    is.getViews().add(view);
                }
                for (ColumnDefinition co : t.getColumns()) {
                    String columnName = co.getOutputName();
                    DataTypeDefinition type = co.getType();
                    Column column = new Column();
                    column.setTableCatalog(catalogName);
                    column.setTableSchema(schemaName);
                    column.setTableName(tableName);
                    column.setColumnName(columnName);
                    if (generateCommentsOnColumns())
                        column.setComment(co.getComment());
                    column.setCharacterMaximumLength(type.getLength());
                    column.setColumnDefault(type.getDefaultValue());
                    column.setDataType(type.getType());
                    if (co.isIdentity())
                        column.setIdentityGeneration("YES");
                    column.setIsNullable(type.isNullable());
                    column.setNumericPrecision(type.getPrecision());
                    column.setNumericScale(type.getScale());
                    column.setOrdinalPosition(co.getPosition());
                    column.setReadonly(co.isReadonly());
                    if (type.isComputed()) {
                        column.setIsGenerated(type.isComputed());
                        column.setGenerationExpression(type.getGeneratedAlwaysAs());
                        column.setGenerationOption(type.getGenerationOption() == VIRTUAL ? "VIRTUAL" : type.getGenerationOption() == STORED ? "STORED" : null);
                    }
                    is.getColumns().add(column);
                }
            }
            for (IndexDefinition i : db.getIndexes(s)) {
                String indexName = i.getOutputName();
                TableDefinition table = i.getTable();
                List<IndexColumnDefinition> columns = i.getIndexColumns();
                Index index = new Index();
                index.setIndexCatalog(catalogName);
                index.setIndexSchema(schemaName);
                index.setIndexName(indexName);
                if (generateCommentsOnKeys())
                    index.setComment(i.getComment());
                index.setTableCatalog(table.getCatalog().getOutputName());
                index.setTableSchema(table.getSchema().getOutputName());
                index.setTableName(table.getOutputName());
                index.setIsUnique(i.isUnique());
                is.getIndexes().add(index);
                for (int j = 0; j < columns.size(); j++) {
                    IndexColumnDefinition indexColumn = columns.get(j);
                    ColumnDefinition column = indexColumn.getColumn();
                    IndexColumnUsage ic = new IndexColumnUsage();
                    ic.setIndexCatalog(catalogName);
                    ic.setIndexSchema(schemaName);
                    ic.setIndexName(indexName);
                    ic.setColumnName(column.getOutputName());
                    ic.setOrdinalPosition(j + 1);
                    ic.setIsDescending(indexColumn.getSortOrder() == SortOrder.DESC);
                    ic.setTableCatalog(table.getCatalog().getOutputName());
                    ic.setTableSchema(table.getSchema().getOutputName());
                    ic.setTableName(table.getOutputName());
                    is.getIndexColumnUsages().add(ic);
                }
            }
            for (UniqueKeyDefinition u : db.getKeys(s)) {
                String constraintName = u.getOutputName();
                TableDefinition table = u.getTable();
                List<ColumnDefinition> columns = u.getKeyColumns();
                TableConstraint tc = new TableConstraint();
                tc.setConstraintCatalog(catalogName);
                tc.setConstraintSchema(schemaName);
                tc.setConstraintName(constraintName);
                tc.setConstraintType(u.isPrimaryKey() ? PRIMARY_KEY : UNIQUE);
                if (generateCommentsOnKeys())
                    tc.setComment(u.getComment());
                tc.setTableCatalog(table.getCatalog().getOutputName());
                tc.setTableSchema(table.getSchema().getOutputName());
                tc.setTableName(table.getOutputName());
                tc.setEnforced(u.enforced());
                is.getTableConstraints().add(tc);
                for (int i = 0; i < columns.size(); i++) {
                    ColumnDefinition column = columns.get(i);
                    KeyColumnUsage kc = new KeyColumnUsage();
                    kc.setConstraintCatalog(catalogName);
                    kc.setConstraintSchema(schemaName);
                    kc.setConstraintName(constraintName);
                    kc.setColumnName(column.getOutputName());
                    kc.setOrdinalPosition(i + 1);
                    kc.setTableCatalog(table.getCatalog().getOutputName());
                    kc.setTableSchema(table.getSchema().getOutputName());
                    kc.setTableName(table.getOutputName());
                    is.getKeyColumnUsages().add(kc);
                }
            }
            for (ForeignKeyDefinition f : db.getForeignKeys(s)) {
                String constraintName = f.getOutputName();
                UniqueKeyDefinition referenced = f.getReferencedKey();
                TableDefinition table = f.getKeyTable();
                List<ColumnDefinition> columns = f.getKeyColumns();
                TableConstraint tc = new TableConstraint();
                tc.setConstraintCatalog(catalogName);
                tc.setConstraintSchema(schemaName);
                tc.setConstraintName(constraintName);
                tc.setConstraintType(FOREIGN_KEY);
                if (generateCommentsOnKeys())
                    tc.setComment(f.getComment());
                tc.setTableCatalog(table.getCatalog().getOutputName());
                tc.setTableSchema(table.getSchema().getOutputName());
                tc.setTableName(table.getOutputName());
                tc.setEnforced(f.enforced());
                ReferentialConstraint rc = new ReferentialConstraint();
                rc.setConstraintCatalog(catalogName);
                rc.setConstraintSchema(schemaName);
                rc.setConstraintName(constraintName);
                rc.setUniqueConstraintCatalog(referenced.getCatalog().getOutputName());
                rc.setUniqueConstraintSchema(referenced.getSchema().getOutputName());
                rc.setUniqueConstraintName(referenced.getOutputName());
                is.getTableConstraints().add(tc);
                is.getReferentialConstraints().add(rc);
                for (int i = 0; i < columns.size(); i++) {
                    ColumnDefinition column = columns.get(i);
                    KeyColumnUsage kc = new KeyColumnUsage();
                    kc.setConstraintCatalog(catalogName);
                    kc.setConstraintSchema(schemaName);
                    kc.setConstraintName(constraintName);
                    kc.setColumnName(column.getOutputName());
                    kc.setOrdinalPosition(i + 1);
                    kc.setTableCatalog(table.getCatalog().getOutputName());
                    kc.setTableSchema(table.getSchema().getOutputName());
                    kc.setTableName(table.getOutputName());
                    is.getKeyColumnUsages().add(kc);
                }
            }
            for (CheckConstraintDefinition ch : db.getCheckConstraints(s)) {
                String constraintName = ch.getOutputName();
                TableDefinition table = ch.getTable();
                TableConstraint tc = new TableConstraint();
                tc.setConstraintCatalog(catalogName);
                tc.setConstraintSchema(schemaName);
                tc.setConstraintName(constraintName);
                tc.setConstraintType(CHECK);
                if (generateCommentsOnKeys())
                    tc.setComment(ch.getComment());
                tc.setTableCatalog(table.getCatalog().getOutputName());
                tc.setTableSchema(table.getSchema().getOutputName());
                tc.setTableName(table.getOutputName());
                tc.setEnforced(ch.enforced());
                is.getTableConstraints().add(tc);
                CheckConstraint cc = new CheckConstraint();
                cc.setConstraintCatalog(catalogName);
                cc.setConstraintSchema(schemaName);
                cc.setConstraintName(constraintName);
                cc.setCheckClause(ch.getCheckClause());
                is.getCheckConstraints().add(cc);
            }
            for (SequenceDefinition se : db.getSequences(s)) {
                String sequenceName = se.getOutputName();
                DataTypeDefinition type = se.getType();
                Sequence sequence = new Sequence();
                sequence.setSequenceCatalog(catalogName);
                sequence.setSequenceSchema(schemaName);
                sequence.setSequenceName(sequenceName);
                if (generateCommentsOnSequences())
                    sequence.setComment(se.getComment());
                sequence.setCharacterMaximumLength(type.getLength());
                sequence.setDataType(type.getType());
                sequence.setNumericPrecision(type.getPrecision());
                sequence.setNumericScale(type.getScale());
                sequence.setStartValue(Convert.convert(se.getStartWith(), BigInteger.class));
                sequence.setIncrement(Convert.convert(se.getIncrementBy(), BigInteger.class));
                sequence.setMinimumValue(Convert.convert(se.getMinvalue(), BigInteger.class));
                sequence.setMaximumValue(Convert.convert(se.getMaxvalue(), BigInteger.class));
                sequence.setCycleOption(se.getCycle());
                sequence.setCache(Convert.convert(se.getCache(), BigInteger.class));
                is.getSequences().add(sequence);
            }
            for (PackageDefinition pkg : db.getPackages(s)) for (RoutineDefinition r : pkg.getRoutines()) exportRoutine(is, r, catalogName, schemaName);
            for (RoutineDefinition r : db.getRoutines(s)) exportRoutine(is, r, catalogName, schemaName);
        }
    }
    StringWriter writer = new StringWriter();
    MiniJAXB.marshal(is, writer);
    out.print(writer.toString());
    out.close();
}
Also used : RoutineDefinition(org.jooq.meta.RoutineDefinition) CheckConstraintDefinition(org.jooq.meta.CheckConstraintDefinition) SequenceDefinition(org.jooq.meta.SequenceDefinition) PackageDefinition(org.jooq.meta.PackageDefinition) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Schema(org.jooq.util.xml.jaxb.Schema) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Index(org.jooq.util.xml.jaxb.Index) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) IndexColumnUsage(org.jooq.util.xml.jaxb.IndexColumnUsage) ForeignKeyDefinition(org.jooq.meta.ForeignKeyDefinition) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) IndexDefinition(org.jooq.meta.IndexDefinition) StringWriter(java.io.StringWriter) Column(org.jooq.util.xml.jaxb.Column) TableDefinition(org.jooq.meta.TableDefinition) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) SchemaDefinition(org.jooq.meta.SchemaDefinition) Table(org.jooq.util.xml.jaxb.Table) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) Sequence(org.jooq.util.xml.jaxb.Sequence) View(org.jooq.util.xml.jaxb.View) Catalog(org.jooq.util.xml.jaxb.Catalog) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint) ColumnDefinition(org.jooq.meta.ColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) CatalogDefinition(org.jooq.meta.CatalogDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) BigInteger(java.math.BigInteger) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint)

Example 10 with RoutineDefinition

use of org.jooq.meta.RoutineDefinition in project jOOQ by jOOQ.

the class JavaGenerator method generateRoutines.

protected void generateRoutines(SchemaDefinition schema) {
    log.info("Generating routines and table-valued functions");
    if (generateGlobalRoutineReferences()) {
        JavaWriter out = newJavaWriter(getStrategy().getGlobalReferencesFile(schema, RoutineDefinition.class));
        printGlobalReferencesPackage(out, schema, RoutineDefinition.class);
        if (!kotlin) {
            printClassJavadoc(out, "Convenience access to all stored procedures and functions in " + schemaNameOrDefault(schema) + ".");
            printClassAnnotations(out, schema, Mode.DEFAULT);
        }
        final String referencesClassName = getStrategy().getGlobalReferencesJavaClassName(schema, RoutineDefinition.class);
        if (scala)
            out.println("%sobject %s {", visibility(), referencesClassName);
        else if (kotlin) {
        } else
            out.println("%sclass %s {", visibility(), referencesClassName);
        for (RoutineDefinition routine : database.getRoutines(schema)) printRoutine(out, routine);
        for (TableDefinition table : database.getTables(schema)) if (table.isTableValuedFunction())
            printTableValuedFunction(out, table, getStrategy().getJavaMethodName(table, Mode.DEFAULT));
        generateRoutinesClassFooter(schema, out);
        if (!kotlin)
            out.println("}");
        closeJavaWriter(out);
    }
    for (RoutineDefinition routine : database.getRoutines(schema)) {
        try {
            generateRoutine(schema, routine);
        } catch (Exception e) {
            log.error("Error while generating routine " + routine, e);
        }
    }
    watch.splitInfo("Routines generated");
}
Also used : RoutineDefinition(org.jooq.meta.RoutineDefinition) PostgresRoutineDefinition(org.jooq.meta.postgres.PostgresRoutineDefinition) TableDefinition(org.jooq.meta.TableDefinition) IOException(java.io.IOException) SQLDialectNotSupportedException(org.jooq.exception.SQLDialectNotSupportedException) ReflectException(org.jooq.tools.reflect.ReflectException)

Aggregations

RoutineDefinition (org.jooq.meta.RoutineDefinition)10 SchemaDefinition (org.jooq.meta.SchemaDefinition)8 ArrayList (java.util.ArrayList)7 Record (org.jooq.Record)6 PackageDefinition (org.jooq.meta.PackageDefinition)5 CatalogDefinition (org.jooq.meta.CatalogDefinition)4 Field (org.jooq.Field)3 Record6 (org.jooq.Record6)3 Result (org.jooq.Result)3 DSL (org.jooq.impl.DSL)3 ArrayDefinition (org.jooq.meta.ArrayDefinition)3 TableDefinition (org.jooq.meta.TableDefinition)3 IOException (java.io.IOException)2 BigDecimal (java.math.BigDecimal)2 SQLException (java.sql.SQLException)2 Arrays.asList (java.util.Arrays.asList)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Collectors.mapping (java.util.stream.Collectors.mapping)2