Skip to content

fix(trino): emit OFFSET before LIMIT for paginated queries - #42899

Merged
eschutho merged 5 commits into
apache:masterfrom
eschutho:sc-115547-trino-offset-pagination
Nov 6, 2026
Merged

eschutho merged 5 commits into
apache:masterfrom
eschutho:sc-115547-trino-offset-pagination

Conversation

@eschutho

@eschutho eschutho commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Drill to Detail pagination fails on Trino/Presto: navigating to page 2 of the results produces a query that Trino rejects with a syntax error:

line 7:11: mismatched input 'OFFSET'. Expecting: <EOF>

This was reported when using Trino as the query engine. The same query runs fine in SQL Lab, because SQL Lab never emits an OFFSET — only the automated pagination path does.

Problem

Superset builds paginated queries with SQLAlchemy's dialect-aware construction (qry.limit(row_limit).offset(row_offset) in models/helpers.py) and compiles them in Database.compile_sqla_query. In SQLAlchemy the compiled clause order is decided entirely by the driver's dialect (limit_clause), not by the order the methods are called.

Trino and Presto require OFFSET to appear before LIMIT (unlike the ANSI LIMIT ... OFFSET ordering). Whether Superset emits valid SQL therefore depends on which driver the connection resolves to:

  • The official trino package and the legacy sqlalchemy-trino package both override limit_clause to emit OFFSET ... LIMIT → correct.
  • PyHive's Presto/Trino dialects (PrestoCompiler / TrinoCompiler) do not override limit_clause; they inherit SQLAlchemy's ANSI LIMIT ... OFFSET → rejected by Presto/Trino.

So any connection that resolves to a PyHive dialect — including any vanilla presto:// connection on stock Superset — produces invalid SQL as soon as an offset is applied (Drill to Detail page 2+, server-side pagination, etc.).

Verified directly:

>>> from sqlalchemy import table, column, select
>>> from pyhive.sqlalchemy_presto import PrestoDialect
>>> q = select([table('t', column('a')).c.a]).limit(50).offset(50)
>>> str(q.compile(dialect=PrestoDialect(), compile_kwargs={'literal_binds': True}))
'SELECT "t"."a" FROM "t" LIMIT 50 OFFSET 50'   # ← invalid for Presto/Trino

Fix

Guarantee the ordering in Superset rather than depending on the driver:

  • Add an offset_before_limit engine-spec flag (default False, set to True on PrestoBaseEngineSpec, inherited by both Presto and Trino).
  • Add BaseEngineSpec.apply_offset_before_limit(sql), which re-renders the statement through sqlglot's dialect-aware generator (which orders OFFSET before LIMIT for these dialects). A cheap textual gate means it only runs when the flag is set and the SQL is actually in the invalid order, so drivers that already emit OFFSET first are left byte-for-byte untouched.
  • Call it once at the end of Database.compile_sqla_query, the single choke point where datasource queries are turned into SQL.

This fixes every automated-offset path (Drill to Detail, samples, server pagination) for Presto and Trino, independent of the installed SQLAlchemy driver.

BEFORE/AFTER

This is a query-generation fix, so the meaningful before/after is the SQL Superset dispatches for Drill to Detail page 2 (row_limit=50, row_offset=50) when the connection resolves to a driver that emits ANSI ordering (e.g. PyHive). Output below is the actual compiled SQL, reproduced end to end.

Before — invalid for Trino/Presto (fails with line N: mismatched input 'OFFSET'. Expecting: <EOF>):

SELECT "cleaned_sales_data"."order_number", "cleaned_sales_data"."sales"
FROM "cleaned_sales_data"
LIMIT 50 OFFSET 50

After — valid; page 2 loads:

SELECT
  "cleaned_sales_data"."order_number",
  "cleaned_sales_data"."sales"
FROM "cleaned_sales_data"
OFFSET 50
LIMIT 50

UI screenshots aren't included because reproducing the failure in the browser requires a live Trino/Presto cluster connected via the PyHive dialect; the SQL above is the exact statement that changes.

