From be0de6ecdce6c5e4772e138dec9f9e452822c92b Mon Sep 17 00:00:00 2001 From: tobymao Date: Tue, 6 Jun 2023 22:07:37 -0700 Subject: [PATCH] Fix: window sql gen closes #1739 --- sqlglot/generator.py | 24 +++++++++--------------- tests/fixtures/identity.sql | 1 + 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/sqlglot/generator.py b/sqlglot/generator.py index 4a6e472e9f..1aa96012f6 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -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) diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql index 0a1e305d4d..e4f83aba90 100644 --- a/tests/fixtures/identity.sql +++ b/tests/fixtures/identity.sql @@ -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