Search in sources :

Example 11 with Db

use of org.h2.jaqu.Db in project h2database by h2database.

the class AlterTableAlterColumn method checkViews.

/**
 * Check that all views and other dependent objects.
 */
private void checkViews(SchemaObject sourceTable, SchemaObject newTable) {
    String sourceTableName = sourceTable.getName();
    String newTableName = newTable.getName();
    Database db = sourceTable.getDatabase();
    // save the real table under a temporary name
    String temp = db.getTempTableName(sourceTableName, session);
    db.renameSchemaObject(session, sourceTable, temp);
    try {
        // have our new table impersonate the target table
        db.renameSchemaObject(session, newTable, sourceTableName);
        checkViewsAreValid(sourceTable);
    } finally {
        // always put the source tables back with their proper names
        try {
            db.renameSchemaObject(session, newTable, newTableName);
        } finally {
            db.renameSchemaObject(session, sourceTable, sourceTableName);
        }
    }
}
Also used : Database(org.h2.engine.Database)

Example 12 with Db

use of org.h2.jaqu.Db in project h2database by h2database.

the class AlterTableAlterColumn method update.

@Override
public int update() {
    session.commit(true);
    Database db = session.getDatabase();
    Table table = getSchema().resolveTableOrView(session, tableName);
    if (table == null) {
        if (ifTableExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
    }
    session.getUser().checkRight(table, Right.ALL);
    table.checkSupportAlter();
    table.lock(session, true, true);
    if (newColumn != null) {
        checkDefaultReferencesTable(table, newColumn.getDefaultExpression());
        checkClustering(newColumn);
    }
    if (columnsToAdd != null) {
        for (Column column : columnsToAdd) {
            checkDefaultReferencesTable(table, column.getDefaultExpression());
            checkClustering(column);
        }
    }
    switch(type) {
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL:
            {
                if (!oldColumn.isNullable()) {
                    // no change
                    break;
                }
                checkNoNullValues(table);
                oldColumn.setNullable(false);
                db.updateMeta(session, table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL:
            {
                if (oldColumn.isNullable()) {
                    // no change
                    break;
                }
                checkNullable(table);
                oldColumn.setNullable(true);
                db.updateMeta(session, table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT:
            {
                Sequence sequence = oldColumn == null ? null : oldColumn.getSequence();
                checkDefaultReferencesTable(table, defaultExpression);
                oldColumn.setSequence(null);
                oldColumn.setDefaultExpression(session, defaultExpression);
                removeSequence(table, sequence);
                db.updateMeta(session, table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE:
            {
                checkDefaultReferencesTable(table, defaultExpression);
                oldColumn.setOnUpdateExpression(session, defaultExpression);
                db.updateMeta(session, table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE:
            {
                // and does not affect the storage structure.
                if (oldColumn.isWideningConversion(newColumn)) {
                    convertAutoIncrementColumn(table, newColumn);
                    oldColumn.copy(newColumn);
                    db.updateMeta(session, table);
                } else {
                    oldColumn.setSequence(null);
                    oldColumn.setDefaultExpression(session, null);
                    oldColumn.setConvertNullToDefault(false);
                    if (oldColumn.isNullable() && !newColumn.isNullable()) {
                        checkNoNullValues(table);
                    } else if (!oldColumn.isNullable() && newColumn.isNullable()) {
                        checkNullable(table);
                    }
                    if (oldColumn.getVisible() ^ newColumn.getVisible()) {
                        oldColumn.setVisible(newColumn.getVisible());
                    }
                    convertAutoIncrementColumn(table, newColumn);
                    copyData(table);
                }
                table.setModified();
                break;
            }
        case CommandInterface.ALTER_TABLE_ADD_COLUMN:
            {
                // ifNotExists only supported for single column add
                if (ifNotExists && columnsToAdd != null && columnsToAdd.size() == 1 && table.doesColumnExist(columnsToAdd.get(0).getName())) {
                    break;
                }
                ArrayList<Sequence> sequences = generateSequences(columnsToAdd, false);
                if (columnsToAdd != null) {
                    changePrimaryKeysToNotNull(columnsToAdd);
                }
                copyData(table, sequences, true);
                break;
            }
        case CommandInterface.ALTER_TABLE_DROP_COLUMN:
            {
                if (table.getColumns().length - columnsToRemove.size() < 1) {
                    throw DbException.get(ErrorCode.CANNOT_DROP_LAST_COLUMN, columnsToRemove.get(0).getSQL());
                }
                table.dropMultipleColumnsConstraintsAndIndexes(session, columnsToRemove);
                copyData(table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_SELECTIVITY:
            {
                int value = newSelectivity.optimize(session).getValue(session).getInt();
                oldColumn.setSelectivity(value);
                db.updateMeta(session, table);
                break;
            }
        case CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY:
            {
                oldColumn.setVisible(newVisibility);
                table.setModified();
                db.updateMeta(session, table);
                break;
            }
        default:
            DbException.throwInternalError("type=" + type);
    }
    return 0;
}
Also used : Table(org.h2.table.Table) Column(org.h2.table.Column) Database(org.h2.engine.Database) ArrayList(java.util.ArrayList) Sequence(org.h2.schema.Sequence)

Example 13 with Db

use of org.h2.jaqu.Db 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 14 with Db

use of org.h2.jaqu.Db in project h2database by h2database.

the class Command method stop.

@Override
public void stop() {
    session.endStatement();
    session.setCurrentCommand(null, false);
    if (!isTransactional()) {
        session.commit(true);
    } else if (session.getAutoCommit()) {
        session.commit(false);
    } else if (session.getDatabase().isMultiThreaded()) {
        Database db = session.getDatabase();
        if (db != null) {
            if (db.getLockMode() == Constants.LOCK_MODE_READ_COMMITTED) {
                session.unlockReadLocks();
            }
        }
    }
    if (trace.isInfoEnabled() && startTimeNanos > 0) {
        long timeMillis = (System.nanoTime() - startTimeNanos) / 1000 / 1000;
        if (timeMillis > Constants.SLOW_QUERY_LIMIT_MS) {
            trace.info("slow query: {0} ms", timeMillis);
        }
    }
}
Also used : Database(org.h2.engine.Database)

Example 15 with Db

use of org.h2.jaqu.Db in project h2database by h2database.

the class AlterTableRenameColumn method update.

@Override
public int update() {
    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);
    }
    Column column = table.getColumn(oldName);
    session.getUser().checkRight(table, Right.ALL);
    table.checkSupportAlter();
    // we need to update CHECK constraint
    // since it might reference the name of the column
    Expression newCheckExpr = column.getCheckConstraint(session, newName);
    table.renameColumn(column, newName);
    column.removeCheckConstraint();
    column.addCheckConstraint(session, newCheckExpr);
    table.setModified();
    db.updateMeta(session, table);
    for (DbObject child : table.getChildren()) {
        if (child.getCreateSQL() != null) {
            db.updateMeta(session, child);
        }
    }
    return 0;
}
Also used : Table(org.h2.table.Table) Column(org.h2.table.Column) Expression(org.h2.expression.Expression) DbObject(org.h2.engine.DbObject) Database(org.h2.engine.Database)

Aggregations

Database (org.h2.engine.Database)70 Connection (java.sql.Connection)31 Statement (java.sql.Statement)20 Table (org.h2.table.Table)19 PreparedStatement (java.sql.PreparedStatement)18 ResultSet (java.sql.ResultSet)13 SQLException (java.sql.SQLException)13 Column (org.h2.table.Column)12 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)9 StatementBuilder (org.h2.util.StatementBuilder)9 DbObject (org.h2.engine.DbObject)8 File (java.io.File)7 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 DbException (org.h2.message.DbException)7 Schema (org.h2.schema.Schema)7 Before (org.junit.Before)7 InputStream (java.io.InputStream)6 ExpressionColumn (org.h2.expression.ExpressionColumn)6 JdbcConnection (org.h2.jdbc.JdbcConnection)6