Search in sources :

Example 91 with IgniteSQLException

use of org.apache.ignite.internal.processors.query.IgniteSQLException in project ignite by apache.

the class IgniteH2Indexing method executeSelect0.

/**
 * Execute an all-ready {@link SqlFieldsQuery}.
 *
 * @param qryId Query id.
 * @param qryDesc Plan key.
 * @param qryParams Parameters.
 * @param select Select.
 * @param keepBinary Whether binary objects must not be deserialized automatically.
 * @param mvccTracker MVCC tracker.
 * @param cancel Query cancel state holder.
 * @param inTx Flag whether query is executed within transaction.
 * @param timeout Timeout.
 * @return Query result.
 * @throws IgniteCheckedException On error.
 */
private Iterable<List<?>> executeSelect0(long qryId, QueryDescriptor qryDesc, QueryParameters qryParams, QueryParserResultSelect select, boolean keepBinary, MvccQueryTracker mvccTracker, GridQueryCancel cancel, boolean inTx, int timeout) throws IgniteCheckedException {
    assert !select.mvccEnabled() || mvccTracker != null;
    // Check security.
    if (ctx.security().enabled())
        checkSecurity(select.cacheIds());
    Iterable<List<?>> iter;
    if (select.splitNeeded()) {
        // Distributed query.
        GridCacheTwoStepQuery twoStepQry = select.forUpdate() && inTx ? select.forUpdateTwoStepQuery() : select.twoStepQuery();
        assert twoStepQry != null;
        iter = executeSelectDistributed(qryId, qryDesc, qryParams, twoStepQry, keepBinary, mvccTracker, cancel, timeout);
    } else {
        // Local query.
        IndexingQueryFilter filter = (qryDesc.local() ? backupFilter(null, qryParams.partitions()) : null);
        GridQueryFieldsResult res = executeSelectLocal(qryId, qryDesc, qryParams, select, filter, mvccTracker, cancel, inTx, timeout);
        iter = () -> {
            try {
                return new GridQueryCacheObjectsIterator(res.iterator(), objectContext(), keepBinary);
            } catch (IgniteCheckedException | IgniteSQLException e) {
                throw new CacheException(e);
            }
        };
    }
    return iter;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheException(javax.cache.CacheException) IndexingQueryFilter(org.apache.ignite.spi.indexing.IndexingQueryFilter) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) List(java.util.List) GridQueryCacheObjectsIterator(org.apache.ignite.internal.processors.query.GridQueryCacheObjectsIterator) GridQueryFieldsResult(org.apache.ignite.internal.processors.query.GridQueryFieldsResult)

Example 92 with IgniteSQLException

use of org.apache.ignite.internal.processors.query.IgniteSQLException in project ignite by apache.

the class IgniteH2Indexing method generateFieldsQuery.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("deprecation")
@Override
public SqlFieldsQuery generateFieldsQuery(String cacheName, SqlQuery qry) {
    String schemaName = schema(cacheName);
    String type = qry.getType();
    H2TableDescriptor tblDesc = schemaMgr.tableForType(schemaName, cacheName, type);
    if (tblDesc == null)
        throw new IgniteSQLException("Failed to find SQL table for type: " + type, IgniteQueryErrorCode.TABLE_NOT_FOUND);
    String sql;
    try {
        sql = generateFieldsQueryString(qry.getSql(), qry.getAlias(), tblDesc);
    } catch (IgniteCheckedException e) {
        throw new IgniteException(e);
    }
    SqlFieldsQuery res = QueryUtils.withQueryTimeout(new SqlFieldsQuery(sql), qry.getTimeout(), TimeUnit.MILLISECONDS);
    res.setArgs(qry.getArgs());
    res.setDistributedJoins(qry.isDistributedJoins());
    res.setLocal(qry.isLocal());
    res.setPageSize(qry.getPageSize());
    res.setPartitions(qry.getPartitions());
    res.setReplicatedOnly(qry.isReplicatedOnly());
    res.setSchema(schemaName);
    res.setSql(sql);
    return res;
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) H2Utils.generateFieldsQueryString(org.apache.ignite.internal.processors.query.h2.H2Utils.generateFieldsQueryString) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery)

Example 93 with IgniteSQLException

use of org.apache.ignite.internal.processors.query.IgniteSQLException 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 94 with IgniteSQLException

use of org.apache.ignite.internal.processors.query.IgniteSQLException in project ignite by apache.

