Search in sources :

Example 1 with Constraint

use of org.h2.constraint.Constraint in project h2database by h2database.

the class Parser method parseAlterTable.

private Prepared parseAlterTable() {
    boolean ifTableExists = readIfExists(false);
    String tableName = readIdentifierWithSchema();
    Schema schema = getSchema();
    if (readIf("ADD")) {
        Prepared command = parseAlterTableAddConstraintIf(tableName, schema, ifTableExists);
        if (command != null) {
            return command;
        }
        return parseAlterTableAddColumn(tableName, schema, ifTableExists);
    } else if (readIf("SET")) {
        read("REFERENTIAL_INTEGRITY");
        int type = CommandInterface.ALTER_TABLE_SET_REFERENTIAL_INTEGRITY;
        boolean value = readBooleanSetting();
        AlterTableSet command = new AlterTableSet(session, schema, type, value);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        if (readIf("CHECK")) {
            command.setCheckExisting(true);
        } else if (readIf("NOCHECK")) {
            command.setCheckExisting(false);
        }
        return command;
    } else if (readIf("RENAME")) {
        if (readIf("COLUMN")) {
            // PostgreSQL syntax
            String columnName = readColumnIdentifier();
            read("TO");
            AlterTableRenameColumn command = new AlterTableRenameColumn(session, schema);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setOldColumnName(columnName);
            String newName = readColumnIdentifier();
            command.setNewColumnName(newName);
            return command;
        } else if (readIf("CONSTRAINT")) {
            String constraintName = readIdentifierWithSchema(schema.getName());
            checkSchema(schema);
            read("TO");
            AlterTableRenameConstraint command = new AlterTableRenameConstraint(session, schema);
            command.setConstraintName(constraintName);
            String newName = readColumnIdentifier();
            command.setNewConstraintName(newName);
            return commandIfTableExists(schema, tableName, ifTableExists, command);
        } else {
            read("TO");
            String newName = readIdentifierWithSchema(schema.getName());
            checkSchema(schema);
            AlterTableRename command = new AlterTableRename(session, getSchema());
            command.setOldTableName(tableName);
            command.setNewTableName(newName);
            command.setIfTableExists(ifTableExists);
            command.setHidden(readIf("HIDDEN"));
            return command;
        }
    } else if (readIf("DROP")) {
        if (readIf("CONSTRAINT")) {
            boolean ifExists = readIfExists(false);
            String constraintName = readIdentifierWithSchema(schema.getName());
            ifExists = readIfExists(ifExists);
            checkSchema(schema);
            AlterTableDropConstraint command = new AlterTableDropConstraint(session, getSchema(), ifExists);
            command.setConstraintName(constraintName);
            return commandIfTableExists(schema, tableName, ifTableExists, command);
        } else if (readIf("FOREIGN")) {
            // MySQL compatibility
            read("KEY");
            String constraintName = readIdentifierWithSchema(schema.getName());
            checkSchema(schema);
            AlterTableDropConstraint command = new AlterTableDropConstraint(session, getSchema(), false);
            command.setConstraintName(constraintName);
            return commandIfTableExists(schema, tableName, ifTableExists, command);
        } else if (readIf("INDEX")) {
            // MySQL compatibility
            String indexOrConstraintName = readIdentifierWithSchema();
            final SchemaCommand command;
            if (schema.findIndex(session, indexOrConstraintName) != null) {
                DropIndex dropIndexCommand = new DropIndex(session, getSchema());
                dropIndexCommand.setIndexName(indexOrConstraintName);
                command = dropIndexCommand;
            } else {
                AlterTableDropConstraint dropCommand = new AlterTableDropConstraint(session, getSchema(), false);
                dropCommand.setConstraintName(indexOrConstraintName);
                command = dropCommand;
            }
            return commandIfTableExists(schema, tableName, ifTableExists, command);
        } else if (readIf("PRIMARY")) {
            read("KEY");
            Table table = tableIfTableExists(schema, tableName, ifTableExists);
            if (table == null) {
                return new NoOperation(session);
            }
            Index idx = table.getPrimaryKey();
            DropIndex command = new DropIndex(session, schema);
            command.setIndexName(idx.getName());
            return command;
        } else {
            readIf("COLUMN");
            boolean ifExists = readIfExists(false);
            ArrayList<Column> columnsToRemove = New.arrayList();
            Table table = tableIfTableExists(schema, tableName, ifTableExists);
            // For Oracle compatibility - open bracket required
            boolean openingBracketDetected = readIf("(");
            do {
                String columnName = readColumnIdentifier();
                if (table != null) {
                    if (!ifExists || table.doesColumnExist(columnName)) {
                        Column column = table.getColumn(columnName);
                        columnsToRemove.add(column);
                    }
                }
            } while (readIf(","));
            if (openingBracketDetected) {
                // For Oracle compatibility - close bracket
                read(")");
            }
            if (table == null || columnsToRemove.isEmpty()) {
                return new NoOperation(session);
            }
            AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
            command.setType(CommandInterface.ALTER_TABLE_DROP_COLUMN);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setColumnsToRemove(columnsToRemove);
            return command;
        }
    } else if (readIf("CHANGE")) {
        // MySQL compatibility
        readIf("COLUMN");
        String columnName = readColumnIdentifier();
        String newColumnName = readColumnIdentifier();
        Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
        boolean nullable = column == null ? true : column.isNullable();
        // new column type ignored. RENAME and MODIFY are
        // a single command in MySQL but two different commands in H2.
        parseColumnForTable(newColumnName, nullable);
        AlterTableRenameColumn command = new AlterTableRenameColumn(session, schema);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        command.setOldColumnName(columnName);
        command.setNewColumnName(newColumnName);
        return command;
    } else if (readIf("MODIFY")) {
        // MySQL compatibility (optional)
        readIf("COLUMN");
        // Oracle specifies (but will not require) an opening parenthesis
        boolean hasOpeningBracket = readIf("(");
        String columnName = readColumnIdentifier();
        AlterTableAlterColumn command = null;
        NullConstraintType nullConstraint = parseNotNullConstraint();
        switch(nullConstraint) {
            case NULL_IS_ALLOWED:
            case NULL_IS_NOT_ALLOWED:
                command = new AlterTableAlterColumn(session, schema);
                command.setTableName(tableName);
                command.setIfTableExists(ifTableExists);
                Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
                command.setOldColumn(column);
                if (nullConstraint == NullConstraintType.NULL_IS_ALLOWED) {
                    command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
                } else {
                    command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL);
                }
                break;
            case NO_NULL_CONSTRAINT_FOUND:
                command = parseAlterTableAlterColumnType(schema, tableName, columnName, ifTableExists);
                break;
            default:
                throw DbException.get(ErrorCode.UNKNOWN_MODE_1, "Internal Error - unhandled case: " + nullConstraint.name());
        }
        if (hasOpeningBracket) {
            read(")");
        }
        return command;
    } else if (readIf("ALTER")) {
        readIf("COLUMN");
        String columnName = readColumnIdentifier();
        Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
        if (readIf("RENAME")) {
            read("TO");
            AlterTableRenameColumn command = new AlterTableRenameColumn(session, schema);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setOldColumnName(columnName);
            String newName = readColumnIdentifier();
            command.setNewColumnName(newName);
            return command;
        } else if (readIf("DROP")) {
            // PostgreSQL compatibility
            if (readIf("DEFAULT")) {
                AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
                command.setTableName(tableName);
                command.setIfTableExists(ifTableExists);
                command.setOldColumn(column);
                command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT);
                command.setDefaultExpression(null);
                return command;
            }
            if (readIf("ON")) {
                read("UPDATE");
                AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
                command.setTableName(tableName);
                command.setIfTableExists(ifTableExists);
                command.setOldColumn(column);
                command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE);
                command.setDefaultExpression(null);
                return command;
            }
            read("NOT");
            read("NULL");
            AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setOldColumn(column);
            command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
            return command;
        } else if (readIf("TYPE")) {
            // PostgreSQL compatibility
            return parseAlterTableAlterColumnType(schema, tableName, columnName, ifTableExists);
        } else if (readIf("SET")) {
            if (readIf("DATA")) {
                // Derby compatibility
                read("TYPE");
                return parseAlterTableAlterColumnType(schema, tableName, columnName, ifTableExists);
            }
            AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setOldColumn(column);
            NullConstraintType nullConstraint = parseNotNullConstraint();
            switch(nullConstraint) {
                case NULL_IS_ALLOWED:
                    command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
                    break;
                case NULL_IS_NOT_ALLOWED:
                    command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL);
                    break;
                case NO_NULL_CONSTRAINT_FOUND:
                    if (readIf("DEFAULT")) {
                        Expression defaultExpression = readExpression();
                        command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT);
                        command.setDefaultExpression(defaultExpression);
                    } else if (readIf("ON")) {
                        read("UPDATE");
                        Expression onUpdateExpression = readExpression();
                        command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE);
                        command.setDefaultExpression(onUpdateExpression);
                    } else if (readIf("INVISIBLE")) {
                        command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY);
                        command.setVisible(false);
                    } else if (readIf("VISIBLE")) {
                        command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY);
                        command.setVisible(true);
                    }
                    break;
                default:
                    throw DbException.get(ErrorCode.UNKNOWN_MODE_1, "Internal Error - unhandled case: " + nullConstraint.name());
            }
            return command;
        } else if (readIf("RESTART")) {
            readIf("WITH");
            Expression start = readExpression();
            AlterSequence command = new AlterSequence(session, schema);
            command.setColumn(column);
            command.setStartWith(start);
            return commandIfTableExists(schema, tableName, ifTableExists, command);
        } else if (readIf("SELECTIVITY")) {
            AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
            command.setTableName(tableName);
            command.setIfTableExists(ifTableExists);
            command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_SELECTIVITY);
            command.setOldColumn(column);
            command.setSelectivity(readExpression());
            return command;
        } else {
            return parseAlterTableAlterColumnType(schema, tableName, columnName, ifTableExists);
        }
    }
    throw getSyntaxError();
}
Also used : AlterSequence(org.h2.command.dml.AlterSequence) RangeTable(org.h2.table.RangeTable) TruncateTable(org.h2.command.ddl.TruncateTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) CreateLinkedTable(org.h2.command.ddl.CreateLinkedTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) AlterTableRename(org.h2.command.ddl.AlterTableRename) DropIndex(org.h2.command.ddl.DropIndex) Index(org.h2.index.Index) CreateIndex(org.h2.command.ddl.CreateIndex) ValueString(org.h2.value.ValueString) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) SchemaCommand(org.h2.command.ddl.SchemaCommand) AlterTableSet(org.h2.command.dml.AlterTableSet) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) NoOperation(org.h2.command.dml.NoOperation) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) DropIndex(org.h2.command.ddl.DropIndex)

