Search in sources :

Example 6 with Comment

use of org.h2.engine.Comment 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 7 with Comment

use of org.h2.engine.Comment in project h2database by h2database.

the class CreateLinkedTable method update.

@Override
public int update() {
    session.commit(true);
    Database db = session.getDatabase();
    session.getUser().checkAdmin();
    if (getSchema().resolveTableOrView(session, tableName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, tableName);
    }
    int id = getObjectId();
    TableLink table = getSchema().createTableLink(id, tableName, driver, url, user, password, originalSchema, originalTable, emitUpdates, force);
    table.setTemporary(temporary);
    table.setGlobalTemporary(globalTemporary);
    table.setComment(comment);
    table.setReadOnly(readOnly);
    if (temporary && !globalTemporary) {
        session.addLocalTempTable(table);
    } else {
        db.addSchemaObject(session, table);
    }
    return 0;
}
Also used : Database(org.h2.engine.Database) TableLink(org.h2.table.TableLink)

Example 8 with Comment

use of org.h2.engine.Comment in project h2database by h2database.

the class ScriptCommand method query.

@Override
public ResultInterface query(int maxrows) {
    session.getUser().checkAdmin();
    reset();
    Database db = session.getDatabase();
    if (schemaNames != null) {
        for (String schemaName : schemaNames) {
            Schema schema = db.findSchema(schemaName);
            if (schema == null) {
                throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
            }
        }
    }
    try {
        result = createResult();
        deleteStore();
        openOutput();
        if (out != null) {
            buffer = new byte[Constants.IO_BUFFER_SIZE];
        }
        if (settings) {
            for (Setting setting : db.getAllSettings()) {
                if (setting.getName().equals(SetTypes.getTypeName(SetTypes.CREATE_BUILD))) {
                    // (it is only set when creating the database)
                    continue;
                }
                add(setting.getCreateSQL(), false);
            }
        }
        if (out != null) {
            add("", true);
        }
        for (User user : db.getAllUsers()) {
            add(user.getCreateSQL(passwords), false);
        }
        for (Role role : db.getAllRoles()) {
            add(role.getCreateSQL(true), false);
        }
        for (Schema schema : db.getAllSchemas()) {
            if (excludeSchema(schema)) {
                continue;
            }
            add(schema.getCreateSQL(), false);
        }
        for (UserDataType datatype : db.getAllUserDataTypes()) {
            if (drop) {
                add(datatype.getDropSQL(), false);
            }
            add(datatype.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.CONSTANT)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constant constant = (Constant) obj;
            add(constant.getCreateSQL(), false);
        }
        final ArrayList<Table> tables = db.getAllTablesAndViews(false);
        // sort by id, so that views are after tables and views on views
        // after the base views
        Collections.sort(tables, new Comparator<Table>() {

            @Override
            public int compare(Table t1, Table t2) {
                return t1.getId() - t2.getId();
            }
        });
        // Generate the DROP XXX  ... IF EXISTS
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String sql = table.getCreateSQL();
            if (sql == null) {
                // null for metadata tables
                continue;
            }
            if (drop) {
                add(table.getDropSQL(), false);
            }
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            if (drop) {
                add(obj.getDropSQL(), false);
            }
            add(obj.getCreateSQL(), false);
        }
        for (UserAggregate agg : db.getAllAggregates()) {
            if (drop) {
                add(agg.getDropSQL(), false);
            }
            add(agg.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.SEQUENCE)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Sequence sequence = (Sequence) obj;
            if (drop) {
                add(sequence.getDropSQL(), false);
            }
            add(sequence.getCreateSQL(), false);
        }
        // Generate CREATE TABLE and INSERT...VALUES
        int count = 0;
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String createTableSql = table.getCreateSQL();
            if (createTableSql == null) {
                // null for metadata tables
                continue;
            }
            final TableType tableType = table.getTableType();
            add(createTableSql, false);
            final ArrayList<Constraint> constraints = table.getConstraints();
            if (constraints != null) {
                for (Constraint constraint : constraints) {
                    if (Constraint.Type.PRIMARY_KEY == constraint.getConstraintType()) {
                        add(constraint.getCreateSQLWithoutIndexes(), false);
                    }
                }
            }
            if (TableType.TABLE == tableType) {
                if (table.canGetRowCount()) {
                    String rowcount = "-- " + table.getRowCountApproximation() + " +/- SELECT COUNT(*) FROM " + table.getSQL();
                    add(rowcount, false);
                }
                if (data) {
                    count = generateInsertValues(count, table);
                }
            }
            final ArrayList<Index> indexes = table.getIndexes();
            for (int j = 0; indexes != null && j < indexes.size(); j++) {
                Index index = indexes.get(j);
                if (!index.getIndexType().getBelongsToConstraint()) {
                    add(index.getCreateSQL(), false);
                }
            }
        }
        if (tempLobTableCreated) {
            add("DROP TABLE IF EXISTS SYSTEM_LOB_STREAM", true);
            add("CALL SYSTEM_COMBINE_BLOB(-1)", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
            tempLobTableCreated = false;
        }
        // Generate CREATE CONSTRAINT ...
        final ArrayList<SchemaObject> constraints = db.getAllSchemaObjects(DbObject.CONSTRAINT);
        Collections.sort(constraints, new Comparator<SchemaObject>() {

            @Override
            public int compare(SchemaObject c1, SchemaObject c2) {
                return ((Constraint) c1).compareTo((Constraint) c2);
            }
        });
        for (SchemaObject obj : constraints) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constraint constraint = (Constraint) obj;
            if (excludeTable(constraint.getTable())) {
                continue;
            }
            if (constraint.getTable().isHidden()) {
                continue;
            }
            if (Constraint.Type.PRIMARY_KEY != constraint.getConstraintType()) {
                add(constraint.getCreateSQLWithoutIndexes(), false);
            }
        }
        // Generate CREATE TRIGGER ...
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.TRIGGER)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            TriggerObject trigger = (TriggerObject) obj;
            if (excludeTable(trigger.getTable())) {
                continue;
            }
            add(trigger.getCreateSQL(), false);
        }
        // Generate GRANT ...
        for (Right right : db.getAllRights()) {
            DbObject object = right.getGrantedObject();
            if (object != null) {
                if (object instanceof Schema) {
                    if (excludeSchema((Schema) object)) {
                        continue;
                    }
                } else if (object instanceof Table) {
                    Table table = (Table) object;
                    if (excludeSchema(table.getSchema())) {
                        continue;
                    }
                    if (excludeTable(table)) {
                        continue;
                    }
                }
            }
            add(right.getCreateSQL(), false);
        }
        // Generate COMMENT ON ...
        for (Comment comment : db.getAllComments()) {
            add(comment.getCreateSQL(), false);
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        throw DbException.convertIOException(e, getFileName());
    } finally {
        closeIO();
    }
    result.done();
    LocalResult r = result;
    reset();
    return r;
}
Also used : SchemaObject(org.h2.schema.SchemaObject) User(org.h2.engine.User) Constraint(org.h2.constraint.Constraint) Constant(org.h2.schema.Constant) Schema(org.h2.schema.Schema) Right(org.h2.engine.Right) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) ValueString(org.h2.value.ValueString) LocalResult(org.h2.result.LocalResult) Database(org.h2.engine.Database) Comment(org.h2.engine.Comment) Table(org.h2.table.Table) TableType(org.h2.table.TableType) DbObject(org.h2.engine.DbObject) Setting(org.h2.engine.Setting) UserDataType(org.h2.engine.UserDataType) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) Constraint(org.h2.constraint.Constraint) Role(org.h2.engine.Role) UserAggregate(org.h2.engine.UserAggregate)

