Search in sources :

Example 1 with Set

use of org.h2.command.dml.Set in project ignite by apache.

the class GridH2TableSelfTest method checkIndexesConsistent.

/**
     * @param idxs Indexes.
     * @param rowSet Rows.
     * @return Rows.
     */
private Set<Row> checkIndexesConsistent(ArrayList<Index> idxs, @Nullable Set<Row> rowSet) throws IgniteCheckedException {
    for (Index idx : idxs) {
        if (!(idx instanceof GridH2TreeIndex))
            continue;
        Set<Row> set = new HashSet<>();
        GridCursor<GridH2Row> cursor = ((GridH2TreeIndex) idx).rows();
        while (cursor.next()) assertTrue(set.add(cursor.get()));
        if (rowSet == null || rowSet.isEmpty())
            rowSet = set;
        else
            assertEquals(rowSet, set);
    }
    return rowSet;
}
Also used : Index(org.h2.index.Index) H2PkHashIndex(org.apache.ignite.internal.processors.query.h2.database.H2PkHashIndex) Row(org.h2.result.Row) SearchRow(org.h2.result.SearchRow) HashSet(java.util.HashSet)

Example 2 with Set

use of org.h2.command.dml.Set in project ignite by apache.

the class GridMapQueryExecutor method onQueryRequest0.

/**
     * @param node Node authored request.
     * @param reqId Request ID.
     * @param segmentId index segment ID.
     * @param schemaName Schema name.
     * @param qrys Queries to execute.
     * @param cacheIds Caches which will be affected by these queries.
     * @param topVer Topology version.
     * @param partsMap Partitions map for unstable topology.
     * @param parts Explicit partitions for current node.
     * @param tbls Tables.
     * @param pageSize Page size.
     * @param distributedJoinMode Query distributed join mode.
     */
private void onQueryRequest0(ClusterNode node, long reqId, int segmentId, String schemaName, Collection<GridCacheSqlQuery> qrys, List<Integer> cacheIds, AffinityTopologyVersion topVer, Map<UUID, int[]> partsMap, int[] parts, Collection<QueryTable> tbls, int pageSize, DistributedJoinMode distributedJoinMode, boolean enforceJoinOrder, boolean replicated, int timeout, Object[] params) {
    // Prepare to run queries.
    GridCacheContext<?, ?> mainCctx = !F.isEmpty(cacheIds) ? ctx.cache().context().cacheContext(cacheIds.get(0)) : null;
    NodeResults nodeRess = resultsForNode(node.id());
    QueryResults qr = null;
    List<GridReservable> reserved = new ArrayList<>();
    try {
        if (topVer != null) {
            // Reserve primary for topology version or explicit partitions.
            if (!reservePartitions(cacheIds, topVer, parts, reserved)) {
                sendRetry(node, reqId, segmentId);
                return;
            }
        }
        qr = new QueryResults(reqId, qrys.size(), mainCctx != null ? mainCctx.name() : null);
        if (nodeRess.put(reqId, segmentId, qr) != null)
            throw new IllegalStateException();
        // Prepare query context.
        GridH2QueryContext qctx = new GridH2QueryContext(ctx.localNodeId(), node.id(), reqId, segmentId, replicated ? REPLICATED : MAP).filter(h2.backupFilter(topVer, parts)).partitionsMap(partsMap).distributedJoinMode(distributedJoinMode).pageSize(pageSize).topologyVersion(topVer).reservations(reserved);
        List<GridH2Table> snapshotedTbls = null;
        if (!F.isEmpty(tbls)) {
            snapshotedTbls = new ArrayList<>(tbls.size());
            for (QueryTable tbl : tbls) {
                GridH2Table h2Tbl = h2.dataTable(tbl);
                Objects.requireNonNull(h2Tbl, tbl.toString());
                h2Tbl.snapshotIndexes(qctx, segmentId);
                snapshotedTbls.add(h2Tbl);
            }
        }
        Connection conn = h2.connectionForSchema(schemaName);
        H2Utils.setupConnection(conn, distributedJoinMode != OFF, enforceJoinOrder);
        GridH2QueryContext.set(qctx);
        // qctx is set, we have to release reservations inside of it.
        reserved = null;
        try {
            if (nodeRess.cancelled(reqId)) {
                GridH2QueryContext.clear(ctx.localNodeId(), node.id(), reqId, qctx.type());
                nodeRess.cancelRequest(reqId);
                throw new QueryCancelledException();
            }
            // Run queries.
            int qryIdx = 0;
            boolean evt = mainCctx != null && ctx.event().isRecordable(EVT_CACHE_QUERY_EXECUTED);
            for (GridCacheSqlQuery qry : qrys) {
                ResultSet rs = null;
                // If we are not the target node for this replicated query, just ignore it.
                if (qry.node() == null || (segmentId == 0 && qry.node().equals(ctx.localNodeId()))) {
                    rs = h2.executeSqlQueryWithTimer(conn, qry.query(), F.asList(qry.parameters(params)), true, timeout, qr.cancels[qryIdx]);
                    if (evt) {
                        assert mainCctx != null;
                        ctx.event().record(new CacheQueryExecutedEvent<>(node, "SQL query executed.", EVT_CACHE_QUERY_EXECUTED, CacheQueryType.SQL.name(), mainCctx.name(), null, qry.query(), null, null, params, node.id(), null));
                    }
                    assert rs instanceof JdbcResultSet : rs.getClass();
                }
                qr.addResult(qryIdx, qry, node.id(), rs, params);
                if (qr.canceled) {
                    qr.result(qryIdx).close();
                    throw new QueryCancelledException();
                }
                // Send the first page.
                sendNextPage(nodeRess, node, qr, qryIdx, segmentId, pageSize);
                qryIdx++;
            }
        } finally {
            GridH2QueryContext.clearThreadLocal();
            if (distributedJoinMode == OFF)
                qctx.clearContext(false);
            if (!F.isEmpty(snapshotedTbls)) {
                for (GridH2Table dataTbl : snapshotedTbls) dataTbl.releaseSnapshots();
            }
        }
    } catch (Throwable e) {
        if (qr != null) {
            nodeRess.remove(reqId, segmentId, qr);
            qr.cancel(false);
        }
        if (X.hasCause(e, GridH2RetryException.class))
            sendRetry(node, reqId, segmentId);
        else {
            U.error(log, "Failed to execute local query.", e);
            sendError(node, reqId, e);
            if (e instanceof Error)
                throw (Error) e;
        }
    } finally {
        if (reserved != null) {
            // Release reserved partitions.
            for (int i = 0; i < reserved.size(); i++) reserved.get(i).release();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Connection(java.sql.Connection) GridH2RetryException(org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException) GridReservable(org.apache.ignite.internal.processors.cache.distributed.dht.GridReservable) QueryTable(org.apache.ignite.internal.processors.cache.query.QueryTable) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) GridCacheSqlQuery(org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) GridH2QueryContext(org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext) JdbcResultSet(org.h2.jdbc.JdbcResultSet)

Example 3 with Set

use of org.h2.command.dml.Set in project ignite by apache.

the class DmlAstUtils method getFastUpdateArgs.

/**
     * @param update UPDATE statement.
     * @return {@code null} if given statement directly updates {@code _val} column with a literal or param value
     * and filters by single non expression key (and, optionally,  by single non expression value).
     */
public static FastUpdateArguments getFastUpdateArgs(GridSqlUpdate update) {
    IgnitePair<GridSqlElement> filter = findKeyValueEqualityCondition(update.where());
    if (filter == null)
        return null;
    if (update.cols().size() != 1)
        return null;
    Table tbl = update.cols().get(0).column().getTable();
    if (!(tbl instanceof GridH2Table))
        return null;
    GridH2RowDescriptor desc = ((GridH2Table) tbl).rowDescriptor();
    if (!desc.isValueColumn(update.cols().get(0).column().getColumnId()))
        return null;
    GridSqlElement set = update.set().get(update.cols().get(0).columnName());
    if (!(set instanceof GridSqlConst || set instanceof GridSqlParameter))
        return null;
    return new FastUpdateArguments(operandForElement(filter.getKey()), operandForElement(filter.getValue()), operandForElement(set));
}
Also used : GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) Table(org.h2.table.Table) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) FastUpdateArguments(org.apache.ignite.internal.processors.query.h2.dml.FastUpdateArguments)

