Search in sources :

Example 1 with Index

use of org.gridgain.internal.h2.index.Index in project SpringStudy by myounghaklee.

the class Insert method handleOnDuplicate.

/**
 * @param de duplicate key exception
 * @param currentRow current row values (optional)
 * @return {@code true} if row was updated, {@code false} if row was ignored
 */
private boolean handleOnDuplicate(DbException de, Value[] currentRow) {
    if (de.getErrorCode() != ErrorCode.DUPLICATE_KEY_1) {
        throw de;
    }
    if (duplicateKeyAssignmentMap == null) {
        if (ignore) {
            return false;
        }
        throw de;
    }
    int columnCount = columns.length;
    Expression[] row = (currentRow == null) ? valuesExpressionList.get((int) getCurrentRowNumber() - 1) : new Expression[columnCount];
    onDuplicateKeyRow = new Value[table.getColumns().length];
    for (int i = 0; i < columnCount; i++) {
        Value value;
        if (currentRow != null) {
            value = currentRow[i];
            row[i] = ValueExpression.get(value);
        } else {
            value = row[i].getValue(session);
        }
        onDuplicateKeyRow[columns[i].getColumnId()] = value;
    }
    StringBuilder builder = new StringBuilder("UPDATE ");
    table.getSQL(builder, HasSQL.DEFAULT_SQL_FLAGS).append(" SET ");
    boolean f = false;
    for (Entry<Column, Expression> entry : duplicateKeyAssignmentMap.entrySet()) {
        if (f) {
            builder.append(", ");
        }
        f = true;
        entry.getKey().getSQL(builder, HasSQL.DEFAULT_SQL_FLAGS).append('=');
        entry.getValue().getUnenclosedSQL(builder, HasSQL.DEFAULT_SQL_FLAGS);
    }
    builder.append(" WHERE ");
    Index foundIndex = (Index) de.getSource();
    if (foundIndex == null) {
        throw DbException.getUnsupportedException("Unable to apply ON DUPLICATE KEY UPDATE, no index found!");
    }
    prepareUpdateCondition(foundIndex, row).getUnenclosedSQL(builder, HasSQL.DEFAULT_SQL_FLAGS);
    String sql = builder.toString();
    Update command = (Update) session.prepare(sql);
    command.setOnDuplicateKeyInsert(this);
    for (Parameter param : command.getParameters()) {
        Parameter insertParam = parameters.get(param.getIndex());
        param.setValue(insertParam.getValue(session));
    }
    boolean result = command.update() > 0;
    onDuplicateKeyRow = null;
    return result;
}
Also used : ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) Value(org.h2.value.Value) Parameter(org.h2.expression.Parameter) MVPrimaryIndex(org.h2.mvstore.db.MVPrimaryIndex) Index(org.h2.index.Index)

Example 2 with Index

use of org.gridgain.internal.h2.index.Index in project SpringStudy by myounghaklee.

the class Merge method merge.

/**
 * Updates an existing row or inserts a new one.
 *
 * @param row row to replace
 * @param expressions source expressions, or null
 * @param deltaChangeCollector target result
 * @param deltaChangeCollectionMode collection mode
 * @return 1 if row was inserted, 1 if row was updated by a MERGE statement,
 *         and 2 if row was updated by a REPLACE statement
 */