Example 9 with Comment

use of org.h2.engine.Comment in project h2database by h2database.

the class Database method removeSchemaObject.

/**
 * Remove an object from the system table.
 *
 * @param session the session
 * @param obj the object to be removed
 */
public void removeSchemaObject(Session session, SchemaObject obj) {
    int type = obj.getType();
    if (type == DbObject.TABLE_OR_VIEW) {
        Table table = (Table) obj;
        if (table.isTemporary() && !table.isGlobalTemporary()) {
            session.removeLocalTempTable(table);
            return;
        }
    } else if (type == DbObject.INDEX) {
        Index index = (Index) obj;
        Table table = index.getTable();
        if (table.isTemporary() && !table.isGlobalTemporary()) {
            session.removeLocalTempTableIndex(index);
            return;
        }
    } else if (type == DbObject.CONSTRAINT) {
        Constraint constraint = (Constraint) obj;
        Table table = constraint.getTable();
        if (table.isTemporary() && !table.isGlobalTemporary()) {
            session.removeLocalTempTableConstraint(constraint);
            return;
        }
    }
    checkWritingAllowed();
    lockMeta(session);
    synchronized (this) {
        Comment comment = findComment(obj);
        if (comment != null) {
            removeDatabaseObject(session, comment);
        }
        obj.getSchema().remove(obj);
        int id = obj.getId();
        if (!starting) {
            Table t = getDependentTable(obj, null);
            if (t != null) {
                obj.getSchema().add(obj);
                throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(), t.getSQL());
            }
            obj.removeChildrenAndResources(session);
        }
        removeMeta(session, id);
    }
}
Also used : MetaTable(org.h2.table.MetaTable) Table(org.h2.table.Table) Constraint(org.h2.constraint.Constraint) Index(org.h2.index.Index) Constraint(org.h2.constraint.Constraint)

