Search in sources :

Example 26 with Prepared

use of org.h2.test.db.Db.Prepared 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 27 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class ExecuteProcedure method update.

@Override
public int update() {
    setParameters();
    Prepared prepared = procedure.getPrepared();
    return prepared.update();
}
Also used : Prepared(org.h2.command.Prepared)

Example 28 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class ExecuteProcedure method query.

@Override
public ResultInterface query(int limit) {
    setParameters();
    Prepared prepared = procedure.getPrepared();
    return prepared.query(limit);
}
Also used : Prepared(org.h2.command.Prepared)

Example 29 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class Select method prepare.

@Override
public void prepare() {
    if (isPrepared) {
        // sometimes a subquery is prepared twice (CREATE TABLE AS SELECT)
        return;
    }
    if (SysProperties.CHECK && !checkInit) {
        DbException.throwInternalError("not initialized");
    }
    if (orderList != null) {
        sort = prepareOrder(orderList, expressions.size());
        orderList = null;
    }
    ColumnNamer columnNamer = new ColumnNamer(session);
    for (int i = 0; i < expressions.size(); i++) {
        Expression e = expressions.get(i);
        String proposedColumnName = e.getAlias();
        String columnName = columnNamer.getColumnName(e, i, proposedColumnName);
        // if the name changed, create an alias
        if (!columnName.equals(proposedColumnName)) {
            e = new Alias(e, columnName, true);
        }
        expressions.set(i, e.optimize(session));
    }
    if (condition != null) {
        condition = condition.optimize(session);
        for (TableFilter f : filters) {
            // left outer join child on p = pc where c is null;
            if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
                condition.createIndexConditions(session, f);
            }
        }
    }
    if (isGroupQuery && groupIndex == null && havingIndex < 0 && filters.size() == 1) {
        if (condition == null) {
            Table t = filters.get(0).getTable();
            ExpressionVisitor optimizable = ExpressionVisitor.getOptimizableVisitor(t);
            isQuickAggregateQuery = isEverything(optimizable);
        }
    }
    cost = preparePlan(session.isParsingCreateView());
    if (distinct && session.getDatabase().getSettings().optimizeDistinct && !isGroupQuery && filters.size() == 1 && expressions.size() == 1 && condition == null) {
        Expression expr = expressions.get(0);
        expr = expr.getNonAliasExpression();
        if (expr instanceof ExpressionColumn) {
            Column column = ((ExpressionColumn) expr).getColumn();
            int selectivity = column.getSelectivity();
            Index columnIndex = topTableFilter.getTable().getIndexForColumn(column, false, true);
            if (columnIndex != null && selectivity != Constants.SELECTIVITY_DEFAULT && selectivity < 20) {
                // the first column must be ascending
                boolean ascending = columnIndex.getIndexColumns()[0].sortType == SortOrder.ASCENDING;
                Index current = topTableFilter.getIndex();
                // if another index is faster
                if (columnIndex.canFindNext() && ascending && (current == null || current.getIndexType().isScan() || columnIndex == current)) {
                    IndexType type = columnIndex.getIndexType();
                    // indexes don't work
                    if (!type.isHash() && (!type.isUnique() || columnIndex.getColumns().length > 1)) {
                        topTableFilter.setIndex(columnIndex);
                        isDistinctQuery = true;
                    }
                }
            }
        }
    }
    if (sort != null && !isQuickAggregateQuery && !isGroupQuery) {
        Index index = getSortIndex();
        Index current = topTableFilter.getIndex();
        if (index != null && current != null) {
            if (current.getIndexType().isScan() || current == index) {
                topTableFilter.setIndex(index);
                if (!topTableFilter.hasInComparisons()) {
                    // in(select ...) and in(1,2,3) may return the key in
                    // another order
                    sortUsingIndex = true;
                }
            } else if (index.getIndexColumns() != null && index.getIndexColumns().length >= current.getIndexColumns().length) {
                IndexColumn[] sortColumns = index.getIndexColumns();
                IndexColumn[] currentColumns = current.getIndexColumns();
                boolean swapIndex = false;
                for (int i = 0; i < currentColumns.length; i++) {
                    if (sortColumns[i].column != currentColumns[i].column) {
                        swapIndex = false;
                        break;
                    }
                    if (sortColumns[i].sortType != currentColumns[i].sortType) {
                        swapIndex = true;
                    }
                }
                if (swapIndex) {
                    topTableFilter.setIndex(index);
                    sortUsingIndex = true;
                }
            }
        }
    }
    if (!isQuickAggregateQuery && isGroupQuery && getGroupByExpressionCount() > 0) {
        Index index = getGroupSortedIndex();
        Index current = topTableFilter.getIndex();
        if (index != null && current != null && (current.getIndexType().isScan() || current == index)) {
            topTableFilter.setIndex(index);
            isGroupSortedQuery = true;
        }
    }
    expressionArray = expressions.toArray(new Expression[0]);
    isPrepared = true;
}
Also used : Index(org.h2.index.Index) IndexType(org.h2.index.IndexType)

Example 30 with Prepared

use of org.h2.test.db.Db.Prepared in project h2database by h2database.

the class ConstraintReferential method checkRowRefTable.

private void checkRowRefTable(Session session, Row oldRow, Row newRow) {
    if (oldRow == null) {
        // this is an insert
        return;
    }
    if (newRow != null && isEqual(oldRow, newRow)) {
        // on an update, if both old and new are the same, don't do anything
        return;
    }
    if (newRow == null) {
        // this is a delete
        if (deleteAction == ConstraintActionType.RESTRICT) {
            checkRow(session, oldRow);
        } else {
            int i = deleteAction == ConstraintActionType.CASCADE ? 0 : columns.length;
            Prepared deleteCommand = getDelete(session);
            setWhere(deleteCommand, i, oldRow);
            updateWithSkipCheck(deleteCommand);
        }
    } else {
        // this is an update
        if (updateAction == ConstraintActionType.RESTRICT) {
            checkRow(session, oldRow);
        } else {
            Prepared updateCommand = getUpdate(session);
            if (updateAction == ConstraintActionType.CASCADE) {
                ArrayList<Parameter> params = updateCommand.getParameters();
                for (int i = 0, len = columns.length; i < len; i++) {
                    Parameter param = params.get(i);
                    Column refCol = refColumns[i].column;
                    param.setValue(newRow.getValue(refCol.getColumnId()));
                }
            }
            setWhere(updateCommand, columns.length, oldRow);
            updateWithSkipCheck(updateCommand);
        }
    }
}
Also used : Column(org.h2.table.Column) IndexColumn(org.h2.table.IndexColumn) Prepared(org.h2.command.Prepared) Parameter(org.h2.expression.Parameter)

Aggregations

Prepared (org.h2.command.Prepared)32 ValueString (org.h2.value.ValueString)16 SQLException (java.sql.SQLException)11 ArrayList (java.util.ArrayList)11 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)11 AlterTableRenameConstraint (org.h2.command.ddl.AlterTableRenameConstraint)11 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)10 Parameter (org.h2.expression.Parameter)10 DbException (org.h2.message.DbException)10 PreparedStatement (java.sql.PreparedStatement)9 Value (org.h2.value.Value)8 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)7 Query (org.h2.command.dml.Query)7 Expression (org.h2.expression.Expression)7 Column (org.h2.table.Column)7 Connection (java.sql.Connection)6 IndexColumn (org.h2.table.IndexColumn)6 ResultSet (java.sql.ResultSet)5 SQLClientInfoException (java.sql.SQLClientInfoException)5 Savepoint (java.sql.Savepoint)5