betodealmeida commented on code in PR #36529:
URL: https://github.com/apache/superset/pull/36529#discussion_r2619938649


##########
superset/sql/execution/celery_task.py:
##########
@@ -0,0 +1,473 @@
+# 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.
+"""
+Celery task for async SQL execution.
+
+This module provides the Celery task for executing SQL queries asynchronously.
+It is used by SQLExecutor.execute_async() to run queries in the background.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import logging
+import uuid
+from typing import Any, TYPE_CHECKING
+
+import msgpack
+from celery.exceptions import SoftTimeLimitExceeded
+from flask import current_app as app, has_app_context
+from flask_babel import gettext as __
+
+from superset import (
+    db,
+    results_backend,
+    security_manager,
+)
+from superset.common.db_query_status import QueryStatus
+from superset.constants import QUERY_CANCEL_KEY
+from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+from superset.exceptions import (
+    SupersetErrorException,
+    SupersetErrorsException,
+)
+from superset.extensions import celery_app
+from superset.models.sql_lab import Query
+from superset.result_set import SupersetResultSet
+from superset.sql.execution.executor import execute_sql_with_cursor
+from superset.sql.parse import SQLScript
+from superset.sqllab.utils import write_ipc_buffer
+from superset.utils import json
+from superset.utils.core import override_user, zlib_compress
+from superset.utils.dates import now_as_float
+from superset.utils.decorators import stats_timing
+
+if TYPE_CHECKING:
+    pass
+
+logger = logging.getLogger(__name__)
+
+BYTES_IN_MB = 1024 * 1024
+
+
+def _get_query(query_id: int) -> Query:
+    """Get the query by ID."""
+    return db.session.query(Query).filter_by(id=query_id).one()
+
+
+def _handle_query_error(
+    ex: Exception,
+    query: Query,
+    payload: dict[str, Any] | None = None,
+    prefix_message: str = "",
+) -> dict[str, Any]:
+    """Handle error while processing the SQL query."""
+    payload = payload or {}
+    msg = f"{prefix_message} {str(ex)}".strip()
+    query.error_message = msg
+    query.tmp_table_name = None
+    # Preserve TIMED_OUT status if already set (from SoftTimeLimitExceeded 
handler)
+    if query.status != QueryStatus.TIMED_OUT:
+        query.status = QueryStatus.FAILED
+
+    if not query.end_time:
+        query.end_time = now_as_float()
+
+    # Extract DB-specific errors
+    if isinstance(ex, SupersetErrorException):
+        errors = [ex.error]
+    elif isinstance(ex, SupersetErrorsException):
+        errors = ex.errors
+    else:
+        errors = query.database.db_engine_spec.extract_errors(
+            str(ex), database_name=query.database.unique_name
+        )
+
+    errors_payload = [dataclasses.asdict(error) for error in errors]
+    if errors:
+        query.set_extra_json_key("errors", errors_payload)
+
+    db.session.commit()  # pylint: disable=consider-using-transaction
+    payload.update(
+        {"status": query.status.value, "error": msg, "errors": errors_payload}
+    )
+    if troubleshooting_link := app.config.get("TROUBLESHOOTING_LINK"):
+        payload["link"] = troubleshooting_link
+    return payload
+
+
+def _serialize_payload(payload: dict[Any, Any]) -> bytes:
+    """Serialize payload for storage based on RESULTS_BACKEND_USE_MSGPACK 
config."""
+    from superset import results_backend_use_msgpack
+
+    if results_backend_use_msgpack:
+        return msgpack.dumps(payload, default=json.json_iso_dttm_ser, 
use_bin_type=True)
+    return json.dumps(payload, default=json.json_iso_dttm_ser, 
ignore_nan=True).encode(
+        "utf-8"
+    )
+
+
+def _prepare_statement_blocks(
+    rendered_query: str,
+    db_engine_spec: Any,
+) -> tuple[SQLScript, list[str]]:
+    """
+    Parse SQL and build statement blocks for execution.
+
+    Note: RLS, security checks, and other preprocessing are handled by
+    SQLExecutor before the query reaches this task.

Review Comment:
   Can we leave a comment here explaining why this is needed? We can use the 
one from `sql_lab.py`:
   
   ```python
       # some databases (like BigQuery and Kusto) do not persist state across 
mmultiple
       # statements if they're run separately (especially when using 
`NullPool`), so we run
       # the query as a single block.
   ```