private int merge(Row row, Expression[] expressions, ResultTarget deltaChangeCollector, ResultOption deltaChangeCollectionMode) {
    long count;
    if (update == null) {
        // if there is no valid primary key,
        // the REPLACE statement degenerates to an INSERT
        count = 0;
    } else {
        ArrayList<Parameter> k = update.getParameters();
        int j = 0;
        for (int i = 0, l = columns.length; i < l; i++) {
            Column col = columns[i];
            if (col.isGeneratedAlways()) {
                if (expressions == null || expressions[i] != ValueExpression.DEFAULT) {
                    throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_ASSIGNED_1, col.getSQLWithTable(new StringBuilder(), HasSQL.TRACE_SQL_FLAGS).toString());
                }
            } else {
                Value v = row.getValue(col.getColumnId());
                if (v == null) {
                    Expression defaultExpression = col.getEffectiveDefaultExpression();
                    v = defaultExpression != null ? defaultExpression.getValue(session) : ValueNull.INSTANCE;
                }
                k.get(j++).setValue(v);
            }
        }
        for (Column col : keys) {
            Value v = row.getValue(col.getColumnId());
            if (v == null) {
                throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getTraceSQL());
            }
            k.get(j++).setValue(v);
        }
        count = update.update(deltaChangeCollector, deltaChangeCollectionMode);
    }
    // if update fails try an insert
    if (count == 0) {
        try {
            table.convertInsertRow(session, row, null);
            if (deltaChangeCollectionMode == ResultOption.NEW) {
                deltaChangeCollector.addRow(row.getValueList().clone());
            }
            if (!table.fireBeforeRow(session, null, row)) {
                table.lock(session, Table.WRITE_LOCK);
                table.addRow(session, row);
                DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector, deltaChangeCollectionMode, row);
                table.fireAfterRow(session, null, row, false);
            } else {
                DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector, deltaChangeCollectionMode, row);
            }
            return 1;
        } catch (DbException e) {
            if (e.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
                // possibly a concurrent merge or insert
                Index index = (Index) e.getSource();
                if (index != null) {
                    // verify the index columns match the key
                    Column[] indexColumns;
                    if (index instanceof MVPrimaryIndex) {
                        MVPrimaryIndex foundMV = (MVPrimaryIndex) index;
                        indexColumns = new Column[] { foundMV.getIndexColumns()[foundMV.getMainIndexColumn()].column };
                    } else {
                        indexColumns = index.getColumns();
                    }
                    boolean indexMatchesKeys;
                    if (indexColumns.length <= keys.length) {
                        indexMatchesKeys = true;
                        for (int i = 0; i < indexColumns.length; i++) {
                            if (indexColumns[i] != keys[i]) {
                                indexMatchesKeys = false;
                                break;
                            }
                        }
                    } else {
                        indexMatchesKeys = false;
                    }
                    if (indexMatchesKeys) {
                        throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, table.getName());
                    }
                }
            }
            throw e;
        }
    } else if (count == 1) {
        return isReplace ? 2 : 1;
    }
    throw DbException.get(ErrorCode.DUPLICATE_KEY_1, table.getTraceSQL());
}
Also used : Column(org.h2.table.Column) ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) Value(org.h2.value.Value) Parameter(org.h2.expression.Parameter) MVPrimaryIndex(org.h2.mvstore.db.MVPrimaryIndex) Index(org.h2.index.Index) MVPrimaryIndex(org.h2.mvstore.db.MVPrimaryIndex) DbException(org.h2.message.DbException)

Example 3 with Index

use of org.gridgain.internal.h2.index.Index in project SpringStudy by myounghaklee.

the class ScriptCommand method query.

