Copilot commented on code in PR #13915:
URL: https://github.com/apache/ignite/pull/13915#discussion_r4800294755
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlannerHelper.java:
##########
@@ -141,6 +149,18 @@ public static IgniteRel optimize(SqlNode sqlNode,
IgnitePlanner planner, IgniteL
rel = planner.transform(PlannerPhase.HEP_PROJECT_PUSH_DOWN,
rel.getTraitSet(), rel);
+ SqlFieldsQuery fieldsQueryCtx = ctx.unwrap(SqlFieldsQuery.class);
+
+ if (sqlNode.getKind() == SqlKind.INSERT && (fieldsQueryCtx == null
|| F.isEmpty(fieldsQueryCtx.getPartitions()))) {
Review Comment:
This partition guard is bypassed on plan-cache hits because
`CalciteQueryProcessor.contextKey()` does not include partition presence. An
INSERT cached without partitions can therefore reuse its `KeyValueModifyPlan`
with `setPartitions(...)`, skipping the required fallback. Include partition
presence in the cache key, or reprepare incompatible cached plans, and test
both execution orders.
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -569,6 +584,124 @@ private FragmentPlan prepareFragment(BaseQueryContext
ctx, String jsonFragment)
}
}
+ /**
+ * Executes a simple modify operation (single row INSERT) by a single
key-value cache operation on the initiator
+ * node, bypassing fragments mapping and execution nodes tree building.
+ */
+ private FieldsQueryCursor<List<?>> executeKeyValueModify(RootQuery<Row>
qry, KeyValueModifyPlan plan) {
+ IgniteKeyValueModify rel = plan.modifyNode();
+
+ IgniteCacheTable tbl = rel.getTable().unwrap(IgniteCacheTable.class);
+ CacheTableDescriptor desc =
rel.getTable().unwrap(CacheTableDescriptor.class);
+
+ if (tbl == null || desc == null)
+ throw new IllegalArgumentException("Unexpected: table=" + tbl + ",
descriptor=" + desc);
+
+ if (ctx.security().enabled())
+ tbl.authorize(IgniteTable.Operation.PUT);
+
+ long timeout = qry.remainingTime();
+
+ if (timeout == 0) {
+ throw new IgniteSQLException("The query was cancelled due to
timeout", IgniteQueryErrorCode.QUERY_CANCELED,
+ new QueryCancelledException());
+ }
+
+ tbl.ensureCacheStarted();
+
+ ExecutionContext<Row> ectx = new ExecutionContext<>(
+ qry.context(),
+ taskExecutor(),
+ injectSvc,
+ qry.id(),
+ locNodeId,
+ locNodeId,
+ topologyVersion(),
+ KEY_VALUE_FRAGMENT_DESC,
+ handler,
+ NoOpMemoryTracker.INSTANCE,
+ NoOpIoTracker.INSTANCE,
+ timeout,
+ Commons.parametersMap(qry.parameters()),
+ null);
+
+ List<RexNode> expressions = rel.expressions();
+
+ Row row;
+ ModifyTuple tuple;
+
+ try {
+ if (expressions.stream().allMatch(e -> e instanceof RexLiteral)) {
+ // Literals don't require expressions compilation.
+ RelDataType rowType =
RexUtil.createStructType(ectx.getTypeFactory(), expressions);
+
+ row =
F.first(ectx.expressionFactory().values(Commons.cast(expressions), rowType));
+ }
+ else
+ row = ectx.expressionFactory().rowSource(expressions).get();
+
+ tuple = desc.toTuple(ectx, row, TableModify.Operation.INSERT,
null);
+ }
+ catch (IgniteSQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new IgniteSQLException(EXECUTING_ERR_PREFIX +
e.getMessage(), IgniteQueryErrorCode.UNKNOWN, e);
+ }
+
+ GridCacheContext<?, ?> cctx = desc.cacheContext();
+ IgniteInternalCache<Object, Object> cache = cctx.cache().keepBinary();
+
+ QueryProperties props = qry.context().unwrap(QueryProperties.class);
+
+ if (props == null || props.keepBinary())
+ cache = cache.withKeepBinaryInInterceptor();
+
+ SessionContextImpl sesCtx =
qry.context().unwrap(SessionContextImpl.class);
+
+ if (sesCtx != null && sesCtx.attributes() != null)
+ cache = cache.withApplicationAttributes(sesCtx.attributes());
+
+ cache = cacheForDML(cache);
+
+ boolean inserted;
+
+ try {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null)
+ inserted = cache.putIfAbsent(tuple.getKey(), tuple.getValue());
Review Comment:
With transaction-aware queries disabled, the caller's transaction remains
attached but `Commons.queryTransaction()` returns null. This synchronous
`putIfAbsent` then enlists the INSERT in that ambient transaction, so rolling
it back unexpectedly removes the inserted row. Suspend and restore the ambient
transaction in this branch, while preserving the explicit transaction-aware
branch.
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -569,6 +584,124 @@ private FragmentPlan prepareFragment(BaseQueryContext
ctx, String jsonFragment)
}
}
+ /**
+ * Executes a simple modify operation (single row INSERT) by a single
key-value cache operation on the initiator
+ * node, bypassing fragments mapping and execution nodes tree building.
+ */
+ private FieldsQueryCursor<List<?>> executeKeyValueModify(RootQuery<Row>
qry, KeyValueModifyPlan plan) {
+ IgniteKeyValueModify rel = plan.modifyNode();
+
+ IgniteCacheTable tbl = rel.getTable().unwrap(IgniteCacheTable.class);
+ CacheTableDescriptor desc =
rel.getTable().unwrap(CacheTableDescriptor.class);
+
+ if (tbl == null || desc == null)
+ throw new IllegalArgumentException("Unexpected: table=" + tbl + ",
descriptor=" + desc);
+
+ if (ctx.security().enabled())
+ tbl.authorize(IgniteTable.Operation.PUT);
+
+ long timeout = qry.remainingTime();
+
+ if (timeout == 0) {
+ throw new IgniteSQLException("The query was cancelled due to
timeout", IgniteQueryErrorCode.QUERY_CANCELED,
+ new QueryCancelledException());
+ }
+
+ tbl.ensureCacheStarted();
+
+ ExecutionContext<Row> ectx = new ExecutionContext<>(
+ qry.context(),
+ taskExecutor(),
+ injectSvc,
+ qry.id(),
+ locNodeId,
+ locNodeId,
+ topologyVersion(),
+ KEY_VALUE_FRAGMENT_DESC,
+ handler,
+ NoOpMemoryTracker.INSTANCE,
+ NoOpIoTracker.INSTANCE,
+ timeout,
+ Commons.parametersMap(qry.parameters()),
+ null);
+
+ List<RexNode> expressions = rel.expressions();
+
+ Row row;
+ ModifyTuple tuple;
+
+ try {
+ if (expressions.stream().allMatch(e -> e instanceof RexLiteral)) {
+ // Literals don't require expressions compilation.
+ RelDataType rowType =
RexUtil.createStructType(ectx.getTypeFactory(), expressions);
+
+ row =
F.first(ectx.expressionFactory().values(Commons.cast(expressions), rowType));
+ }
+ else
+ row = ectx.expressionFactory().rowSource(expressions).get();
+
+ tuple = desc.toTuple(ectx, row, TableModify.Operation.INSERT,
null);
+ }
+ catch (IgniteSQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new IgniteSQLException(EXECUTING_ERR_PREFIX +
e.getMessage(), IgniteQueryErrorCode.UNKNOWN, e);
+ }
+
+ GridCacheContext<?, ?> cctx = desc.cacheContext();
+ IgniteInternalCache<Object, Object> cache = cctx.cache().keepBinary();
+
+ QueryProperties props = qry.context().unwrap(QueryProperties.class);
+
+ if (props == null || props.keepBinary())
+ cache = cache.withKeepBinaryInInterceptor();
+
+ SessionContextImpl sesCtx =
qry.context().unwrap(SessionContextImpl.class);
+
+ if (sesCtx != null && sesCtx.attributes() != null)
+ cache = cache.withApplicationAttributes(sesCtx.attributes());
+
+ cache = cacheForDML(cache);
+
+ boolean inserted;
+
+ try {
+ GridNearTxLocal userTx = Commons.queryTransaction(qry.context(),
ctx.cache().context());
+
+ if (userTx == null)
+ inserted = cache.putIfAbsent(tuple.getKey(), tuple.getValue());
Review Comment:
The synchronous `putIfAbsent` calls do not observe SQL cancellation or the
deadline checked before cache startup and expression evaluation. A write
blocked on a key lock can outlast the timeout or be cancelled yet still return
a successful update count, because this execution context is not connected to
query cancellation. Integrate both transaction branches with
cancellation-aware, deadline-bounded waiting and check query state before
mutation and before returning success.
##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/TableModifyToKeyValuePutRule.java:
##########
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.query.calcite.rule;
+
+import java.util.List;
+import com.google.common.collect.ImmutableList;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.core.TableModify;
+import org.apache.calcite.rel.core.Values;
+import org.apache.calcite.rel.logical.LogicalProject;
+import org.apache.calcite.rel.logical.LogicalTableModify;
+import org.apache.calcite.rel.logical.LogicalValues;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.sql.validate.SqlUserDefinedFunction;
+import org.apache.calcite.util.ControlFlowException;
+import org.apache.calcite.util.Util;
+import
org.apache.ignite.internal.processors.query.calcite.rel.IgniteConvention;
+import
org.apache.ignite.internal.processors.query.calcite.rel.IgniteKeyValueModify;
+import
org.apache.ignite.internal.processors.query.calcite.schema.CacheTableDescriptor;
+import
org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions;
+import org.apache.ignite.internal.processors.query.calcite.util.RexUtils;
+import org.apache.ignite.internal.util.typedef.F;
+import org.immutables.value.Value;
+
+/**
+ * Rule that converts {@link TableModify} representing INSERT operation with a
determined source (single tuple
+ * of values, optionally with a projection on top of it) to a key-value PUT
operation.
+ *
+ * <p>Note: at the moment, this rule supports only single row insert.
+ */
[email protected]
+public class TableModifyToKeyValuePutRule extends
RelRule<TableModifyToKeyValuePutRule.Config> {
+ /** Instance for INSERT with VALUES source. */
+ public static final RelOptRule VALUES = Config.VALUES.toRule();
+
+ /** Instance for INSERT with projection over VALUES source. */
+ public static final RelOptRule PROJECT = Config.PROJECT.toRule();
+
+ /** */
+ private TableModifyToKeyValuePutRule(Config cfg) {
+ super(cfg);
+ }
+
+ /** {@inheritDoc} */
+ @Override public void onMatch(RelOptRuleCall call) {
+ LogicalTableModify modify = call.rel(0);
+
+ List<RexNode> expressions;
+
+ if (call.getRelList().size() == 2) {
+ // Currently this branch is not involved,
https://issues.apache.org/jira/browse/IGNITE-29382
+ LogicalValues values = call.rel(1);
+
+ expressions = cast(values.getTuples().get(0));
+ }
+ else {
+ LogicalProject project = call.rel(1);
+ LogicalValues values = call.rel(2);
+
+ if (!Values.isSingleValue(values))
+ return;
+
+ ImmutableList<RexLiteral> inputExpressions =
F.first(values.getTuples());
+
+ try {
+ expressions = new RexShuttle() {
+ @Override public RexNode visitInputRef(RexInputRef
inputRef) {
+ return inputExpressions.get(inputRef.getIndex());
+ }
+
+ @Override public RexNode visitCall(RexCall call) {
+ if (call.getOperator() instanceof
SqlUserDefinedFunction)
+ throw Util.FoundOne.NULL; // UDF not supported, it
can be pushed as single fragment to server node.
+
+ return super.visitCall(call);
+ }
+ }.apply(project.getProjects());
+ }
+ catch (ControlFlowException ignored) {
+ // Fall back.
+ return;
+ }
+ }
+
+ call.transformTo(
+ new IgniteKeyValueModify(
+ modify.getCluster(),
+
modify.getCluster().traitSetOf(IgniteConvention.INSTANCE).replace(IgniteDistributions.single()),
+ modify.getTable(),
+ IgniteKeyValueModify.Operation.PUT,
+ expressions
+ )
+ );
+ }
+
+ /** */
+ private static <T> T cast(Object src) {
+ return (T)src;
+ }
+
+ /** */
+ private static boolean supported(LogicalTableModify modify) {
+ return modify.isInsert() &&
modify.getTable().unwrap(CacheTableDescriptor.class) != null;
Review Comment:
This rule also selects caches with interceptors, but an atomic cache's
`putIfAbsent` returns false when `onBeforePut()` cancels the write, even if the
key is absent. The fast path then incorrectly reports `DUPLICATE_KEY`, whereas
the regular entry processor preserves its insertion result. Exclude
interceptor-backed caches from this optimization to retain the existing
behavior.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]