Search in sources :

Example 1 with InformationSchema

use of org.jooq.util.xml.jaxb.InformationSchema in project jOOQ by jOOQ.

the class XMLDatabase method info.

private InformationSchema info() {
    if (info == null) {
        String xml = getProperties().getProperty(P_XML_FILE);
        String xsl = getProperties().getProperty(P_XSL_FILE);
        InputStream xmlIs = null;
        InputStream xslIs = null;
        log.info("Using XML file", xml);
        try {
            xmlIs = XMLDatabase.class.getResourceAsStream(xml);
            if (xmlIs == null)
                xmlIs = new FileInputStream(xml);
            if (StringUtils.isBlank(xsl)) {
                info = JAXB.unmarshal(new File(xml), InformationSchema.class);
            } else {
                log.info("Using XSL file", xsl);
                xslIs = XMLDatabase.class.getResourceAsStream(xsl);
                if (xslIs == null)
                    xslIs = new FileInputStream(xsl);
                try {
                    StringWriter writer = new StringWriter();
                    TransformerFactory factory = TransformerFactory.newInstance();
                    Transformer transformer = factory.newTransformer(new StreamSource(xslIs));
                    transformer.transform(new StreamSource(xmlIs), new StreamResult(writer));
                    info = JAXB.unmarshal(new StringReader(writer.getBuffer().toString()), InformationSchema.class);
                } catch (TransformerException e) {
                    throw new RuntimeException("Error while transforming XML file " + xml + " with XSL file " + xsl, e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error while opening files " + xml + " or " + xsl, e);
        } finally {
            if (xmlIs != null) {
                try {
                    xmlIs.close();
                } catch (Exception ignore) {
                }
            }
            if (xslIs != null) {
                try {
                    xslIs.close();
                } catch (Exception ignore) {
                }
            }
        }
    }
    return info;
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) TransformerException(javax.xml.transform.TransformerException) SQLException(java.sql.SQLException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 2 with InformationSchema

use of org.jooq.util.xml.jaxb.InformationSchema in project jOOQ by jOOQ.

the class XMLGenerator method generate.

@Override
public void generate(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();
    for (CatalogDefinition c : db.getCatalogs()) {
        String catalogName = c.getOutputName();
        for (SchemaDefinition s : c.getSchemata()) {
            String schemaName = s.getOutputName();
            Schema schema = new Schema();
            schema.setCatalogName(catalogName);
            schema.setSchemaName(schemaName);
            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);
                is.getTables().add(table);
                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);
                    column.setCharacterMaximumLength(type.getLength());
                    column.setColumnDefault(type.getDefaultValue());
                    column.setDataType(type.getType());
                    //                      TODO This is not yet supported
                    //                      column.setIdentityGeneration(co.isIdentity());
                    column.setIsNullable(column.isIsNullable());
                    column.setNumericPrecision(type.getPrecision());
                    column.setNumericScale(type.getScale());
                    column.setOrdinalPosition(co.getPosition());
                    is.getColumns().add(column);
                }
            }
            for (UniqueKeyDefinition u : db.getUniqueKeys(s)) {
                String constraintName = u.getOutputName();
                TableDefinition table = u.getTable();
                List<ColumnDefinition> columns = u.getKeyColumns();
                TableConstraint constraint = new TableConstraint();
                constraint.setConstraintCatalog(catalogName);
                constraint.setConstraintSchema(schemaName);
                constraint.setConstraintName(constraintName);
                constraint.setConstraintType(u.isPrimaryKey() ? PRIMARY_KEY : UNIQUE);
                constraint.setTableCatalog(table.getCatalog().getOutputName());
                constraint.setTableSchema(table.getSchema().getOutputName());
                constraint.setTableName(table.getOutputName());
                is.getTableConstraints().add(constraint);
                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);
                    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);
                tc.setTableCatalog(table.getCatalog().getOutputName());
                tc.setTableSchema(table.getSchema().getOutputName());
                tc.setTableName(table.getOutputName());
                ReferentialConstraint rc = new ReferentialConstraint();
                rc.setConstraintCatalog(catalogName);
                rc.setConstraintSchema(schemaName);
                rc.setConstraintName(constraintName);
                rc.setUniqueConstraintCatalog(referenced.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);
                    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 constraint = new TableConstraint();
                constraint.setConstraintCatalog(catalogName);
                constraint.setConstraintSchema(schemaName);
                constraint.setConstraintName(constraintName);
                constraint.setConstraintType(CHECK);
                constraint.setTableCatalog(table.getCatalog().getOutputName());
                constraint.setTableSchema(table.getSchema().getOutputName());
                constraint.setTableName(table.getOutputName());
                is.getTableConstraints().add(constraint);
            }
            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);
                sequence.setCharacterMaximumLength(type.getLength());
                sequence.setDataType(type.getType());
                sequence.setNumericPrecision(type.getPrecision());
                sequence.setNumericScale(type.getScale());
                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();
    JAXB.marshal(is, writer);
    out.print(writer.toString());
    out.close();
}
Also used : Table(org.jooq.util.xml.jaxb.Table) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) Schema(org.jooq.util.xml.jaxb.Schema) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Sequence(org.jooq.util.xml.jaxb.Sequence) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) StringWriter(java.io.StringWriter) Column(org.jooq.util.xml.jaxb.Column) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint)

Example 3 with InformationSchema

use of org.jooq.util.xml.jaxb.InformationSchema in project jOOQ by jOOQ.

the class InformationSchemaExport method exportSchemas.

static final InformationSchema exportSchemas(Configuration configuration, List<Schema> schemas) {
    InformationSchema result = new InformationSchema();
    Set<Table<?>> includedTables = new LinkedHashSet<Table<?>>();
    for (Schema s : schemas) for (Table<?> t : s.getTables()) includedTables.add(t);
    for (Schema s : schemas) {
        exportSchema0(result, s);
        for (Table<?> t : s.getTables()) exportTable0(configuration, result, t, includedTables);
        for (Sequence<?> q : s.getSequences()) exportSequences0(configuration, result, q);
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Table(org.jooq.Table) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Schema(org.jooq.Schema) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema)

Example 4 with InformationSchema

use of org.jooq.util.xml.jaxb.InformationSchema in project jOOQ by jOOQ.

the class InformationSchemaExport method exportTables.

static final InformationSchema exportTables(Configuration configuration, List<Table<?>> tables) {
    InformationSchema result = new InformationSchema();
    Set<Schema> includedSchemas = new LinkedHashSet<Schema>();
    Set<Table<?>> includedTables = new LinkedHashSet<Table<?>>(tables);
    for (Table<?> t : tables) includedSchemas.add(t.getSchema());
    for (Schema s : includedSchemas) exportSchema0(result, s);
    for (Table<?> t : tables) exportTable0(configuration, result, t, includedTables);
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Table(org.jooq.Table) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Schema(org.jooq.Schema) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema)

Example 5 with InformationSchema

use of org.jooq.util.xml.jaxb.InformationSchema in project jOOQ by jOOQ.

the class InformationSchemaMetaImpl method init.

private final void init(InformationSchema meta) {
    List<String> errors = new ArrayList<String>();
    // -------------------------------------------------------------------------------------------------------------
    for (org.jooq.util.xml.jaxb.Schema xs : meta.getSchemata()) {
        InformationSchemaCatalog catalog = new InformationSchemaCatalog(xs.getCatalogName());
        if (!catalogs.contains(catalog))
            catalogs.add(catalog);
        InformationSchemaSchema is = new InformationSchemaSchema(xs.getSchemaName(), catalog);
        schemas.add(is);
        schemasByName.put(name(xs.getCatalogName(), xs.getSchemaName()), is);
    }
    // -------------------------------------------------------------------------------------------------------------
    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(String.format("Schema " + schemaName + " not defined for table " + xt.getTableName()));
            continue tableLoop;
        }
        InformationSchemaTable it = new InformationSchemaTable(xt.getTableName(), schema);
        tables.add(it);
        tablesByName.put(name(xt.getTableCatalog(), xt.getTableSchema(), xt.getTableName()), it);
    }
    // Columns
    // -------------------------------------------------------------------------------------------------------------
    List<Column> columns = new ArrayList<Column>(meta.getColumns());
    Collections.sort(columns, new Comparator<Column>() {

        @Override
        public int compare(Column o1, Column o2) {
            Integer p1 = o1.getOrdinalPosition();
            Integer p2 = o2.getOrdinalPosition();
            if (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 = xc.isIsNullable() == null ? true : xc.isIsNullable();
        // 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(String.format("Table " + tableName + " not defined for column " + xc.getColumnName()));
            continue columnLoop;
        }
        AbstractTable.createField(xc.getColumnName(), type(typeName, length, precision, scale, nullable), table);
    }
    // Constraints
    // -------------------------------------------------------------------------------------------------------------
    Map<Name, List<TableField<Record, ?>>> columnsByConstraint = new HashMap<Name, List<TableField<Record, ?>>>();
    List<KeyColumnUsage> keyColumnUsages = new ArrayList<KeyColumnUsage>(meta.getKeyColumnUsages());
    Collections.sort(keyColumnUsages, new Comparator<KeyColumnUsage>() {

        @Override
        public int compare(KeyColumnUsage o1, KeyColumnUsage o2) {
            int p1 = o1.getOrdinalPosition();
            int p2 = o2.getOrdinalPosition();
            return (p1 < p2) ? -1 : ((p1 == p2) ? 0 : 1);
        }
    });
    keyColumnLoop: for (KeyColumnUsage xc : keyColumnUsages) {
        Name constraintName = name(xc.getConstraintCatalog(), xc.getConstraintSchema(), xc.getConstraintName());
        List<TableField<Record, ?>> fields = columnsByConstraint.get(constraintName);
        if (fields == null) {
            fields = new ArrayList<TableField<Record, ?>>();
            columnsByConstraint.put(constraintName, fields);
        }
        Name tableName = name(xc.getTableCatalog(), xc.getTableSchema(), xc.getTableName());
        InformationSchemaTable table = tablesByName.get(tableName);
        if (table == null) {
            errors.add(String.format("Table " + tableName + " not defined for constraint " + constraintName));
            continue keyColumnLoop;
        }
        TableField<Record, ?> field = (TableField<Record, ?>) table.field(xc.getColumnName());
        if (field == null) {
            errors.add(String.format("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(String.format("Table " + tableName + " not defined for constraint " + constraintName));
                        continue tableConstraintLoop;
                    }
                    List<TableField<Record, ?>> c = columnsByConstraint.get(constraintName);
                    if (c == null || c.isEmpty()) {
                        errors.add(String.format("No columns defined for constraint " + constraintName));
                        continue tableConstraintLoop;
                    }
                    UniqueKeyImpl<Record> key = (UniqueKeyImpl<Record>) AbstractKeys.createUniqueKey(table, xc.getConstraintName(), c.toArray(new TableField[0]));
                    if (xc.getConstraintType() == PRIMARY_KEY) {
                        table.primaryKey = key;
                        primaryKeys.add(key);
                    }
                    table.uniqueKeys.add(key);
                    uniqueKeysByName.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(String.format("Table " + tableName + " not defined for constraint " + constraintName));
                        continue tableConstraintLoop;
                    }
                    List<TableField<Record, ?>> c = columnsByConstraint.get(constraintName);
                    if (c == null || c.isEmpty()) {
                        errors.add(String.format("No columns defined for constraint " + constraintName));
                        continue tableConstraintLoop;
                    }
                    UniqueKeyImpl<Record> uniqueKey = uniqueKeysByName.get(referentialKeys.get(constraintName));
                    if (uniqueKey == null) {
                        errors.add(String.format("No unique key defined for foreign key " + constraintName));
                        continue tableConstraintLoop;
                    }
                    ForeignKey<Record, Record> key = AbstractKeys.createForeignKey(uniqueKey, table, xc.getConstraintName(), c.toArray(new TableField[0]));
                    table.foreignKeys.add(key);
                    break;
                }
        }
    }
    // -------------------------------------------------------------------------------------------------------------
    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(String.format("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;
        @SuppressWarnings({ "rawtypes", "unchecked" }) InformationSchemaSequence is = new InformationSchemaSequence(xs.getSequenceName(), schema, type(typeName, length, precision, scale, nullable));
        sequences.add(is);
    }
    // -------------------------------------------------------------------------------------------------------------
    for (Schema s : schemas) {
        Catalog c = s.getCatalog();
        List<Schema> list = schemasPerCatalog.get(c);
        if (list == null) {
            list = new ArrayList<Schema>();
            schemasPerCatalog.put(c, list);
        }
        list.add(s);
    }
    for (InformationSchemaTable t : tables) {
        Schema s = t.getSchema();
        List<InformationSchemaTable> list = tablesPerSchema.get(s);
        if (list == null) {
            list = new ArrayList<InformationSchemaTable>();
            tablesPerSchema.put(s, list);
        }
        list.add(t);
    }
    for (Sequence<?> q : sequences) {
        Schema s = q.getSchema();
        List<Sequence<?>> list = sequencesPerSchema.get(s);
        if (list == null) {
            list = new ArrayList<Sequence<?>>();
            sequencesPerSchema.put(s, list);
        }
        list.add(q);
    }
    if (!errors.isEmpty())
        throw new IllegalArgumentException(errors.toString());
}
Also used : HashMap(java.util.HashMap) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) Schema(org.jooq.Schema) ArrayList(java.util.ArrayList) Name(org.jooq.Name) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) Column(org.jooq.util.xml.jaxb.Column) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ArrayList(java.util.ArrayList) List(java.util.List) Record(org.jooq.Record) Table(org.jooq.Table) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) Sequence(org.jooq.Sequence) TableField(org.jooq.TableField) Catalog(org.jooq.Catalog) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint)

Aggregations

InformationSchema (org.jooq.util.xml.jaxb.InformationSchema)5 Schema (org.jooq.Schema)3 Table (org.jooq.Table)3 StringWriter (java.io.StringWriter)2 LinkedHashSet (java.util.LinkedHashSet)2 Column (org.jooq.util.xml.jaxb.Column)2 KeyColumnUsage (org.jooq.util.xml.jaxb.KeyColumnUsage)2 ReferentialConstraint (org.jooq.util.xml.jaxb.ReferentialConstraint)2 TableConstraint (org.jooq.util.xml.jaxb.TableConstraint)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 StringReader (java.io.StringReader)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 Collections.unmodifiableList (java.util.Collections.unmodifiableList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Transformer (javax.xml.transform.Transformer)1