TESTING INSTRUCTIONS

  1. Connect a Trino (or Presto) database whose connection uses a driver that emits ANSI LIMIT ... OFFSET (e.g. PyHive).
  2. Open any chart → Drill to Detail → go to page 2 of the results.
  3. Before this change the query fails with mismatched input 'OFFSET'; after it, the page loads.

Automated coverage added:

  • tests/unit_tests/db_engine_specs/test_trino.py — apply_offset_before_limit reorders ANSI ordering, leaves already-correct/limit-only SQL untouched, and is a no-op for engines that don't set the flag.
  • tests/unit_tests/models/core_test.py — end-to-end through compile_sqla_query, driving a Trino Database backed by a dialect that emits ANSI ordering and asserting the compiled SQL puts OFFSET before LIMIT.
pytest tests/unit_tests/db_engine_specs/test_trino.py tests/unit_tests/db_engine_specs/test_presto.py \
       tests/unit_tests/db_engine_specs/test_base.py tests/unit_tests/models/core_test.py

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
  • Introduces new feature or API
  • Removes existing feature or API

🤖 Generated with Claude Code

@dosubot dosubot Bot added data:connect:presto Related to Presto data:connect:trino Related to Trino labels Aug 7, 2026
@bito-code-review

bito-code-review Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #42f9d6

Actionable Suggestions - 0
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/db_engine_specs/base.py - 1
Review Details
  • Files reviewed - 5 · Commit Range: b3c2be0..b3c2be0
    • superset/db_engine_specs/base.py
    • superset/db_engine_specs/presto.py
    • superset/models/core.py
    • tests/unit_tests/db_engine_specs/test_trino.py
    • tests/unit_tests/models/core_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@netlify

netlify Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit ef5eab4
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aea85e7e500ed20ddc44d90
😎 Deploy Preview https://deploy-preview-42899--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.00%. Comparing base (61e8627) to head (6f9be4c).
⚠️ Report is 32 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #42899      +/-   ##
==========================================
+ Coverage   84.94%   85.00%   +0.05%     
==========================================
  Files        3077     3079       +2     
  Lines      208282   209261     +979     
  Branches    49121    49234     +113     
