Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(tsql): Transpile standalone exp.Fetch LIMIT #4680

Merged
merged 1 commit into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions sqlglot/dialects/tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,14 +967,22 @@ def scope_resolution(self, rhs: str, scope_name: str) -> str:
return f"{scope_name}::{rhs}"

def select_sql(self, expression: exp.Select) -> str:
if expression.args.get("offset"):
limit = expression.args.get("limit")
offset = expression.args.get("offset")

if isinstance(limit, exp.Fetch) and not offset:
# Dialects like Oracle can FETCH directly from a row set but
# T-SQL requires an ORDER BY + OFFSET clause in order to FETCH
offset = exp.Offset(expression=exp.Literal.number(0))
expression.set("offset", offset)

if offset:
if not expression.args.get("order"):
# ORDER BY is required in order to use OFFSET in a query, so we use
# a noop order by, since we don't really care about the order.
# See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819
expression.order_by(exp.select(exp.null()).subquery(), copy=False)

limit = expression.args.get("limit")
if isinstance(limit, exp.Limit):
# TOP and OFFSET can't be combined, we need use FETCH instead of TOP
# we replace here because otherwise TOP would be generated in select_sql
Expand Down
8 changes: 8 additions & 0 deletions tests/dialects/test_oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,14 @@ def test_oracle(self):
"SELECT /*+ ORDERED */ * /* test */ FROM tbl",
)

self.validate_all(
"SELECT * FROM t FETCH FIRST 10 ROWS ONLY",
write={
"oracle": "SELECT * FROM t FETCH FIRST 10 ROWS ONLY",
"tsql": "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH FIRST 10 ROWS ONLY",
},
)

def test_join_marker(self):
self.validate_identity("SELECT e1.x, e2.x FROM e e1, e e2 WHERE e1.y (+) = e2.y")

Expand Down