Example 2 with Constraint

use of org.h2.constraint.Constraint in project h2database by h2database.

the class AlterTableAlterColumn method copyData.

private void copyData(Table table, ArrayList<Sequence> sequences, boolean createConstraints) {
    if (table.isTemporary()) {
        throw DbException.getUnsupportedException("TEMP TABLE");
    }
    Database db = session.getDatabase();
    String baseName = table.getName();
    String tempName = db.getTempTableName(baseName, session);
    Column[] columns = table.getColumns();
    ArrayList<Column> newColumns = New.arrayList();
    Table newTable = cloneTableStructure(table, columns, db, tempName, newColumns);
    if (sequences != null) {
        for (Sequence sequence : sequences) {
            table.addSequence(sequence);
        }
    }
    try {
        // check if a view would become invalid
        // (because the column to drop is referenced or so)
        checkViews(table, newTable);
    } catch (DbException e) {
        execute("DROP TABLE " + newTable.getName(), true);
        throw DbException.get(ErrorCode.VIEW_IS_INVALID_2, e, getSQL(), e.getMessage());
    }
    String tableName = table.getName();
    ArrayList<TableView> dependentViews = new ArrayList<>(table.getDependentViews());
    for (TableView view : dependentViews) {
        table.removeDependentView(view);
    }
    execute("DROP TABLE " + table.getSQL() + " IGNORE", true);
    db.renameSchemaObject(session, newTable, tableName);
    for (DbObject child : newTable.getChildren()) {
        if (child instanceof Sequence) {
            continue;
        }
        String name = child.getName();
        if (name == null || child.getCreateSQL() == null) {
            continue;
        }
        if (name.startsWith(tempName + "_")) {
            name = name.substring(tempName.length() + 1);
            SchemaObject so = (SchemaObject) child;
            if (so instanceof Constraint) {
                if (so.getSchema().findConstraint(session, name) != null) {
                    name = so.getSchema().getUniqueConstraintName(session, newTable);
                }
            } else if (so instanceof Index) {
                if (so.getSchema().findIndex(session, name) != null) {
                    name = so.getSchema().getUniqueIndexName(session, newTable, name);
                }
            }
            db.renameSchemaObject(session, so, name);
        }
    }
    if (createConstraints) {
        createConstraints();
    }
    for (TableView view : dependentViews) {
        String sql = view.getCreateSQL(true, true);
        execute(sql, true);
    }
}
Also used : SchemaObject(org.h2.schema.SchemaObject) Table(org.h2.table.Table) DbObject(org.h2.engine.DbObject) Constraint(org.h2.constraint.Constraint) ArrayList(java.util.ArrayList) Index(org.h2.index.Index) Sequence(org.h2.schema.Sequence) DbException(org.h2.message.DbException) Column(org.h2.table.Column) Database(org.h2.engine.Database) TableView(org.h2.table.TableView)

