This is an automated email from the ASF dual-hosted git repository.

villebro pushed a commit to branch 7.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 506aa487c70fc38c3c595428b8efe1d1ee94e6eb
Author: Elizabeth Thompson <[email protected]>
AuthorDate: Thu Nov 5 16:32:30 2026 -0800

    fix(trino): emit OFFSET before LIMIT for paginated queries (#42899)
    
    Co-authored-by: Claude Opus 4.8 <[email protected]>
    Co-authored-by: Evan Rusackas <[email protected]>
    (cherry picked from commit c01ffe6eb706ffc1c2961b2d76092e13d263dabb)
---
 superset/db_engine_specs/base.py               | 40 +++++++++++
 superset/db_engine_specs/hive.py               |  5 ++
 superset/db_engine_specs/presto.py             |  7 ++
 superset/models/core.py                        |  6 ++
 tests/unit_tests/db_engine_specs/test_trino.py | 93 ++++++++++++++++++++++++++
 tests/unit_tests/jinja_context_test.py         |  2 +-
 tests/unit_tests/models/core_test.py           | 48 +++++++++++++
 7 files changed, 200 insertions(+), 1 deletion(-)

diff --git a/superset/db_engine_specs/base.py b/superset/db_engine_specs/base.py
index 4bea971475e..38492fd0e79 100644
--- a/superset/db_engine_specs/base.py
+++ b/superset/db_engine_specs/base.py
@@ -122,6 +122,12 @@ ColumnTypeMapping = tuple[
     GenericDataType,
 ]
 
+# Trailing ``LIMIT n OFFSET m`` (optionally followed by a semicolon), anchored
+# to the end of the statement so subqueries are never touched.
+_TRAILING_LIMIT_OFFSET = re.compile(
+    r"\s+LIMIT\s+(\d+)\s+OFFSET\s+(\d+)(\s*;?\s*)$", re.IGNORECASE
+)
+
 logger = logging.getLogger()
 
 # When connecting to a database it's hard to catch specific exceptions, since 
we support
@@ -579,6 +585,16 @@ class BaseEngineSpec:  # pylint: 
disable=too-many-public-methods
     # pagination via another mechanism (e.g. Elasticsearch's cursor API).
     supports_offset = True
 
+    # Whether the engine's SQL grammar requires OFFSET to appear *before* LIMIT
+    # (Presto and Trino), unlike the ANSI ``LIMIT ... OFFSET`` ordering. Most
+    # SQLAlchemy dialects for these engines emit the clauses in the correct
+    # order, but some drivers (notably PyHive's Presto/Trino dialects) inherit
+    # the ANSI ordering, which Presto and Trino reject with a syntax error
+    # (``mismatched input 'OFFSET'``). When True, Superset normalizes compiled
+    # SQL so OFFSET precedes LIMIT, making paginated queries (e.g. Drill to
+    # Detail page 2+) valid regardless of the installed driver.
+    offset_before_limit = False
+
     # Whether ORDER BY clause can use aliases created in SELECT
     # that are the same as a source column
     allows_alias_to_source_column = True
@@ -1774,6 +1790,30 @@ class BaseEngineSpec:  # pylint: 
disable=too-many-public-methods
             # not parseable in sqlglot 30+, which now requires an expression 
arg.
             return None
 
+    @classmethod
+    def apply_offset_before_limit(cls, sql: str) -> str:
+        """
+        Reorder a trailing ``LIMIT n OFFSET m`` into ``OFFSET m LIMIT n``
+        for engines whose grammar requires OFFSET to precede LIMIT.
+
+        This is a no-op unless ``offset_before_limit`` is set (Presto/Trino) 
and
+        the compiled SQL ends in the invalid ANSI order. Some drivers (e.g.
+        PyHive's Presto/Trino dialects) emit ``LIMIT n OFFSET m``, which Presto
+        and Trino reject with ``mismatched input 'OFFSET'``.
+
+        Only the anchored trailing clause is rewritten; the rest of the query 
is
+        left byte-for-byte unchanged rather than re-rendered, so dialect
+        differences in the rest of the statement (e.g. ``log(10, x)`` becoming
+        ``LOG(x, 10)``) can't leak in.
+
+        :param sql: A single compiled SQL statement
+        :return: The statement with OFFSET before LIMIT when required
+        """
+        if not cls.offset_before_limit:
+            return sql
+
+        return _TRAILING_LIMIT_OFFSET.sub(r" OFFSET \2 LIMIT \1\3", sql, 
count=1)
+
     @classmethod
     def get_cte_query(cls, sql: str) -> str | None:
         """
diff --git a/superset/db_engine_specs/hive.py b/superset/db_engine_specs/hive.py
index 79d5923fee1..f09eb9fb1e1 100644
--- a/superset/db_engine_specs/hive.py
+++ b/superset/db_engine_specs/hive.py
@@ -102,6 +102,11 @@ class HiveEngineSpec(PrestoEngineSpec):
 
     supports_dynamic_schema = True
     supports_cross_catalog_queries = False
+
+    # Hive, Spark and Databricks (Hive-based) use the ANSI ``LIMIT ... OFFSET``
+    # order emitted by PyHive's Hive dialect; opt out of the Presto/Trino
+    # OFFSET-before-LIMIT rewrite inherited from PrestoBaseEngineSpec.
+    offset_before_limit = False
     # Explicitly opt out (overriding the inherited PrestoEngineSpec value):
     # Hive/Spark's GROUPING SETS + GROUPING() marker semantics have not been
     # verified against this query pattern, so fall back to one query per
diff --git a/superset/db_engine_specs/presto.py 
b/superset/db_engine_specs/presto.py
index 91dac92806b..939b3ef840f 100644
--- a/superset/db_engine_specs/presto.py
+++ b/superset/db_engine_specs/presto.py
@@ -167,6 +167,13 @@ class PrestoBaseEngineSpec(BaseEngineSpec, 
metaclass=ABCMeta):
     supports_dynamic_schema = True
     supports_catalog = supports_dynamic_catalog = 
supports_cross_catalog_queries = True
 
+    # Presto and Trino require OFFSET to appear before LIMIT in the SQL 
grammar.
+    # Superset normalizes compiled SQL accordingly so pagination works even 
when
+    # the connection resolves to a driver whose dialect emits the ANSI
+    # ``LIMIT ... OFFSET`` ordering (e.g. PyHive). See
+    # ``BaseEngineSpec.apply_offset_before_limit``.
+    offset_before_limit = True
+
     encrypted_extra_sensitive_fields = {
         "$.auth_params.password": "Password",
         "$.auth_params.token": "JWT Token",
diff --git a/superset/models/core.py b/superset/models/core.py
index ab484f7409c..7c4dde4aa9f 100755
--- a/superset/models/core.py
+++ b/superset/models/core.py
@@ -1101,6 +1101,12 @@ class Database(CoreDatabase, AuditMixinNullable, 
ImportExportMixin):  # pylint:
             script = SQLScript(sql, self.db_engine_spec.engine).optimize()
             sql = script.format()
 
+        # Presto/Trino require OFFSET before LIMIT; normalize the compiled SQL
+        # so pagination stays valid regardless of the installed driver's 
dialect
+        # (e.g. PyHive emits the ANSI ``LIMIT ... OFFSET`` order these engines
+        # reject). No-op for engines that don't need it.
+        sql = self.db_engine_spec.apply_offset_before_limit(sql)
+
         return sql
 
     def select_star(  # pylint: disable=too-many-arguments
diff --git a/tests/unit_tests/db_engine_specs/test_trino.py 
b/tests/unit_tests/db_engine_specs/test_trino.py
index 343efef4e11..f128f0ce8b5 100644
--- a/tests/unit_tests/db_engine_specs/test_trino.py
+++ b/tests/unit_tests/db_engine_specs/test_trino.py
@@ -1951,3 +1951,96 @@ def 
test_impersonate_user_with_token_no_verify_configured() -> None:
     connect_args = new_kwargs["connect_args"]
     assert "verify" not in connect_args
     assert connect_args["http_session"].verify is True
+
+
+def test_apply_offset_before_limit_reorders_ansi_ordering() -> None:
+    """
+    Trino requires OFFSET before LIMIT. Some SQLAlchemy drivers (e.g. PyHive)
+    compile paginated queries in the ANSI ``LIMIT ... OFFSET`` order, which
+    Trino rejects with ``mismatched input 'OFFSET'``. The engine spec must
+    normalize such SQL so OFFSET precedes LIMIT.
+    """
+    from superset.db_engine_specs.trino import TrinoEngineSpec
+
+    ansi_sql = "SELECT a, b\nFROM t\nLIMIT 50 OFFSET 50"
+    result = TrinoEngineSpec.apply_offset_before_limit(ansi_sql)
+
+    upper = result.upper()
+    assert "OFFSET" in upper
+    assert "LIMIT" in upper
+    assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
+        f"OFFSET must precede LIMIT for Trino, got: {result!r}"
+    )
+
+
+def test_apply_offset_before_limit_leaves_correct_order_untouched() -> None:
+    """
+    When a driver already emits ``OFFSET ... LIMIT`` (e.g. the official trino
+    package), the SQL is left byte-for-byte unchanged — no needless reparse.
+    """
+    from superset.db_engine_specs.trino import TrinoEngineSpec
+
+    valid_sql = "SELECT a, b\nFROM t\nOFFSET 50\nLIMIT 50"
+    assert TrinoEngineSpec.apply_offset_before_limit(valid_sql) == valid_sql
+
+
+def test_apply_offset_before_limit_limit_only_untouched() -> None:
+    """A query with LIMIT but no OFFSET (e.g. page 1) is not rewritten."""
+    from superset.db_engine_specs.trino import TrinoEngineSpec
+
+    limit_only = "SELECT a, b\nFROM t\nLIMIT 50"
+    assert TrinoEngineSpec.apply_offset_before_limit(limit_only) == limit_only
+
+
+def test_apply_offset_before_limit_noop_for_ansi_engines() -> None:
+    """
+    Engines that don't set ``offset_before_limit`` (the default) never touch 
the
+    SQL, even when it is in ANSI ``LIMIT ... OFFSET`` order (valid for them).
+    """
+    from superset.db_engine_specs.base import BaseEngineSpec
+
+    ansi_sql = "SELECT a, b FROM t LIMIT 50 OFFSET 50"
+    assert BaseEngineSpec.offset_before_limit is False
+    assert BaseEngineSpec.apply_offset_before_limit(ansi_sql) == ansi_sql
+
+
+def test_apply_offset_before_limit_not_applied_to_hive_family() -> None:
+    """
+    Hive, Spark and Databricks (Hive) inherit from the Presto spec but use the
+    ANSI ``LIMIT ... OFFSET`` order, so they must not get the Trino rewrite.
+    """
+    from superset.db_engine_specs.databricks import DatabricksHiveEngineSpec
+    from superset.db_engine_specs.hive import HiveEngineSpec
+    from superset.db_engine_specs.spark import SparkEngineSpec
+
+    ansi_sql = "SELECT a, b\nFROM t\nLIMIT 50 OFFSET 50"
+    for spec in (HiveEngineSpec, SparkEngineSpec, DatabricksHiveEngineSpec):
+        assert spec.offset_before_limit is False
+        assert spec.apply_offset_before_limit(ansi_sql) == ansi_sql
+
+
+def test_apply_offset_before_limit_rewrites_only_trailing_clause() -> None:
+    """
+    Only the anchored trailing ``LIMIT n OFFSET m`` is rewritten; the rest of 
the
+    statement (including function calls and subqueries) is preserved verbatim.
+    """
+    from superset.db_engine_specs.trino import TrinoEngineSpec
+
+    sql = (
+        "SELECT log(10, x) AS y\n"
+        "FROM (SELECT x FROM t LIMIT 5 OFFSET 1) s\n"
+        "LIMIT 50 OFFSET 100"
+    )
+    assert TrinoEngineSpec.apply_offset_before_limit(sql) == (
+        "SELECT log(10, x) AS y\n"
+        "FROM (SELECT x FROM t LIMIT 5 OFFSET 1) s"
+        " OFFSET 100 LIMIT 50"
+    )
+
+
+def test_apply_offset_before_limit_ignores_non_trailing_limit_offset() -> None:
+    """A ``LIMIT ... OFFSET`` that isn't at the end of the statement is 
untouched."""
+    from superset.db_engine_specs.trino import TrinoEngineSpec
+
+    sql = "SELECT x FROM (SELECT x FROM t LIMIT 5 OFFSET 1) s WHERE x > 0"
+    assert TrinoEngineSpec.apply_offset_before_limit(sql) == sql
diff --git a/tests/unit_tests/jinja_context_test.py 
b/tests/unit_tests/jinja_context_test.py
index 4fcd567bbf4..a995d0f5c00 100644
--- a/tests/unit_tests/jinja_context_test.py
+++ b/tests/unit_tests/jinja_context_test.py
@@ -1220,7 +1220,7 @@ def test_where_in_chart_compilation(
 
     sql_dialect = dialect_factory()
     engine = mocker.MagicMock(dialect=sql_dialect)
-    database = Database(database_name="test")
+    database = Database(database_name="test", sqlalchemy_uri="sqlite://")
     mocker.patch.object(
         database, "get_sqla_engine"
     ).return_value.__enter__.return_value = engine
diff --git a/tests/unit_tests/models/core_test.py 
b/tests/unit_tests/models/core_test.py
index 50633300423..d846b2c4b72 100644
--- a/tests/unit_tests/models/core_test.py
+++ b/tests/unit_tests/models/core_test.py
@@ -2586,3 +2586,51 @@ def test_has_view_closes_its_connection(tmp_path: Path) 
-> None:
     _duckdb_database(path, threads=1).has_view(Table("missing"))
 
     _query_duckdb(_duckdb_database(path, threads=2))
+
+
+def test_compile_sqla_query_offset_before_limit_for_trino(
+    mocker: MockerFixture,
+) -> None:
+    """
+    ``compile_sqla_query`` must emit OFFSET before LIMIT for Trino/Presto even
+    when the underlying SQLAlchemy driver compiles paginated queries in the
+    ANSI ``LIMIT ... OFFSET`` order (as PyHive's Presto/Trino dialects do).
+
+    We drive a Trino ``Database`` but back it with a SQLite engine, whose
+    dialect emits ANSI ordering — standing in for a driver that lacks the
+    OFFSET-before-LIMIT override. The fix must reorder the compiled SQL so it
+    is valid Trino.
+    """
+    from contextlib import contextmanager
+
+    from sqlalchemy import create_engine
+
+    from superset.models.core import Database
+
+    database = Database(
+        database_name="trino_db",
+        sqlalchemy_uri="trino://user@localhost:8080/catalog",
+    )
+    # SQLite compiles `LIMIT x OFFSET y` (ANSI order), mimicking PyHive.
+    ansi_engine = create_engine("sqlite://")
+
+    @contextmanager
+    def _get_engine(catalog=None, schema=None, **kwargs):
+        yield ansi_engine
+
+    mocker.patch.object(database, "get_sqla_engine", new=_get_engine)
+
+    # Sanity: the engine spec resolves to Trino, which requires the reorder.
+    assert database.db_engine_spec.offset_before_limit is True
+
+    tbl = SqlalchemyTable("t", MetaData(), Column("a", Integer))
+    qry = select(tbl.c.a).limit(50).offset(50)
+
+    sql = database.compile_sqla_query(qry)
+
+    upper = sql.upper()
+    assert "OFFSET" in upper
+    assert "LIMIT" in upper
+    assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
+        f"OFFSET must precede LIMIT for Trino, got: {sql!r}"
+    )

Reply via email to