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
|
from collections import OrderedDict
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from django.core.exceptions import SuspiciousOperation
from django.db import models, router
from django.db.backends.utils import CursorWrapper
from django.db.models import Expression, Q, QuerySet
from django.db.models.fields import NOT_PROVIDED
from .expressions import ExcludedCol
from .introspect import model_from_cursor, models_from_cursor
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
self.update_values = 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,
update_values: Optional[Dict[str, Union[Any, Expression]]] = 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.
update_values:
Optionally, values/expressions to use when rows
conflict. If not specified, all columns specified
in the rows are updated with the values you specified.
"""
self.conflict_target = fields
self.conflict_action = action
self.conflict_update_condition = update_condition
self.index_predicate = index_predicate
self.update_values = update_values
return self
def bulk_insert(
self,
rows: Iterable[Dict[str, Any]],
return_model: bool = False,
using: Optional[str] = None,
):
"""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.
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)
with compiler.connection.cursor() as cursor:
for sql, params in compiler.as_sql(return_id=not return_model):
cursor.execute(sql, params)
if return_model:
return list(models_from_cursor(self.model, cursor))
return self._consume_cursor_as_dicts(
cursor, original_rows=deduped_rows
)
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:
if not self.model or not self.model.pk:
return None
compiler = self._build_insert_compiler([fields], using=using)
with compiler.connection.cursor() as cursor:
for sql, params in compiler.as_sql(return_id=True):
cursor.execute(sql, params)
row = cursor.fetchone()
if not row:
return None
return row[0]
# 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)
with compiler.connection.cursor() as cursor:
for sql, params in compiler.as_sql(return_id=False):
cursor.execute(sql, params)
return model_from_cursor(self.model, cursor)
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,
update_values: Optional[Dict[str, Union[Any, Expression]]] = None,
) -> 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.
update_values:
Optionally, values/expressions to use when rows
conflict. If not specified, all columns specified
in the rows are updated with the values you specified.
Returns:
The primary key of the row that was created/updated.
"""
self.on_conflict(
conflict_target,
ConflictAction.UPDATE
if (update_condition or update_condition is None)
else ConflictAction.NOTHING,
index_predicate=index_predicate,
update_condition=update_condition,
update_values=update_values,
)
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,
update_values: Optional[Dict[str, Union[Any, Expression]]] = None,
):
"""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.
update_values:
Optionally, values/expressions to use when rows
conflict. If not specified, all columns specified
in the rows are updated with the values you specified.
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,
update_values=update_values,
)
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,
update_values: Optional[Dict[str, Union[Any, Expression]]] = None,
):
"""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.
update_values:
Optionally, values/expressions to use when rows
conflict. If not specified, all columns specified
in the rows are updated with the values you specified.
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,
update_values=update_values,
)
return self.bulk_insert(rows, return_model, using=using)
@staticmethod
def _consume_cursor_as_dicts(
cursor: CursorWrapper, *, original_rows: Iterable[Dict[str, Any]]
) -> List[dict]:
cursor_description = cursor.description
return [
{
**original_row,
**{
column.name: row[column_index]
for column_index, column in enumerate(cursor_description)
if row
},
}
for original_row, row in zip(original_rows, cursor)
]
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)
)
obj = self.model(**row.copy())
obj._state.db = using
obj._state.adding = False
objs.append(obj)
# get the fields to be used during update/insert
insert_fields, update_values = self._get_upsert_fields(first_row)
# allow the user to override what should happen on update
if self.update_values is not None:
update_values = self.update_values
# 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.insert_on_conflict_values(objs, insert_fields, update_values)
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_values = {}
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_values[field.name] = ExcludedCol(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_values[field.name] = ExcludedCol(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_values[field.name] = ExcludedCol(field)
return insert_fields, update_values
|