Search in sources :

Example 11 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class IgniteH2Indexing method queryLocalSql.

/**
 * Executes regular query.
 *
 * @param schemaName Schema name.
 * @param cacheName Cache name.
 * @param qry Query.
 * @param alias Table alias.
 * @param params Query parameters.
 * @param type Query return type.
 * @param filter Cache name and key filter.
 * @param cancel Cancel object.
 * @return Queried rows.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
<K, V> GridCloseableIterator<IgniteBiTuple<K, V>> queryLocalSql(String schemaName, String cacheName, final String qry, String alias, @Nullable final Collection<Object> params, String type, final IndexingQueryFilter filter, GridQueryCancel cancel) throws IgniteCheckedException {
    final H2TableDescriptor tbl = tableDescriptor(schemaName, cacheName, type);
    if (tbl == null)
        throw new IgniteSQLException("Failed to find SQL table for type: " + type, IgniteQueryErrorCode.TABLE_NOT_FOUND);
    String sql = generateQuery(qry, alias, tbl);
    Connection conn = connectionForThread(tbl.schemaName());
    H2Utils.setupConnection(conn, false, false);
    GridH2QueryContext.set(new GridH2QueryContext(nodeId, nodeId, 0, LOCAL).filter(filter).distributedJoinMode(OFF));
    GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL, schemaName, U.currentTimeMillis(), null, true);
    runs.put(run.id(), run);
    try {
        ResultSet rs = executeSqlQueryWithTimer(conn, sql, params, true, 0, cancel);
        return new H2KeyValueIterator(rs);
    } finally {
        GridH2QueryContext.clearThreadLocal();
        runs.remove(run.id());
    }
}
Also used : IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Connection(java.sql.Connection) GridRunningQueryInfo(org.apache.ignite.internal.processors.query.GridRunningQueryInfo) ResultSet(java.sql.ResultSet) IgniteSystemProperties.getString(org.apache.ignite.IgniteSystemProperties.getString) GridH2QueryContext(org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext)

Example 12 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class IgniteH2Indexing method queryLocalSqlFields.

/**
 * Queries individual fields (generally used by JDBC drivers).
 *
 * @param schemaName Schema name.
 * @param qry Query.
 * @param params Query parameters.
 * @param filter Cache name and key filter.
 * @param enforceJoinOrder Enforce join order of tables in the query.
 * @param timeout Query timeout in milliseconds.
 * @param cancel Query cancel.
 * @return Query result.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
GridQueryFieldsResult queryLocalSqlFields(final String schemaName, final String qry, @Nullable final Collection<Object> params, final IndexingQueryFilter filter, boolean enforceJoinOrder, final int timeout, final GridQueryCancel cancel) throws IgniteCheckedException {
    final Connection conn = connectionForSchema(schemaName);
    H2Utils.setupConnection(conn, false, enforceJoinOrder);
    final PreparedStatement stmt = preparedStatementWithParams(conn, qry, params, true);
    if (GridSqlQueryParser.checkMultipleStatements(stmt))
        throw new IgniteSQLException("Multiple statements queries are not supported for local queries");
    Prepared p = GridSqlQueryParser.prepared(stmt);
    if (DmlStatementsProcessor.isDmlStatement(p)) {
        SqlFieldsQuery fldsQry = new SqlFieldsQuery(qry);
        if (params != null)
            fldsQry.setArgs(params.toArray());
        fldsQry.setEnforceJoinOrder(enforceJoinOrder);
        fldsQry.setTimeout(timeout, TimeUnit.MILLISECONDS);
        return dmlProc.updateSqlFieldsLocal(schemaName, conn, p, fldsQry, filter, cancel);
    } else if (DdlStatementsProcessor.isDdlStatement(p))
        throw new IgniteSQLException("DDL statements are supported for the whole cluster only", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    List<GridQueryFieldMetadata> meta;
    try {
        meta = H2Utils.meta(stmt.getMetaData());
    } catch (SQLException e) {
        throw new IgniteCheckedException("Cannot prepare query metadata", e);
    }
    final GridH2QueryContext ctx = new GridH2QueryContext(nodeId, nodeId, 0, LOCAL).filter(filter).distributedJoinMode(OFF);
    return new GridQueryFieldsResultAdapter(meta, null) {

        @Override
        public GridCloseableIterator<List<?>> iterator() throws IgniteCheckedException {
            assert GridH2QueryContext.get() == null;
            GridH2QueryContext.set(ctx);
            GridRunningQueryInfo run = new GridRunningQueryInfo(qryIdGen.incrementAndGet(), qry, SQL_FIELDS, schemaName, U.currentTimeMillis(), cancel, true);
            runs.putIfAbsent(run.id(), run);
            try {
                ResultSet rs = executeSqlQueryWithTimer(stmt, conn, qry, params, timeout, cancel);
                return new H2FieldsIterator(rs);
            } finally {
                GridH2QueryContext.clearThreadLocal();
                runs.remove(run.id());
            }
        }
    };
}
Also used : GridQueryFieldsResultAdapter(org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Connection(java.sql.Connection) Prepared(org.h2.command.Prepared) GridRunningQueryInfo(org.apache.ignite.internal.processors.query.GridRunningQueryInfo) GridQueryFieldMetadata(org.apache.ignite.internal.processors.query.GridQueryFieldMetadata) PreparedStatement(java.sql.PreparedStatement) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) GridH2QueryContext(org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext)

Example 13 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class DmlStatementsProcessor method doUpdate.

/**
 * Perform UPDATE operation on top of results of SELECT.
 * @param cursor SELECT results.
 * @param pageSize Batch size for streaming, anything <= 0 for single page operations.
 * @return Pair [cursor corresponding to results of UPDATE (contains number of items affected); keys whose values
 *     had been modified concurrently (arguments for a re-run)].
 */