##########
superset-core/src/superset_core/api/types.py:
##########
@@ -0,0 +1,174 @@
+# 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.
+
+"""
+Query execution types for superset-core.
+
+Provides type definitions for query execution that are partially aligned
+with frontend types in superset-ui-core/src/query/types/.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+from typing import Any, TYPE_CHECKING
+
+if TYPE_CHECKING:
+    import pandas as pd
+
+
+class QueryStatus(Enum):
+    """
+    Status of query execution.
+    """
+
+    PENDING = "pending"
+    RUNNING = "running"
+    SUCCESS = "success"
+    FAILED = "failed"
+    TIMED_OUT = "timed_out"
+    STOPPED = "stopped"
+
+
+@dataclass
+class CacheOptions:
+    """
+    Options for query result caching.
+    """
+
+    timeout: int | None = None  # Override default cache timeout (seconds)
+    force_refresh: bool = False  # Bypass cache and re-execute query
+
+
+@dataclass
+class QueryOptions:
+    """
+    Options for query execution via Database.execute() and execute_async().
+
+    Supports customization of:
+    - Basic: catalog, schema, limit, timeout
+    - Templates: Jinja2 template parameters
+    - Caching: Cache timeout and refresh control
+    - Dry run: Return transformed SQL without execution
+    """
+
+    # Basic options
+    catalog: str | None = None
+    schema: str | None = None
+    limit: int | None = None
+    timeout_seconds: int | None = None
+
+    # Template options
+    template_params: dict[str, Any] | None = None  # For Jinja2 rendering
+
+    # Caching options
+    cache: CacheOptions | None = None
+
+    # Dry run option
+    dry_run: bool = False  # Return transformed SQL without executing
+
+
+@dataclass
+class StatementResult:
+    """
+    Result of a single SQL statement execution.
+
+    For SELECT queries: data contains DataFrame, row_count is len(data)
+    For DML queries: data is None, row_count contains affected rows
+    """
+
+    statement: str  # The SQL statement after transformations

Review Comment:
   It would be nice to have both `submitted_statement` and `executed_statement` 
here, so it's clear how the original statement was transformed.



##########
superset/sql/execution/executor.py:
##########
@@ -0,0 +1,1081 @@
+# 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.
+
+"""
+SQL Executor implementation for Database.execute() and execute_async().
+
+This module provides the SQLExecutor class that implements the query execution
+methods defined in superset_core.api.models.Database.
+
+Implementation Features
+-----------------------
+
+Query Preparation (applies to both sync and async):
+- Jinja2 template rendering (via template_params in QueryOptions)
+- SQL mutation via SQL_QUERY_MUTATOR config hook
+- DML permission checking (requires database.allow_dml=True for DML)
+- Disallowed functions checking via DISALLOWED_SQL_FUNCTIONS config
+- Row-level security (RLS) via AST transformation (always applied)
+- Result limit application via SQL_MAX_ROW config
+- Catalog/schema resolution and validation
+
+Synchronous Execution (execute):
+- Multi-statement SQL parsing and execution
+- Progress tracking via Query model
+- Result caching via cache_manager.data_cache
+- Query logging via QUERY_LOGGER config hook
+- Timeout protection via SQLLAB_TIMEOUT config
+- Dry run mode (returns transformed SQL without execution)
+
+Asynchronous Execution (execute_async):
+- Celery task submission for background execution
+- Security validation before submission
+- Query model creation with PENDING status
+- Result caching check (returns cached if available)
+- Background execution with timeout via SQLLAB_ASYNC_TIME_LIMIT_SEC
+- Results stored in results backend for retrieval
+- Handle-based progress tracking and cancellation
+
+See Database.execute() and Database.execute_async() docstrings in
+superset_core.api.models for the public API contract.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import time
+from datetime import datetime
+from typing import Any, TYPE_CHECKING
+
+from flask import current_app as app, g, has_app_context
+
+from superset import db
+from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+from superset.exceptions import (
+    SupersetSecurityException,
+    SupersetTimeoutException,
+)
+from superset.extensions import cache_manager
+from superset.sql.parse import SQLScript
+from superset.utils import core as utils
+
+if TYPE_CHECKING:
+    from superset_core.api.types import (
+        AsyncQueryHandle,
+        QueryOptions,
+        QueryResult,
+    )
+
+    from superset.models.core import Database
+    from superset.result_set import SupersetResultSet
+
+logger = logging.getLogger(__name__)
+
+
+def execute_sql_with_cursor(
+    database: Database,
+    cursor: Any,
+    statements: list[str],
+    query: Any,
+    log_query_fn: Any | None = None,
+    check_stopped_fn: Any | None = None,
+    execute_fn: Any | None = None,
+) -> list[tuple[str, SupersetResultSet | None, float, int]]:
+    """
+    Execute SQL statements with a cursor and return all result sets.
+
+    This is the shared execution logic used by both sync (SQLExecutor) and
+    async (celery_task) execution paths. It handles multi-statement execution
+    with progress tracking via the Query model.
+
+    :param database: Database model to execute against
+    :param cursor: Database cursor to use for execution
+    :param statements: List of SQL statements to execute
+    :param query: Query model for progress tracking
+    :param log_query_fn: Optional function to log queries, called as fn(sql, 
schema)
+    :param check_stopped_fn: Optional function to check if query was stopped.
+        Should return True if stopped. Used by async execution for 
cancellation.
+    :param execute_fn: Optional custom execute function. If not provided, uses
+        database.db_engine_spec.execute(cursor, sql, database). Custom function
+        should accept (cursor, sql) and handle execution.
+    :returns: List of (statement_sql, result_set, execution_time_ms, rowcount) 
tuples
+        Returns empty list if stopped. Raises exception on error (fail-fast).
+    """
+    from superset.result_set import SupersetResultSet
+
+    total = len(statements)
+    if total == 0:
+        return []
+
+    results: list[tuple[str, SupersetResultSet | None, float, int]] = []
+
+    for i, statement in enumerate(statements):
+        # Check if query was stopped (async cancellation)
+        if check_stopped_fn and check_stopped_fn():
+            return results
+
+        stmt_start_time = time.time()
+
+        # Apply SQL mutation
+        stmt_sql = database.mutate_sql_based_on_config(
+            statement,
+            is_split=True,
+        )
+
+        # Log query
+        if log_query_fn:
+            log_query_fn(stmt_sql, query.schema)
+
+        # Execute - use custom function or default
+        if execute_fn:
+            execute_fn(cursor, stmt_sql)
+        else:
+            database.db_engine_spec.execute(cursor, stmt_sql, database)
+
+        stmt_execution_time = (time.time() - stmt_start_time) * 1000
+
+        # Fetch results from ALL statements
+        description = cursor.description
+        if description:
+            rows = database.db_engine_spec.fetch_data(cursor)
+            result_set = SupersetResultSet(
+                rows,
+                description,
+                database.db_engine_spec,
+            )
+        else:
+            # DML statement - no result set
+            result_set = None
+
+        # Get row count for DML statements
+        rowcount = cursor.rowcount if hasattr(cursor, "rowcount") else 0
+
+        results.append((stmt_sql, result_set, stmt_execution_time, rowcount))
+
+        # Update progress on Query model
+        progress_pct = int(((i + 1) / total) * 100)
+        query.progress = progress_pct
+        query.set_extra_json_key(
+            "progress",
+            f"Running statement {i + 1} of {total}",
+        )
+        db.session.commit()  # pylint: disable=consider-using-transaction
+
+    return results
+
+
+class SQLExecutor:
+    """
+    SQL query executor implementation.
+
+    Implements Database.execute() and execute_async() methods.
+    See superset_core.api.models.Database for the full public API 
documentation.
+    """
+
+    def __init__(self, database: Database) -> None:
+        """
+        Initialize the executor with a database.
+
+        :param database: Database model instance to execute queries against
+        """
+        self.database = database
+
+    def execute(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> QueryResult:
+        """
+        Execute SQL synchronously.
+
+        If options.dry_run=True, returns the transformed SQL without execution.
+        All transformations (RLS, templates, limits) are still applied.
+
+        See superset_core.api.models.Database.execute() for full documentation.
+        """
+        from superset_core.api.types import (
+            QueryOptions as QueryOptionsType,
+            QueryResult as QueryResultType,
+            QueryStatus,
+            StatementResult,
+        )
+
+        opts: QueryOptionsType = options or QueryOptionsType()
+        start_time = time.time()
+
+        try:
+            # 1. Prepare SQL (assembly only, no security checks)
+            script, catalog, schema = self._prepare_sql(sql, opts)
+
+            # 2. Security checks
+            self._check_security(script)
+
+            # 3. Get mutation status and format SQL
+            has_mutation = script.has_mutation()
+            final_sql = script.format()
+
+            # DRY RUN: Return transformed SQL without execution
+            if opts.dry_run:
+                total_execution_time_ms = (time.time() - start_time) * 1000
+                # Create a StatementResult for each statement in dry-run mode
+                dry_run_statements = [
+                    StatementResult(
+                        statement=stmt.format(),
+                        data=None,
+                        row_count=0,
+                        execution_time_ms=0,
+                    )
+                    for stmt in script.statements
+                ]
+                return QueryResultType(
+                    status=QueryStatus.SUCCESS,
+                    statements=dry_run_statements,
+                    query_id=None,
+                    total_execution_time_ms=total_execution_time_ms,
+                    is_cached=False,
+                )
+
+            # 4. Check cache
+            cached_result = self._try_get_cached_result(has_mutation, 
final_sql, opts)
+            if cached_result:
+                return cached_result
+
+            # 5. Create Query model for audit
+            query = self._create_query_record(
+                final_sql, opts, catalog, schema, status="running"
+            )
+
+            # 6. Execute with timeout
+            timeout = opts.timeout_seconds or app.config.get("SQLLAB_TIMEOUT", 
30)
+            timeout_msg = f"Query exceeded the {timeout} seconds timeout."
+
+            with utils.timeout(seconds=timeout, error_message=timeout_msg):
+                statement_results = self._execute_statements(
+                    final_sql,
+                    catalog,
+                    schema,
+                    query,
+                )
+
+            total_execution_time_ms = (time.time() - start_time) * 1000
+
+            # Calculate total row count for Query model
+            total_rows = sum(stmt.row_count for stmt in statement_results)
+
+            # Update query record
+            query.status = "success"
+            query.rows = total_rows
+            query.progress = 100
+            db.session.commit()  # pylint: disable=consider-using-transaction
+
+            result = QueryResultType(
+                status=QueryStatus.SUCCESS,
+                statements=statement_results,
+                query_id=query.id,
+                total_execution_time_ms=total_execution_time_ms,
+            )
+
+            # Store in cache (if SELECT and caching enabled)
+            if not has_mutation:
+                self._store_in_cache(result, final_sql, opts)
+
+            return result
+
+        except SupersetTimeoutException:
+            return self._create_error_result(
+                QueryStatus.TIMED_OUT,
+                "Query exceeded the timeout limit",
+                sql,
+                start_time,
+            )
+        except SupersetSecurityException as ex:
+            return self._create_error_result(
+                QueryStatus.FAILED, str(ex), sql, start_time
+            )
+        except Exception as ex:
+            error_msg = self.database.db_engine_spec.extract_error_message(ex)
+            return self._create_error_result(
+                QueryStatus.FAILED, error_msg, sql, start_time
+            )
+
+    def execute_async(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> AsyncQueryHandle:
+        """
+        Execute SQL asynchronously via Celery.
+
+        If options.dry_run=True, returns the transformed SQL as a completed
+        AsyncQueryHandle without submitting to Celery.
+
+        See superset_core.api.models.Database.execute_async() for full 
documentation.
+        """
+        from superset_core.api.types import (
+            QueryOptions as QueryOptionsType,
+            QueryResult as QueryResultType,
+            QueryStatus,
+        )
+
+        opts: QueryOptionsType = options or QueryOptionsType()
+
+        # 1. Prepare SQL (assembly only, no security checks)
+        script, catalog, schema = self._prepare_sql(sql, opts)
+
+        # 2. Security checks
+        self._check_security(script)
+
+        # 3. Get mutation status and format SQL
+        has_mutation = script.has_mutation()
+        final_sql = script.format()
+
+        # DRY RUN: Return transformed SQL as completed async handle
+        if opts.dry_run:
+            from superset_core.api.types import StatementResult
+
+            dry_run_statements = [
+                StatementResult(
+                    statement=stmt.format(),
+                    data=None,
+                    row_count=0,
+                    execution_time_ms=0,
+                )
+                for stmt in script.statements
+            ]
+            dry_run_result = QueryResultType(
+                status=QueryStatus.SUCCESS,
+                statements=dry_run_statements,
+                query_id=None,
+                total_execution_time_ms=0,
+                is_cached=False,
+            )
+            return self._create_cached_handle(dry_run_result)
+
+        # 4. Check cache
+        if cached_result := self._try_get_cached_result(has_mutation, 
final_sql, opts):
+            return self._create_cached_handle(cached_result)
+
+        # 5. Create Query model for audit
+        query = self._create_query_record(
+            final_sql, opts, catalog, schema, status="pending"

Review Comment:
   Ditto here.



##########
superset/sql/execution/executor.py:
##########
@@ -0,0 +1,1081 @@
+# 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.
+
+"""
+SQL Executor implementation for Database.execute() and execute_async().
+
+This module provides the SQLExecutor class that implements the query execution
+methods defined in superset_core.api.models.Database.
+
+Implementation Features
+-----------------------
+
+Query Preparation (applies to both sync and async):
+- Jinja2 template rendering (via template_params in QueryOptions)
+- SQL mutation via SQL_QUERY_MUTATOR config hook
+- DML permission checking (requires database.allow_dml=True for DML)
+- Disallowed functions checking via DISALLOWED_SQL_FUNCTIONS config
+- Row-level security (RLS) via AST transformation (always applied)
+- Result limit application via SQL_MAX_ROW config
+- Catalog/schema resolution and validation
+
+Synchronous Execution (execute):
+- Multi-statement SQL parsing and execution
+- Progress tracking via Query model
+- Result caching via cache_manager.data_cache
+- Query logging via QUERY_LOGGER config hook
+- Timeout protection via SQLLAB_TIMEOUT config
+- Dry run mode (returns transformed SQL without execution)
+
+Asynchronous Execution (execute_async):
+- Celery task submission for background execution
+- Security validation before submission
+- Query model creation with PENDING status
+- Result caching check (returns cached if available)
+- Background execution with timeout via SQLLAB_ASYNC_TIME_LIMIT_SEC
+- Results stored in results backend for retrieval
+- Handle-based progress tracking and cancellation
+
+See Database.execute() and Database.execute_async() docstrings in
+superset_core.api.models for the public API contract.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import time
+from datetime import datetime
+from typing import Any, TYPE_CHECKING
+
+from flask import current_app as app, g, has_app_context
+
+from superset import db
+from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+from superset.exceptions import (
+    SupersetSecurityException,
+    SupersetTimeoutException,
+)
+from superset.extensions import cache_manager
+from superset.sql.parse import SQLScript
+from superset.utils import core as utils
+
+if TYPE_CHECKING:
+    from superset_core.api.types import (
+        AsyncQueryHandle,
+        QueryOptions,
+        QueryResult,
+    )
+
+    from superset.models.core import Database
+    from superset.result_set import SupersetResultSet
+
+logger = logging.getLogger(__name__)
+
+
+def execute_sql_with_cursor(
+    database: Database,
+    cursor: Any,
+    statements: list[str],
+    query: Any,
+    log_query_fn: Any | None = None,
+    check_stopped_fn: Any | None = None,
+    execute_fn: Any | None = None,
+) -> list[tuple[str, SupersetResultSet | None, float, int]]:
+    """
+    Execute SQL statements with a cursor and return all result sets.
+
+    This is the shared execution logic used by both sync (SQLExecutor) and
+    async (celery_task) execution paths. It handles multi-statement execution
+    with progress tracking via the Query model.
+
+    :param database: Database model to execute against
+    :param cursor: Database cursor to use for execution
+    :param statements: List of SQL statements to execute
+    :param query: Query model for progress tracking
+    :param log_query_fn: Optional function to log queries, called as fn(sql, 
schema)
+    :param check_stopped_fn: Optional function to check if query was stopped.
+        Should return True if stopped. Used by async execution for 
cancellation.
+    :param execute_fn: Optional custom execute function. If not provided, uses
+        database.db_engine_spec.execute(cursor, sql, database). Custom function
+        should accept (cursor, sql) and handle execution.
+    :returns: List of (statement_sql, result_set, execution_time_ms, rowcount) 
tuples
+        Returns empty list if stopped. Raises exception on error (fail-fast).
+    """
+    from superset.result_set import SupersetResultSet
+
+    total = len(statements)
+    if total == 0:
+        return []
+
+    results: list[tuple[str, SupersetResultSet | None, float, int]] = []
+
+    for i, statement in enumerate(statements):
+        # Check if query was stopped (async cancellation)
+        if check_stopped_fn and check_stopped_fn():
+            return results
+
+        stmt_start_time = time.time()
+
+        # Apply SQL mutation
+        stmt_sql = database.mutate_sql_based_on_config(
+            statement,
+            is_split=True,
+        )
+
+        # Log query
+        if log_query_fn:
+            log_query_fn(stmt_sql, query.schema)
+
+        # Execute - use custom function or default
+        if execute_fn:
+            execute_fn(cursor, stmt_sql)
+        else:
+            database.db_engine_spec.execute(cursor, stmt_sql, database)
+
+        stmt_execution_time = (time.time() - stmt_start_time) * 1000
+
+        # Fetch results from ALL statements
+        description = cursor.description
+        if description:
+            rows = database.db_engine_spec.fetch_data(cursor)
+            result_set = SupersetResultSet(
+                rows,
+                description,
+                database.db_engine_spec,
+            )
+        else:
+            # DML statement - no result set
+            result_set = None
+
+        # Get row count for DML statements
+        rowcount = cursor.rowcount if hasattr(cursor, "rowcount") else 0
+
+        results.append((stmt_sql, result_set, stmt_execution_time, rowcount))
+
+        # Update progress on Query model
+        progress_pct = int(((i + 1) / total) * 100)
+        query.progress = progress_pct
+        query.set_extra_json_key(
+            "progress",
+            f"Running statement {i + 1} of {total}",
+        )
+        db.session.commit()  # pylint: disable=consider-using-transaction
+
+    return results
+
+
+class SQLExecutor:
+    """
+    SQL query executor implementation.
+
+    Implements Database.execute() and execute_async() methods.
+    See superset_core.api.models.Database for the full public API 
documentation.
+    """
+
+    def __init__(self, database: Database) -> None:
+        """
+        Initialize the executor with a database.
+
+        :param database: Database model instance to execute queries against
+        """
+        self.database = database
+
+    def execute(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> QueryResult:
+        """
+        Execute SQL synchronously.
+
+        If options.dry_run=True, returns the transformed SQL without execution.
+        All transformations (RLS, templates, limits) are still applied.
+
+        See superset_core.api.models.Database.execute() for full documentation.
+        """
+        from superset_core.api.types import (
+            QueryOptions as QueryOptionsType,
+            QueryResult as QueryResultType,
+            QueryStatus,
+            StatementResult,
+        )
+
+        opts: QueryOptionsType = options or QueryOptionsType()
+        start_time = time.time()
+
+        try:
+            # 1. Prepare SQL (assembly only, no security checks)
+            script, catalog, schema = self._prepare_sql(sql, opts)
+
+            # 2. Security checks
+            self._check_security(script)
+
+            # 3. Get mutation status and format SQL
+            has_mutation = script.has_mutation()
+            final_sql = script.format()
+
+            # DRY RUN: Return transformed SQL without execution
+            if opts.dry_run:
+                total_execution_time_ms = (time.time() - start_time) * 1000
+                # Create a StatementResult for each statement in dry-run mode
+                dry_run_statements = [
+                    StatementResult(
+                        statement=stmt.format(),
+                        data=None,
+                        row_count=0,
+                        execution_time_ms=0,
+                    )
+                    for stmt in script.statements
+                ]
+                return QueryResultType(
+                    status=QueryStatus.SUCCESS,
+                    statements=dry_run_statements,
+                    query_id=None,
+                    total_execution_time_ms=total_execution_time_ms,
+                    is_cached=False,
+                )
+
+            # 4. Check cache
+            cached_result = self._try_get_cached_result(has_mutation, 
final_sql, opts)
+            if cached_result:
+                return cached_result
+
+            # 5. Create Query model for audit
+            query = self._create_query_record(
+                final_sql, opts, catalog, schema, status="running"
+            )
+
+            # 6. Execute with timeout
+            timeout = opts.timeout_seconds or app.config.get("SQLLAB_TIMEOUT", 
30)
+            timeout_msg = f"Query exceeded the {timeout} seconds timeout."
+
+            with utils.timeout(seconds=timeout, error_message=timeout_msg):
+                statement_results = self._execute_statements(
+                    final_sql,
+                    catalog,
+                    schema,
+                    query,
+                )
+
+            total_execution_time_ms = (time.time() - start_time) * 1000
+
+            # Calculate total row count for Query model
+            total_rows = sum(stmt.row_count for stmt in statement_results)
+
+            # Update query record
+            query.status = "success"
+            query.rows = total_rows
+            query.progress = 100
+            db.session.commit()  # pylint: disable=consider-using-transaction
+
+            result = QueryResultType(
+                status=QueryStatus.SUCCESS,
+                statements=statement_results,
+                query_id=query.id,
+                total_execution_time_ms=total_execution_time_ms,
+            )
+
+            # Store in cache (if SELECT and caching enabled)
+            if not has_mutation:
+                self._store_in_cache(result, final_sql, opts)
+
+            return result
+
+        except SupersetTimeoutException:
+            return self._create_error_result(
+                QueryStatus.TIMED_OUT,
+                "Query exceeded the timeout limit",
+                sql,
+                start_time,
+            )
+        except SupersetSecurityException as ex:
+            return self._create_error_result(
+                QueryStatus.FAILED, str(ex), sql, start_time
+            )
+        except Exception as ex:
+            error_msg = self.database.db_engine_spec.extract_error_message(ex)
+            return self._create_error_result(
+                QueryStatus.FAILED, error_msg, sql, start_time
+            )
+
+    def execute_async(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> AsyncQueryHandle:
+        """
+        Execute SQL asynchronously via Celery.
+
+        If options.dry_run=True, returns the transformed SQL as a completed
+        AsyncQueryHandle without submitting to Celery.
+
+        See superset_core.api.models.Database.execute_async() for full 
documentation.
+        """
+        from superset_core.api.types import (
+            QueryOptions as QueryOptionsType,
+            QueryResult as QueryResultType,
+            QueryStatus,
+        )
+
+        opts: QueryOptionsType = options or QueryOptionsType()
+
+        # 1. Prepare SQL (assembly only, no security checks)
+        script, catalog, schema = self._prepare_sql(sql, opts)
+
+        # 2. Security checks
+        self._check_security(script)
+
+        # 3. Get mutation status and format SQL
+        has_mutation = script.has_mutation()
+        final_sql = script.format()
+
+        # DRY RUN: Return transformed SQL as completed async handle
+        if opts.dry_run:
+            from superset_core.api.types import StatementResult
+
+            dry_run_statements = [
+                StatementResult(
+                    statement=stmt.format(),
+                    data=None,
+                    row_count=0,
+                    execution_time_ms=0,
+                )
+                for stmt in script.statements
+            ]
+            dry_run_result = QueryResultType(
+                status=QueryStatus.SUCCESS,
+                statements=dry_run_statements,
+                query_id=None,
+                total_execution_time_ms=0,
+                is_cached=False,
+            )
+            return self._create_cached_handle(dry_run_result)
+
+        # 4. Check cache
+        if cached_result := self._try_get_cached_result(has_mutation, 
final_sql, opts):
+            return self._create_cached_handle(cached_result)
+
+        # 5. Create Query model for audit
+        query = self._create_query_record(
+            final_sql, opts, catalog, schema, status="pending"
+        )
+
+        # 6. Submit to Celery
+        self._submit_query_to_celery(query, final_sql, opts)
+
+        # 7. Create and return handle with bound methods
+        return self._create_async_handle(query.id)
+
+    def _prepare_sql(
+        self,
+        sql: str,
+        opts: QueryOptions,
+    ) -> tuple[SQLScript, str | None, str | None]:
+        """
+        Prepare SQL for execution (no side effects, no security checks).
+
+        This method performs SQL preprocessing:
+        1. Template rendering
+        2. SQL parsing
+        3. Catalog/schema resolution
+        4. RLS application
+        5. Limit application (if not mutation)
+
+        Security checks (disallowed functions, DML permission) are performed
+        by the caller after receiving the prepared script.
+
+        :param sql: Original SQL query
+        :param opts: Query options
+        :returns: Tuple of (prepared SQLScript, catalog, schema)
+        """
+        # 1. Render Jinja2 templates
+        rendered_sql = self._render_sql_template(sql, opts.template_params)
+
+        # 2. Parse SQL with SQLScript
+        script = SQLScript(rendered_sql, self.database.db_engine_spec.engine)
+
+        # 3. Get catalog and schema
+        catalog = opts.catalog or self.database.get_default_catalog()
+        schema = opts.schema or self.database.get_default_schema(catalog)
+
+        # 4. Apply RLS directly to script statements
+        self._apply_rls_to_script(script, catalog, schema)
+
+        # 5. Apply limit only if not a mutation
+        if not script.has_mutation():
+            self._apply_limit_to_script(script, opts)
+
+        return script, catalog, schema
+
+    def _check_security(self, script: SQLScript) -> None:
+        """
+        Perform security checks on prepared SQL script.
+
+        :param script: Prepared SQLScript
+        :raises SupersetSecurityException: If security checks fail
+        """
+        # Check disallowed functions
+        if disallowed := self._check_disallowed_functions(script):
+            raise SupersetSecurityException(
+                SupersetError(
+                    message=f"Disallowed SQL functions: {', 
'.join(disallowed)}",
+                    error_type=SupersetErrorType.INVALID_SQL_ERROR,
+                    level=ErrorLevel.ERROR,
+                )
+            )
+
+        # Check DML permission
+        if script.has_mutation() and not self.database.allow_dml:
+            raise SupersetSecurityException(
+                SupersetError(
+                    message="DML queries are not allowed on this database",
+                    error_type=SupersetErrorType.DML_NOT_ALLOWED_ERROR,
+                    level=ErrorLevel.ERROR,
+                )
+            )
+
+    def _execute_statements(
+        self,
+        sql: str,
+        catalog: str | None,
+        schema: str | None,
+        query: Any,
+    ) -> list[Any]:
+        """
+        Execute SQL statements and return per-statement results.
+
+        Progress is tracked via Query.progress field.
+        Uses the same execution path for both single and multi-statement 
queries.
+
+        :param sql: Final SQL to execute (with RLS and all transformations 
applied)
+        :param catalog: Catalog name
+        :param schema: Schema name
+        :param query: Query model for progress tracking
+        :returns: List of StatementResult objects
+        """
+        from superset_core.api.types import StatementResult
+
+        # Parse the final SQL (with RLS applied) to get statements
+        script = SQLScript(sql, self.database.db_engine_spec.engine)
+        statements = script.statements
+
+        # Handle empty script
+        if not statements:
+            return []
+
+        results_list = []
+
+        # Use consistent execution path for all queries
+        with self.database.get_raw_connection(catalog=catalog, schema=schema) 
as conn:
+            with contextlib.closing(conn.cursor()) as cursor:
+                execution_results = execute_sql_with_cursor(
+                    database=self.database,
+                    cursor=cursor,
+                    statements=[stmt.format() for stmt in statements],
+                    query=query,
+                    log_query_fn=self._log_query,
+                )
+
+                # Build StatementResult for each executed statement
+                for stmt_sql, result_set, exec_time, rowcount in 
execution_results:
+                    if result_set is not None:
+                        # SELECT statement
+                        df = result_set.to_pandas_df()
+                        stmt_result = StatementResult(
+                            statement=stmt_sql,
+                            data=df,
+                            row_count=len(df),
+                            execution_time_ms=exec_time,
+                        )
+                    else:
+                        # DML statement - no data, just row count
+                        stmt_result = StatementResult(
+                            statement=stmt_sql,
+                            data=None,
+                            row_count=rowcount,
+                            execution_time_ms=exec_time,
+                        )
+
+                    results_list.append(stmt_result)
+
+        return results_list
+
+    def _log_query(
+        self,
+        sql: str,
+        schema: str | None,
+    ) -> None:
+        """
+        Log query using QUERY_LOGGER config.
+
+        :param sql: SQL to log
+        :param schema: Schema name
+        """
+        from superset import security_manager
+
+        if log_query := app.config.get("QUERY_LOGGER"):
+            log_query(
+                self.database,
+                sql,
+                schema,
+                __name__,
+                security_manager,
+                {},
+            )
+
+    def _create_error_result(
+        self,
+        status: Any,
+        error_message: str,
+        sql: str,
+        start_time: float,
+        partial_results: list[Any] | None = None,
+    ) -> QueryResult:
+        """
+        Create a QueryResult for error cases.
+
+        :param status: QueryStatus enum value
+        :param error_message: Error message to include
+        :param sql: SQL query (original if error occurred before 
transformation)
+        :param start_time: Start time for calculating execution duration
+        :param partial_results: Optional list of StatementResult from 
successful
+            statements before the failure
+        :returns: QueryResult with error status
+        """
+        from superset_core.api.types import QueryResult as QueryResultType
+
+        return QueryResultType(
+            status=status,
+            statements=partial_results or [],
+            error_message=error_message,
+            total_execution_time_ms=(time.time() - start_time) * 1000,
+        )
+
+    def _render_sql_template(
+        self, sql: str, template_params: dict[str, Any] | None
+    ) -> str:
+        """
+        Render Jinja2 template with params.
+
+        :param sql: SQL string potentially containing Jinja2 templates
+        :param template_params: Parameters to pass to the template
+        :returns: Rendered SQL string
+        """
+        if template_params is None:
+            return sql
+
+        from superset.jinja_context import get_template_processor
+
+        tp = get_template_processor(database=self.database)
+        return tp.process_template(sql, **template_params)
+
+    def _apply_limit_to_script(self, script: SQLScript, opts: QueryOptions) -> 
None:
+        """
+        Apply limit to the last statement in the script in place.
+
+        :param script: SQLScript object to modify
+        :param opts: Query options
+        """
+        # Skip if no limit requested
+        if opts.limit is None:
+            return
+
+        sql_max_row = app.config.get("SQL_MAX_ROW")
+        effective_limit = opts.limit
+        if sql_max_row and opts.limit > sql_max_row:
+            effective_limit = sql_max_row
+
+        # Apply limit to last statement only
+        if script.statements:
+            script.statements[-1].set_limit_value(
+                effective_limit,
+                self.database.db_engine_spec.limit_method,
+            )
+
+    def _try_get_cached_result(
+        self,
+        has_mutation: bool,
+        sql: str,
+        opts: QueryOptions,
+    ) -> QueryResult | None:
+        """
+        Try to get a cached result if conditions allow.
+
+        :param has_mutation: Whether the query contains mutations (DML)
+        :param sql: SQL query
+        :param opts: Query options
+        :returns: Cached QueryResult or None
+        """
+        if has_mutation or (opts.cache and opts.cache.force_refresh):
+            return None
+
+        return self._get_from_cache(sql, opts)
+
+    def _check_disallowed_functions(self, script: SQLScript) -> set[str] | 
None:
+        """
+        Check for disallowed SQL functions.
+
+        :param script: Parsed SQL script
+        :returns: Set of disallowed functions found, or None if none found
+        """
+        disallowed_config = app.config.get("DISALLOWED_SQL_FUNCTIONS", {})
+        engine_name = self.database.db_engine_spec.engine
+
+        # Get disallowed functions for this engine
+        engine_disallowed = disallowed_config.get(engine_name, set())
+        if not engine_disallowed:
+            return None
+
+        # Check each statement for disallowed functions
+        found = set()
+        for statement in script.statements:
+            # Use the statement's AST to check for function calls
+            statement_str = str(statement).upper()
+            for func in engine_disallowed:
+                if func.upper() in statement_str:
+                    found.add(func)
+
+        return found if found else None
+
+    def _apply_rls_to_script(
+        self, script: SQLScript, catalog: str | None, schema: str | None
+    ) -> None:
+        """
+        Apply Row-Level Security to SQLScript statements in place.
+
+        :param script: SQLScript object to modify
+        :param catalog: Catalog name
+        :param schema: Schema name
+        """
+        from superset.utils.rls import apply_rls
+
+        # Apply RLS to each statement in the script
+        for statement in script.statements:
+            apply_rls(self.database, catalog, schema or "", statement)
+
+    def _create_query_record(
+        self,
+        sql: str,
+        opts: QueryOptions,
+        catalog: str | None,
+        schema: str | None,
+        status: str = "running",
+    ) -> Any:
+        """
+        Create Query model for audit/tracking.
+
+        :param sql: SQL to execute
+        :param opts: Query options
+        :param catalog: Catalog name
+        :param schema: Schema name
+        :param status: Initial query status ("running" for sync, "pending" for 
async)
+        :returns: Query model instance
+        """
+        import uuid

Review Comment:
   Stdlib imports can always be at the top level.



##########
superset-core/src/superset_core/api/models.py:
##########
@@ -75,6 +84,83 @@ def backend(self) -> str:
     def data(self) -> dict[str, Any]:
         raise NotImplementedError
 
+    def execute(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> QueryResult:
+        """
+        Execute SQL synchronously.
+
+        :param sql: SQL query to execute

Review Comment:
   One concern I have here: is `sql` a single statement, or can it have 
multiple statements? I think we need to support both, because some databases 
don't support sessions, so queries like these must be executed in a single 
block:
   
   ```sql
   SET foo=1;  -- needed for the next statement
   SELECT * FROM t;
   ```
   
   But some database drivers don't support multiple statements, so we need to 
send them one-by-one.



##########
superset/sql/execution/executor.py:
##########
@@ -0,0 +1,1081 @@
+# 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.
+
+"""
+SQL Executor implementation for Database.execute() and execute_async().
+
+This module provides the SQLExecutor class that implements the query execution
+methods defined in superset_core.api.models.Database.
+
+Implementation Features
+-----------------------
+
+Query Preparation (applies to both sync and async):
+- Jinja2 template rendering (via template_params in QueryOptions)
+- SQL mutation via SQL_QUERY_MUTATOR config hook
+- DML permission checking (requires database.allow_dml=True for DML)
+- Disallowed functions checking via DISALLOWED_SQL_FUNCTIONS config
+- Row-level security (RLS) via AST transformation (always applied)
+- Result limit application via SQL_MAX_ROW config
+- Catalog/schema resolution and validation
+
+Synchronous Execution (execute):
+- Multi-statement SQL parsing and execution
+- Progress tracking via Query model
+- Result caching via cache_manager.data_cache
+- Query logging via QUERY_LOGGER config hook
+- Timeout protection via SQLLAB_TIMEOUT config
+- Dry run mode (returns transformed SQL without execution)
+
+Asynchronous Execution (execute_async):
+- Celery task submission for background execution
+- Security validation before submission
+- Query model creation with PENDING status
+- Result caching check (returns cached if available)
+- Background execution with timeout via SQLLAB_ASYNC_TIME_LIMIT_SEC
+- Results stored in results backend for retrieval
+- Handle-based progress tracking and cancellation
+
+See Database.execute() and Database.execute_async() docstrings in
+superset_core.api.models for the public API contract.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import time
+from datetime import datetime
+from typing import Any, TYPE_CHECKING
+
+from flask import current_app as app, g, has_app_context
+
+from superset import db
+from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
+from superset.exceptions import (
+    SupersetSecurityException,
+    SupersetTimeoutException,
+)
+from superset.extensions import cache_manager
+from superset.sql.parse import SQLScript
+from superset.utils import core as utils
+
+if TYPE_CHECKING:
+    from superset_core.api.types import (
+        AsyncQueryHandle,
+        QueryOptions,
+        QueryResult,
+    )
+
+    from superset.models.core import Database
+    from superset.result_set import SupersetResultSet
+
+logger = logging.getLogger(__name__)
+
+
+def execute_sql_with_cursor(
+    database: Database,
+    cursor: Any,
+    statements: list[str],
+    query: Any,
+    log_query_fn: Any | None = None,
+    check_stopped_fn: Any | None = None,
+    execute_fn: Any | None = None,
+) -> list[tuple[str, SupersetResultSet | None, float, int]]:
+    """
+    Execute SQL statements with a cursor and return all result sets.
+
+    This is the shared execution logic used by both sync (SQLExecutor) and
+    async (celery_task) execution paths. It handles multi-statement execution
+    with progress tracking via the Query model.
+
+    :param database: Database model to execute against
+    :param cursor: Database cursor to use for execution
+    :param statements: List of SQL statements to execute
+    :param query: Query model for progress tracking
+    :param log_query_fn: Optional function to log queries, called as fn(sql, 
schema)
+    :param check_stopped_fn: Optional function to check if query was stopped.
+        Should return True if stopped. Used by async execution for 
cancellation.
+    :param execute_fn: Optional custom execute function. If not provided, uses
+        database.db_engine_spec.execute(cursor, sql, database). Custom function
+        should accept (cursor, sql) and handle execution.
+    :returns: List of (statement_sql, result_set, execution_time_ms, rowcount) 
tuples
+        Returns empty list if stopped. Raises exception on error (fail-fast).
+    """
+    from superset.result_set import SupersetResultSet
+
+    total = len(statements)
+    if total == 0:
+        return []
+
+    results: list[tuple[str, SupersetResultSet | None, float, int]] = []
+
+    for i, statement in enumerate(statements):
+        # Check if query was stopped (async cancellation)
+        if check_stopped_fn and check_stopped_fn():
+            return results
+
+        stmt_start_time = time.time()
+
+        # Apply SQL mutation
+        stmt_sql = database.mutate_sql_based_on_config(
+            statement,
+            is_split=True,
+        )
+
+        # Log query
+        if log_query_fn:
+            log_query_fn(stmt_sql, query.schema)
+
+        # Execute - use custom function or default
+        if execute_fn:
+            execute_fn(cursor, stmt_sql)
+        else:
+            database.db_engine_spec.execute(cursor, stmt_sql, database)
+
+        stmt_execution_time = (time.time() - stmt_start_time) * 1000
+
+        # Fetch results from ALL statements
+        description = cursor.description
+        if description:
+            rows = database.db_engine_spec.fetch_data(cursor)
+            result_set = SupersetResultSet(
+                rows,
+                description,
+                database.db_engine_spec,
+            )
+        else:
+            # DML statement - no result set
+            result_set = None
+
+        # Get row count for DML statements
+        rowcount = cursor.rowcount if hasattr(cursor, "rowcount") else 0
+
+        results.append((stmt_sql, result_set, stmt_execution_time, rowcount))
+
+        # Update progress on Query model
+        progress_pct = int(((i + 1) / total) * 100)
+        query.progress = progress_pct
+        query.set_extra_json_key(
+            "progress",
+            f"Running statement {i + 1} of {total}",
+        )
+        db.session.commit()  # pylint: disable=consider-using-transaction
+
+    return results
+
+
+class SQLExecutor:
+    """
+    SQL query executor implementation.
+
+    Implements Database.execute() and execute_async() methods.
+    See superset_core.api.models.Database for the full public API 
documentation.
+    """
+
+    def __init__(self, database: Database) -> None:
+        """
+        Initialize the executor with a database.
+
+        :param database: Database model instance to execute queries against
+        """
+        self.database = database
+
+    def execute(
+        self,
+        sql: str,
+        options: QueryOptions | None = None,
+    ) -> QueryResult:
+        """
+        Execute SQL synchronously.
+
+        If options.dry_run=True, returns the transformed SQL without execution.
+        All transformations (RLS, templates, limits) are still applied.
+
+        See superset_core.api.models.Database.execute() for full documentation.
+        """
+        from superset_core.api.types import (
+            QueryOptions as QueryOptionsType,
+            QueryResult as QueryResultType,
+            QueryStatus,
+            StatementResult,
+        )
+
+        opts: QueryOptionsType = options or QueryOptionsType()
+        start_time = time.time()
+
+        try:
+            # 1. Prepare SQL (assembly only, no security checks)
+            script, catalog, schema = self._prepare_sql(sql, opts)
+
+            # 2. Security checks
+            self._check_security(script)
+
+            # 3. Get mutation status and format SQL
+            has_mutation = script.has_mutation()
+            final_sql = script.format()
+
+            # DRY RUN: Return transformed SQL without execution
+            if opts.dry_run:
+                total_execution_time_ms = (time.time() - start_time) * 1000
+                # Create a StatementResult for each statement in dry-run mode
+                dry_run_statements = [
+                    StatementResult(
+                        statement=stmt.format(),
+                        data=None,
+                        row_count=0,
+                        execution_time_ms=0,
+                    )
+                    for stmt in script.statements
+                ]
+                return QueryResultType(
+                    status=QueryStatus.SUCCESS,
+                    statements=dry_run_statements,
+                    query_id=None,
+                    total_execution_time_ms=total_execution_time_ms,
+                    is_cached=False,
+                )
+
+            # 4. Check cache
+            cached_result = self._try_get_cached_result(has_mutation, 
final_sql, opts)
+            if cached_result:
+                return cached_result
+
+            # 5. Create Query model for audit
+            query = self._create_query_record(
+                final_sql, opts, catalog, schema, status="running"

Review Comment:
   We have an enum for `"running"`, let's use 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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to