Search in sources :

Example 26 with Database

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

the class Command method filterConcurrentUpdate.

private long filterConcurrentUpdate(DbException e, long start) {
    int errorCode = e.getErrorCode();
    if (errorCode != ErrorCode.CONCURRENT_UPDATE_1 && errorCode != ErrorCode.ROW_NOT_FOUND_IN_PRIMARY_INDEX && errorCode != ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1) {
        throw e;
    }
    long now = System.nanoTime() / 1_000_000;
    if (start != 0 && now - start > session.getLockTimeout()) {
        throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, e.getCause(), "");
    }
    Database database = session.getDatabase();
    int sleep = 1 + MathUtils.randomInt(10);
    while (true) {
        try {
            if (database.isMultiThreaded()) {
                Thread.sleep(sleep);
            } else {
                database.wait(sleep);
            }
        } catch (InterruptedException e1) {
        // ignore
        }
        long slept = System.nanoTime() / 1_000_000 - now;
        if (slept >= sleep) {
            break;
        }
    }
    return start == 0 ? now : start;
}
Also used : Database(org.h2.engine.Database)

Example 27 with Database

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

the class Command method executeUpdate.

@Override
public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
    long start = 0;
    Database database = session.getDatabase();
    Object sync = database.isMultiThreaded() ? (Object) session : (Object) database;
    session.waitIfExclusiveModeEnabled();
    boolean callStop = true;
    boolean writing = !isReadOnly();
    if (writing) {
        while (!database.beforeWriting()) {
        // wait
        }
    }
    synchronized (sync) {
        Session.Savepoint rollback = session.setSavepoint();
        session.setCurrentCommand(this, generatedKeysRequest);
        try {
            while (true) {
                database.checkPowerOff();
                try {
                    int updateCount = update();
                    if (!Boolean.FALSE.equals(generatedKeysRequest)) {
                        return new ResultWithGeneratedKeys.WithKeys(updateCount, session.getGeneratedKeys().getKeys(session));
                    }
                    return ResultWithGeneratedKeys.of(updateCount);
                } catch (DbException e) {
                    start = filterConcurrentUpdate(e, start);
                } catch (OutOfMemoryError e) {
                    callStop = false;
                    database.shutdownImmediately();
                    throw DbException.convert(e);
                } catch (Throwable e) {
                    throw DbException.convert(e);
                }
            }
        } catch (DbException e) {
            e = e.addSQL(sql);
            SQLException s = e.getSQLException();
            database.exceptionThrown(s, sql);
            if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
                callStop = false;
                database.shutdownImmediately();
                throw e;
            }
            database.checkPowerOff();
            if (s.getErrorCode() == ErrorCode.DEADLOCK_1) {
                session.rollback();
            } else {
                session.rollbackTo(rollback, false);
            }
            throw e;
        } finally {
            try {
                if (callStop) {
                    stop();
                }
            } finally {
                if (writing) {
                    database.afterWriting();
                }
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) Database(org.h2.engine.Database) Session(org.h2.engine.Session) DbException(org.h2.message.DbException)

Example 28 with Database

use of org.h2.engine.Database 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)

Example 29 with Database

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

the class Analyze method analyzeTable.

/**
 * Analyze this table.
 *
 * @param session the session
 * @param table the table
 * @param sample the number of sample rows
 * @param manual whether the command was called by the user
 */
