Skip to content

Commit 484a87d

Browse files
committed
Use the ordinal number as aliases for GROUP BY
Closes #96
1 parent df2a504 commit 484a87d

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
* Use the ordinal number as aliases for GROUP BY
12
* Check the coherence of the aliases of GROUP BY and ORDER BY expressions
23
* Do not use parameter for EXTRACT field
34
* Remove support for Python older than 3.6

sql/__init__.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -629,19 +629,26 @@ def __str__(self):
629629
and (self.limit is not None or self.offset is not None)):
630630
return self._rownum(str)
631631

632+
ordinals = {}
632633
for expression in chain(
633634
self.group_by or [],
634635
self.order_by or []):
635636
if not isinstance(expression, As):
636637
continue
637-
for column in self.columns:
638+
for i, column in enumerate(self.columns, start=1):
638639
if not isinstance(column, As):
639640
continue
640641
if column.output_name != expression.output_name:
641642
continue
642643
if (str(column.expression) != str(expression.expression)
643644
or column.params != expression.params):
644645
raise ValueError("%r != %r" % (expression, column))
646+
ordinals[column.output_name] = i
647+
648+
def str_or_ordinal(expression):
649+
if isinstance(expression, As):
650+
expression = ordinals.get(expression.output_name, expression)
651+
return str(expression)
645652

646653
with AliasManager():
647654
if self.from_ is not None:
@@ -671,7 +678,8 @@ def __str__(self):
671678
where = ' WHERE ' + str(self.where)
672679
group_by = ''
673680
if self.group_by:
674-
group_by = ' GROUP BY ' + ', '.join(map(str, self.group_by))
681+
group_by = ' GROUP BY ' + ', '.join(
682+
map(str_or_ordinal, self.group_by))
675683
having = ''
676684
if self.having:
677685
having = ' HAVING ' + str(self.having)

sql/tests/test_select.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def test_select_group_by(self):
197197
output = column.as_('c1')
198198
query = self.table.select(output, group_by=output)
199199
self.assertEqual(str(query),
200-
'SELECT "a"."c" AS "c1" FROM "t" AS "a" GROUP BY "c1"')
200+
'SELECT "a"."c" AS "c1" FROM "t" AS "a" GROUP BY 1')
201201
self.assertEqual(tuple(query.params), ())
202202

203203
query = self.table.select(Literal('foo'), group_by=Literal('foo'))

0 commit comments

Comments
 (0)