Skip to content

Commit b3ad082

Browse files
committed
added support for adding columns to other columns in update queries
Applies to all operator types - multiplation, division etc too.
1 parent 8861b80 commit b3ad082

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

piccolo/columns/column_types.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,31 @@ def _get_querystring(self, operator: str, value: int, reverse=False):
8888
8989
await Band.update({Band.popularity: Band.popularity + 100}).run()
9090
"""
91-
if not isinstance(value, (int, float)):
92-
raise ValueError("Only integers and floats can be added.")
93-
if reverse:
94-
return QueryString(f"{{}} {operator} {self._meta.name} ", value)
91+
if isinstance(value, Integer):
92+
column: Integer = value
93+
if len(column._meta.call_chain) > 0:
94+
raise ValueError(
95+
"Adding values across joins isn't currently supported."
96+
)
97+
column_name = column._meta.name
98+
if reverse:
99+
return QueryString(
100+
f"{column_name} {operator} {self._meta.name}"
101+
)
102+
else:
103+
return QueryString(
104+
f"{self._meta.name} {operator} {column_name}"
105+
)
106+
elif isinstance(value, (int, float)):
107+
if reverse:
108+
return QueryString(f"{{}} {operator} {self._meta.name}", value)
109+
else:
110+
return QueryString(f"{self._meta.name} {operator} {{}}", value)
95111
else:
96-
return QueryString(f"{self._meta.name} {operator} {{}}", value)
112+
raise ValueError(
113+
"Only integers, floats, and other Integer columns can be "
114+
"added."
115+
)
97116

98117
def __add__(self, value: int):
99118
return self._get_querystring("+", value)

tests/table/test_update.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@ def test_add(self):
4646

4747
self.assertEqual(response["popularity"], 1010)
4848

49+
def test_add_column(self):
50+
self.insert_row()
51+
52+
Band.update(
53+
{Band.popularity: Band.popularity + Band.popularity}
54+
).run_sync()
55+
56+
response = Band.select(Band.popularity).first().run_sync()
57+
58+
self.assertEqual(response["popularity"], 2000)
59+
4960
def test_radd(self):
5061
self.insert_row()
5162

0 commit comments

Comments
 (0)