Example 3 with Constraint

use of org.h2.constraint.Constraint in project h2database by h2database.

the class AlterTableAddConstraint method tryUpdate.

/**
 * Try to execute the statement.
 *
 * @return the update count
 */
private int tryUpdate() {
    if (!transactional) {
        session.commit(true);
    }
    Database db = session.getDatabase();
    Table table = getSchema().findTableOrView(session, tableName);
    if (table == null) {
        if (ifTableExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
    }
    if (getSchema().findConstraint(session, constraintName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
    }
    session.getUser().checkRight(table, Right.ALL);
    db.lockMeta(session);
    table.lock(session, true, true);
    Constraint constraint;
    switch(type) {
        case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY:
            {
                IndexColumn.mapColumns(indexColumns, table);
                index = table.findPrimaryKey();
                ArrayList<Constraint> constraints = table.getConstraints();
                for (int i = 0; constraints != null && i < constraints.size(); i++) {
                    Constraint c = constraints.get(i);
                    if (Constraint.Type.PRIMARY_KEY == c.getConstraintType()) {
                        throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
                    }
                }
                if (index != null) {
                    // if there is an index, it must match with the one declared
                    // we don't test ascending / descending
                    IndexColumn[] pkCols = index.getIndexColumns();
                    if (pkCols.length != indexColumns.length) {
                        throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
                    }
                    for (int i = 0; i < pkCols.length; i++) {
                        if (pkCols[i].column != indexColumns[i].column) {
                            throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
                        }
                    }
                }
                if (index == null) {
                    IndexType indexType = IndexType.createPrimaryKey(table.isPersistIndexes(), primaryKeyHash);
                    String indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY);
                    int id = getObjectId();
                    try {
                        index = table.addIndex(session, indexName, id, indexColumns, indexType, true, null);
                    } finally {
                        getSchema().freeUniqueName(indexName);
                    }
                }
                index.getIndexType().setBelongsToConstraint(true);
                int constraintId = getObjectId();
                String name = generateConstraintName(table);
                ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
                pk.setColumns(indexColumns);
                pk.setIndex(index, true);
                constraint = pk;
                break;
            }
        case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE:
            {
                IndexColumn.mapColumns(indexColumns, table);
                boolean isOwner = false;
                if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
                    isOwner = true;
                    index.getIndexType().setBelongsToConstraint(true);
                } else {
                    index = getUniqueIndex(table, indexColumns);
                    if (index == null) {
                        index = createIndex(table, indexColumns, true);
                        isOwner = true;
                    }
                }
                int id = getObjectId();
                String name = generateConstraintName(table);
                ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
                unique.setColumns(indexColumns);
                unique.setIndex(index, isOwner);
                constraint = unique;
                break;
            }
        case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK:
            {
                int id = getObjectId();
                String name = generateConstraintName(table);
                ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
                TableFilter filter = new TableFilter(session, table, null, false, null, 0, null);
                checkExpression.mapColumns(filter, 0);
                checkExpression = checkExpression.optimize(session);
                check.setExpression(checkExpression);
                check.setTableFilter(filter);
                constraint = check;
                if (checkExisting) {
                    check.checkExistingData(session);
                }
                break;
            }
        case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL:
            {
                Table refTable = refSchema.resolveTableOrView(session, refTableName);
                if (refTable == null) {
                    throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, refTableName);
                }
                session.getUser().checkRight(refTable, Right.ALL);
                if (!refTable.canReference()) {
                    throw DbException.getUnsupportedException("Reference " + refTable.getSQL());
                }
                boolean isOwner = false;
                IndexColumn.mapColumns(indexColumns, table);
                if (index != null && canUseIndex(index, table, indexColumns, false)) {
                    isOwner = true;
                    index.getIndexType().setBelongsToConstraint(true);
                } else {
                    index = getIndex(table, indexColumns, false);
                    if (index == null) {
                        index = createIndex(table, indexColumns, false);
                        isOwner = true;
                    }
                }
                if (refIndexColumns == null) {
                    Index refIdx = refTable.getPrimaryKey();
                    refIndexColumns = refIdx.getIndexColumns();
                } else {
                    IndexColumn.mapColumns(refIndexColumns, refTable);
                }
                if (refIndexColumns.length != indexColumns.length) {
                    throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
                }
                boolean isRefOwner = false;
                if (refIndex != null && refIndex.getTable() == refTable && canUseIndex(refIndex, refTable, refIndexColumns, false)) {
                    isRefOwner = true;
                    refIndex.getIndexType().setBelongsToConstraint(true);
                } else {
                    refIndex = null;
                }
                if (refIndex == null) {
                    refIndex = getIndex(refTable, refIndexColumns, false);
                    if (refIndex == null) {
                        refIndex = createIndex(refTable, refIndexColumns, true);
                        isRefOwner = true;
                    }
                }
                int id = getObjectId();
                String name = generateConstraintName(table);
                ConstraintReferential refConstraint = new ConstraintReferential(getSchema(), id, name, table);
                refConstraint.setColumns(indexColumns);
                refConstraint.setIndex(index, isOwner);
                refConstraint.setRefTable(refTable);
                refConstraint.setRefColumns(refIndexColumns);
                refConstraint.setRefIndex(refIndex, isRefOwner);
                if (checkExisting) {
                    refConstraint.checkExistingData(session);
                }
                refTable.addConstraint(refConstraint);
                refConstraint.setDeleteAction(deleteAction);
                refConstraint.setUpdateAction(updateAction);
                constraint = refConstraint;
                break;
            }
        default:
            throw DbException.throwInternalError("type=" + type);
    }
    // parent relationship is already set with addConstraint
    constraint.setComment(comment);
    if (table.isTemporary() && !table.isGlobalTemporary()) {
        session.addLocalTempTableConstraint(constraint);
    } else {
        db.addSchemaObject(session, constraint);
    }
    table.addConstraint(constraint);
    return 0;
}
Also used : Table(org.h2.table.Table) Constraint(org.h2.constraint.Constraint) TableFilter(org.h2.table.TableFilter) Database(org.h2.engine.Database) ArrayList(java.util.ArrayList) ConstraintUnique(org.h2.constraint.ConstraintUnique) Index(org.h2.index.Index) ConstraintCheck(org.h2.constraint.ConstraintCheck) IndexType(org.h2.index.IndexType) ConstraintReferential(org.h2.constraint.ConstraintReferential)

