Copilot commented on code in PR #36529:
URL: https://github.com/apache/superset/pull/36529#discussion_r2619406368
##########
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
+ :param options: Query execution options (see `QueryOptions`).
+ If not provided, defaults are used.
+ :returns: QueryResult with status, data (DataFrame), and metadata
+
+ Example:
+ from superset_core.api.daos import DatabaseDAO
+ from superset_core.api.types import QueryOptions, QueryStatus
+
+ db = DatabaseDAO.find_one_or_none(id=1)
+ result = db.execute(
+ "SELECT * FROM users WHERE active = true",
+ options=QueryOptions(schema="public", limit=100)
+ )
+ if result.status == QueryStatus.SUCCESS:
+ df = result.data
+ print(f"Found {result.row_count} rows")
Review Comment:
The example code references `result.row_count` which does not exist on the
`QueryResult` type. According to the type definition in types.py, `QueryResult`
contains a list of `StatementResult` objects, and row counts would need to be
accessed via `sum(s.row_count for s in result.statements)`.
```suggestion
print(f"Found {sum(s.row_count for s in result.statements)}
rows")
```
##########
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
+ :param options: Query execution options (see `QueryOptions`).
+ If not provided, defaults are used.
+ :returns: QueryResult with status, data (DataFrame), and metadata
+
+ Example:
+ from superset_core.api.daos import DatabaseDAO
+ from superset_core.api.types import QueryOptions, QueryStatus
+
+ db = DatabaseDAO.find_one_or_none(id=1)
+ result = db.execute(
+ "SELECT * FROM users WHERE active = true",
+ options=QueryOptions(schema="public", limit=100)
+ )
+ if result.status == QueryStatus.SUCCESS:
+ df = result.data
+ print(f"Found {result.row_count} rows")
+
+ Example with templates:
+ result = db.execute(
+ "SELECT * FROM {{ table }} WHERE date > '{{ start_date }}'",
+ options=QueryOptions(
+ schema="analytics",
+ template_params={"table": "events", "start_date":
"2024-01-01"}
+ )
+ )
+
+ Example with dry_run:
+ result = db.execute(
+ "SELECT * FROM users",
+ options=QueryOptions(schema="public", limit=100, dry_run=True)
+ )
+ print(f"Would execute: {result.query}")
Review Comment:
The example code references `result.query` which does not exist on the
`QueryResult` type. For dry-run mode, the transformed SQL is available in
`result.statements[0].statement` (or iterate through all statements).
```suggestion
print(f"Would execute: {result.statements[0].statement}")
```
##########
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
+ :param options: Query execution options (see `QueryOptions`).
+ If not provided, defaults are used.
+ :returns: QueryResult with status, data (DataFrame), and metadata
+
+ Example:
+ from superset_core.api.daos import DatabaseDAO
+ from superset_core.api.types import QueryOptions, QueryStatus
+
+ db = DatabaseDAO.find_one_or_none(id=1)
+ result = db.execute(
+ "SELECT * FROM users WHERE active = true",
+ options=QueryOptions(schema="public", limit=100)
+ )
+ if result.status == QueryStatus.SUCCESS:
+ df = result.data
+ print(f"Found {result.row_count} rows")
+
+ Example with templates:
+ result = db.execute(
+ "SELECT * FROM {{ table }} WHERE date > '{{ start_date }}'",
+ options=QueryOptions(
+ schema="analytics",
+ template_params={"table": "events", "start_date":
"2024-01-01"}
+ )
+ )
+
+ Example with dry_run:
+ result = db.execute(
+ "SELECT * FROM users",
+ options=QueryOptions(schema="public", limit=100, dry_run=True)
+ )
+ print(f"Would execute: {result.query}")
+ """
+ raise NotImplementedError("Method will be replaced during
initialization")
+
+ def execute_async(
+ self,
+ sql: str,
+ options: QueryOptions | None = None,
+ ) -> AsyncQueryHandle:
+ """
+ Execute SQL asynchronously.
+
+ Returns immediately with a handle for tracking progress and retrieving
+ results from the background worker.
+
+ :param sql: SQL query to execute
+ :param options: Query execution options (see `QueryOptions`).
+ If not provided, defaults are used.
+ :returns: AsyncQueryHandle for tracking the query
+
+ Example:
+ handle = db.execute_async(
+ "SELECT * FROM large_table",
+ options=QueryOptions(schema="analytics")
+ )
+
+ # Check status and get results
+ status = handle.get_status()
+ if status == QueryStatus.SUCCESS:
+ query_result = handle.get_result()
+ df = query_result.data
Review Comment:
The example code references `query_result.data` which does not exist on the
`QueryResult` type. According to the type definition, data is stored per
statement in `query_result.statements[i].data`.
```suggestion
df = query_result.statements[0].data
```
##########
superset/sql/execution/executor.py:
##########
@@ -0,0 +1,1080 @@
+# 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 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
Review Comment:
Multiple direct `db.session.commit()` calls throughout the codebase bypass
transaction management. Consider using context managers or explicit transaction
boundaries to ensure proper rollback on errors and maintain data consistency.
```suggestion
with db.session.begin():
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}",
)
# Commit handled by context manager
```
--
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]