Skip to content

Commit

Permalink
Fix(tsql): regression related to CTEs in CREATE VIEW AS statements (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
georgesittas committed Jul 30, 2024
1 parent 864d150 commit a295b3a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
21 changes: 11 additions & 10 deletions sqlglot/dialects/tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,31 +999,32 @@ def create_sql(self, expression: exp.Create) -> str:
kind = expression.kind
exists = expression.args.pop("exists", None)

if kind == "VIEW":
expression.this.set("catalog", None)

sql = super().create_sql(expression)

like_property = expression.find(exp.LikeProperty)
if like_property:
ctas_expression = like_property.this
else:
ctas_expression = expression.expression

if kind == "VIEW":
expression.this.set("catalog", None)
with_ = expression.args.get("with")
if ctas_expression and with_:
# We've already preprocessed the Create expression to bubble up any nested CTEs,
# but CREATE VIEW actually requires the WITH clause to come after it so we need
# 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)

# Convert CTAS statement to SELECT .. INTO ..
if kind == "TABLE" and ctas_expression:
ctas_with = ctas_expression.args.get("with")
if ctas_with:
ctas_with = ctas_with.pop()

if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
ctas_expression = ctas_expression.subquery()

select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
select_into.set("into", exp.Into(this=table))
select_into.set("with", ctas_with)

if like_property:
select_into.limit(0, copy=False)
Expand Down
1 change: 1 addition & 0 deletions tests/dialects/test_tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ def test_ddl(self):
f"UNIQUE {clustered_keyword} ([internal_id] ASC))",
)

self.validate_identity("CREATE VIEW t AS WITH cte AS (SELECT 1 AS c) SELECT c FROM cte")
self.validate_identity(
"ALTER TABLE tbl SET SYSTEM_VERSIONING=ON(HISTORY_TABLE=db.tbl, DATA_CONSISTENCY_CHECK=OFF, HISTORY_RETENTION_PERIOD=5 DAYS)"
)
Expand Down

0 comments on commit a295b3a

Please sign in to comment.