public static void analyzeTable(Session session, Table table, int sample, boolean manual) {
    if (table.getTableType() != TableType.TABLE || table.isHidden() || session == null) {
        return;
    }
    if (!manual) {
        if (session.getDatabase().isSysTableLocked()) {
            return;
        }
        if (table.hasSelectTrigger()) {
            return;
        }
    }
    if (table.isTemporary() && !table.isGlobalTemporary() && session.findLocalTempTable(table.getName()) == null) {
        return;
    }
    if (table.isLockedExclusively() && !table.isLockedExclusivelyBy(session)) {
        return;
    }
    if (!session.getUser().hasRight(table, Right.SELECT)) {
        return;
    }
    if (session.getCancel() != 0) {
        // if the connection is closed and there is something to undo
        return;
    }
    Column[] columns = table.getColumns();
    if (columns.length == 0) {
        return;
    }
    Database db = session.getDatabase();
    StatementBuilder buff = new StatementBuilder("SELECT ");
    for (Column col : columns) {
        buff.appendExceptFirst(", ");
        int type = col.getType();
        if (type == Value.BLOB || type == Value.CLOB) {
            // can not index LOB columns, so calculating
            // the selectivity is not required
            buff.append("MAX(NULL)");
        } else {
            buff.append("SELECTIVITY(").append(col.getSQL()).append(')');
        }
    }
    buff.append(" FROM ").append(table.getSQL());
    if (sample > 0) {
        buff.append(" LIMIT ? SAMPLE_SIZE ? ");
    }
    String sql = buff.toString();
    Prepared command = session.prepare(sql);
    if (sample > 0) {
        ArrayList<Parameter> params = command.getParameters();
        params.get(0).setValue(ValueInt.get(1));
        params.get(1).setValue(ValueInt.get(sample));
    }
    ResultInterface result = command.query(0);
    result.next();
    for (int j = 0; j < columns.length; j++) {
        Value v = result.currentRow()[j];
        if (v != ValueNull.INSTANCE) {
            int selectivity = v.getInt();
            columns[j].setSelectivity(selectivity);
        }
    }
    db.updateMeta(session, table);
}
Also used : ResultInterface(org.h2.result.ResultInterface) Column(org.h2.table.Column) StatementBuilder(org.h2.util.StatementBuilder) Database(org.h2.engine.Database) Prepared(org.h2.command.Prepared) Value(org.h2.value.Value) Parameter(org.h2.expression.Parameter)

Example 30 with Database

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

the class CreateFunctionAlias method update.

@Override
public int update() {
    session.commit(true);
    session.getUser().checkAdmin();
    Database db = session.getDatabase();
    if (getSchema().findFunction(aliasName) != null) {
        if (!ifNotExists) {
            throw DbException.get(ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1, aliasName);
        }
    } else {
        int id = getObjectId();
        FunctionAlias functionAlias;
        if (javaClassMethod != null) {
            functionAlias = FunctionAlias.newInstance(getSchema(), id, aliasName, javaClassMethod, force, bufferResultSetToLocalTemp);
        } else {
            functionAlias = FunctionAlias.newInstanceFromSource(getSchema(), id, aliasName, source, force, bufferResultSetToLocalTemp);
        }
        functionAlias.setDeterministic(deterministic);
        db.addSchemaObject(session, functionAlias);
    }
    return 0;
}
Also used : FunctionAlias(org.h2.engine.FunctionAlias) Database(org.h2.engine.Database)

Aggregations

Database (org.h2.engine.Database)79 SQLException (java.sql.SQLException)45 PreparedStatement (java.sql.PreparedStatement)38 DbException (org.h2.message.DbException)37 ResultSet (java.sql.ResultSet)34 Statement (java.sql.Statement)32 SimpleResultSet (org.h2.tools.SimpleResultSet)32 Connection (java.sql.Connection)27 Table (org.h2.table.Table)25 Value (org.h2.value.Value)25 Column (org.h2.table.Column)22 IOException (java.io.IOException)19 Constraint (org.h2.constraint.Constraint)18 Expression (org.h2.expression.Expression)17 ExpressionColumn (org.h2.expression.ExpressionColumn)17 ValueString (org.h2.value.ValueString)15 ValueExpression (org.h2.expression.ValueExpression)14 Session (org.h2.engine.Session)13 JdbcConnection (org.h2.jdbc.JdbcConnection)13 Schema (org.h2.schema.Schema)13