==========================================
+ Hits       176932   177884     +952     
- Misses      27985    27998      +13     
- Partials     3365     3379      +14     
Flag Coverage Δ
hive 34.18% <76.47%> (-0.01%) ⬇️
mysql 52.00% <100.00%> (-0.16%) ⬇️
postgres 52.02% <100.00%> (-0.17%) ⬇️
presto 35.84% <82.35%> (-0.05%) ⬇️
python 87.97% <100.00%> (+0.07%) ⬆️
sqlite 51.76% <100.00%> (-0.17%) ⬇️
unit 82.93% <64.70%> (+0.15%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment on lines +170 to +175
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The flag is defined on PrestoBaseEngineSpec, but HiveEngineSpec inherits PrestoEngineSpec, and SparkEngineSpec and DatabricksHiveEngineSpec inherit HiveEngineSpec. Consequently, every compiled Hive, Spark, and Databricks Interactive Cluster query with LIMIT and OFFSET is reparsed and regenerated using that engine's sqlglot dialect, even though this change is intended only for Presto and Trino. This can rewrite valid engine-specific SQL or alter function semantics; define the flag only on PrestoEngineSpec and TrinoEngineSpec, or explicitly disable it on the Hive-family descendants. [api mismatch]

Severity Level: Major ⚠️
- ⚠️ Hive pagination queries receive unintended SQL reformatting.
- ⚠️ Spark pagination queries use the shared normalization path.
- ⚠️ Databricks interactive-cluster SQL is reparsed unnecessarily.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/db_engine_specs/presto.py
**Line:** 170:175
**Comment:**
	*Api Mismatch: The flag is defined on `PrestoBaseEngineSpec`, but `HiveEngineSpec` inherits `PrestoEngineSpec`, and `SparkEngineSpec` and `DatabricksHiveEngineSpec` inherit `HiveEngineSpec`. Consequently, every compiled Hive, Spark, and Databricks Interactive Cluster query with `LIMIT` and `OFFSET` is reparsed and regenerated using that engine's sqlglot dialect, even though this change is intended only for Presto and Trino. This can rewrite valid engine-specific SQL or alter function semantics; define the flag only on `PrestoEngineSpec` and `TrinoEngineSpec`, or explicitly disable it on the Hive-family descendants.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. The offset_before_limit flag is currently defined on PrestoBaseEngineSpec, which is inherited by HiveEngineSpec and its descendants (SparkEngineSpec, DatabricksHiveEngineSpec). This causes unnecessary SQL re-parsing for these engines, which do not require the OFFSET before LIMIT reordering.

To resolve this, you should move the flag definition from PrestoBaseEngineSpec to PrestoEngineSpec and TrinoEngineSpec specifically, or explicitly set offset_before_limit = False in HiveEngineSpec.

Proposed Fix

  1. In superset/db_engine_specs/presto.py: Remove the flag from PrestoBaseEngineSpec and add it to the specific engine classes.
  2. In superset/db_engine_specs/hive.py: Explicitly set offset_before_limit = False to ensure descendants inherit the correct behavior.

Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well?

superset/db_engine_specs/presto.py

class PrestoBaseEngineSpec(BaseEngineSpec, metaclass=ABCMeta):
    # ...
    # Remove offset_before_limit = True from here

class PrestoEngineSpec(PrestoBaseEngineSpec):
    offset_before_limit = True

class TrinoEngineSpec(PrestoBaseEngineSpec):
    offset_before_limit = True

rusackas pushed a commit that referenced this pull request Aug 27, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
rusackas pushed a commit that referenced this pull request Aug 28, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
rusackas pushed a commit that referenced this pull request Aug 29, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 3, 2026
rusackas pushed a commit that referenced this pull request Sep 3, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
rusackas pushed a commit that referenced this pull request Sep 4, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
rusackas pushed a commit that referenced this pull request Sep 6, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
rusackas pushed a commit that referenced this pull request Sep 9, 2026
Pilot for real-container testing of db_engine_specs against actual
databases (CockroachDB, CrateDB, Trino), via testcontainers-python.
Existing unit tests mock the driver/dialect layer entirely, which cannot
catch real SQL-compilation or type-mapping bugs -- e.g. #42899, where
Trino emitted OFFSET before LIMIT for paginated queries.

Runs nightly (.github/workflows/nightly-testcontainers.yml), not on every
merge: container pulls and startup are slower and more flake-prone than
the existing mocked unit tests, and this measures that cost/signal
tradeoff before considering wider adoption.

Building this surfaced two real bugs, fixed/documented separately:
- The cockroachdb dialect was completely broken under SQLAlchemy 2.0 due
  to a dead upstream package -- fixed in #43501.
- testcontainers-python's TrinoContainer.get_connection_url() returns the
  container-internal port instead of the Docker-mapped host port; worked
  around locally, filed upstream.
Drill to Detail pagination (and any paginated query) fails on Trino/Presto
with `mismatched input 'OFFSET'` on page 2+. Superset builds the query with
SQLAlchemy `.limit()`/`.offset()`, and the compiled clause order is decided by
the driver's dialect. The official `trino` package and `sqlalchemy-trino`
override `limit_clause` to emit `OFFSET ... LIMIT`, but PyHive's Presto/Trino
dialects inherit SQLAlchemy's ANSI `LIMIT ... OFFSET` ordering, which Presto
and Trino reject. Connections that resolve to a PyHive dialect (and any vanilla
`presto://` connection) therefore produce invalid SQL when an offset is applied.

Guarantee the ordering in Superset instead of relying on the driver: add an
`offset_before_limit` engine-spec flag (True for Presto/Trino) and normalize
compiled SQL via sqlglot's dialect-aware generator in `compile_sqla_query`. The
reorder only runs when the flag is set and the SQL is in the invalid order, so
drivers that already emit OFFSET first are untouched.

Reported when using Trino as the query engine.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@eschutho
eschutho force-pushed the sc-115547-trino-offset-pagination branch from b3c2be0 to e1517c0 Compare October 26, 2026 16:28
@eschutho eschutho removed the requires:rebase Requires rebasing on top of current master label Oct 26, 2026
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; Hive-family specs disable the Presto pagination rewrite, avoiding unintended changes to their SQL.

Assessed commit: 6f9be4c13d7a

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes: the fix works for PyHive presto://, but the new flag also leaks into Hive, Spark and Databricks Hive, and the required pre-commit (current) check fails. Details inline.

# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 High — offset_before_limit leaks into Hive, Spark and Databricks Hive

HiveEngineSpec subclasses PrestoEngineSpec (hive.py:104), so Hive, SparkEngineSpec and DatabricksHiveEngineSpec all inherit offset_before_limit = True from this line. PyHive's Hive dialect emits LIMIT x OFFSET y, so every page-2+ query on these engines gets fully re-rendered by sqlglot, and the clause order stays the same.

The SQL still changes, though. Through get_query_str on spark:// with a filter value C:\users\data:

  • page 1: `path` = 'C:\users\data'
  • page 2: `path` = 'C:\\users\\data'

So two pages of the same Drill to Detail filter on different values. On Hive the re-render also drops /*+ MAPJOIN(...) */ hints (sqlglot logs "Hints are not supported").

Fix: opt out in HiveEngineSpec, next to its existing supports_grouping_sets = False override (hive.py isn't in the diff, so no applyable suggestion):

    # Hive/Spark accept the ANSI ``LIMIT ... OFFSET`` order; don't inherit
    # the Presto/Trino reordering (and the sqlglot re-render it triggers).
    offset_before_limit = False

Plus a test that paginated Hive/Spark SQL comes back unchanged.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open after the master merge. A correction to my example above: with sqlglot 30.24 (#45704) the backslash value no longer changes. Page 2 now renders 'C:usersdata', which Spark reads the same as page 1's 'C:\users\data'.

The re-render still breaks page 2 on Hive, though:

  • named_struct('x', f.a, 'y', d.q).x becomes STRUCT(f.a, d.q).x. Hive names those fields col1/col2, so .x fails.
  • The /*+ MAPJOIN(d) */ hint is still dropped.

Hive and Spark already accept LIMIT … OFFSET, so they get the rewrite with no benefit. The fix is the same: offset_before_limit = False on HiveEngineSpec.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d6dc352: HiveEngineSpec now sets offset_before_limit = False (superset/db_engine_specs/hive.py), overriding the value inherited from PrestoBaseEngineSpec. SparkEngineSpec and DatabricksHiveEngineSpec subclass HiveEngineSpec, so they pick up the opt-out too. The non-Hive Databricks specs derive from BaseEngineSpec (default False), so they need no override. Added test_apply_offset_before_limit_not_applied_to_hive_family asserting Hive/Spark/Databricks-Hive leave ANSI LIMIT ... OFFSET SQL untouched. I also fixed the ruff 0.9.7 formatting and the where_in chart test fixture. The sqlglot literal re-rendering concern is not addressed here.

Comment on lines +3080 to +3082
assert upper.rfind("OFFSET") < upper.rfind(
"LIMIT"
), f"OFFSET must precede LIMIT for Trino, got: {result!r}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 High — required pre-commit (current) check fails on ruff-format

ruff 0.9.7 (pinned in requirements/development.txt) reformats this assert, and pre-commit (current) is a required check in .asf.yaml.

Suggested change
assert upper.rfind("OFFSET") < upper.rfind(
"LIMIT"
), f"OFFSET must precede LIMIT for Trino, got: {result!r}"
assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
f"OFFSET must precede LIMIT for Trino, got: {result!r}"
)

Comment thread tests/unit_tests/models/core_test.py Outdated
Comment on lines +2988 to +2990
assert upper.rfind("OFFSET") < upper.rfind(
"LIMIT"
), f"OFFSET must precede LIMIT for Trino, got: {sql!r}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 High — same ruff-format failure as in test_trino.py

Suggested change
assert upper.rfind("OFFSET") < upper.rfind(
"LIMIT"
), f"OFFSET must precede LIMIT for Trino, got: {sql!r}"
assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
f"OFFSET must precede LIMIT for Trino, got: {sql!r}"
)

Comment thread superset/db_engine_specs/base.py Outdated
return sql

try:
return SQLScript(sql, engine=cls.engine).format()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium (non-blocking) — re-rendering the whole statement can silently change Presto SQL

When the gate fires on presto://, sqlglot regenerates the entire query, not just the trailing clause. A custom WHERE price >= DECIMAL '9.99' comes out on page 2 as price >= CAST('9.99' AS DECIMAL). Presto/Trino read a bare DECIMAL as decimal(38,0), so page 2 effectively filters >= 10 while page 1 filters >= 9.99. Master leaves user clauses as written for exactly this reason (sanitize_clause, #36113), and the gate comment's "never wrong SQL" doesn't hold.

A narrower option that avoids the round-trip: make PyHive's PrestoCompiler.limit_clause emit OFFSET then LIMIT (as the official trino dialect does), or rewrite only an anchored trailing LIMIT n OFFSET m. The compiler route also fixes the OFFSET-only LIMIT -1 OFFSET n case and leaves Hive/Spark untouched.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking follow-up: one more case where the page-2 re-render changes results on presto://. log(10, x) becomes LOG(x, 10), so on a Trino server page 1 and page 2 compute different values. Rewriting only an anchored trailing LIMIT n OFFSET m would avoid the round-trip, and the gate comment's "never wrong SQL" line could go.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @rebenitez1802, good catch. Pushed 6f9be4c: apply_offset_before_limit now rewrites only an anchored trailing LIMIT n OFFSET m into OFFSET m LIMIT n with a regex, so the rest of the query is no longer re-rendered (no more log(10, x) → LOG(x, 10) between pages). The sqlglot round-trip and the "never wrong SQL" comment are gone, and I added tests for the trailing-only rewrite and for non-trailing LIMIT/OFFSET in subqueries being left alone.

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Hive leak is still open (see thread). CI is also blocked: tests/unit_tests/jinja_context_test.py::test_where_in_chart_compilation fails with this change, because its Database has no sqlalchemy_uri.

# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open after the master merge. A correction to my example above: with sqlglot 30.24 (#45704) the backslash value no longer changes. Page 2 now renders 'C:usersdata', which Spark reads the same as page 1's 'C:\users\data'.

The re-render still breaks page 2 on Hive, though:

  • named_struct('x', f.a, 'y', d.q).x becomes STRUCT(f.a, d.q).x. Hive names those fields col1/col2, so .x fails.
  • The /*+ MAPJOIN(d) */ hint is still dropped.

Hive and Spark already accept LIMIT … OFFSET, so they get the rewrite with no benefit. The fix is the same: offset_before_limit = False on HiveEngineSpec.

…t and jinja test fixture

- HiveEngineSpec (and Spark/Databricks Hive) opt out of offset_before_limit
- reformat asserts for ruff 0.9.7
- give where_in chart test Database a sqlalchemy_uri

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ffset-pagination

# Conflicts:
#	superset/db_engine_specs/hive.py

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Hive opt-out, formatting and test-fixture fixes look good, and CI is green. LGTM.

Comment thread superset/db_engine_specs/base.py Outdated
return sql

try:
return SQLScript(sql, engine=cls.engine).format()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking follow-up: one more case where the page-2 re-render changes results on presto://. log(10, x) becomes LOG(x, 10), so on a Trino server page 1 and page 2 compute different values. Rewriting only an anchored trailing LIMIT n OFFSET m would avoid the round-trip, and the gate comment's "never wrong SQL" line could go.

…ering the query

Re-rendering the whole statement through sqlglot could change semantics on
presto:// (e.g. log(10, x) -> LOG(x, 10)). Rewrite only an anchored trailing
`LIMIT n OFFSET m` and leave the rest of the SQL untouched.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@eschutho
eschutho merged commit c01ffe6 into apache:master Nov 6, 2026
98 checks passed
hainenber pushed a commit that referenced this pull request Nov 14, 2026
villebro pushed a commit that referenced this pull request Nov 14, 2026
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Evan Rusackas <[email protected]>
(cherry picked from commit c01ffe6)
@github-actions github-actions Bot added 🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels 🚢 0.20.2 First shipped in 0.20.2 labels Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels data:connect:presto Related to Presto data:connect:trino Related to Trino size/L 🚢 0.20.2 First shipped in 0.20.2

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants