Search in sources :

Example 1 with DataDefinitionException

use of org.jooq.exception.DataDefinitionException in project jOOQ by jOOQ.

the class Interpreter method accept0.

private final void accept0(TruncateImpl<?> query) {
    Table<?> table = query.$table();
    MutableSchema schema = getSchema(table.getSchema());
    MutableTable existing = schema.table(table);
    if (existing == null)
        throw notExists(table);
    else if (!existing.options.type().isTable())
        throw objectNotTable(table);
    else if (query.$cascade() != Cascade.CASCADE && existing.hasReferencingKeys())
        throw new DataDefinitionException("Cannot truncate table referenced by other tables. Use CASCADE: " + table);
}
Also used : DataDefinitionException(org.jooq.exception.DataDefinitionException)

Example 2 with DataDefinitionException

use of org.jooq.exception.DataDefinitionException in project jOOQ by jOOQ.

the class Interpreter method accept0.

private final void accept0(DropDomainImpl query) {
    Domain<?> domain = query.$domain();
    MutableSchema schema = getSchema(domain.getSchema());
    MutableDomain existing = schema.domain(domain);
    if (existing == null) {
        if (!query.$ifExists())
            throw notExists(domain);
        return;
    }
    if (query.$cascade() != Cascade.CASCADE && !existing.fields.isEmpty())
        throw new DataDefinitionException("Domain " + domain.getQualifiedName() + " is still being referenced by fields.");
    List<MutableField> field = new ArrayList<>(existing.fields);
    for (MutableField mf : field) dropColumns(mf.table, existing.fields, CASCADE);
    schema.domains.remove(existing);
}
Also used : DataDefinitionException(org.jooq.exception.DataDefinitionException) ArrayList(java.util.ArrayList)

Example 3 with DataDefinitionException

use of org.jooq.exception.DataDefinitionException in project jOOQ by jOOQ.

the class Interpreter method accept0.

private final void accept0(AlterTableImpl query) {
    Table<?> table = query.$table();
    MutableSchema schema = getSchema(table.getSchema());
    MutableTable existing = schema.table(table);
    if (existing == null) {
        if (!query.$ifExists())
            throw notExists(table);
        return;
    } else if (!existing.options.type().isTable())
        throw objectNotTable(table);
    if (query.$add() != null) {
        for (TableElement fc : query.$add()) if (fc instanceof Field && find(existing.fields, (Field<?>) fc) != null)
            throw alreadyExists(fc);
        else if (fc instanceof Constraint && !fc.getUnqualifiedName().empty() && existing.constraint((Constraint) fc) != null)
            throw alreadyExists(fc);
        // TODO: ReverseIterable is not a viable approach if we also allow constraints to be added this way
        if (query.$addFirst()) {
            for (Field<?> f : assertFields(query, reverseIterable(query.$add()))) addField(existing, 0, (UnqualifiedName) f.getUnqualifiedName(), f.getDataType());
        } else if (query.$addBefore() != null) {
            int index = indexOrFail(existing.fields, query.$addBefore());
            for (Field<?> f : assertFields(query, reverseIterable(query.$add()))) addField(existing, index, (UnqualifiedName) f.getUnqualifiedName(), f.getDataType());
        } else if (query.$addAfter() != null) {
            int index = indexOrFail(existing.fields, query.$addAfter()) + 1;
            for (Field<?> f : assertFields(query, reverseIterable(query.$add()))) addField(existing, index, (UnqualifiedName) f.getUnqualifiedName(), f.getDataType());
        } else {
            for (TableElement fc : query.$add()) if (fc instanceof Field)
                addField(existing, Integer.MAX_VALUE, (UnqualifiedName) fc.getUnqualifiedName(), ((Field<?>) fc).getDataType());
            else if (fc instanceof ConstraintImpl)
                addConstraint(query, (ConstraintImpl) fc, existing);
            else
                throw unsupportedQuery(query);
        }
    } else if (query.$addColumn() != null) {
        if (find(existing.fields, query.$addColumn()) != null)
            if (!query.$ifNotExistsColumn())
                throw alreadyExists(query.$addColumn());
            else
                return;
        UnqualifiedName name = (UnqualifiedName) query.$addColumn().getUnqualifiedName();
        DataType<?> dataType = query.$addColumnType();
        if (query.$addFirst())
            addField(existing, 0, name, dataType);
        else if (query.$addBefore() != null)
            addField(existing, indexOrFail(existing.fields, query.$addBefore()), name, dataType);
        else if (query.$addAfter() != null)
            addField(existing, indexOrFail(existing.fields, query.$addAfter()) + 1, name, dataType);
        else
            addField(existing, Integer.MAX_VALUE, name, dataType);
    } else if (query.$addConstraint() != null) {
        addConstraint(query, (ConstraintImpl) query.$addConstraint(), existing);
    } else if (query.$alterColumn() != null) {
        MutableField existingField = find(existing.fields, query.$alterColumn());
        if (existingField == null)
            if (!query.$ifExistsColumn())
                throw notExists(query.$alterColumn());
            else
                return;
        if (query.$alterColumnNullability() != null)
            existingField.type = existingField.type.nullability(query.$alterColumnNullability());
        else if (query.$alterColumnType() != null)
            existingField.type = query.$alterColumnType().nullability(query.$alterColumnType().nullability() == Nullability.DEFAULT ? existingField.type.nullability() : query.$alterColumnType().nullability());
        else if (query.$alterColumnDefault() != null)
            existingField.type = existingField.type.default_((Field) query.$alterColumnDefault());
        else if (query.$alterColumnDropDefault())
            existingField.type = existingField.type.default_((Field) null);
        else
            throw unsupportedQuery(query);
    } else if (query.$renameTo() != null && checkNotExists(schema, query.$renameTo())) {
        existing.name((UnqualifiedName) query.$renameTo().getUnqualifiedName());
    } else if (query.$renameColumn() != null) {
        MutableField mf = find(existing.fields, query.$renameColumn());
        if (mf == null)
            throw notExists(query.$renameColumn());
        else if (find(existing.fields, query.$renameColumnTo()) != null)
            throw alreadyExists(query.$renameColumnTo());
        else
            mf.name((UnqualifiedName) query.$renameColumnTo().getUnqualifiedName());
    } else if (query.$renameConstraint() != null) {
        MutableConstraint mc = existing.constraint(query.$renameConstraint(), true);
        if (existing.constraint(query.$renameConstraintTo()) != null)
            throw alreadyExists(query.$renameConstraintTo());
        else
            mc.name((UnqualifiedName) query.$renameConstraintTo().getUnqualifiedName());
    } else if (query.$alterConstraint() != null) {
        existing.constraint(query.$alterConstraint(), true).enforced = query.$alterConstraintEnforced();
    } else if (query.$dropColumns() != null) {
        List<MutableField> fields = existing.fields(query.$dropColumns().toArray(EMPTY_FIELD), false);
        if (fields.size() < query.$dropColumns().size() && !query.$ifExistsColumn())
            existing.fields(query.$dropColumns().toArray(EMPTY_FIELD), true);
        dropColumns(existing, fields, query.$dropCascade());
    } else if (query.$dropConstraint() != null)
        dropConstraint: {
            ConstraintImpl impl = (ConstraintImpl) query.$dropConstraint();
            if (impl.getUnqualifiedName().empty()) {
                if (impl.$foreignKey() != null) {
                    throw new DataDefinitionException("Cannot drop unnamed foreign key");
                } else if (impl.$check() != null) {
                    throw new DataDefinitionException("Cannot drop unnamed check constraint");
                } else if (impl.$unique() != null) {
                    Iterator<MutableUniqueKey> uks = existing.uniqueKeys.iterator();
                    while (uks.hasNext()) {
                        MutableUniqueKey key = uks.next();
                        if (key.fieldsEquals(impl.$unique())) {
                            cascade(key, null, query.$dropCascade());
                            uks.remove();
                            break dropConstraint;
                        }
                    }
                }
            } else {
                Iterator<MutableForeignKey> fks = existing.foreignKeys.iterator();
                while (fks.hasNext()) {
                    if (fks.next().nameEquals((UnqualifiedName) impl.getUnqualifiedName())) {
                        fks.remove();
                        break dropConstraint;
                    }
                }
                if (query.$dropConstraintType() != FOREIGN_KEY) {
                    Iterator<MutableUniqueKey> uks = existing.uniqueKeys.iterator();
                    while (uks.hasNext()) {
                        MutableUniqueKey key = uks.next();
                        if (key.nameEquals((UnqualifiedName) impl.getUnqualifiedName())) {
                            cascade(key, null, query.$dropCascade());
                            uks.remove();
                            break dropConstraint;
                        }
                    }
                    Iterator<MutableCheck> chks = existing.checks.iterator();
                    while (chks.hasNext()) {
                        MutableCheck check = chks.next();
                        if (check.nameEquals((UnqualifiedName) impl.getUnqualifiedName())) {
                            chks.remove();
                            break dropConstraint;
                        }
                    }
                    if (existing.primaryKey != null) {
                        if (existing.primaryKey.nameEquals((UnqualifiedName) impl.getUnqualifiedName())) {
                            cascade(existing.primaryKey, null, query.$dropCascade());
                            existing.primaryKey = null;
                            break dropConstraint;
                        }
                    }
                }
            }
            Iterator<DelayedForeignKey> it = delayedForeignKeyDeclarations.iterator();
            while (it.hasNext()) {
                DelayedForeignKey key = it.next();
                if (existing.equals(key.table) && key.constraint.getUnqualifiedName().equals(impl.getUnqualifiedName())) {
                    it.remove();
                    break dropConstraint;
                }
            }
            if (!query.$ifExistsConstraint())
                throw notExists(query.$dropConstraint());
        }
    else if (query.$dropConstraintType() == PRIMARY_KEY) {
        if (existing.primaryKey != null)
            existing.primaryKey = null;
        else
            throw primaryKeyNotExists(table);
    } else
        throw unsupportedQuery(query);
}
Also used : FieldOrConstraint(org.jooq.FieldOrConstraint) Constraint(org.jooq.Constraint) TableElement(org.jooq.TableElement) FieldOrConstraint(org.jooq.FieldOrConstraint) Constraint(org.jooq.Constraint) Field(org.jooq.Field) TableField(org.jooq.TableField) SortField(org.jooq.SortField) OrderField(org.jooq.OrderField) DataDefinitionException(org.jooq.exception.DataDefinitionException) DataType(org.jooq.DataType)