@Override
public ResultInterface query(long 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 (version) {
            add("-- H2 " + Constants.VERSION, true);
        }
        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);
        }
        RightOwner[] rightOwners = db.getAllUsersAndRoles().toArray(new RightOwner[0]);
        // ADMIN users first, other users next, roles last
        Arrays.sort(rightOwners, (o1, o2) -> {
            boolean b = o1 instanceof User;
            if (b != o2 instanceof User) {
                return b ? -1 : 1;
            }
            if (b) {
                b = ((User) o1).isAdmin();
                if (b != ((User) o2).isAdmin()) {
                    return b ? -1 : 1;
                }
            }
            return o1.getName().compareTo(o2.getName());
        });
        for (RightOwner rightOwner : rightOwners) {
            if (rightOwner instanceof User) {
                add(((User) rightOwner).getCreateSQL(passwords), false);
            } else {
                add(((Role) rightOwner).getCreateSQL(true), false);
            }
        }
        ArrayList<Schema> schemas = new ArrayList<>();
        for (Schema schema : db.getAllSchemas()) {
            if (excludeSchema(schema)) {
                continue;
            }
            schemas.add(schema);
            add(schema.getCreateSQL(), false);
        }
        dumpDomains(schemas);
        for (Schema schema : schemas) {
            for (Constant constant : sorted(schema.getAllConstants(), Constant.class)) {
                add(constant.getCreateSQL(), false);
            }
        }
        final ArrayList<Table> tables = db.getAllTablesAndViews();
        // sort by id, so that views are after tables and views on views
        // after the base views
        tables.sort(Comparator.comparingInt(Table::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, Table.READ_LOCK);
            String sql = table.getCreateSQL();
            if (sql == null) {
                // null for metadata tables
                continue;
            }
            if (drop) {
                add(table.getDropSQL(), false);
            }
        }
        for (Schema schema : schemas) {
            for (UserDefinedFunction userDefinedFunction : sorted(schema.getAllFunctionsAndAggregates(), UserDefinedFunction.class)) {
                if (drop) {
                    add(userDefinedFunction.getDropSQL(), false);
                }
                add(userDefinedFunction.getCreateSQL(), false);
            }
        }
        for (Schema schema : schemas) {
            for (Sequence sequence : sorted(schema.getAllSequences(), Sequence.class)) {
                if (sequence.getBelongsToTable()) {
                    continue;
                }
                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, Table.READ_LOCK);
            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(session)) {
                    StringBuilder builder = new StringBuilder("-- ").append(table.getRowCountApproximation(session)).append(" +/- SELECT COUNT(*) FROM ");
                    table.getSQL(builder, HasSQL.TRACE_SQL_FLAGS);
                    add(builder.toString(), 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("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
            tempLobTableCreated = false;
        }
        // Generate CREATE CONSTRAINT ...
        ArrayList<Constraint> constraints = new ArrayList<>();
        for (Schema schema : schemas) {
            for (Constraint constraint : schema.getAllConstraints()) {
                if (excludeTable(constraint.getTable())) {
                    continue;
                }
                Type constraintType = constraint.getConstraintType();
                if (constraintType != Type.DOMAIN && constraint.getTable().isHidden()) {
                    continue;
                }
                if (constraintType != Constraint.Type.PRIMARY_KEY) {
                    constraints.add(constraint);
                }
            }
        }
        constraints.sort(null);
        for (Constraint constraint : constraints) {
            add(constraint.getCreateSQLWithoutIndexes(), false);
        }
        // Generate CREATE TRIGGER ...
        for (Schema schema : schemas) {
            for (TriggerObject trigger : schema.getAllTriggers()) {
                if (excludeTable(trigger.getTable())) {
                    continue;
                }
                add(trigger.getCreateSQL(), false);
            }
        }
        // Generate GRANT ...
        dumpRights(db);
        // 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 : User(org.h2.engine.User) UserDefinedFunction(org.h2.schema.UserDefinedFunction) Constraint(org.h2.constraint.Constraint) Constant(org.h2.schema.Constant) Schema(org.h2.schema.Schema) ArrayList(java.util.ArrayList) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) 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) Setting(org.h2.engine.Setting) RightOwner(org.h2.engine.RightOwner) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) Constraint(org.h2.constraint.Constraint) Type(org.h2.constraint.Constraint.Type) TableType(org.h2.table.TableType)

Example 4 with Index

use of org.gridgain.internal.h2.index.Index in project SpringStudy by myounghaklee.

the class Select method prepare.

@Override
public void prepare() {
    if (isPrepared) {
        // sometimes a subquery is prepared twice (CREATE TABLE AS SELECT)
        return;
    }
    if (!checkInit) {
        throw DbException.getInternalError("not initialized");
    }
    if (orderList != null) {
        prepareOrder(orderList, expressions.size());
    }
    ExpressionNames expressionNames = session.getMode().expressionNames;
    if (expressionNames == ExpressionNames.ORIGINAL_SQL || expressionNames == ExpressionNames.POSTGRESQL_STYLE) {
        optimizeExpressionsAndPreserveAliases();
    } else {
        for (int i = 0; i < expressions.size(); i++) {
            expressions.set(i, expressions.get(i).optimize(session));
        }
    }
    if (sort != null) {
        cleanupOrder();
    }
    if (condition != null) {
        condition = condition.optimizeCondition(session);
        if (condition != null) {
            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 && qualifyIndex < 0 && condition == null && filters.size() == 1) {
        isQuickAggregateQuery = isEverything(ExpressionVisitor.getOptimizableVisitor(filters.get(0).getTable()));
    }
    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) {
                Index current = topTableFilter.getIndex();
                // if another index is faster
                if (current == null || current.getIndexType().isScan() || columnIndex == current) {
                    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 (sortUsingIndex && isForUpdate && !topTableFilter.getIndex().isRowIdIndex()) {
            sortUsingIndex = false;
        }
    }
    if (!isQuickAggregateQuery && isGroupQuery) {
        Index index = getGroupSortedIndex();
        if (index != null) {
            Index current = topTableFilter.getIndex();
            if (current != null && (current.getIndexType().isScan() || current == index)) {
                topTableFilter.setIndex(index);
                isGroupSortedQuery = true;
            }
        }
    }
    expressionArray = expressions.toArray(new Expression[0]);
    isPrepared = true;
}
Also used : TableFilter(org.h2.table.TableFilter) Expression(org.h2.expression.Expression) IndexColumn(org.h2.table.IndexColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) Index(org.h2.index.Index) ViewIndex(org.h2.index.ViewIndex) ExpressionNames(org.h2.engine.Mode.ExpressionNames) ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 5 with Index

use of org.gridgain.internal.h2.index.Index in project SpringStudy by myounghaklee.

the class DropIndex method update.

@Override
public long update() {
    Database db = session.getDatabase();
    Index index = getSchema().findIndex(session, indexName);
    if (index == null) {
        if (!ifExists) {
            throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName);
        }
    } else {
        Table table = index.getTable();
        session.getUser().checkTableRight(index.getTable(), Right.SCHEMA_OWNER);
        Constraint pkConstraint = null;
        ArrayList<Constraint> constraints = table.getConstraints();
        for (int i = 0; constraints != null && i < constraints.size(); i++) {
            Constraint cons = constraints.get(i);
            if (cons.usesIndex(index)) {
                // can drop primary key index (for compatibility)
                if (Constraint.Type.PRIMARY_KEY == cons.getConstraintType()) {
                    for (Constraint c : constraints) {
                        if (c.getReferencedConstraint() == cons) {
                            throw DbException.get(ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, indexName, cons.getName());
                        }
                    }
                    pkConstraint = cons;
                } else {
                    throw DbException.get(ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, indexName, cons.getName());
                }
            }
        }
        index.getTable().setModified();
        if (pkConstraint != null) {
            db.removeSchemaObject(session, pkConstraint);
        } else {
            db.removeSchemaObject(session, index);
        }
    }
    return 0;
}
Also used : Table(org.h2.table.Table) Constraint(org.h2.constraint.Constraint) Database(org.h2.engine.Database) Index(org.h2.index.Index) Constraint(org.h2.constraint.Constraint)

Aggregations

Index (org.h2.index.Index)162 ArrayList (java.util.ArrayList)76 Index (org.gridgain.internal.h2.index.Index)71 SQLException (java.sql.SQLException)62 Value (org.gridgain.internal.h2.value.Value)62 ResultSet (java.sql.ResultSet)61 DbException (org.gridgain.internal.h2.message.DbException)59 Statement (java.sql.Statement)53 Column (org.gridgain.internal.h2.table.Column)53 Constraint (org.h2.constraint.Constraint)50 Column (org.h2.table.Column)49 Connection (java.sql.Connection)48 PreparedStatement (java.sql.PreparedStatement)47 IndexColumn (org.gridgain.internal.h2.table.IndexColumn)45 SimpleResultSet (org.gridgain.internal.h2.tools.SimpleResultSet)39 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)32 Table (org.h2.table.Table)32 H2TreeIndex (org.apache.ignite.internal.processors.query.h2.database.H2TreeIndex)27 Expression (org.gridgain.internal.h2.expression.Expression)27 ValueString (org.gridgain.internal.h2.value.ValueString)27