the class IgniteH2Indexing method streamerParse.

/**
 * Parse statement for streamer.
 *
 * @param schemaName Schema name.
 * @param qry Query.
 * @return DML.
 */
private QueryParserResultDml streamerParse(String schemaName, String qry) {
    QueryParserResult parseRes = parser.parse(schemaName, new SqlFieldsQuery(qry), false);
    QueryParserResultDml dml = parseRes.dml();
    if (dml == null || !dml.streamable()) {
        throw new IgniteSQLException("Streaming mode supports only INSERT commands without subqueries.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
    }
    return dml;
}
Also used : IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery)

Example 95 with IgniteSQLException

use of org.apache.ignite.internal.processors.query.IgniteSQLException in project ignite by apache.

the class IgniteH2Indexing method executeDml.

/**
 * Execute an all-ready {@link SqlFieldsQuery}.
 *
 * @param qryDesc Plan key.
 * @param qryParams Parameters.
 * @param dml DML.
 * @param cancel Query cancel state holder.
 * @return Query result.
 */
private List<? extends FieldsQueryCursor<List<?>>> executeDml(QueryDescriptor qryDesc, QueryParameters qryParams, QueryParserResultDml dml, GridQueryCancel cancel) {
    IndexingQueryFilter filter = (qryDesc.local() ? backupFilter(null, qryParams.partitions()) : null);
    long qryId = registerRunningQuery(qryDesc, qryParams, cancel, dml.statement());
    Exception failReason = null;
    try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_DML_QRY_EXECUTE, MTC.span()))) {
        if (!dml.mvccEnabled() && !updateInTxAllowed && ctx.cache().context().tm().inUserTx()) {
            throw new IgniteSQLException("DML statements are not allowed inside a transaction over " + "cache(s) with TRANSACTIONAL atomicity mode (change atomicity mode to " + "TRANSACTIONAL_SNAPSHOT or disable this error message with system property " + "\"-DIGNITE_ALLOW_DML_INSIDE_TRANSACTION=true\")");
        }
        if (!qryDesc.local()) {
            return executeUpdateDistributed(qryId, qryDesc, qryParams, dml, cancel);
        } else {
            UpdateResult updRes = executeUpdate(qryId, qryDesc, qryParams, dml, true, filter, cancel);
            return singletonList(new QueryCursorImpl<>(new Iterable<List<?>>() {

                @Override
                public Iterator<List<?>> iterator() {
                    return new IgniteSingletonIterator<>(singletonList(updRes.counter()));
                }
            }, cancel, true, false));
        }
    } catch (IgniteException e) {
        failReason = e;
        throw e;
    } catch (IgniteCheckedException e) {
        failReason = e;
        IgniteClusterReadOnlyException roEx = X.cause(e, IgniteClusterReadOnlyException.class);
        if (roEx != null) {
            throw new IgniteSQLException("Failed to execute DML statement. Cluster in read-only mode [stmt=" + qryDesc.sql() + ", params=" + Arrays.deepToString(qryParams.arguments()) + "]", IgniteQueryErrorCode.CLUSTER_READ_ONLY_MODE_ENABLED, e);
        }
        throw new IgniteSQLException("Failed to execute DML statement [stmt=" + qryDesc.sql() + ", params=" + Arrays.deepToString(qryParams.arguments()) + "]", e);
    } finally {
        runningQryMgr.unregister(qryId, failReason);
    }
}
Also used : IgniteSingletonIterator(org.apache.ignite.internal.util.lang.IgniteSingletonIterator) IgniteClusterReadOnlyException(org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException) IndexingQueryFilter(org.apache.ignite.spi.indexing.IndexingQueryFilter) 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) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)112 SQLException (java.sql.SQLException)38 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)37 ArrayList (java.util.ArrayList)34 List (java.util.List)27 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)19 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)18 Column (org.h2.table.Column)18 IgniteException (org.apache.ignite.IgniteException)16 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)16 GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)12 BatchUpdateException (java.sql.BatchUpdateException)11 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)11 LinkedHashMap (java.util.LinkedHashMap)10 CacheException (javax.cache.CacheException)9 QueryCursorImpl (org.apache.ignite.internal.processors.cache.QueryCursorImpl)9 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)9 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)9 Connection (java.sql.Connection)8 PreparedStatement (java.sql.PreparedStatement)8