Example 4 with DataDefinitionException

use of org.jooq.exception.DataDefinitionException in project jOOQ by jOOQ.

the class SQLiteDatabase method loadCheckConstraints.

@Override
protected void loadCheckConstraints(DefaultRelations r) throws SQLException {
    DSLContext ctx = create().configuration().deriveSettings(s -> s.withInterpreterDelayForeignKeyDeclarations(true)).dsl();
    SchemaDefinition schema = getSchemata().get(0);
    for (Record record : ctx.select(SQLiteMaster.TBL_NAME, SQLiteMaster.SQL).from(SQLITE_MASTER).where(SQLiteMaster.SQL.likeIgnoreCase("%CHECK%")).orderBy(SQLiteMaster.TBL_NAME)) {
        TableDefinition table = getTable(schema, record.get(SQLiteMaster.TBL_NAME));
        if (table != null) {
            String sql = record.get(SQLiteMaster.SQL);
            try {
                Query query = ctx.parser().parseQuery(sql);
                for (Table<?> t : ctx.meta(query).getTables(table.getName())) {
                    for (Check<?> check : t.getChecks()) {
                        r.addCheckConstraint(table, new DefaultCheckConstraintDefinition(schema, table, check.getName(), ctx.renderInlined(check.condition()), check.enforced()));
                    }
                }
            } catch (ParserException e) {
                log.info("Cannot parse SQL: " + sql, e);
            } catch (DataDefinitionException e) {
                log.info("Cannot interpret SQL: " + sql, e);
            }
        }
    }
}
Also used : UniqueKey(org.jooq.UniqueKey) DSL(org.jooq.impl.DSL) DefaultIndexColumnDefinition(org.jooq.meta.DefaultIndexColumnDefinition) DSL.field(org.jooq.impl.DSL.field) Table(org.jooq.Table) DSL.all(org.jooq.impl.DSL.all) DSL.when(org.jooq.impl.DSL.when) RoutineDefinition(org.jooq.meta.RoutineDefinition) PackageDefinition(org.jooq.meta.PackageDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) Record1(org.jooq.Record1) Map(java.util.Map) DSLContext(org.jooq.DSLContext) DSL.coalesce(org.jooq.impl.DSL.coalesce) SQLDialect(org.jooq.SQLDialect) SortOrder(org.jooq.SortOrder) Select(org.jooq.Select) DSL.name(org.jooq.impl.DSL.name) JooqLogger(org.jooq.tools.JooqLogger) Check(org.jooq.Check) Field(org.jooq.Field) DSL.select(org.jooq.impl.DSL.select) Meta(org.jooq.Meta) Result(org.jooq.Result) TableType(org.jooq.TableOptions.TableType) DomainDefinition(org.jooq.meta.DomainDefinition) List(java.util.List) SQLITE_MASTER(org.jooq.meta.sqlite.sqlite_master.SQLiteMaster.SQLITE_MASTER) TableField(org.jooq.TableField) DSL.noCondition(org.jooq.impl.DSL.noCondition) Entry(java.util.Map.Entry) ParserException(org.jooq.impl.ParserException) SchemaMappingType(org.jooq.meta.jaxb.SchemaMappingType) Query(org.jooq.Query) DefaultCheckConstraintDefinition(org.jooq.meta.DefaultCheckConstraintDefinition) AbstractIndexDefinition(org.jooq.meta.AbstractIndexDefinition) DefaultRelations(org.jooq.meta.DefaultRelations) SequenceDefinition(org.jooq.meta.SequenceDefinition) TableDefinition(org.jooq.meta.TableDefinition) HashMap(java.util.HashMap) DSL.replace(org.jooq.impl.DSL.replace) ForeignKey(org.jooq.ForeignKey) IndexDefinition(org.jooq.meta.IndexDefinition) ArrayList(java.util.ArrayList) SelectConditionStep(org.jooq.SelectConditionStep) SQLException(java.sql.SQLException) DSL.selectFrom(org.jooq.impl.DSL.selectFrom) VARCHAR(org.jooq.impl.SQLDataType.VARCHAR) ArrayDefinition(org.jooq.meta.ArrayDefinition) UDTDefinition(org.jooq.meta.UDTDefinition) DSL.inline(org.jooq.impl.DSL.inline) Record(org.jooq.Record) SettingsTools(org.jooq.conf.SettingsTools) SQLiteMaster(org.jooq.meta.sqlite.sqlite_master.SQLiteMaster) StringUtils(org.jooq.tools.StringUtils) DSL.one(org.jooq.impl.DSL.one) DataDefinitionException(org.jooq.exception.DataDefinitionException) SchemaDefinition(org.jooq.meta.SchemaDefinition) DSL.any(org.jooq.impl.DSL.any) EnumDefinition(org.jooq.meta.EnumDefinition) DSL.table(org.jooq.impl.DSL.table) CommonTableExpression(org.jooq.CommonTableExpression) AbstractDatabase(org.jooq.meta.AbstractDatabase) CatalogDefinition(org.jooq.meta.CatalogDefinition) ParserException(org.jooq.impl.ParserException) SchemaDefinition(org.jooq.meta.SchemaDefinition) DataDefinitionException(org.jooq.exception.DataDefinitionException) Query(org.jooq.Query) DSLContext(org.jooq.DSLContext) TableDefinition(org.jooq.meta.TableDefinition) Record(org.jooq.Record) DefaultCheckConstraintDefinition(org.jooq.meta.DefaultCheckConstraintDefinition)

Example 5 with DataDefinitionException

use of org.jooq.exception.DataDefinitionException in project jOOQ by jOOQ.

the class SQLiteTableDefinition method interpretedTable.

Table<?> interpretedTable() {
    if (interpretedTable == null) {
        try {
            Configuration c = create().configuration().derive();
            c.settings().withParseWithMetaLookups(THROW_ON_FAILURE);
            Query query = create().parser().parseQuery(getSource());
            for (Table<?> t : create().meta(query).getTables(getInputName())) return interpretedTable = t;
        } catch (ParserException e) {
            log.info("Cannot parse SQL: " + getSource(), e);
        } catch (DataDefinitionException e) {
            log.info("Cannot interpret SQL: " + getSource(), e);
        }
    }
    return interpretedTable;
}
Also used : ParserException(org.jooq.impl.ParserException) DataDefinitionException(org.jooq.exception.DataDefinitionException) Configuration(org.jooq.Configuration) Query(org.jooq.Query)

Aggregations

DataDefinitionException (org.jooq.exception.DataDefinitionException)6 ArrayList (java.util.ArrayList)2 Field (org.jooq.Field)2 Query (org.jooq.Query)2 TableField (org.jooq.TableField)2 ParserException (org.jooq.impl.ParserException)2 SQLException (java.sql.SQLException)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 Check (org.jooq.Check)1 CommonTableExpression (org.jooq.CommonTableExpression)1 Configuration (org.jooq.Configuration)1 Constraint (org.jooq.Constraint)1 DSLContext (org.jooq.DSLContext)1 DataType (org.jooq.DataType)1 FieldOrConstraint (org.jooq.FieldOrConstraint)1 ForeignKey (org.jooq.ForeignKey)1 Meta (org.jooq.Meta)1