Skip to content

Commit

Permalink
Fix: window sql gen closes tobymao#1739
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao authored and adrianisk committed Jun 21, 2023
1 parent 3bd9211 commit 8dfa184
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 15 deletions.
24 changes: 9 additions & 15 deletions sqlglot/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -1651,32 +1651,26 @@ def where_sql(self, expression: exp.Where) -> str:

def window_sql(self, expression: exp.Window) -> str:
this = self.sql(expression, "this")

partition = self.partition_by_sql(expression)

order = expression.args.get("order")
order_sql = self.order_sql(order, flat=True) if order else ""

partition_sql = partition + " " if partition and order else partition

spec = expression.args.get("spec")
spec_sql = " " + self.windowspec_sql(spec) if spec else ""

order = self.order_sql(order, flat=True) if order else ""
spec = self.sql(expression, "spec")
alias = self.sql(expression, "alias")
over = self.sql(expression, "over") or "OVER"

this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"

first = expression.args.get("first")
if first is not None:
first = " FIRST " if first else " LAST "
first = first or ""
if first is None:
first = ""
else:
first = "FIRST" if first else "LAST"

if not partition and not order and not spec and alias:
return f"{this} {alias}"

window_args = alias + first + partition_sql + order_sql + spec_sql

return f"{this} ({window_args.strip()})"
args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
return f"{this} ({args})"

def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
partition = self.expressions(expression, key="partition_by", flat=True)
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/identity.sql
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ CASE WHEN SUM(x) > 3 THEN 1 END OVER (PARTITION BY x)
SUM(ROW() OVER (PARTITION BY x))
SUM(ROW() OVER (PARTITION BY x + 1))
SUM(ROW() OVER (PARTITION BY x AND y))
SUM(x) OVER (w ORDER BY y)
(ROW() OVER ())
CASE WHEN (x > 1) THEN 1 ELSE 0 END
CASE (1) WHEN 1 THEN 1 ELSE 0 END
Expand Down

0 comments on commit 8dfa184

Please sign in to comment.