@SuppressWarnings({ "unchecked", "ThrowableResultOfMethodCallIgnored" })
private UpdateResult doUpdate(UpdatePlan plan, Iterable<List<?>> cursor, int pageSize) throws IgniteCheckedException {
    GridCacheContext cctx = plan.cacheContext();
    DmlBatchSender sender = new DmlBatchSender(cctx, pageSize, 1);
    for (List<?> row : cursor) {
        T3<Object, Object, Object> row0 = plan.processRowForUpdate(row);
        Object key = row0.get1();
        Object oldVal = row0.get2();
        Object newVal = row0.get3();
        sender.add(key, new ModifyingEntryProcessor(oldVal, new EntryValueUpdater(newVal)), 0);
    }
    sender.flush();
    SQLException resEx = sender.error();
    if (resEx != null) {
        if (!F.isEmpty(sender.failedKeys())) {
            // Don't go for a re-run if processing of some keys yielded exceptions and report keys that
            // had been modified concurrently right away.
            String msg = "Failed to UPDATE some keys because they had been modified concurrently " + "[keys=" + sender.failedKeys() + ']';
            SQLException dupEx = createJdbcSqlException(msg, IgniteQueryErrorCode.CONCURRENT_UPDATE);
            dupEx.setNextException(resEx);
            resEx = dupEx;
        }
        throw new IgniteSQLException(resEx);
    }
    return new UpdateResult(sender.updateCount(), sender.failedKeys().toArray());
}
Also used : GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) DmlBatchSender(org.apache.ignite.internal.processors.query.h2.dml.DmlBatchSender)

Example 14 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class DmlStatementsProcessor method executeUpdateStatement.

/**
 * Actually perform SQL DML operation locally.
 *
 * @param schemaName Schema name.
 * @param cctx Cache context.
 * @param c Connection.
 * @param prepared Prepared statement for DML query.
 * @param fieldsQry Fields query.
 * @param loc Local query flag.
 * @param filters Cache name and key filter.
 * @param cancel Query cancel state holder.
 * @return Pair [number of successfully processed items; keys that have failed to be processed]
 * @throws IgniteCheckedException if failed.
 */
