-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathquerystring.py
More file actions
335 lines (267 loc) · 10.1 KB
/
Copy pathquerystring.py
File metadata and controls
335 lines (267 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import date, datetime
from importlib.util import find_spec
from string import Formatter
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING: # pragma: no cover
from piccolo.columns import Column
from piccolo.table import Table
from uuid import UUID
if find_spec("asyncpg"):
from asyncpg.pgproto.pgproto import UUID as apgUUID
else:
apgUUID = UUID
class Selectable(metaclass=ABCMeta):
"""
Anything which inherits from this can be used in a select query.
"""
__slots__ = ("_alias",)
_alias: Optional[str]
@abstractmethod
def get_select_string(
self, engine_type: str, with_alias: bool = True
) -> QueryString:
"""
In a query, what to output after the select statement - could be a
column name, a sub query, a function etc. For a column it will be the
column name.
"""
raise NotImplementedError()
def as_alias(self, alias: str) -> Selectable:
"""
Allows column names to be changed in the result of a select.
"""
self._alias = alias
return self
@dataclass
class Fragment:
prefix: str
index: int = 0
no_arg: bool = False
class QueryString(Selectable):
"""
When we're composing complex queries, we're combining QueryStrings, rather
than concatenating strings directly. The reason for this is QueryStrings
keep the parameters separate, so we can pass parameterised queries to the
engine - which helps prevent SQL Injection attacks.
"""
__slots__ = (
"template",
"args",
"query_type",
"table",
"_frozen_compiled_strings",
"columns",
)
def __init__(
self,
template: str,
*args: Any,
query_type: str = "generic",
table: Optional[type[Table]] = None,
alias: Optional[str] = None,
) -> None:
"""
:param template:
The SQL query, with curly brackets as placeholders for any values::
"WHERE {} = {}"
:param args:
The values to insert (one value is needed for each set of curly
braces in the template).
:param query_type:
The query type is sometimes used by the engine to modify how the
query is run. For example, INSERT queries on old SQLite versions.
:param table:
Sometimes the ``piccolo.engine.base.Engine`` needs access to the
table that the query is being run on.
"""
self.template = template
self.query_type = query_type
self.table = table
self._frozen_compiled_strings: Optional[tuple[str, list[Any]]] = None
self._alias = alias
self.args, self.columns = self.process_args(args)
def process_args(
self, args: Sequence[Any]
) -> tuple[Sequence[Any], Sequence[Column]]:
"""
If a Column is passed in, we convert it to the name of the column
(including joins).
"""
from piccolo.columns import Column
processed_args = []
columns = []
for arg in args:
if isinstance(arg, Column):
columns.append(arg)
arg = QueryString(
f"{arg._meta.get_full_name(with_alias=False)}"
)
elif isinstance(arg, QueryString):
columns.extend(arg.columns)
processed_args.append(arg)
return (processed_args, columns)
def as_alias(self, alias: str) -> QueryString:
self._alias = alias
return self
def __str__(self):
"""
The SQL returned by the ``__str__`` method isn't used directly in
queries - it's just a usability feature.
The only exception to this is CHECK constraints, where we use this to
convert simple querystrings into strings.
"""
_, bundled, combined_args = self.bundle(
start_index=1, bundled=[], combined_args=[]
)
template = "".join(
fragment.prefix + ("" if fragment.no_arg else "{}")
for fragment in bundled
)
# Do some basic type conversion here.
converted_args = []
for arg in combined_args:
_type = type(arg)
if _type == str:
converted_args.append(f"'{arg}'")
elif _type == datetime or _type == date:
dt_string = arg.isoformat()
converted_args.append(f"'{dt_string}'")
elif _type == UUID or _type == apgUUID:
converted_args.append(f"'{arg}'")
elif arg is None:
converted_args.append("null")
else:
converted_args.append(arg)
return template.format(*converted_args)
def bundle(
self,
start_index: int = 1,
bundled: Optional[list[Fragment]] = None,
combined_args: Optional[list] = None,
):
# Split up the string, separating by {}.
fragments = [
Fragment(prefix=i[0]) for i in Formatter().parse(self.template)
]
bundled = [] if bundled is None else bundled
combined_args = [] if combined_args is None else combined_args
for index, fragment in enumerate(fragments):
try:
value = self.args[index]
except IndexError:
# trailing element
fragment.no_arg = True
bundled.append(fragment)
else:
if isinstance(value, QueryString):
fragment.no_arg = True
bundled.append(fragment)
start_index, _, _ = value.bundle(
start_index=start_index,
bundled=bundled,
combined_args=combined_args,
)
else:
fragment.index = start_index
bundled.append(fragment)
start_index += 1
combined_args.append(value)
return (start_index, bundled, combined_args)
def compile_string(
self, engine_type: str = "postgres"
) -> tuple[str, list[Any]]:
"""
Compiles the template ready for the engine - keeping the arguments
separate from the template.
"""
if self._frozen_compiled_strings is not None:
return self._frozen_compiled_strings
_, bundled, combined_args = self.bundle(
start_index=1, bundled=[], combined_args=[]
)
if engine_type in ("postgres", "cockroach"):
string = "".join(
fragment.prefix
+ ("" if fragment.no_arg else f"${fragment.index}")
for fragment in bundled
)
elif engine_type == "sqlite":
string = "".join(
fragment.prefix + ("" if fragment.no_arg else "?")
for fragment in bundled
)
else:
raise Exception("Engine type not recognised")
return (string, combined_args)
def freeze(self, engine_type: str = "postgres"):
self._frozen_compiled_strings = self.compile_string(
engine_type=engine_type
)
###########################################################################
def get_select_string(
self, engine_type: str, with_alias: bool = True
) -> QueryString:
if with_alias and self._alias:
return QueryString("{} AS " + f'"{self._alias}"', self)
else:
return self
def get_where_string(self, engine_type: str) -> QueryString:
return self.get_select_string(
engine_type=engine_type, with_alias=False
)
###########################################################################
# Basic logic
def __eq__(self, value) -> QueryString: # type: ignore[override]
if value is None:
return QueryString("{} IS NULL", self)
else:
return QueryString("{} = {}", self, value)
def __ne__(self, value) -> QueryString: # type: ignore[override]
if value is None:
return QueryString("{} IS NOT NULL", self, value)
else:
return QueryString("{} != {}", self, value)
def eq(self, value) -> QueryString:
return self.__eq__(value)
def ne(self, value) -> QueryString:
return self.__ne__(value)
def __or__(self, value) -> QueryString:
from piccolo.query.functions.conditional import Coalesce
return Coalesce(self, value, alias=self._alias)
def __add__(self, value) -> QueryString:
return QueryString("{} + {}", self, value)
def __sub__(self, value) -> QueryString:
return QueryString("{} - {}", self, value)
def __gt__(self, value) -> QueryString:
return QueryString("{} > {}", self, value)
def __ge__(self, value) -> QueryString:
return QueryString("{} >= {}", self, value)
def __lt__(self, value) -> QueryString:
return QueryString("{} < {}", self, value)
def __le__(self, value) -> QueryString:
return QueryString("{} <= {}", self, value)
def __truediv__(self, value) -> QueryString:
return QueryString("{} / {}", self, value)
def __mul__(self, value) -> QueryString:
return QueryString("{} * {}", self, value)
def __pow__(self, value) -> QueryString:
return QueryString("{} ^ {}", self, value)
def __mod__(self, value) -> QueryString:
return QueryString("{} % {}", self, value)
def is_in(self, value) -> QueryString:
return QueryString("{} IN {}", self, value)
def not_in(self, value) -> QueryString:
return QueryString("{} NOT IN {}", self, value)
def like(self, value: str) -> QueryString:
return QueryString("{} LIKE {}", self, value)
def ilike(self, value: str) -> QueryString:
return QueryString("{} ILIKE {}", self, value)
class Unquoted(QueryString):
"""
This is deprecated - just use QueryString directly.
"""
pass