Copilot commented on code in PR #13915:
URL: https://github.com/apache/ignite/pull/13915#discussion_r4798325678


##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlannerHelper.java:
##########
@@ -141,6 +142,16 @@ public static IgniteRel optimize(SqlNode sqlNode, 
IgnitePlanner planner, IgniteL
 
             rel = planner.transform(PlannerPhase.HEP_PROJECT_PUSH_DOWN, 
rel.getTraitSet(), rel);
 
+            if (sqlNode.getKind() == SqlKind.INSERT) {
+                // Try to convert the tree to a simple key-value operation. 
The result of this phase must not be passed
+                // to the next stages: if the whole tree was collapsed to a 
single key-value node, return it right away,
+                // otherwise discard the result and proceed with the regular 
flow.
+                RelNode simpleOperation = 
planner.transform(PlannerPhase.HEP_TO_SIMPLE_KEY_VALUE_OPERATION, 
rel.getTraitSet(), rel);
+
+                if (simpleOperation instanceof IgniteKeyValueModify)
+                    return (IgniteRel)simpleOperation;
+            }

Review Comment:
   The new optimization does not account for 
`SqlFieldsQuery.setPartitions(...)`. Regular plans apply the requested 
partition filter during mapping, but `executeKeyValueModify` performs 
`putIfAbsent` directly from the initiator, so a single-row INSERT can modify a 
key whose affinity partition is not selected. Skip this optimization when 
explicit partitions are present, or enforce the partition constraint before 
executing the cache operation.



##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ExecutionServiceImpl.java:
##########
@@ -569,6 +584,119 @@ 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 (Exception e) {
+            throw new IgniteSQLException(EXECUTING_ERR_PREFIX + 
e.getMessage(), IgniteQueryErrorCode.UNKNOWN, e);

Review Comment:
   `CacheTableDescriptorImpl.toTuple` can throw an `IgniteSQLException` with a 
specific status (for example `NULL_KEY`, `NULL_VALUE`, or a length/precision 
error). Catching it here and rewrapping it as `UNKNOWN` discards that status, 
unlike the regular DML path, which preserves `IgniteSQLException` in 
`RootNode.checkException`. Re-throw existing `IgniteSQLException` instances 
before wrapping other exceptions.



##########
modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/TableModifyToKeyValuePutRule.java:
##########
@@ -0,0 +1,162 @@
+/*
+ * 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);

Review Comment:
   This rule can still convert an uncorrelated scalar subquery in a VALUES 
expression because `RexSubQuery` is not a `SqlUserDefinedFunction` and 
`RexUtils.hasCorrelation` does not reject uncorrelated subqueries. The direct 
executor then sends that expression to `RexToLixTranslator`, whose 
`visitSubQuery` unconditionally throws, so valid statements such as `INSERT ... 
VALUES ((SELECT SUM(...)))` take the optimized path and fail instead of falling 
back to the regular plan. Reject `RexSubQuery` (including nested occurrences) 
here or otherwise leave such expressions on the regular execution path.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/QueryCursorImpl.java:
##########
@@ -177,21 +178,26 @@ private void closeIter() {
      * @param fieldsMeta SQL Fields query result metadata.
      */
     public void fieldsMeta(List<GridQueryFieldMetadata> fieldsMeta) {
+        fieldsMeta(() -> fieldsMeta);
+    }
+
+    /** @param fieldsMeta SQL Fields query result metadata supplier. */
+    public void fieldsMeta(Supplier<List<GridQueryFieldMetadata>> fieldsMeta) {
         this.fieldsMeta = fieldsMeta;
     }
 
     /**
      * @return SQL Fields query result metadata.
      */
     @Override public List<GridQueryFieldMetadata> fieldsMeta() {
-        return fieldsMeta;
+        return fieldsMeta.get();

Review Comment:
   This changes the no-metadata behavior of `QueryCursorImpl`: scan/index 
cursors are also constructed without calling `fieldsMeta(...)`, and the 
previous implementation returned `null` from `fieldsMeta()` for those cursors. 
Dereferencing the unset supplier now causes an NPE when that metadata method is 
queried; preserve the nullable result here.



-- 
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]

Reply via email to