Search in sources :

Example 16 with ColumnDefinition

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

the class SQLiteTableDefinition method getElements0.

@Override
public List<ColumnDefinition> getElements0() throws SQLException {
    List<ColumnDefinition> result = new ArrayList<>();
    Field<String> fName = field(name("name"), String.class);
    Field<String> fType = field(name("type"), String.class);
    Field<Boolean> fNotnull = field(name("notnull"), boolean.class);
    Field<String> fDefaultValue = field(name("dflt_value"), String.class);
    Field<Integer> fPk = field(name("pk"), int.class);
    Field<Integer> fHidden = field(name("hidden"), int.class);
    for (Record record : create().select(fName, fType, fNotnull, fDefaultValue, fPk, fHidden).from("pragma_table_xinfo({0})", inline(getName())).where("hidden in (0, 2, 3)")) {
        String name = record.get(fName);
        String dataType = record.get(fType).replaceAll("\\(\\d+(\\s*,\\s*\\d+)?\\)", "");
        Number precision = parsePrecision(record.get(fType));
        Number scale = parseScale(record.get(fType));
        // SQLite identities are primary keys whose tables are mentioned in
        // sqlite_sequence
        int pk = record.get(fPk);
        int hidden = record.get(fHidden);
        boolean identity = false;
        boolean generated = hidden == 2 || hidden == 3;
        String generator = null;
        // [#8278] [#11172] SQLite doesn't store the data type for all views or virtual tables
        if (isBlank(dataType) || "other".equals(dataType)) {
            Table<?> t = interpretedTable();
            if (t != null) {
                Field<?> f = t.field(name);
                if (f != null) {
                    dataType = f.getDataType().getName();
                    precision = f.getDataType().precision();
                    scale = f.getDataType().scale();
                }
            }
        }
        if (generated) {
            // SQLite's type affinity feature gets in the way of correctly
            // interpreting data types when the column is computed, see
            // https://sqlite.org/forum/forumpost/8ebb993012
            // This is ignoring typos, because things like "generaated aways"
            // also work in SQLite, as long as there's an "as" keyword...
            dataType = dataType.replaceAll("(?i:\\s*generated\\s+always\\s*)", "");
        }
        if (pk > 0) {
            // [#6854] sqlite_sequence only contains identity information once a table contains records.
            identity |= existsSqliteSequence() && create().fetchOne("select count(*) from sqlite_sequence where name = ?", getName()).get(0, Boolean.class);
            if (!identity && !create().fetchExists(selectOne().from("{0}", DSL.name(getName()))))
                identity = getSource().matches("(?s:.*\\b" + getName() + "\\b[^,]*(?i:\\bautoincrement\\b)[^,]*.*)");
        }
        DefaultDataTypeDefinition type = new DefaultDataTypeDefinition(getDatabase(), getSchema(), dataType, precision, precision, scale, !record.get(fNotnull), record.get(fDefaultValue)).generatedAlwaysAs(generator).generationOption(hidden == 2 ? VIRTUAL : hidden == 3 ? STORED : null);
        result.add(new DefaultColumnDefinition(getDatabase().getTable(getSchema(), getName()), name, result.size() + 1, type, identity, null));
    }
    return result;
}
Also used : DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) ArrayList(java.util.ArrayList) DefaultColumnDefinition(org.jooq.meta.DefaultColumnDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) DefaultColumnDefinition(org.jooq.meta.DefaultColumnDefinition) Record(org.jooq.Record)

Example 17 with ColumnDefinition

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

the class XMLDatabase method getIndexes0.

