Skip to content

fix(tsql): Retain limit clause in subquery expression.#5227

Merged
georgesittas merged 3 commits intotobymao:mainfrom
MarcusRisanger:fix/tsql-subquery-limit
Jun 16, 2025
Merged

fix(tsql): Retain limit clause in subquery expression.#5227
georgesittas merged 3 commits intotobymao:mainfrom
MarcusRisanger:fix/tsql-subquery-limit

Conversation

@MarcusRisanger
Copy link
Contributor

@MarcusRisanger MarcusRisanger commented Jun 15, 2025

Fixes issue: TobikoData/sqlmesh#4649

Subqueries are parsed twice (at least for tsql) by select_sql, which causes subqueries using LIMIT or TOP to drop these on the second run, when converting CTAS statement to SELECT .. INTO ...

The subquery expression object suffers a side-effect in Generator.select_sql method where any limit expression is popped from the expression and propagated within the method as a string component.

This simple fix reinjects the original limit expression to any query that HAD a limit expression prior to select_sql, but lacks it afterward.

@MarcusRisanger MarcusRisanger changed the title Some semantics to keep limit clause in expression. fix(tsql): Some semantics to keep limit clause in expression. Jun 15, 2025
@MarcusRisanger MarcusRisanger changed the title fix(tsql): Some semantics to keep limit clause in expression. fix(tsql): Retain limit clause in subquery expression. Jun 15, 2025
@georgesittas
Copy link
Collaborator

Hey @MarcusRisanger 👋

Thanks a lot for digging into this! I think we may be able to simplify this a bit. I see that the TOP 1 is preserved given this diff:

+++ b/sqlglot/dialects/tsql.py
@@ -1224,7 +1224,6 @@ class TSQL(Dialect):
                     # to amend the AST by moving the CTEs to the CREATE VIEW statement's query.
                     ctas_expression.set("with", with_.pop())

-            sql = super().create_sql(expression)

             table = expression.find(exp.Table)

@@ -1243,6 +1242,8 @@ class TSQL(Dialect):
                     select_into.limit(0, copy=False)

                 sql = self.sql(select_into)
+            else:
+                sql = super().create_sql(expression)

Wanna give it a shot? Feel free to update the PR and I can merge shortly.

@MarcusRisanger
Copy link
Contributor Author

Very nice @georgesittas - this is the difference between knowing the code base and just blindly implementing change based on debugging call stacks... 🚀

@georgesittas georgesittas merged commit df73a79 into tobymao:main Jun 16, 2025
7 checks passed
@MarcusRisanger MarcusRisanger deleted the fix/tsql-subquery-limit branch June 16, 2025 08:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants