You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@ignite.apache.org by "korlov42 (via GitHub)" <gi...@apache.org> on 2024/10/29 17:03:54 UTC

[PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

korlov42 opened a new pull request, #4653:
URL: https://github.com/apache/ignite-3/pull/4653

   Thank you for submitting the pull request.
   
   To streamline the review process of the patch and ensure better code quality
   we ask both an author and a reviewer to verify the following:
   
   ### The Review Checklist
   - [ ] **Formal criteria:** TC status, codestyle, mandatory documentation. Also make sure to complete the following:  
   \- There is a single JIRA ticket related to the pull request.  
   \- The web-link to the pull request is attached to the JIRA ticket.  
   \- The JIRA ticket has the Patch Available state.  
   \- The description of the JIRA ticket explains WHAT was made, WHY and HOW.  
   \- The pull request title is treated as the final commit message. The following pattern must be used: IGNITE-XXXX Change summary where XXXX - number of JIRA issue.
   - [ ] **Design:** new code conforms with the design principles of the components it is added to.
   - [ ] **Patch quality:** patch cannot be split into smaller pieces, its size must be reasonable.
   - [ ] **Code quality:** code is clean and readable, necessary developer documentation is added if needed.
   - [ ] **Tests code quality:** test set covers positive/negative scenarios, happy/edge cases. Tests are effective in terms of execution time and resources.
   
   ### Notes
   - [Apache Ignite Coding Guidelines](https://cwiki.apache.org/confluence/display/IGNITE/Java+Code+Style+Guide)


-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "korlov42 (via GitHub)" <gi...@apache.org>.
korlov42 commented on code in PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#discussion_r1824304877


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/ParsingPhaseHandler.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.sql.engine.QueryProperty.ALLOWED_QUERY_TYPES;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+
+/** Parses the query string and populate {@link Query query state} with results. */
+class ParsingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new ParsingPhaseHandler();
+
+    private ParsingPhaseHandler() { }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult parsedResult = query.executor.lookupParsedResultInCache(query.sql);
+
+        if (parsedResult != null) {
+            query.parsedResult = parsedResult;
+
+            query.moveTo(ExecutionPhase.OPTIMIZING);
+
+            return Result.proceedImmediately();
+        }
+
+        CompletableFuture<Void> awaitFuture = new CompletableFuture<>();
+        query.executor.execute(() -> {
+            try {
+                ParsedResult result;
+                if (multiStatementQueryAllowed(query.properties)) {
+                    List<ParsedResult> results = query.executor.parseScript(query.sql);
+
+                    if (results.size() != 1 || results.get(0).queryType() == SqlQueryType.TX_CONTROL) {
+                        // the query is script indeed, need different execution path
+                        query.parsedScript = results;
+
+                        query.moveTo(ExecutionPhase.SCRIPT_INITIALIZATION);
+                        awaitFuture.complete(null);
+
+                        return;
+                    }
+
+                    result = results.get(0);
+                } else {
+                    result = query.executor.parse(query.sql);
+                }
+
+                if (shouldBeCached(result.queryType())) {
+                    query.executor.updateParsedResultCache(query.sql, result);
+                }
+
+                query.parsedResult = result;
+
+                query.moveTo(ExecutionPhase.OPTIMIZING);
+                awaitFuture.complete(null);
+            } catch (Throwable th) {
+                awaitFuture.completeExceptionally(th);
+            }
+        });
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    private static boolean shouldBeCached(SqlQueryType queryType) {
+        return queryType == SqlQueryType.QUERY || queryType == SqlQueryType.DML;
+    }
+
+    /** Returns {@code true} if the specified properties allow multi-statement query execution. */
+    private static boolean multiStatementQueryAllowed(SqlProperties properties) {

Review Comment:
   good catch! Replaced



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/OptimizingPhaseHandler.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
+import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR;
+import static org.apache.ignite.lang.ErrorGroups.Sql.STMT_VALIDATION_ERR;
+
+import java.time.ZoneId;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.sql.engine.QueryProperty;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.SqlQueryProcessor.PrefetchCallback;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.prepare.PrepareService;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionWrapper;
+import org.apache.ignite.internal.sql.engine.util.TypeUtils;
+import org.apache.ignite.sql.SqlException;
+
+/** Validates parsed AST acquired on the previous phase and submit optimization task to {@link PrepareService}. */
+class OptimizingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new OptimizingPhaseHandler();
+
+    private OptimizingPhaseHandler() {
+    }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult result = query.parsedResult;
+
+        assert result != null : "Query is expected to be parsed at this phase";
+
+        validateParsedStatement(query.properties, result);
+        validateDynamicParameters(result.dynamicParamsCount(), query.params, true);
+        ensureStatementMatchesTx(result.queryType(), query.txContext);
+
+        HybridTimestamp operationTime = query.executor.deriveOperationTime(query.txContext);
+
+        String schemaName = query.properties.get(QueryProperty.DEFAULT_SCHEMA);
+        ZoneId timeZoneId = query.properties.get(QueryProperty.TIME_ZONE_ID);
+
+        SqlOperationContext operationContext = SqlOperationContext.builder()
+                .queryId(query.id)
+                .cancel(query.cancel)
+                .prefetchCallback(new PrefetchCallback())
+                .parameters(query.params)
+                .timeZoneId(timeZoneId)
+                .defaultSchemaName(schemaName)
+                .operationTime(operationTime)
+                .txContext(query.txContext)
+                .txUsedListener(tx -> query.usedTransaction = tx)
+                .build();
+
+        query.operationContext = operationContext;
+
+        CompletableFuture<Void> awaitFuture = query.executor.waitForMetadata(operationTime)
+                .thenCompose(none -> query.executor.prepare(result, operationContext)
+                        .thenAccept(plan -> {
+                            if (query.txContext.explicitTx() == null) {
+                                // in case of implicit tx we have to update observable time to prevent tx manager to start
+                                // implicit transaction too much in the past where version of catalog we used to prepare the
+                                // plan was not yet available
+                                query.txContext.updateObservableTime(query.executor.deriveMinimalRequiredTime(plan));
+                            }
+
+                            query.plan = plan;
+
+                            query.moveTo(ExecutionPhase.CURSOR_INITIALIZATION);
+                        }));
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    /** Performs additional validation of a parsed statement. **/
+    private static void validateParsedStatement(
+            SqlProperties properties,
+            ParsedResult parsedResult
+    ) {
+        Set<SqlQueryType> allowedTypes = properties.get(QueryProperty.ALLOWED_QUERY_TYPES);
+        SqlQueryType queryType = parsedResult.queryType();
+
+        if (parsedResult.queryType() == SqlQueryType.TX_CONTROL) {
+            String message = "Transaction control statement can not be executed as an independent statement";
+
+            throw new SqlException(STMT_VALIDATION_ERR, message);
+        }
+
+        if (!allowedTypes.contains(queryType)) {
+            String message = format("Invalid SQL statement type. Expected {} but got {}", allowedTypes, queryType);
+
+            throw new SqlException(STMT_VALIDATION_ERR, message);
+        }
+    }
+
+    private static void validateDynamicParameters(int expectedParamsCount, Object[] params, boolean exactMatch) throws SqlException {

Review Comment:
   good catch! Moved all such validation to `ValidationHelper` in order to reuse it



-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "korlov42 (via GitHub)" <gi...@apache.org>.
korlov42 commented on code in PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#discussion_r1824304564


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/OptimizingPhaseHandler.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
+import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR;
+import static org.apache.ignite.lang.ErrorGroups.Sql.STMT_VALIDATION_ERR;
+
+import java.time.ZoneId;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.sql.engine.QueryProperty;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.SqlQueryProcessor.PrefetchCallback;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.prepare.PrepareService;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionWrapper;
+import org.apache.ignite.internal.sql.engine.util.TypeUtils;
+import org.apache.ignite.sql.SqlException;
+
+/** Validates parsed AST acquired on the previous phase and submit optimization task to {@link PrepareService}. */
+class OptimizingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new OptimizingPhaseHandler();
+
+    private OptimizingPhaseHandler() {
+    }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult result = query.parsedResult;
+
+        assert result != null : "Query is expected to be parsed at this phase";
+
+        validateParsedStatement(query.properties, result);
+        validateDynamicParameters(result.dynamicParamsCount(), query.params, true);
+        ensureStatementMatchesTx(result.queryType(), query.txContext);
+
+        HybridTimestamp operationTime = query.executor.deriveOperationTime(query.txContext);
+
+        String schemaName = query.properties.get(QueryProperty.DEFAULT_SCHEMA);
+        ZoneId timeZoneId = query.properties.get(QueryProperty.TIME_ZONE_ID);
+
+        SqlOperationContext operationContext = SqlOperationContext.builder()
+                .queryId(query.id)
+                .cancel(query.cancel)
+                .prefetchCallback(new PrefetchCallback())
+                .parameters(query.params)
+                .timeZoneId(timeZoneId)
+                .defaultSchemaName(schemaName)
+                .operationTime(operationTime)
+                .txContext(query.txContext)
+                .txUsedListener(tx -> query.usedTransaction = tx)
+                .build();
+
+        query.operationContext = operationContext;
+
+        CompletableFuture<Void> awaitFuture = query.executor.waitForMetadata(operationTime)
+                .thenCompose(none -> query.executor.prepare(result, operationContext)
+                        .thenAccept(plan -> {
+                            if (query.txContext.explicitTx() == null) {
+                                // in case of implicit tx we have to update observable time to prevent tx manager to start
+                                // implicit transaction too much in the past where version of catalog we used to prepare the
+                                // plan was not yet available
+                                query.txContext.updateObservableTime(query.executor.deriveMinimalRequiredTime(plan));
+                            }
+
+                            query.plan = plan;
+
+                            query.moveTo(ExecutionPhase.CURSOR_INITIALIZATION);
+                        }));
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    /** Performs additional validation of a parsed statement. **/
+    private static void validateParsedStatement(

Review Comment:
   good catch! Moved all such validation to `ValidationHelper` in order to reuse it



-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "lowka (via GitHub)" <gi...@apache.org>.
lowka commented on code in PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#discussion_r1824219615


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/Query.java:
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.apache.ignite.internal.sql.engine.AsyncSqlCursor;
+import org.apache.ignite.internal.sql.engine.InternalSqlRow;
+import org.apache.ignite.internal.sql.engine.QueryCancel;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.exec.fsm.Result.Status;
+import org.apache.ignite.internal.sql.engine.prepare.QueryPlan;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.tx.InternalTransaction;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Represents a query initiated on current node.
+ * 
+ * <p>Encapsulates intermediate state populated throughout query lifecycle.
+ */
+class Query implements Runnable {
+    // Below are attributes the query was initialized with
+    final Instant createdAt;
+    final @Nullable UUID parentId;
+    final int statementNum;
+    final UUID id;
+    final String sql;
+    final Object[] params;
+    final QueryCancel cancel = new QueryCancel();
+    final QueryExecutor executor;
+    final SqlProperties properties;
+    final QueryTransactionContext txContext;
+    final @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture;
+
+    // Below is volatile state populated during processing of particular stage for single statement execution
+    volatile @Nullable ParsedResult parsedResult = null;
+    volatile @Nullable SqlOperationContext operationContext = null;
+    volatile @Nullable QueryPlan plan = null;
+    volatile @Nullable InternalTransaction usedTransaction = null;
+    volatile @Nullable AsyncSqlCursor<InternalSqlRow> cursor = null;
+
+    // Below is volatile state for script processing
+    volatile @Nullable List<ParsedResult> parsedScript = null;
+
+    // Below are internal attributes
+    private final ConcurrentMap<ExecutionPhase, CompletableFuture<Void>> onPhaseStartedCallback = new ConcurrentHashMap<>();
+    private final Object mux = new Object();
+
+    private volatile ExecutionPhase currentPhase = ExecutionPhase.REGISTERED;
+
+    Query(
+            Instant createdAt,
+            QueryExecutor executor,
+            UUID id,
+            String sql,
+            SqlProperties properties,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = executor;
+        this.id = id;
+        this.sql = sql;
+        this.properties = properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parentId = null;
+        this.statementNum = -1;
+    }
+
+    Query(
+            Instant createdAt,
+            Query parent,
+            ParsedResult parsedResult,
+            int statementNum,
+            UUID id,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = parent.executor;
+        this.parentId = parent.id;
+        this.statementNum = statementNum;
+        this.id = id;
+        this.sql = parsedResult.originalQuery();
+        this.properties = parent.properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parsedResult = parsedResult;
+    }
+
+    @Override
+    public void run() {
+        Result result;
+        do {
+            ExecutionPhase phaseBefore = currentPhase;
+
+            try {
+                result = phaseBefore.evaluate(this);
+            } catch (Throwable th) {
+                // handles exception from synchronous part of phase evaluation
+
+                onError(th);
+
+                return;
+            }
+
+            if (IgniteUtils.assertionsEnabled()

Review Comment:
   I think this method can be simplified to something like this without additional extra steps after the while loop because it either schedules a next phase or terminates.
   
   ```
       @Override
       public void run() {
           Result result;
           do {
               ExecutionPhase phaseBefore = currentPhase;
   
               try {
                   result = phaseBefore.evaluate(this);
               } catch (Throwable th) {
                   // handles exception from synchronous part of phase evaluation
   
                   onError(th);
   
                   return;
               }
   
               switch (result.status()) {
                   case PROCEED_IMMEDIATELY:
                       checkCanProceedImmediately(result, phaseBefore);
                       break;
                   case SCHEDULE:
                       if (doSchedule(result)) {
                           return;
                       }
                       break;
                   case STOP:
                       return;
                   default:
                       throw new IllegalStateException("Unexpected status: " + result.status());
               }
           } while (true);
       }
   ```
   
   doSchedule (a hypothetical example)
   
   ```
      private boolean doSchedule(Result result) {
           CompletableFuture<Void> awaitFuture = result.await();
           assert awaitFuture != null;
   
           // reschedule only if required computation has not been done yet or it was completed exceptionally
           if (!awaitFuture.isDone() || awaitFuture.isCompletedExceptionally()) {
               awaitFuture.whenComplete((ignored, ex) -> {
                           if (ex != null) {
                               // handles exception from asynchronous part of phase evaluation
                               onError(ex);
                           }
                       })
                       .thenRun(this);
               return true;
           } else {
               return false;
           }
       }
   ```



-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "korlov42 (via GitHub)" <gi...@apache.org>.
korlov42 commented on code in PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#discussion_r1824314426


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/Query.java:
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.apache.ignite.internal.sql.engine.AsyncSqlCursor;
+import org.apache.ignite.internal.sql.engine.InternalSqlRow;
+import org.apache.ignite.internal.sql.engine.QueryCancel;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.exec.fsm.Result.Status;
+import org.apache.ignite.internal.sql.engine.prepare.QueryPlan;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.tx.InternalTransaction;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Represents a query initiated on current node.
+ * 
+ * <p>Encapsulates intermediate state populated throughout query lifecycle.
+ */
+class Query implements Runnable {
+    // Below are attributes the query was initialized with
+    final Instant createdAt;
+    final @Nullable UUID parentId;
+    final int statementNum;
+    final UUID id;
+    final String sql;
+    final Object[] params;
+    final QueryCancel cancel = new QueryCancel();
+    final QueryExecutor executor;
+    final SqlProperties properties;
+    final QueryTransactionContext txContext;
+    final @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture;
+
+    // Below is volatile state populated during processing of particular stage for single statement execution
+    volatile @Nullable ParsedResult parsedResult = null;
+    volatile @Nullable SqlOperationContext operationContext = null;
+    volatile @Nullable QueryPlan plan = null;
+    volatile @Nullable InternalTransaction usedTransaction = null;
+    volatile @Nullable AsyncSqlCursor<InternalSqlRow> cursor = null;
+
+    // Below is volatile state for script processing
+    volatile @Nullable List<ParsedResult> parsedScript = null;
+
+    // Below are internal attributes
+    private final ConcurrentMap<ExecutionPhase, CompletableFuture<Void>> onPhaseStartedCallback = new ConcurrentHashMap<>();
+    private final Object mux = new Object();
+
+    private volatile ExecutionPhase currentPhase = ExecutionPhase.REGISTERED;
+
+    Query(
+            Instant createdAt,
+            QueryExecutor executor,
+            UUID id,
+            String sql,
+            SqlProperties properties,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = executor;
+        this.id = id;
+        this.sql = sql;
+        this.properties = properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parentId = null;
+        this.statementNum = -1;
+    }
+
+    Query(
+            Instant createdAt,
+            Query parent,
+            ParsedResult parsedResult,
+            int statementNum,
+            UUID id,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = parent.executor;
+        this.parentId = parent.id;
+        this.statementNum = statementNum;
+        this.id = id;
+        this.sql = parsedResult.originalQuery();
+        this.properties = parent.properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parsedResult = parsedResult;
+    }
+
+    @Override
+    public void run() {
+        Result result;
+        do {
+            ExecutionPhase phaseBefore = currentPhase;
+
+            try {
+                result = phaseBefore.evaluate(this);
+            } catch (Throwable th) {
+                // handles exception from synchronous part of phase evaluation
+
+                onError(th);
+
+                return;
+            }
+
+            if (IgniteUtils.assertionsEnabled()

Review Comment:
   I moved step after loop inside the loop bod, but decided not to derive it to distinct method. Intuitively, I would expect from method with name `doSomething` and returning boolean to return status of operation. And this is not clear why should we proceed immediately if we were unable to schedule task (I believe the general pattern is to fail in such cases)



-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "AMashenkov (via GitHub)" <gi...@apache.org>.
AMashenkov commented on PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#issuecomment-2447498773

   However, I don't like the idea when a stage knows about and triggers the next stage, but it is ok for now.
   Looking forward to the feature, when we could schedule some plans for background optimization to find better plan, we might need more control over FSM state transitions and stop the process after optimization stage. 
   
   Anyway, the PR looks great and makes code much better for understanding.


-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "korlov42 (via GitHub)" <gi...@apache.org>.
korlov42 merged PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653


-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] IGNITE-23544 Sql. Rework query execution pipeline [ignite-3]

Posted by "lowka (via GitHub)" <gi...@apache.org>.
lowka commented on code in PR #4653:
URL: https://github.com/apache/ignite-3/pull/4653#discussion_r1824195568


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/ParsingPhaseHandler.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.sql.engine.QueryProperty.ALLOWED_QUERY_TYPES;
+
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+
+/** Parses the query string and populate {@link Query query state} with results. */
+class ParsingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new ParsingPhaseHandler();
+
+    private ParsingPhaseHandler() { }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult parsedResult = query.executor.lookupParsedResultInCache(query.sql);
+
+        if (parsedResult != null) {
+            query.parsedResult = parsedResult;
+
+            query.moveTo(ExecutionPhase.OPTIMIZING);
+
+            return Result.proceedImmediately();
+        }
+
+        CompletableFuture<Void> awaitFuture = new CompletableFuture<>();
+        query.executor.execute(() -> {
+            try {
+                ParsedResult result;
+                if (multiStatementQueryAllowed(query.properties)) {
+                    List<ParsedResult> results = query.executor.parseScript(query.sql);
+
+                    if (results.size() != 1 || results.get(0).queryType() == SqlQueryType.TX_CONTROL) {
+                        // the query is script indeed, need different execution path
+                        query.parsedScript = results;
+
+                        query.moveTo(ExecutionPhase.SCRIPT_INITIALIZATION);
+                        awaitFuture.complete(null);
+
+                        return;
+                    }
+
+                    result = results.get(0);
+                } else {
+                    result = query.executor.parse(query.sql);
+                }
+
+                if (shouldBeCached(result.queryType())) {
+                    query.executor.updateParsedResultCache(query.sql, result);
+                }
+
+                query.parsedResult = result;
+
+                query.moveTo(ExecutionPhase.OPTIMIZING);
+                awaitFuture.complete(null);
+            } catch (Throwable th) {
+                awaitFuture.completeExceptionally(th);
+            }
+        });
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    private static boolean shouldBeCached(SqlQueryType queryType) {
+        return queryType == SqlQueryType.QUERY || queryType == SqlQueryType.DML;
+    }
+
+    /** Returns {@code true} if the specified properties allow multi-statement query execution. */
+    private static boolean multiStatementQueryAllowed(SqlProperties properties) {

Review Comment:
   Perhaps we can use `Commons::isMultiStatementQueryAllowed` here ? 



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/Query.java:
##########
@@ -0,0 +1,199 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.apache.ignite.internal.sql.engine.AsyncSqlCursor;
+import org.apache.ignite.internal.sql.engine.InternalSqlRow;
+import org.apache.ignite.internal.sql.engine.QueryCancel;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.exec.fsm.Result.Status;
+import org.apache.ignite.internal.sql.engine.prepare.QueryPlan;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.tx.InternalTransaction;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Represents a query initiated on current node.
+ * 
+ * <p>Encapsulates intermediate state populated throughout query lifecycle.
+ */
+class Query implements Runnable {
+    // Below are attributes the query was initialized with
+    final Instant createdAt;
+    final @Nullable UUID parentId;
+    final int statementNum;
+    final UUID id;
+    final String sql;
+    final Object[] params;
+    final QueryCancel cancel = new QueryCancel();
+    final QueryExecutor executor;
+    final SqlProperties properties;
+    final QueryTransactionContext txContext;
+    final @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture;
+
+    // Below is volatile state populated during processing of particular stage for single statement execution
+    volatile @Nullable ParsedResult parsedResult = null;
+    volatile @Nullable SqlOperationContext operationContext = null;
+    volatile @Nullable QueryPlan plan = null;
+    volatile @Nullable InternalTransaction usedTransaction = null;
+    volatile @Nullable AsyncSqlCursor<InternalSqlRow> cursor = null;
+
+    // Below is volatile state for script processing
+    volatile @Nullable List<ParsedResult> parsedScript = null;
+
+    // Below are internal attributes
+    private final ConcurrentMap<ExecutionPhase, CompletableFuture<Void>> onPhaseStartedCallback = new ConcurrentHashMap<>();
+    private final Object mux = new Object();
+
+    private volatile ExecutionPhase currentPhase = ExecutionPhase.REGISTERED;
+
+    Query(
+            Instant createdAt,
+            QueryExecutor executor,
+            UUID id,
+            String sql,
+            SqlProperties properties,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = executor;
+        this.id = id;
+        this.sql = sql;
+        this.properties = properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parentId = null;
+        this.statementNum = -1;
+    }
+
+    Query(
+            Instant createdAt,
+            Query parent,
+            ParsedResult parsedResult,
+            int statementNum,
+            UUID id,
+            QueryTransactionContext txContext,
+            Object[] params,
+            @Nullable CompletableFuture<AsyncSqlCursor<InternalSqlRow>> nextCursorFuture
+    ) {
+        this.createdAt = createdAt;
+        this.executor = parent.executor;
+        this.parentId = parent.id;
+        this.statementNum = statementNum;
+        this.id = id;
+        this.sql = parsedResult.originalQuery();
+        this.properties = parent.properties;
+        this.txContext = txContext;
+        this.params = params;
+        this.nextCursorFuture = nextCursorFuture;
+
+        this.parsedResult = parsedResult;
+    }
+
+    @Override
+    public void run() {
+        Result result;
+        do {
+            ExecutionPhase phaseBefore = currentPhase;
+
+            try {
+                result = phaseBefore.evaluate(this);
+            } catch (Throwable th) {
+                // handles exception from synchronous part of phase evaluation
+
+                onError(th);
+
+                return;
+            }
+
+            if (IgniteUtils.assertionsEnabled()

Review Comment:
   I think this method can be simplified to something like without additional extra steps after the while loop because it either schedules a next phase or terminates.
   
   ```
       @Override
       public void run() {
           Result result;
           do {
               ExecutionPhase phaseBefore = currentPhase;
   
               try {
                   result = phaseBefore.evaluate(this);
               } catch (Throwable th) {
                   // handles exception from synchronous part of phase evaluation
   
                   onError(th);
   
                   return;
               }
   
               switch (result.status()) {
                   case PROCEED_IMMEDIATELY:
                       checkCanProceedImmediately(result, phaseBefore);
                       break;
                   case SCHEDULE:
                       if (doSchedule(result)) {
                           return;
                       }
                       break;
                   case STOP:
                       return;
                   default:
                       throw new IllegalStateException("Unexpected status: " + result.status());
               }
           } while (true);
       }
   ```
   
   doSchedule (a hypothetical example)
   
   ```
      private boolean doSchedule(Result result) {
           CompletableFuture<Void> awaitFuture = result.await();
           assert awaitFuture != null;
   
           // reschedule only if required computation has not been done yet or it was completed exceptionally
           if (!awaitFuture.isDone() || awaitFuture.isCompletedExceptionally()) {
               awaitFuture.whenComplete((ignored, ex) -> {
                           if (ex != null) {
                               // handles exception from asynchronous part of phase evaluation
                               onError(ex);
                           }
                       })
                       .thenRun(this);
               return true;
           } else {
               return false;
           }
       }
   ```



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/OptimizingPhaseHandler.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
+import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR;
+import static org.apache.ignite.lang.ErrorGroups.Sql.STMT_VALIDATION_ERR;
+
+import java.time.ZoneId;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.sql.engine.QueryProperty;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.SqlQueryProcessor.PrefetchCallback;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.prepare.PrepareService;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionWrapper;
+import org.apache.ignite.internal.sql.engine.util.TypeUtils;
+import org.apache.ignite.sql.SqlException;
+
+/** Validates parsed AST acquired on the previous phase and submit optimization task to {@link PrepareService}. */
+class OptimizingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new OptimizingPhaseHandler();
+
+    private OptimizingPhaseHandler() {
+    }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult result = query.parsedResult;
+
+        assert result != null : "Query is expected to be parsed at this phase";
+
+        validateParsedStatement(query.properties, result);
+        validateDynamicParameters(result.dynamicParamsCount(), query.params, true);
+        ensureStatementMatchesTx(result.queryType(), query.txContext);
+
+        HybridTimestamp operationTime = query.executor.deriveOperationTime(query.txContext);
+
+        String schemaName = query.properties.get(QueryProperty.DEFAULT_SCHEMA);
+        ZoneId timeZoneId = query.properties.get(QueryProperty.TIME_ZONE_ID);
+
+        SqlOperationContext operationContext = SqlOperationContext.builder()
+                .queryId(query.id)
+                .cancel(query.cancel)
+                .prefetchCallback(new PrefetchCallback())
+                .parameters(query.params)
+                .timeZoneId(timeZoneId)
+                .defaultSchemaName(schemaName)
+                .operationTime(operationTime)
+                .txContext(query.txContext)
+                .txUsedListener(tx -> query.usedTransaction = tx)
+                .build();
+
+        query.operationContext = operationContext;
+
+        CompletableFuture<Void> awaitFuture = query.executor.waitForMetadata(operationTime)
+                .thenCompose(none -> query.executor.prepare(result, operationContext)
+                        .thenAccept(plan -> {
+                            if (query.txContext.explicitTx() == null) {
+                                // in case of implicit tx we have to update observable time to prevent tx manager to start
+                                // implicit transaction too much in the past where version of catalog we used to prepare the
+                                // plan was not yet available
+                                query.txContext.updateObservableTime(query.executor.deriveMinimalRequiredTime(plan));
+                            }
+
+                            query.plan = plan;
+
+                            query.moveTo(ExecutionPhase.CURSOR_INITIALIZATION);
+                        }));
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    /** Performs additional validation of a parsed statement. **/
+    private static void validateParsedStatement(

Review Comment:
   Looks like this function duplicates the `validateParsedStatement` from the `SqlQueryProcessor`. Perhaps it would be better to define this function once.



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/exec/fsm/OptimizingPhaseHandler.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.sql.engine.exec.fsm;
+
+import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
+import static org.apache.ignite.lang.ErrorGroups.Sql.RUNTIME_ERR;
+import static org.apache.ignite.lang.ErrorGroups.Sql.STMT_VALIDATION_ERR;
+
+import java.time.ZoneId;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.sql.engine.QueryProperty;
+import org.apache.ignite.internal.sql.engine.SqlOperationContext;
+import org.apache.ignite.internal.sql.engine.SqlQueryProcessor.PrefetchCallback;
+import org.apache.ignite.internal.sql.engine.SqlQueryType;
+import org.apache.ignite.internal.sql.engine.prepare.PrepareService;
+import org.apache.ignite.internal.sql.engine.property.SqlProperties;
+import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionContext;
+import org.apache.ignite.internal.sql.engine.tx.QueryTransactionWrapper;
+import org.apache.ignite.internal.sql.engine.util.TypeUtils;
+import org.apache.ignite.sql.SqlException;
+
+/** Validates parsed AST acquired on the previous phase and submit optimization task to {@link PrepareService}. */
+class OptimizingPhaseHandler implements ExecutionPhaseHandler {
+    static final ExecutionPhaseHandler INSTANCE = new OptimizingPhaseHandler();
+
+    private OptimizingPhaseHandler() {
+    }
+
+    @Override
+    public Result handle(Query query) {
+        ParsedResult result = query.parsedResult;
+
+        assert result != null : "Query is expected to be parsed at this phase";
+
+        validateParsedStatement(query.properties, result);
+        validateDynamicParameters(result.dynamicParamsCount(), query.params, true);
+        ensureStatementMatchesTx(result.queryType(), query.txContext);
+
+        HybridTimestamp operationTime = query.executor.deriveOperationTime(query.txContext);
+
+        String schemaName = query.properties.get(QueryProperty.DEFAULT_SCHEMA);
+        ZoneId timeZoneId = query.properties.get(QueryProperty.TIME_ZONE_ID);
+
+        SqlOperationContext operationContext = SqlOperationContext.builder()
+                .queryId(query.id)
+                .cancel(query.cancel)
+                .prefetchCallback(new PrefetchCallback())
+                .parameters(query.params)
+                .timeZoneId(timeZoneId)
+                .defaultSchemaName(schemaName)
+                .operationTime(operationTime)
+                .txContext(query.txContext)
+                .txUsedListener(tx -> query.usedTransaction = tx)
+                .build();
+
+        query.operationContext = operationContext;
+
+        CompletableFuture<Void> awaitFuture = query.executor.waitForMetadata(operationTime)
+                .thenCompose(none -> query.executor.prepare(result, operationContext)
+                        .thenAccept(plan -> {
+                            if (query.txContext.explicitTx() == null) {
+                                // in case of implicit tx we have to update observable time to prevent tx manager to start
+                                // implicit transaction too much in the past where version of catalog we used to prepare the
+                                // plan was not yet available
+                                query.txContext.updateObservableTime(query.executor.deriveMinimalRequiredTime(plan));
+                            }
+
+                            query.plan = plan;
+
+                            query.moveTo(ExecutionPhase.CURSOR_INITIALIZATION);
+                        }));
+
+        return Result.proceedAfter(awaitFuture);
+    }
+
+    /** Performs additional validation of a parsed statement. **/
+    private static void validateParsedStatement(
+            SqlProperties properties,
+            ParsedResult parsedResult
+    ) {
+        Set<SqlQueryType> allowedTypes = properties.get(QueryProperty.ALLOWED_QUERY_TYPES);
+        SqlQueryType queryType = parsedResult.queryType();
+
+        if (parsedResult.queryType() == SqlQueryType.TX_CONTROL) {
+            String message = "Transaction control statement can not be executed as an independent statement";
+
+            throw new SqlException(STMT_VALIDATION_ERR, message);
+        }
+
+        if (!allowedTypes.contains(queryType)) {
+            String message = format("Invalid SQL statement type. Expected {} but got {}", allowedTypes, queryType);
+
+            throw new SqlException(STMT_VALIDATION_ERR, message);
+        }
+    }
+
+    private static void validateDynamicParameters(int expectedParamsCount, Object[] params, boolean exactMatch) throws SqlException {

Review Comment:
   Looks like this function is written 3 times - here, in the `SqlQueryProcessor` and in the `MultistatementHandler`).
   Perhaps it would be better to have a single definition.



-- 
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: notifications-unsubscribe@ignite.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org