@Override
protected List<IndexDefinition> getIndexes0() throws SQLException {
    List<IndexDefinition> result = new ArrayList<>();
    final Map<Name, SortedSet<IndexColumnUsage>> indexColumnUsage = new HashMap<>();
    for (IndexColumnUsage ic : info().getIndexColumnUsages()) {
        Name name = name(ic.getIndexCatalog(), ic.getIndexSchema(), ic.getTableName(), ic.getIndexName());
        SortedSet<IndexColumnUsage> list = indexColumnUsage.computeIfAbsent(name, k -> new TreeSet<>((o1, o2) -> {
            int r = 0;
            r = defaultIfNull(o1.getIndexCatalog(), "").compareTo(defaultIfNull(o2.getIndexCatalog(), ""));
            if (r != 0)
                return r;
            r = defaultIfNull(o1.getIndexSchema(), "").compareTo(defaultIfNull(o2.getIndexSchema(), ""));
            if (r != 0)
                return r;
            r = defaultIfNull(o1.getTableName(), "").compareTo(defaultIfNull(o2.getTableName(), ""));
            if (r != 0)
                return r;
            r = defaultIfNull(o1.getIndexName(), "").compareTo(defaultIfNull(o2.getIndexName(), ""));
            if (r != 0)
                return r;
            return Integer.compare(o1.getOrdinalPosition(), o2.getOrdinalPosition());
        }));
        list.add(ic);
    }
    indexLoop: for (Index i : info().getIndexes()) {
        if (getInputSchemata().contains(i.getTableSchema())) {
            final SchemaDefinition schema = getSchema(i.getTableSchema());
            final TableDefinition table = getTable(schema, i.getTableName());
            if (table == null)
                continue indexLoop;
            final Name name = name(i.getIndexCatalog(), i.getIndexSchema(), i.getTableName(), i.getIndexName());
            IndexDefinition index = new AbstractIndexDefinition(schema, i.getIndexName(), table, Boolean.TRUE.equals(i.isIsUnique()), i.getComment()) {

                private final List<IndexColumnDefinition> indexColumns;

                {
                    indexColumns = new ArrayList<>();
                    SortedSet<IndexColumnUsage> list = indexColumnUsage.get(name);
                    if (list != null)
                        for (IndexColumnUsage ic : list) {
                            ColumnDefinition column = table.getColumn(ic.getColumnName());
                            if (column != null)
                                indexColumns.add(new DefaultIndexColumnDefinition(this, column, Boolean.TRUE.equals(ic.isIsDescending()) ? SortOrder.DESC : SortOrder.ASC, ic.getOrdinalPosition()));
                            else
                                log.error(String.format("Column %s not found in table %s.", ic.getColumnName(), table));
                        }
                    else
                        log.error(String.format("No columns found for index %s.", name));
                }

                @Override
                protected List<IndexColumnDefinition> getIndexColumns0() {
                    return indexColumns;
                }
            };
            result.add(index);
        }
    }
    return result;
}
Also used : Transformer(javax.xml.transform.Transformer) DSL(org.jooq.impl.DSL) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) SortedSet(java.util.SortedSet) StringUtils.isBlank(org.jooq.tools.StringUtils.isBlank) XMLInputFactory(javax.xml.stream.XMLInputFactory) StreamResult(javax.xml.transform.stream.StreamResult) MiniJAXB(org.jooq.util.jaxb.tools.MiniJAXB) DefaultSequenceDefinition(org.jooq.meta.DefaultSequenceDefinition) Table(org.jooq.util.xml.jaxb.Table) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) RoutineDefinition(org.jooq.meta.RoutineDefinition) PackageDefinition(org.jooq.meta.PackageDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) IOException(org.jooq.exception.IOException) InformationSchema(org.jooq.util.xml.jaxb.InformationSchema) XMLStreamReader(javax.xml.stream.XMLStreamReader) Map(java.util.Map) XMLStreamException(javax.xml.stream.XMLStreamException) DSLContext(org.jooq.DSLContext) SQLDialect(org.jooq.SQLDialect) SortOrder(org.jooq.SortOrder) DSL.name(org.jooq.impl.DSL.name) JooqLogger(org.jooq.tools.JooqLogger) Routine(org.jooq.util.xml.jaxb.Routine) View(org.jooq.util.xml.jaxb.View) Name(org.jooq.Name) CheckConstraint(org.jooq.util.xml.jaxb.CheckConstraint) Set(java.util.Set) Constants(org.jooq.Constants) UNIQUE(org.jooq.util.xml.jaxb.TableConstraintType.UNIQUE) Reader(java.io.Reader) Schema(org.jooq.util.xml.jaxb.Schema) TableConstraintType(org.jooq.util.xml.jaxb.TableConstraintType) PRIMARY_KEY(org.jooq.util.xml.jaxb.TableConstraintType.PRIMARY_KEY) JDBCUtils(org.jooq.tools.jdbc.JDBCUtils) FilePattern(org.jooq.FilePattern) TableType(org.jooq.TableOptions.TableType) DomainDefinition(org.jooq.meta.DomainDefinition) List(java.util.List) StringUtils.defaultIfNull(org.jooq.tools.StringUtils.defaultIfNull) IndexColumnUsage(org.jooq.util.xml.jaxb.IndexColumnUsage) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultCheckConstraintDefinition(org.jooq.meta.DefaultCheckConstraintDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultRelations(org.jooq.meta.DefaultRelations) SequenceDefinition(org.jooq.meta.SequenceDefinition) TransformerException(javax.xml.transform.TransformerException) StreamSource(javax.xml.transform.stream.StreamSource) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) TableDefinition(org.jooq.meta.TableDefinition) HashMap(java.util.HashMap) Sequence(org.jooq.util.xml.jaxb.Sequence) IndexDefinition(org.jooq.meta.IndexDefinition) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SQLException(java.sql.SQLException) ArrayDefinition(org.jooq.meta.ArrayDefinition) UDTDefinition(org.jooq.meta.UDTDefinition) KeyColumnUsage(org.jooq.util.xml.jaxb.KeyColumnUsage) FALSE(java.lang.Boolean.FALSE) StringUtils.defaultIfBlank(org.jooq.tools.StringUtils.defaultIfBlank) ReferentialConstraint(org.jooq.util.xml.jaxb.ReferentialConstraint) StringWriter(java.io.StringWriter) FileInputStream(java.io.FileInputStream) StringUtils(org.jooq.tools.StringUtils) File(java.io.File) Index(org.jooq.util.xml.jaxb.Index) Sort(org.jooq.FilePattern.Sort) StringReader(java.io.StringReader) SchemaDefinition(org.jooq.meta.SchemaDefinition) TableConstraint(org.jooq.util.xml.jaxb.TableConstraint) EnumDefinition(org.jooq.meta.EnumDefinition) TransformerFactory(javax.xml.transform.TransformerFactory) Collections(java.util.Collections) AbstractDatabase(org.jooq.meta.AbstractDatabase) CatalogDefinition(org.jooq.meta.CatalogDefinition) InputStream(java.io.InputStream) SchemaDefinition(org.jooq.meta.SchemaDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Index(org.jooq.util.xml.jaxb.Index) SortedSet(java.util.SortedSet) IndexColumnUsage(org.jooq.util.xml.jaxb.IndexColumnUsage) Name(org.jooq.Name) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) TableDefinition(org.jooq.meta.TableDefinition) List(java.util.List) ArrayList(java.util.ArrayList)

