Skip to content

Commit eea5c7a

Browse files
authored
add alias and as_alias to Count method (piccolo-orm#150)
* add `alias` and `as_alias` to Count method * move `as_alias` to `Selectable` * add docs and split tests * minor tweak * Remove unused `as_alias` in AVG
1 parent 96965ca commit eea5c7a

File tree

3 files changed

+64
-18
lines changed

3 files changed

+64
-18
lines changed

piccolo/columns/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,8 @@ def __deepcopy__(self, memo) -> ColumnMeta:
233233

234234

235235
class Selectable(metaclass=ABCMeta):
236+
alias: t.Optional[str]
237+
236238
@abstractmethod
237239
def get_select_string(self, engine_type: str, just_alias=False) -> str:
238240
"""
@@ -242,6 +244,13 @@ def get_select_string(self, engine_type: str, just_alias=False) -> str:
242244
"""
243245
pass
244246

247+
def as_alias(self, alias: str) -> Selectable:
248+
"""
249+
Allows column names to be changed in the result of a select.
250+
"""
251+
self.alias = alias
252+
return self
253+
245254

246255
class Column(Selectable):
247256
"""

piccolo/query/methods/select.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@ def __init__(self, column: Column, alias: str = "avg"):
4545
raise ValueError("Column type must be numeric to run the query.")
4646
self.alias = alias
4747

48-
def as_alias(self, alias: str) -> Avg:
49-
self.alias = alias
50-
return self
51-
5248
def get_select_string(self, engine_type: str, just_alias=False) -> str:
5349
column_name = self.column._meta.get_full_name(just_alias=just_alias)
5450
return f"AVG({column_name}) AS {self.alias}"
@@ -61,10 +57,17 @@ class Count(Selectable):
6157
If a column is specified, the count is for non-null values in that
6258
column. If no column is specified, the count is for all rows, whether
6359
they have null values or not.
60+
61+
Band.select(Band.name, Count()).group_by(Band.name).run()
62+
Band.select(Band.name, Count(alias="total")).group_by(Band.name).run()
63+
Band.select(Band.name, Count().as_alias("total")).group_by(Band.name).run()
6464
"""
6565

66-
def __init__(self, column: t.Optional[Column] = None):
66+
def __init__(
67+
self, column: t.Optional[Column] = None, alias: str = "count"
68+
):
6769
self.column = column
70+
self.alias = alias
6871

6972
def get_select_string(self, engine_type: str, just_alias=False) -> str:
7073
if self.column is None:
@@ -73,7 +76,7 @@ def get_select_string(self, engine_type: str, just_alias=False) -> str:
7376
column_name = self.column._meta.get_full_name(
7477
just_alias=just_alias
7578
)
76-
return f"COUNT({column_name}) AS count"
79+
return f"COUNT({column_name}) AS {self.alias}"
7780

7881

7982
class Max(Selectable):
@@ -89,10 +92,6 @@ def __init__(self, column: Column, alias: str = "max"):
8992
self.column = column
9093
self.alias = alias
9194

92-
def as_alias(self, alias: str) -> Max:
93-
self.alias = alias
94-
return self
95-
9695
def get_select_string(self, engine_type: str, just_alias=False) -> str:
9796
column_name = self.column._meta.get_full_name(just_alias=just_alias)
9897
return f"MAX({column_name}) AS {self.alias}"
@@ -111,10 +110,6 @@ def __init__(self, column: Column, alias: str = "min"):
111110
self.column = column
112111
self.alias = alias
113112

114-
def as_alias(self, alias: str) -> Min:
115-
self.alias = alias
116-
return self
117-
118113
def get_select_string(self, engine_type: str, just_alias=False) -> str:
119114
column_name = self.column._meta.get_full_name(just_alias=just_alias)
120115
return f"MIN({column_name}) AS {self.alias}"
@@ -136,10 +131,6 @@ def __init__(self, column: Column, alias: str = "sum"):
136131
raise ValueError("Column type must be numeric to run the query.")
137132
self.alias = alias
138133

139-
def as_alias(self, alias: str) -> Sum:
140-
self.alias = alias
141-
return self
142-
143134
def get_select_string(self, engine_type: str, just_alias=False) -> str:
144135
column_name = self.column._meta.get_full_name(just_alias=just_alias)
145136
return f"SUM({column_name}) AS {self.alias}"

tests/table/test_select.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,52 @@ def test_count_group_by(self):
448448
]
449449
)
450450

451+
def test_count_with_alias_group_by(self):
452+
"""
453+
Test grouping and counting all rows with alias.
454+
"""
455+
self.insert_rows()
456+
self.insert_rows()
457+
458+
response = (
459+
Band.select(Band.name, Count(alias="total"))
460+
.group_by(Band.name)
461+
.order_by(Band.name)
462+
.run_sync()
463+
)
464+
465+
self.assertTrue(
466+
response
467+
== [
468+
{"name": "CSharps", "total": 2},
469+
{"name": "Pythonistas", "total": 2},
470+
{"name": "Rustaceans", "total": 2},
471+
]
472+
)
473+
474+
def test_count_with_as_alias_group_by(self):
475+
"""
476+
Test grouping and counting all rows with as_alias.
477+
"""
478+
self.insert_rows()
479+
self.insert_rows()
480+
481+
response = (
482+
Band.select(Band.name, Count().as_alias("total"))
483+
.group_by(Band.name)
484+
.order_by(Band.name)
485+
.run_sync()
486+
)
487+
488+
self.assertTrue(
489+
response
490+
== [
491+
{"name": "CSharps", "total": 2},
492+
{"name": "Pythonistas", "total": 2},
493+
{"name": "Rustaceans", "total": 2},
494+
]
495+
)
496+
451497
def test_count_column_group_by(self):
452498
"""
453499
Test grouping and counting a specific column. Any null values in the

0 commit comments

Comments
 (0)