Example 4 with Constraint

use of org.h2.constraint.Constraint in project h2database by h2database.

the class Parser method parseTableColumnDefinition.

private void parseTableColumnDefinition(CommandWithColumns command, Schema schema, String tableName) {
    DefineCommand c = parseAlterTableAddConstraintIf(tableName, schema, false);
    if (c != null) {
        command.addConstraintCommand(c);
    } else {
        String columnName = readColumnIdentifier();
        Column column = parseColumnForTable(columnName, true);
        if (column.isAutoIncrement() && column.isPrimaryKey()) {
            column.setPrimaryKey(false);
            IndexColumn[] cols = { new IndexColumn() };
            cols[0].columnName = column.getName();
            AlterTableAddConstraint pk = new AlterTableAddConstraint(session, schema, false);
            pk.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
            pk.setTableName(tableName);
            pk.setIndexColumns(cols);
            command.addConstraintCommand(pk);
        }
        command.addColumn(column);
        String constraintName = null;
        if (readIf("CONSTRAINT")) {
            constraintName = readColumnIdentifier();
        }
        // For compatibility with Apache Ignite.
        boolean allowAffinityKey = database.getMode().allowAffinityKey;
        boolean affinity = allowAffinityKey && readIfAffinity();
        if (readIf("PRIMARY")) {
            read("KEY");
            boolean hash = readIf("HASH");
            IndexColumn[] cols = { new IndexColumn() };
            cols[0].columnName = column.getName();
            AlterTableAddConstraint pk = new AlterTableAddConstraint(session, schema, false);
            pk.setConstraintName(constraintName);
            pk.setPrimaryKeyHash(hash);
            pk.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
            pk.setTableName(tableName);
            pk.setIndexColumns(cols);
            command.addConstraintCommand(pk);
            if (readIf("AUTO_INCREMENT")) {
                parseAutoIncrement(column);
            }
            if (affinity) {
                CreateIndex idx = createAffinityIndex(schema, tableName, cols);
                command.addConstraintCommand(idx);
            }
        } else if (affinity) {
            read("KEY");
            IndexColumn[] cols = { new IndexColumn() };
            cols[0].columnName = column.getName();
            CreateIndex idx = createAffinityIndex(schema, tableName, cols);
            command.addConstraintCommand(idx);
        } else if (readIf("UNIQUE")) {
            AlterTableAddConstraint unique = new AlterTableAddConstraint(session, schema, false);
            unique.setConstraintName(constraintName);
            unique.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE);
            IndexColumn[] cols = { new IndexColumn() };
            cols[0].columnName = columnName;
            unique.setIndexColumns(cols);
            unique.setTableName(tableName);
            command.addConstraintCommand(unique);
        }
        if (NullConstraintType.NULL_IS_NOT_ALLOWED == parseNotNullConstraint()) {
            column.setNullable(false);
        }
        if (readIf("CHECK")) {
            Expression expr = readExpression();
            column.addCheckConstraint(session, expr);
        }
        if (readIf("REFERENCES")) {
            AlterTableAddConstraint ref = new AlterTableAddConstraint(session, schema, false);
            ref.setConstraintName(constraintName);
            ref.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL);
            IndexColumn[] cols = { new IndexColumn() };
            cols[0].columnName = columnName;
            ref.setIndexColumns(cols);
            ref.setTableName(tableName);
            parseReferences(ref, schema, tableName);
            command.addConstraintCommand(ref);
        }
    }
}
Also used : AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CreateIndex(org.h2.command.ddl.CreateIndex) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) ValueString(org.h2.value.ValueString) DefineCommand(org.h2.command.ddl.DefineCommand) IndexColumn(org.h2.table.IndexColumn)