Example 18 with ColumnDefinition

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

the class MySQLTableDefinition method getElements0.

@Override
public List<ColumnDefinition> getElements0() throws SQLException {
    List<ColumnDefinition> result = new ArrayList<>();
    for (Record record : create().select(COLUMNS.ORDINAL_POSITION, COLUMNS.COLUMN_NAME, COLUMNS.COLUMN_COMMENT, COLUMNS.COLUMN_TYPE, COLUMNS.DATA_TYPE, COLUMNS.IS_NULLABLE, COLUMNS.COLUMN_DEFAULT, COLUMNS.EXTRA, COLUMNS.GENERATION_EXPRESSION, COLUMNS.CHARACTER_MAXIMUM_LENGTH, // [#10856] Some older versions of MySQL 5.7 don't have the DATETIME_PRECISION column yet
    getDatabase().exists(COLUMNS.DATETIME_PRECISION) ? coalesce(COLUMNS.NUMERIC_PRECISION, COLUMNS.DATETIME_PRECISION).as(COLUMNS.NUMERIC_PRECISION) : COLUMNS.NUMERIC_PRECISION, COLUMNS.NUMERIC_SCALE, COLUMNS.EXTRA).from(COLUMNS).where(COLUMNS.TABLE_SCHEMA.in(getSchema().getName(), getSchema().getName())).and(COLUMNS.TABLE_NAME.equal(getName())).orderBy(COLUMNS.ORDINAL_POSITION)) {
        String dataType = record.get(COLUMNS.DATA_TYPE);
        // [#519] Some types have unsigned versions
        boolean unsigned = getDatabase().supportsUnsignedTypes();
        // [#7719]
        boolean displayWidths = getDatabase().integerDisplayWidths();
        // [#6492] MariaDB supports a standard IS_GENERATED, but MySQL doesn't (yet)
        boolean generated = record.get(COLUMNS.EXTRA) != null && record.get(COLUMNS.EXTRA).toUpperCase().contains("GENERATED");
        GenerationOption generationOption = "VIRTUAL GENERATED".equalsIgnoreCase(record.get(COLUMNS.EXTRA)) ? GenerationOption.VIRTUAL : "STORED GENERATED".equalsIgnoreCase(record.get(COLUMNS.EXTRA)) ? GenerationOption.STORED : null;
        columnTypeFix: if (unsigned || displayWidths) {
            if (asList("tinyint", "smallint", "mediumint", "int", "bigint").contains(dataType.toLowerCase())) {
                String columnType = record.get(COLUMNS.COLUMN_TYPE).toLowerCase();
                Matcher matcher = COLUMN_TYPE.matcher(columnType);
                if (matcher.find()) {
                    String mType = matcher.group(1);
                    String mPrecision = matcher.group(2);
                    String mUnsigned = matcher.group(3);
                    dataType = mType + (unsigned && mUnsigned != null ? mUnsigned : "") + (displayWidths && mPrecision != null ? mPrecision : "");
                }
            }
        }
        DataTypeDefinition type = new DefaultDataTypeDefinition(getDatabase(), getSchema(), dataType, record.get(COLUMNS.CHARACTER_MAXIMUM_LENGTH), record.get(COLUMNS.NUMERIC_PRECISION), record.get(COLUMNS.NUMERIC_SCALE), record.get(COLUMNS.IS_NULLABLE, boolean.class), generated ? null : record.get(COLUMNS.COLUMN_DEFAULT), name(getSchema().getName(), getName() + "_" + record.get(COLUMNS.COLUMN_NAME))).generatedAlwaysAs(generated ? record.get(COLUMNS.GENERATION_EXPRESSION) : null).generationOption(generationOption);
        result.add(new DefaultColumnDefinition(getDatabase().getTable(getSchema(), getName()), record.get(COLUMNS.COLUMN_NAME), result.size() + 1, type, "auto_increment".equalsIgnoreCase(record.get(COLUMNS.EXTRA)), record.get(COLUMNS.COLUMN_COMMENT)));
    }
    return result;
}
Also used : GenerationOption(org.jooq.impl.QOM.GenerationOption) Matcher(java.util.regex.Matcher) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) DefaultColumnDefinition(org.jooq.meta.DefaultColumnDefinition) ArrayList(java.util.ArrayList) Record(org.jooq.Record) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) DefaultColumnDefinition(org.jooq.meta.DefaultColumnDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition)

Example 19 with ColumnDefinition

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

the class PostgresDatabase method getIndexes0.

@Override
protected List<IndexDefinition> getIndexes0() throws SQLException {
    List<IndexDefinition> result = new ArrayList<>();
    PgIndex i = PG_INDEX.as("i");
    PgClass trel = PG_CLASS.as("trel");
    PgConstraint c = PG_CONSTRAINT.as("c");
    indexLoop: for (Record6<String, String, String, Boolean, String[], Integer[]> record : create().select(trel.pgNamespace().NSPNAME, trel.RELNAME, i.indexClass().RELNAME, i.INDISUNIQUE, array(select(field("pg_get_indexdef({0}, k + 1, true)", String.class, i.INDEXRELID)).from("generate_subscripts({0}, 1) as k", i.INDKEY).orderBy(field("k"))).as("columns"), field("{0}::int[]", Integer[].class, i.INDOPTION).as("asc_or_desc")).from(i).join(trel).on(trel.OID.eq(i.INDRELID)).where(trel.pgNamespace().NSPNAME.in(getInputSchemata())).and(getIncludeSystemIndexes() ? noCondition() : row(trel.pgNamespace().NSPNAME, i.indexClass().RELNAME).notIn(select(c.pgNamespace().NSPNAME, c.CONNAME).from(c))).orderBy(1, 2, 3)) {
        final SchemaDefinition tableSchema = getSchema(record.get(trel.pgNamespace().NSPNAME));
        if (tableSchema == null)
            continue indexLoop;
        final String indexName = record.get(i.indexClass().RELNAME);
        final String tableName = record.get(trel.RELNAME);
        final String[] columns = record.value5();
        final Integer[] options = record.value6();
        final TableDefinition table = getTable(tableSchema, tableName);
        if (table == null)
            continue indexLoop;
        final boolean unique = record.get(i.INDISUNIQUE);
        for (int k = 0; k < columns.length; k++) // the column expression, because it might be quoted
        if (table.getColumn(columns[k]) == null && table.getColumn(columns[k] = tryParseColumnName(columns[k])) == null)
            continue indexLoop;
        else // columns without options
        if (k >= options.length)
            continue indexLoop;
        result.add(new AbstractIndexDefinition(tableSchema, indexName, table, unique) {

            List<IndexColumnDefinition> indexColumns = new ArrayList<>();

            {
                for (int ordinal = 0; ordinal < columns.length; ordinal++) {
                    ColumnDefinition column = table.getColumn(columns[ordinal]);
                    // [#6307] Some background info on this bitwise operation here:
                    // https://stackoverflow.com/a/18128104/521799
                    SortOrder order = (options[ordinal] & 1) == 1 ? SortOrder.DESC : SortOrder.ASC;
                    indexColumns.add(new DefaultIndexColumnDefinition(this, column, order, ordinal + 1));
                }
            }

            @Override
            protected List<IndexColumnDefinition> getIndexColumns0() {
                return indexColumns;
            }
        });
    }
    return result;
}
Also used : SchemaDefinition(org.jooq.meta.SchemaDefinition) ArrayList(java.util.ArrayList) SortOrder(org.jooq.SortOrder) PgConstraint(org.jooq.meta.postgres.pg_catalog.tables.PgConstraint) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) BigInteger(java.math.BigInteger) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) PgConstraint(org.jooq.meta.postgres.pg_catalog.tables.PgConstraint) PgIndex(org.jooq.meta.postgres.pg_catalog.tables.PgIndex) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) PgClass(org.jooq.meta.postgres.pg_catalog.tables.PgClass) TableDefinition(org.jooq.meta.TableDefinition) Record6(org.jooq.Record6) Records.intoList(org.jooq.Records.intoList) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList)