@SuppressWarnings({ "ConstantConditions", "unchecked" })
private UpdateResult executeUpdateStatement(String schemaName, final GridCacheContext cctx, Connection c, Prepared prepared, SqlFieldsQuery fieldsQry, boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
    Integer errKeysPos = null;
    UpdatePlan plan = getPlanForStatement(schemaName, c, prepared, fieldsQry, loc, errKeysPos);
    UpdateResult fastUpdateRes = plan.processFast(fieldsQry.getArgs());
    if (fastUpdateRes != null)
        return fastUpdateRes;
    if (plan.distributedPlan() != null) {
        UpdateResult result = doDistributedUpdate(schemaName, fieldsQry, plan, cancel);
        // null is returned in case not all nodes support distributed DML.
        if (result != null)
            return result;
    }
    Iterable<List<?>> cur;
    // sub-query and not some dummy stuff like "select 1, 2, 3;"
    if (!loc && !plan.isLocalSubquery()) {
        assert !F.isEmpty(plan.selectQuery());
        SqlFieldsQuery newFieldsQry = new SqlFieldsQuery(plan.selectQuery(), fieldsQry.isCollocated()).setArgs(fieldsQry.getArgs()).setDistributedJoins(fieldsQry.isDistributedJoins()).setEnforceJoinOrder(fieldsQry.isEnforceJoinOrder()).setLocal(fieldsQry.isLocal()).setPageSize(fieldsQry.getPageSize()).setTimeout(fieldsQry.getTimeout(), TimeUnit.MILLISECONDS);
        cur = (QueryCursorImpl<List<?>>) idx.querySqlFields(schemaName, newFieldsQry, null, true, true, cancel).get(0);
    } else if (plan.hasRows())
        cur = plan.createRows(fieldsQry.getArgs());
    else {
        final GridQueryFieldsResult res = idx.queryLocalSqlFields(schemaName, plan.selectQuery(), F.asList(fieldsQry.getArgs()), filters, fieldsQry.isEnforceJoinOrder(), fieldsQry.getTimeout(), cancel);
        cur = new QueryCursorImpl<>(new Iterable<List<?>>() {

            @Override
            public Iterator<List<?>> iterator() {
                try {
                    return new GridQueryCacheObjectsIterator(res.iterator(), idx.objectContext(), true);
                } catch (IgniteCheckedException e) {
                    throw new IgniteException(e);
                }
            }
        }, cancel);
    }
    int pageSize = loc ? 0 : fieldsQry.getPageSize();
    return processDmlSelectResult(cctx, plan, cur, pageSize);
}
Also used : QueryCursorImpl(org.apache.ignite.internal.processors.cache.QueryCursorImpl) GridQueryCacheObjectsIterator(org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) GridQueryFieldsResult(org.apache.ignite.internal.processors.query.GridQueryFieldsResult) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) GridQueryCacheObjectsIterator(org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator) IgniteSingletonIterator(org.apache.ignite.internal.util.lang.IgniteSingletonIterator) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Example 15 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class DmlStatementsProcessor method updateSqlFields.

/**
 * Execute DML statement, possibly with few re-attempts in case of concurrent data modifications.
 *
 * @param schemaName Schema.
 * @param conn Connection.
 * @param prepared Prepared statement.
 * @param fieldsQry Original query.
 * @param loc Query locality flag.
 * @param filters Cache name and key filter.
 * @param cancel Cancel.
 * @return Update result (modified items count and failed keys).
 * @throws IgniteCheckedException if failed.
 */
private UpdateResult updateSqlFields(String schemaName, Connection conn, Prepared prepared, SqlFieldsQuery fieldsQry, boolean loc, IndexingQueryFilter filters, GridQueryCancel cancel) throws IgniteCheckedException {
    Object[] errKeys = null;
    long items = 0;
    UpdatePlan plan = getPlanForStatement(schemaName, conn, prepared, fieldsQry, loc, null);
    GridCacheContext<?, ?> cctx = plan.cacheContext();
    for (int i = 0; i < DFLT_DML_RERUN_ATTEMPTS; i++) {
        CacheOperationContext opCtx = setKeepBinaryContext(cctx);
        UpdateResult r;
        try {
            r = executeUpdateStatement(schemaName, cctx, conn, prepared, fieldsQry, loc, filters, cancel);
        } finally {
            cctx.operationContextPerCall(opCtx);
        }
        items += r.counter();
        errKeys = r.errorKeys();
        if (F.isEmpty(errKeys))
            break;
    }
    if (F.isEmpty(errKeys)) {
        if (items == 1L)
            return UpdateResult.ONE;
        else if (items == 0L)
            return UpdateResult.ZERO;
    }
    return new UpdateResult(items, errKeys);
}
Also used : CacheOperationContext(org.apache.ignite.internal.processors.cache.CacheOperationContext) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)37 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)33 ArrayList (java.util.ArrayList)26 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)25 List (java.util.List)22 IgniteException (org.apache.ignite.IgniteException)21 SQLException (java.sql.SQLException)15 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)15 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)13 HashMap (java.util.HashMap)12 Column (org.h2.table.Column)12 LinkedHashMap (java.util.LinkedHashMap)11 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)11 Index (org.h2.index.Index)11 PreparedStatement (java.sql.PreparedStatement)9 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)9 GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)9 UpdatePlan (org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)9 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)9 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)9