-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathquery.py
633 lines (494 loc) · 21.4 KB
/
query.py
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
from collections import OrderedDict
from itertools import chain
from typing import (
TYPE_CHECKING,
Dict,
Generic,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from django.core.exceptions import SuspiciousOperation
from django.db import connections, models, router
from django.db.models import Expression, Q, QuerySet
from django.db.models.fields import NOT_PROVIDED
from .sql import PostgresInsertQuery, PostgresQuery
from .types import ConflictAction
if TYPE_CHECKING:
from django.db.models.constraints import BaseConstraint
from django.db.models.indexes import Index
ConflictTarget = Union[List[Union[str, Tuple[str]]], "BaseConstraint", "Index"]
TModel = TypeVar("TModel", bound=models.Model, covariant=True)
if TYPE_CHECKING:
from typing_extensions import Self
QuerySetBase = QuerySet[TModel]
else:
QuerySetBase = QuerySet
class PostgresQuerySet(QuerySetBase, Generic[TModel]):
"""Adds support for PostgreSQL specifics."""
def __init__(self, model=None, query=None, using=None, hints=None):
"""Initializes a new instance of :see:PostgresQuerySet."""
super().__init__(model, query, using, hints)
self.query = query or PostgresQuery(self.model)
self.conflict_target = None
self.conflict_action = None
self.conflict_update_condition = None
self.index_predicate = None
def annotate(self, **annotations) -> "Self": # type: ignore[valid-type, override]
"""Custom version of the standard annotate function that allows using
field names as annotated fields.
Normally, the annotate function doesn't allow you to use the
name of an existing field on the model as the alias name. This
version of the function does allow that.
This is done by temporarily renaming the fields in order to avoid the
check for conflicts that the base class does.
We rename all fields instead of the ones that already exist because
the annotations are stored in an OrderedDict. Renaming only the
conflicts will mess up the order.
"""
fields = {field.name: field for field in self.model._meta.get_fields()}
new_annotations = OrderedDict()
renames = {}
for name, value in annotations.items():
if name in fields:
new_name = "%s_new" % name
new_annotations[new_name] = value
renames[new_name] = name
else:
new_annotations[name] = value
# run the base class's annotate function
result = super().annotate(**new_annotations)
# rename the annotations back to as specified
result.rename_annotations(**renames)
return result
def rename_annotations(self, **annotations):
"""Renames the aliases for the specified annotations:
.annotate(myfield=F('somestuf__myfield'))
.rename_annotations(myfield='field')
Arguments:
annotations:
The annotations to rename. Mapping the
old name to the new name.
"""
self.query.rename_annotations(annotations)
return self
def on_conflict(
self,
fields: ConflictTarget,
action: ConflictAction,
index_predicate: Optional[Union[Expression, Q, str]] = None,
update_condition: Optional[Union[Expression, Q, str]] = None,
):
"""Sets the action to take when conflicts arise when attempting to
insert/create a new row.
Arguments:
fields:
The fields the conflicts can occur in.
action:
The action to take when the conflict occurs.
index_predicate:
The index predicate to satisfy an arbiter partial index (i.e. what partial index to use for checking
conflicts)
update_condition:
Only update if this SQL expression evaluates to true.
"""
self.conflict_target = fields
self.conflict_action = action
self.conflict_update_condition = update_condition
self.index_predicate = index_predicate
return self
def bulk_insert(
self,
rows: Iterable[dict],
return_model: bool = False,
using: Optional[str] = None,
return_operation_type: bool = False,
):
"""Creates multiple new records in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
rows:
An iterable of dictionaries, where each dictionary
describes the fields to insert.
return_model (default: False):
If model instances should be returned rather than
just dicts.
using:
Optional name of the database connection to use for
this query.
return_operation_type (default: False):
If the operation type should be returned for each row.
This is only supported when return_model is False.
The operation_type is either 'INSERT' or 'UPDATE' and
the value will be contained in the '_operation_type' key
of the returned dict.
Returns:
A list of either the dicts of the rows inserted, including the pk or
the models of the rows inserted with defaults for any fields not specified
"""
def is_empty(r):
return all([False for _ in r])
if not rows or is_empty(rows):
return []
if not self.conflict_target and not self.conflict_action:
# no special action required, use the standard Django bulk_create(..)
return super().bulk_create(
[self.model(**fields) for fields in rows]
)
deduped_rows = rows
# when we do a ConflictAction.NOTHING, we are actually
# doing a ON CONFLICT DO UPDATE with a trick to avoid
# touching conflicting rows... however, ON CONFLICT UPDATE
# barfs when you specify the exact same row twice:
#
# > "cannot affect row a second time"
#
# we filter out the duplicates here to make sure we maintain
# the same behaviour as the real ON CONFLICT DO NOTHING
if self.conflict_action == ConflictAction.NOTHING:
deduped_rows = []
for row in rows:
if row in deduped_rows:
continue
deduped_rows.append(row)
compiler = self._build_insert_compiler(deduped_rows, using=using)
objs = compiler.execute_sql(
return_id=not return_model,
return_operation_type=return_operation_type and not return_model,
)
if return_model:
return [
self._create_model_instance(dict(row, **obj), compiler.using)
for row, obj in zip(deduped_rows, objs)
]
return [dict(row, **obj) for row, obj in zip(deduped_rows, objs)]
def insert(self, using: Optional[str] = None, **fields):
"""Creates a new record in the database.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fields:
The fields of the row to create.
using:
The name of the database connection
to use for this query.
Returns:
The primary key of the record that was created.
"""
if self.conflict_target or self.conflict_action:
compiler = self._build_insert_compiler([fields], using=using)
rows = compiler.execute_sql(return_id=True)
if not self.model or not self.model.pk:
return None
_, pk_db_column = self.model._meta.pk.get_attname_column() # type: ignore[union-attr]
if not rows or len(rows) == 0:
return None
return rows[0][pk_db_column]
# no special action required, use the standard Django create(..)
return super().create(**fields).pk
def insert_and_get(self, using: Optional[str] = None, **fields):
"""Creates a new record in the database and then gets the entire row.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fields:
The fields of the row to create.
using:
The name of the database connection
to use for this query.
Returns:
The model instance representing the row that was created.
"""
if not self.conflict_target and not self.conflict_action:
# no special action required, use the standard Django create(..)
return super().create(**fields)
compiler = self._build_insert_compiler([fields], using=using)
rows = compiler.execute_sql(
return_id=False, return_operation_type=False
)
if not rows:
return None
columns = rows[0]
# get a list of columns that are officially part of the model and
# preserve the fact that the attribute name
# might be different than the database column name
model_columns = {}
for field in self.model._meta.local_concrete_fields: # type: ignore[attr-defined]
model_columns[field.column] = field.attname
# strip out any columns/fields returned by the db that
# are not present in the model
model_init_fields = {}
for column_name, column_value in columns.items():
try:
model_init_fields[model_columns[column_name]] = column_value
except KeyError:
pass
return self._create_model_instance(model_init_fields, compiler.using)
def upsert(
self,
conflict_target: ConflictTarget,
fields: dict,
index_predicate: Optional[Union[Expression, Q, str]] = None,
using: Optional[str] = None,
update_condition: Optional[Union[Expression, Q, str]] = None,
) -> Optional[int]:
"""Creates a new record or updates the existing one with the specified
data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
fields:
Fields to insert/update.
index_predicate:
The index predicate to satisfy an arbiter partial index (i.e. what partial index to use for checking
conflicts)
using:
The name of the database connection to
use for this query.
update_condition:
Only update if this SQL expression evaluates to true.
Returns:
The primary key of the row that was created/updated.
"""
self.on_conflict(
conflict_target,
ConflictAction.UPDATE,
index_predicate=index_predicate,
update_condition=update_condition,
)
kwargs = {**fields, "using": using}
return self.insert(**kwargs)
def upsert_and_get(
self,
conflict_target: ConflictTarget,
fields: dict,
index_predicate: Optional[Union[Expression, Q, str]] = None,
using: Optional[str] = None,
update_condition: Optional[Union[Expression, Q, str]] = None,
) -> Optional[TModel]:
"""Creates a new record or updates the existing one with the specified
data and then gets the row.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
fields:
Fields to insert/update.
index_predicate:
The index predicate to satisfy an arbiter partial index (i.e. what partial index to use for checking
conflicts)
using:
The name of the database connection to
use for this query.
update_condition:
Only update if this SQL expression evaluates to true.
Returns:
The model instance representing the row
that was created/updated.
"""
self.on_conflict(
conflict_target,
ConflictAction.UPDATE,
index_predicate=index_predicate,
update_condition=update_condition,
)
kwargs = {**fields, "using": using}
return self.insert_and_get(**kwargs)
def bulk_upsert(
self,
conflict_target: ConflictTarget,
rows: Iterable[Dict],
index_predicate: Optional[Union[Expression, Q, str]] = None,
return_model: bool = False,
using: Optional[str] = None,
update_condition: Optional[Union[Expression, Q, str]] = None,
return_operation_type: bool = False,
):
"""Creates a set of new records or updates the existing ones with the
specified data.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
rows:
Rows to upsert.
index_predicate:
The index predicate to satisfy an arbiter partial index (i.e. what partial index to use for checking
conflicts)
return_model (default: False):
If model instances should be returned rather than
just dicts.
using:
The name of the database connection to use
for this query.
update_condition:
Only update if this SQL expression evaluates to true.
return_operation_type (default: False):
If the operation type should be returned for each row.
This is only supported when return_model is False.
The operation_type is either 'INSERT' or 'UPDATE' and
the value will be contained in the '_operation_type' key
of the returned dict.
Returns:
A list of either the dicts of the rows upserted, including the pk or
the models of the rows upserted
"""
self.on_conflict(
conflict_target,
ConflictAction.UPDATE,
index_predicate=index_predicate,
update_condition=update_condition,
)
return self.bulk_insert(
rows,
return_model,
using=using,
return_operation_type=return_operation_type,
)
def _create_model_instance(
self, field_values: dict, using: str, apply_converters: bool = True
):
"""Creates a new instance of the model with the specified field.
Use this after the row was inserted/updated into the database.
The new instance will be marked as "saved".
"""
converted_field_values = field_values.copy()
if apply_converters:
connection = connections[using]
for field in self.model._meta.local_concrete_fields: # type: ignore[attr-defined]
if field.attname not in converted_field_values:
continue
# converters can be defined on the field, or by
# the database back-end we're using
field_column = field.get_col(self.model._meta.db_table)
converters = field.get_db_converters(
connection
) + connection.ops.get_db_converters(field_column)
for converter in converters:
converted_field_values[field.attname] = converter(
converted_field_values[field.attname],
field_column,
connection,
)
instance = self.model(**converted_field_values)
instance._state.db = using
instance._state.adding = False
return instance
def _build_insert_compiler(
self, rows: Iterable[Dict], using: Optional[str] = None
):
"""Builds the SQL compiler for a insert query.
Arguments:
rows:
An iterable of dictionaries, where each entry
describes a record to insert.
using:
The name of the database connection to use
for this query.
Returns:
The SQL compiler for the insert.
"""
# ask the db router which connection to use
using = (
using or self._db or router.db_for_write(self.model, **self._hints) # type: ignore[attr-defined]
)
# create model objects, we also have to detect cases
# such as:
# [dict(first_name='swen'), dict(fist_name='swen', last_name='kooij')]
# we need to be certain that each row specifies the exact same
# amount of fields/columns
objs = []
rows_iter = iter(rows)
first_row = next(rows_iter)
field_count = len(first_row)
for index, row in enumerate(chain([first_row], rows_iter)):
if field_count != len(row):
raise SuspiciousOperation(
(
"In bulk upserts, you cannot have rows with different field "
"configurations. Row {0} has a different field config than "
"the first row."
).format(index)
)
objs.append(
self._create_model_instance(row, using, apply_converters=False)
)
# get the fields to be used during update/insert
insert_fields, update_fields = self._get_upsert_fields(first_row)
# build a normal insert query
query = PostgresInsertQuery(self.model)
query.conflict_action = self.conflict_action
query.conflict_target = self.conflict_target
query.conflict_update_condition = self.conflict_update_condition
query.index_predicate = self.index_predicate
query.values(objs, insert_fields, update_fields)
compiler = query.get_compiler(using)
return compiler
def _is_magical_field(self, model_instance, field, is_insert: bool):
"""Verifies whether this field is gonna modify something on its own.
"Magical" means that a field modifies the field value
during the pre_save.
Arguments:
model_instance:
The model instance the field is defined on.
field:
The field to get of whether the field is
magical.
is_insert:
Pretend whether this is an insert?
Returns:
True when this field modifies something.
"""
# does this field modify someting upon insert?
old_value = getattr(model_instance, field.name, None)
field.pre_save(model_instance, is_insert)
new_value = getattr(model_instance, field.name, None)
return old_value != new_value
def _get_upsert_fields(self, kwargs):
"""Gets the fields to use in an upsert.
This some nice magic. We'll split the fields into
a group of "insert fields" and "update fields":
INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
insert_fields update_fields
Often, fields appear in both lists. But, for example,
a :see:DateTime field with `auto_now_add=True` set, will
only appear in "insert_fields", since it won't be set
on existing rows.
Other than that, the user specificies a list of fields
in the upsert() call. That migt not be all fields. The
user could decide to leave out optional fields. If we
end up doing an update, we don't want to overwrite
those non-specified fields.
We cannot just take the list of fields the user
specifies, because as mentioned, some fields
make modifications to the model on their own.
We'll have to detect which fields make modifications
and include them in the list of insert/update fields.
"""
model_instance = self.model(**kwargs)
insert_fields = []
update_fields = []
for field in model_instance._meta.local_concrete_fields:
has_default = field.default != NOT_PROVIDED
if field.name in kwargs or field.column in kwargs:
insert_fields.append(field)
update_fields.append(field)
continue
elif has_default:
insert_fields.append(field)
continue
# special handling for 'pk' which always refers to
# the primary key, so if we the user specifies `pk`
# instead of a concrete field, we have to handle that
if field.primary_key is True and "pk" in kwargs:
insert_fields.append(field)
update_fields.append(field)
continue
if self._is_magical_field(model_instance, field, is_insert=True):
insert_fields.append(field)
if self._is_magical_field(model_instance, field, is_insert=False):
update_fields.append(field)
return insert_fields, update_fields