Search in sources :

Example 1 with CreateIndex

use of org.h2.command.ddl.CreateIndex in project h2database by h2database.

the class Parser method parseCreate.

private Prepared parseCreate() {
    boolean orReplace = false;
    if (readIf("OR")) {
        read("REPLACE");
        orReplace = true;
    }
    boolean force = readIf("FORCE");
    if (readIf("VIEW")) {
        return parseCreateView(force, orReplace);
    } else if (readIf("ALIAS")) {
        return parseCreateFunctionAlias(force);
    } else if (readIf("SEQUENCE")) {
        return parseCreateSequence();
    } else if (readIf("USER")) {
        return parseCreateUser();
    } else if (readIf("TRIGGER")) {
        return parseCreateTrigger(force);
    } else if (readIf("ROLE")) {
        return parseCreateRole();
    } else if (readIf("SCHEMA")) {
        return parseCreateSchema();
    } else if (readIf("CONSTANT")) {
        return parseCreateConstant();
    } else if (readIf("DOMAIN")) {
        return parseCreateUserDataType();
    } else if (readIf("TYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("DATATYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("AGGREGATE")) {
        return parseCreateAggregate(force);
    } else if (readIf("LINKED")) {
        return parseCreateLinkedTable(false, false, force);
    }
    // tables or linked tables
    boolean memory = false, cached = false;
    if (readIf("MEMORY")) {
        memory = true;
    } else if (readIf("CACHED")) {
        cached = true;
    }
    if (readIf("LOCAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, false, force);
        }
        read("TABLE");
        return parseCreateTable(true, false, cached);
    } else if (readIf("GLOBAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TEMP") || readIf("TEMPORARY")) {
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TABLE")) {
        if (!cached && !memory) {
            cached = database.getDefaultTableType() == Table.TYPE_CACHED;
        }
        return parseCreateTable(false, false, cached);
    } else if (readIf("SYNONYM")) {
        return parseCreateSynonym(orReplace);
    } else {
        boolean hash = false, primaryKey = false;
        boolean unique = false, spatial = false;
        String indexName = null;
        Schema oldSchema = null;
        boolean ifNotExists = false;
        if (readIf("PRIMARY")) {
            read("KEY");
            if (readIf("HASH")) {
                hash = true;
            }
            primaryKey = true;
            if (!isToken("ON")) {
                ifNotExists = readIfNotExists();
                indexName = readIdentifierWithSchema(null);
                oldSchema = getSchema();
            }
        } else {
            if (readIf("UNIQUE")) {
                unique = true;
            }
            if (readIf("HASH")) {
                hash = true;
            }
            if (readIf("SPATIAL")) {
                spatial = true;
            }
            if (readIf("INDEX")) {
                if (!isToken("ON")) {
                    ifNotExists = readIfNotExists();
                    indexName = readIdentifierWithSchema(null);
                    oldSchema = getSchema();
                }
            } else {
                throw getSyntaxError();
            }
        }
        read("ON");
        String tableName = readIdentifierWithSchema();
        checkSchema(oldSchema);
        CreateIndex command = new CreateIndex(session, getSchema());
        command.setIfNotExists(ifNotExists);
        command.setPrimaryKey(primaryKey);
        command.setTableName(tableName);
        command.setUnique(unique);
        command.setIndexName(indexName);
        command.setComment(readCommentIf());
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("USING")) {
            if (hash) {
                throw getSyntaxError();
            }
            if (spatial) {
                throw getSyntaxError();
            }
            if (readIf("BTREE")) {
            // default
            } else if (readIf("RTREE")) {
                spatial = true;
            } else if (readIf("HASH")) {
                hash = true;
            } else {
                throw getSyntaxError();
            }
        }
        command.setHash(hash);
        command.setSpatial(spatial);
        return command;
    }
}
Also used : CreateIndex(org.h2.command.ddl.CreateIndex) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) ValueString(org.h2.value.ValueString)

Example 2 with CreateIndex

use of org.h2.command.ddl.CreateIndex 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 3 with CreateIndex

use of org.h2.command.ddl.CreateIndex 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 4 with CreateIndex

use of org.h2.command.ddl.CreateIndex 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)

Example 5 with CreateIndex

use of org.h2.command.ddl.CreateIndex in project h2database by h2database.

the class Parser method createAffinityIndex.

private CreateIndex createAffinityIndex(Schema schema, String tableName, IndexColumn[] indexColumns) {
    CreateIndex idx = new CreateIndex(session, schema);
    idx.setTableName(tableName);
    idx.setIndexColumns(indexColumns);
    idx.setAffinity(true);
    return idx;
}
Also used : CreateIndex(org.h2.command.ddl.CreateIndex)

Aggregations

CreateIndex (org.h2.command.ddl.CreateIndex)4 ResultSet (java.sql.ResultSet)3 Statement (java.sql.Statement)3 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)3 IndexType (org.h2.index.IndexType)3 IndexColumn (org.h2.table.IndexColumn)3 SimpleResultSet (org.h2.tools.SimpleResultSet)3 ValueString (org.h2.value.ValueString)3 PreparedStatement (java.sql.PreparedStatement)2 Constraint (org.h2.constraint.Constraint)2 Database (org.h2.engine.Database)2 Index (org.h2.index.Index)2 Schema (org.h2.schema.Schema)2 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 QueryIndex (org.apache.ignite.cache.QueryIndex)1 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)1 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)1