Example 4 with Set

use of org.h2.command.dml.Set in project ignite by apache.

the class DmlAstUtils method selectForUpdate.

/**
     * Generate SQL SELECT based on UPDATE's WHERE, LIMIT, etc.
     *
     * @param update Update statement.
     * @param keysParamIdx Index of new param for the array of keys.
     * @return SELECT statement.
     */
public static GridSqlSelect selectForUpdate(GridSqlUpdate update, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(update.target());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(update.target(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for UPDATE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for UPDATE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    for (GridSqlColumn c : update.cols()) {
        String newColName = Parser.quoteIdentifier("_upd_" + c.columnName());
        // We have to use aliases to cover cases when the user
        // wants to update _val field directly (if it's a literal)
        GridSqlAlias alias = new GridSqlAlias(newColName, elementOrDefault(update.set().get(c.columnName()), c), true);
        alias.resultType(c.resultType());
        mapQry.addColumn(alias, true);
    }
    GridSqlElement where = update.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(update.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) ValueString(org.h2.value.ValueString) HashSet(java.util.HashSet)

Example 5 with Set

use of org.h2.command.dml.Set in project ignite by apache.

the class DmlAstUtils method selectForDelete.

/**
     * Generate SQL SELECT based on DELETE's WHERE, LIMIT, etc.
     *
     * @param del Delete statement.
     * @param keysParamIdx Index for .
     * @return SELECT statement.
     */
public static GridSqlSelect selectForDelete(GridSqlDelete del, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(del.from());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(del.from(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for DELETE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for DELETE";
    Column h2KeyCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2AbstractKeyValueRow.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    GridSqlElement where = del.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(del.limit());
    return mapQry;
}
Also used : Column(org.h2.table.Column) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) HashSet(java.util.HashSet)

Aggregations

SQLException (java.sql.SQLException)107 DbException (org.h2.message.DbException)80 PreparedStatement (java.sql.PreparedStatement)78 Connection (java.sql.Connection)70 Statement (java.sql.Statement)63 ResultSet (java.sql.ResultSet)62 Value (org.h2.value.Value)51 JdbcConnection (org.h2.jdbc.JdbcConnection)48 SimpleResultSet (org.h2.tools.SimpleResultSet)36 HashSet (java.util.HashSet)28 Column (org.h2.table.Column)24 Savepoint (java.sql.Savepoint)23 ValueString (org.h2.value.ValueString)21 IOException (java.io.IOException)20 Random (java.util.Random)17 Expression (org.h2.expression.Expression)16 Task (org.h2.util.Task)16 ExpressionColumn (org.h2.expression.ExpressionColumn)14 ValueExpression (org.h2.expression.ValueExpression)13 IndexColumn (org.h2.table.IndexColumn)13