Example 10 with Comment

use of org.h2.engine.Comment in project h2database by h2database.

the class SetComment method update.

@Override
public int update() {
    session.commit(true);
    Database db = session.getDatabase();
    session.getUser().checkAdmin();
    DbObject object = null;
    int errorCode = ErrorCode.GENERAL_ERROR_1;
    if (schemaName == null) {
        schemaName = session.getCurrentSchemaName();
    }
    switch(objectType) {
        case DbObject.CONSTANT:
            object = db.getSchema(schemaName).getConstant(objectName);
            break;
        case DbObject.CONSTRAINT:
            object = db.getSchema(schemaName).getConstraint(objectName);
            break;
        case DbObject.FUNCTION_ALIAS:
            object = db.getSchema(schemaName).findFunction(objectName);
            errorCode = ErrorCode.FUNCTION_ALIAS_NOT_FOUND_1;
            break;
        case DbObject.INDEX:
            object = db.getSchema(schemaName).getIndex(objectName);
            break;
        case DbObject.ROLE:
            schemaName = null;
            object = db.findRole(objectName);
            errorCode = ErrorCode.ROLE_NOT_FOUND_1;
            break;
        case DbObject.SCHEMA:
            schemaName = null;
            object = db.findSchema(objectName);
            errorCode = ErrorCode.SCHEMA_NOT_FOUND_1;
            break;
        case DbObject.SEQUENCE:
            object = db.getSchema(schemaName).getSequence(objectName);
            break;
        case DbObject.TABLE_OR_VIEW:
            object = db.getSchema(schemaName).getTableOrView(session, objectName);
            break;
        case DbObject.TRIGGER:
            object = db.getSchema(schemaName).findTrigger(objectName);
            errorCode = ErrorCode.TRIGGER_NOT_FOUND_1;
            break;
        case DbObject.USER:
            schemaName = null;
            object = db.getUser(objectName);
            break;
        case DbObject.USER_DATATYPE:
            schemaName = null;
            object = db.findUserDataType(objectName);
            errorCode = ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1;
            break;
        default:
    }
    if (object == null) {
        throw DbException.get(errorCode, objectName);
    }
    String text = expr.optimize(session).getValue(session).getString();
    if (column) {
        Table table = (Table) object;
        table.getColumn(columnName).setComment(text);
    } else {
        object.setComment(text);
    }
    if (column || objectType == DbObject.TABLE_OR_VIEW || objectType == DbObject.USER || objectType == DbObject.INDEX || objectType == DbObject.CONSTRAINT) {
        db.updateMeta(session, object);
    } else {
        Comment comment = db.findComment(object);
        if (comment == null) {
            if (text == null) {
            // reset a non-existing comment - nothing to do
            } else {
                int id = getObjectId();
                comment = new Comment(db, id, object);
                comment.setCommentText(text);
                db.addDatabaseObject(session, comment);
            }
        } else {
            if (text == null) {
                db.removeDatabaseObject(session, comment);
            } else {
                comment.setCommentText(text);
                db.updateMeta(session, comment);
            }
        }
    }
    return 0;
}
Also used : Comment(org.h2.engine.Comment) Table(org.h2.table.Table) DbObject(org.h2.engine.DbObject) Database(org.h2.engine.Database)

Aggregations

Database (org.h2.engine.Database)9 ValueString (org.h2.value.ValueString)8 Table (org.h2.table.Table)7 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)5 StatementBuilder (org.h2.util.StatementBuilder)5 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)4 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)4 Constraint (org.h2.constraint.Constraint)4 ExpressionColumn (org.h2.expression.ExpressionColumn)4 DbException (org.h2.message.DbException)4 Column (org.h2.table.Column)4 IndexColumn (org.h2.table.IndexColumn)4 PreparedStatement (java.sql.PreparedStatement)3 DbObject (org.h2.engine.DbObject)3 Expression (org.h2.expression.Expression)3 ValueExpression (org.h2.expression.ValueExpression)3 Index (org.h2.index.Index)3 Sequence (org.h2.schema.Sequence)3 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2