Example 5 with Constraint

use of org.h2.constraint.Constraint in project h2database by h2database.

the class Parser method parseAlterTableAddConstraintIf.

private DefineCommand parseAlterTableAddConstraintIf(String tableName, Schema schema, boolean ifTableExists) {
    String constraintName = null, comment = null;
    boolean ifNotExists = false;
    boolean allowIndexDefinition = database.getMode().indexDefinitionInCreateTable;
    boolean allowAffinityKey = database.getMode().allowAffinityKey;
    if (readIf("CONSTRAINT")) {
        ifNotExists = readIfNotExists();
        constraintName = readIdentifierWithSchema(schema.getName());
        checkSchema(schema);
        comment = readCommentIf();
        allowIndexDefinition = true;
    }
    if (readIf("PRIMARY")) {
        read("KEY");
        AlterTableAddConstraint command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
        command.setComment(comment);
        command.setConstraintName(constraintName);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        if (readIf("HASH")) {
            command.setPrimaryKeyHash(true);
        }
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(getSchema().findIndex(session, indexName));
        }
        return command;
    } else if (allowIndexDefinition && (isToken("INDEX") || isToken("KEY"))) {
        // MySQL
        // need to read ahead, as it could be a column name
        int start = lastParseIndex;
        read();
        if (DataType.getTypeByName(currentToken, database.getMode()) != null) {
            // known data type
            parseIndex = start;
            read();
            return null;
        }
        CreateIndex command = new CreateIndex(session, schema);
        command.setComment(comment);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        if (!readIf("(")) {
            command.setIndexName(readUniqueIdentifier());
            read("(");
        }
        command.setIndexColumns(parseIndexColumnList());
        // MySQL compatibility
        if (readIf("USING")) {
            read("BTREE");
        }
        return command;
    } else if (allowAffinityKey && readIfAffinity()) {
        read("KEY");
        read("(");
        CreateIndex command = createAffinityIndex(schema, tableName, parseIndexColumnList());
        command.setIfTableExists(ifTableExists);
        return command;
    }
    AlterTableAddConstraint command;
    if (readIf("CHECK")) {
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK);
        command.setCheckExpression(readExpression());
    } else if (readIf("UNIQUE")) {
        readIf("KEY");
        readIf("INDEX");
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE);
        if (!readIf("(")) {
            constraintName = readUniqueIdentifier();
            read("(");
        }
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(getSchema().findIndex(session, indexName));
        }
        // MySQL compatibility
        if (readIf("USING")) {
            read("BTREE");
        }
    } else if (readIf("FOREIGN")) {
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL);
        read("KEY");
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(schema.findIndex(session, indexName));
        }
        read("REFERENCES");
        parseReferences(command, schema, tableName);
    } else {
        if (constraintName != null) {
            throw getSyntaxError();
        }
        return null;
    }
    if (readIf("NOCHECK")) {
        command.setCheckExisting(false);
    } else {
        readIf("CHECK");
        command.setCheckExisting(true);
    }
    command.setTableName(tableName);
    command.setIfTableExists(ifTableExists);
    command.setConstraintName(constraintName);
    command.setComment(comment);
    return command;
}
Also used : AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CreateIndex(org.h2.command.ddl.CreateIndex) ValueString(org.h2.value.ValueString)

Aggregations

Constraint (org.h2.constraint.Constraint)15 Index (org.h2.index.Index)10 ValueString (org.h2.value.ValueString)9 Table (org.h2.table.Table)8 Column (org.h2.table.Column)6 IndexColumn (org.h2.table.IndexColumn)6 Connection (java.sql.Connection)5 Statement (java.sql.Statement)5 Database (org.h2.engine.Database)5 StatementBuilder (org.h2.util.StatementBuilder)5 ResultSet (java.sql.ResultSet)4 ArrayList (java.util.ArrayList)4 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)4 DbObject (org.h2.engine.DbObject)4 Right (org.h2.engine.Right)4 Expression (org.h2.expression.Expression)4 ExpressionColumn (org.h2.expression.ExpressionColumn)4 Schema (org.h2.schema.Schema)4 Sequence (org.h2.schema.Sequence)4 PreparedStatement (java.sql.PreparedStatement)3