Search in sources :

Example 31 with UpdatePlan

use of org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan in project ignite by apache.

the class IgniteH2Indexing method executeUpdateTransactional.

/**
 * Execute update in transactional mode.
 *
 * @param qryId Query id.
 * @param qryDesc Query descriptor.
 * @param qryParams Query parameters.
 * @param dml Plan.
 * @param loc Local flag.
 * @param cancel Cancel hook.
 * @return Update result.
 * @throws IgniteCheckedException If failed.
 */
private UpdateResult executeUpdateTransactional(long qryId, QueryDescriptor qryDesc, QueryParameters qryParams, QueryParserResultDml dml, boolean loc, GridQueryCancel cancel) throws IgniteCheckedException {
    UpdatePlan plan = dml.plan();
    GridCacheContext cctx = plan.cacheContext();
    assert cctx != null;
    assert cctx.transactional();
    GridNearTxLocal tx = tx(ctx);
    boolean implicit = (tx == null);
    boolean commit = implicit && qryParams.autoCommit();
    if (implicit)
        tx = txStart(cctx, qryParams.timeout());
    requestSnapshot(tx);
    try (GridNearTxLocal toCommit = commit ? tx : null) {
        DmlDistributedPlanInfo distributedPlan = loc ? null : plan.distributedPlan();
        long timeout = implicit ? tx.remainingTime() : operationTimeout(qryParams.timeout(), tx);
        if (cctx.isReplicated() || distributedPlan == null || ((plan.mode() == UpdateMode.INSERT || plan.mode() == UpdateMode.MERGE) && !plan.isLocalSubquery())) {
            boolean sequential = true;
            UpdateSourceIterator<?> it;
            if (plan.fastResult()) {
                IgniteBiTuple row = plan.getFastRow(qryParams.arguments());
                assert row != null;
                EnlistOperation op = UpdatePlan.enlistOperation(plan.mode());
                it = new DmlUpdateSingleEntryIterator<>(op, op.isDeleteOrLock() ? row.getKey() : row);
            } else if (plan.hasRows()) {
                it = new DmlUpdateResultsIterator(UpdatePlan.enlistOperation(plan.mode()), plan, plan.createRows(qryParams.arguments()));
            } else {
                SqlFieldsQuery selectFieldsQry = new SqlFieldsQuery(plan.selectQuery(), qryDesc.collocated()).setArgs(qryParams.arguments()).setDistributedJoins(qryDesc.distributedJoins()).setEnforceJoinOrder(qryDesc.enforceJoinOrder()).setLocal(qryDesc.local()).setPageSize(qryParams.pageSize()).setTimeout((int) timeout, TimeUnit.MILLISECONDS).setLazy(qryParams.lazy());
                FieldsQueryCursor<List<?>> cur = executeSelectForDml(qryId, qryDesc.schemaName(), selectFieldsQry, MvccUtils.mvccTracker(cctx, tx), cancel, (int) timeout);
                it = plan.iteratorForTransaction(connMgr, cur);
            }
            // TODO: IGNITE-11176 - Need to support cancellation
            IgniteInternalFuture<Long> fut = tx.updateAsync(cctx, it, qryParams.pageSize(), timeout, sequential);
            UpdateResult res = new UpdateResult(fut.get(), X.EMPTY_OBJECT_ARRAY, plan.distributedPlan() != null ? plan.distributedPlan().derivedPartitions() : null);
            if (commit)
                toCommit.commit();
            return res;
        }
        int[] ids = U.toIntArray(distributedPlan.getCacheIds());
        int flags = 0;
        if (qryDesc.enforceJoinOrder())
            flags |= GridH2QueryRequest.FLAG_ENFORCE_JOIN_ORDER;
        if (distributedPlan.isReplicatedOnly())
            flags |= GridH2QueryRequest.FLAG_REPLICATED;
        if (qryParams.lazy())
            flags |= GridH2QueryRequest.FLAG_LAZY;
        flags = GridH2QueryRequest.setDataPageScanEnabled(flags, qryParams.dataPageScanEnabled());
        int[] parts = PartitionResult.calculatePartitions(qryParams.partitions(), distributedPlan.derivedPartitions(), qryParams.arguments());
        if (parts != null && parts.length == 0)
            return new UpdateResult(0, X.EMPTY_OBJECT_ARRAY, distributedPlan.derivedPartitions());
        else {
            // TODO: IGNITE-11176 - Need to support cancellation
            IgniteInternalFuture<Long> fut = tx.updateAsync(cctx, ids, parts, qryDesc.schemaName(), qryDesc.sql(), qryParams.arguments(), flags, qryParams.pageSize(), timeout);
            UpdateResult res = new UpdateResult(fut.get(), X.EMPTY_OBJECT_ARRAY, distributedPlan.derivedPartitions());
            if (commit)
                toCommit.commit();
            return res;
        }
    } catch (ClusterTopologyServerNotFoundException e) {
        throw new CacheServerNotFoundException(e.getMessage(), e);
    } catch (IgniteCheckedException e) {
        IgniteSQLException sqlEx = X.cause(e, IgniteSQLException.class);
        if (sqlEx != null)
            throw sqlEx;
        Exception ex = IgniteUtils.convertExceptionNoWrap(e);
        if (ex instanceof IgniteException)
            throw (IgniteException) ex;
        U.error(log, "Error during update [localNodeId=" + ctx.localNodeId() + "]", ex);
        throw new IgniteSQLException("Failed to run update. " + ex.getMessage(), ex);
    } finally {
        if (commit)
            cctx.tm().resetContext();
    }
}
Also used : FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) CacheServerNotFoundException(org.apache.ignite.cache.CacheServerNotFoundException) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) EnlistOperation(org.apache.ignite.internal.processors.query.EnlistOperation) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) DmlUpdateResultsIterator(org.apache.ignite.internal.processors.query.h2.dml.DmlUpdateResultsIterator) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) DmlDistributedPlanInfo(org.apache.ignite.internal.processors.query.h2.dml.DmlDistributedPlanInfo) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) BatchUpdateException(java.sql.BatchUpdateException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteClusterReadOnlyException(org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException) CacheServerNotFoundException(org.apache.ignite.cache.CacheServerNotFoundException) SQLException(java.sql.SQLException) IgniteException(org.apache.ignite.IgniteException) CacheException(javax.cache.CacheException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Example 32 with UpdatePlan

use of org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan in project ignite by apache.

the class IgniteH2Indexing method streamQuery0.

/**
 * Perform given statement against given data streamer. Only rows based INSERT is supported.
 *
 * @param qry Query.
 * @param schemaName Schema name.
 * @param streamer Streamer to feed data to.
 * @param dml DML statement.
 * @param args Statement arguments.
 * @return Number of rows in given INSERT statement.
 * @throws IgniteCheckedException if failed.
 */
@SuppressWarnings({ "unchecked" })
private long streamQuery0(String qry, String schemaName, IgniteDataStreamer streamer, QueryParserResultDml dml, final Object[] args, String qryInitiatorId) throws IgniteCheckedException {
    long qryId = runningQryMgr.register(QueryUtils.INCLUDE_SENSITIVE ? qry : sqlWithoutConst(dml.statement()), GridCacheQueryType.SQL_FIELDS, schemaName, true, null, qryInitiatorId);
    Exception failReason = null;
    try {
        UpdatePlan plan = dml.plan();
        Iterator<List<?>> iter = new GridQueryCacheObjectsIterator(updateQueryRows(qryId, schemaName, plan, args), objectContext(), true);
        if (!iter.hasNext())
            return 0;
        IgniteBiTuple<?, ?> t = plan.processRow(iter.next());
        if (!iter.hasNext()) {
            streamer.addData(t.getKey(), t.getValue());
            return 1;
        } else {
            Map<Object, Object> rows = new LinkedHashMap<>(plan.rowCount());
            rows.put(t.getKey(), t.getValue());
            while (iter.hasNext()) {
                List<?> row = iter.next();
                t = plan.processRow(row);
                rows.put(t.getKey(), t.getValue());
            }
            streamer.addData(rows);
            return rows.size();
        }
    } catch (IgniteException | IgniteCheckedException e) {
        failReason = e;
        throw e;
    } finally {
        runningQryMgr.unregister(qryId, failReason);
    }
}
Also used : GridQueryCacheObjectsIterator(org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) BatchUpdateException(java.sql.BatchUpdateException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteClusterReadOnlyException(org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException) CacheServerNotFoundException(org.apache.ignite.cache.CacheServerNotFoundException) SQLException(java.sql.SQLException) IgniteException(org.apache.ignite.IgniteException) CacheException(javax.cache.CacheException) LinkedHashMap(java.util.LinkedHashMap) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) List(java.util.List) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Example 33 with UpdatePlan

use of org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan in project ignite by apache.

the class CommandProcessor method processBulkLoadCommand.

/**
 * Process bulk load COPY command.
 *
 * @param cmd The command.
 * @param qryId Query id.
 * @return The context (which is the result of the first request/response).
 * @throws IgniteCheckedException If something failed.
 */
private FieldsQueryCursor<List<?>> processBulkLoadCommand(SqlBulkLoadCommand cmd, long qryId) throws IgniteCheckedException {
    if (cmd.packetSize() == null)
        cmd.packetSize(BulkLoadAckClientParameters.DFLT_PACKET_SIZE);
    GridH2Table tbl = schemaMgr.dataTable(cmd.schemaName(), cmd.tableName());
    if (tbl == null) {
        throw new IgniteSQLException("Table does not exist: " + cmd.tableName(), IgniteQueryErrorCode.TABLE_NOT_FOUND);
    }
    H2Utils.checkAndStartNotStartedCache(ctx, tbl);
    UpdatePlan plan = UpdatePlanBuilder.planForBulkLoad(cmd, tbl);
    IgniteClosureX<List<?>, IgniteBiTuple<?, ?>> dataConverter = new DmlBulkLoadDataConverter(plan);
    IgniteDataStreamer<Object, Object> streamer = ctx.grid().dataStreamer(tbl.cacheName());
    BulkLoadCacheWriter outputWriter = new BulkLoadStreamerWriter(streamer);
    BulkLoadParser inputParser = BulkLoadParser.createParser(cmd.inputFormat());
    BulkLoadProcessor processor = new BulkLoadProcessor(inputParser, dataConverter, outputWriter, idx.runningQueryManager(), qryId, ctx.tracing());
    BulkLoadAckClientParameters params = new BulkLoadAckClientParameters(cmd.localFileName(), cmd.packetSize());
    return new BulkLoadContextCursor(processor, params);
}
Also used : BulkLoadContextCursor(org.apache.ignite.cache.query.BulkLoadContextCursor) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) BulkLoadCacheWriter(org.apache.ignite.internal.processors.bulkload.BulkLoadCacheWriter) DmlBulkLoadDataConverter(org.apache.ignite.internal.processors.query.h2.dml.DmlBulkLoadDataConverter) BulkLoadAckClientParameters(org.apache.ignite.internal.processors.bulkload.BulkLoadAckClientParameters) BulkLoadParser(org.apache.ignite.internal.processors.bulkload.BulkLoadParser) BulkLoadProcessor(org.apache.ignite.internal.processors.bulkload.BulkLoadProcessor) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) BulkLoadStreamerWriter(org.apache.ignite.internal.processors.bulkload.BulkLoadStreamerWriter) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ArrayList(java.util.ArrayList) List(java.util.List) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)

Aggregations

IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)24 UpdatePlan (org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)18 ArrayList (java.util.ArrayList)16 List (java.util.List)15 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)13 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)12 SQLException (java.sql.SQLException)11 IgniteException (org.apache.ignite.IgniteException)11 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)10 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)8 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)7 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)7 BatchUpdateException (java.sql.BatchUpdateException)6 GridQueryCacheObjectsIterator (org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator)6 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)6 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)6 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)6 Column (org.h2.table.Column)6 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)5 GridQueryFieldsResult (org.apache.ignite.internal.processors.query.GridQueryFieldsResult)5