Example 20 with ColumnDefinition

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

the class CUBRIDDatabase method getEnums0.

@Override
protected List<EnumDefinition> getEnums0() throws SQLException {
    List<EnumDefinition> result = new ArrayList<>();
    for (TableDefinition tableDefinition : getTables(getSchemata().get(0))) {
        for (Record record : create().fetch("SHOW COLUMNS FROM {0} WHERE TYPE LIKE 'ENUM(%)'", field(name(tableDefinition.getInputName())))) {
            String table = tableDefinition.getInputName();
            String column = record.get("Field", String.class);
            String columnType = record.get("Type", String.class);
            String name = table + "_" + column;
            ColumnDefinition columnDefinition = tableDefinition.getColumn(column);
            // are explicitly forced to another type
            if (getConfiguredForcedType(columnDefinition) == null) {
                DefaultEnumDefinition definition = new DefaultEnumDefinition(getSchemata().get(0), name, "");
                for (String string : columnType.replaceAll("ENUM\\(|\\)", "").split(",")) {
                    definition.addLiteral(string.trim().replaceAll("'", ""));
                }
                result.add(definition);
            }
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) TableDefinition(org.jooq.meta.TableDefinition) DefaultEnumDefinition(org.jooq.meta.DefaultEnumDefinition) Record(org.jooq.Record) DefaultEnumDefinition(org.jooq.meta.DefaultEnumDefinition) EnumDefinition(org.jooq.meta.EnumDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition)

Aggregations

ColumnDefinition (org.jooq.meta.ColumnDefinition)26 ArrayList (java.util.ArrayList)21 DefaultDataTypeDefinition (org.jooq.meta.DefaultDataTypeDefinition)18 Record (org.jooq.Record)16 DataTypeDefinition (org.jooq.meta.DataTypeDefinition)16 SchemaDefinition (org.jooq.meta.SchemaDefinition)15 DefaultColumnDefinition (org.jooq.meta.DefaultColumnDefinition)14 IndexColumnDefinition (org.jooq.meta.IndexColumnDefinition)10 TableDefinition (org.jooq.meta.TableDefinition)10 IndexDefinition (org.jooq.meta.IndexDefinition)7 Name (org.jooq.Name)6 CatalogDefinition (org.jooq.meta.CatalogDefinition)6 EnumDefinition (org.jooq.meta.EnumDefinition)6 List (java.util.List)5 SortOrder (org.jooq.SortOrder)5 PackageDefinition (org.jooq.meta.PackageDefinition)5 RoutineDefinition (org.jooq.meta.RoutineDefinition)5 SequenceDefinition (org.jooq.meta.SequenceDefinition)5 UniqueKeyDefinition (org.jooq.meta.UniqueKeyDefinition)5 File (java.io.File)4