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
|
import django
import pytest
from django.db import connection, models
from django.db.models import F, Q
from django.db.models.expressions import CombinedExpression, Value
from django.test.utils import CaptureQueriesContext
from psqlextra.expressions import ExcludedCol
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model
def test_upsert():
"""Tests whether simple upserts works correctly."""
model = get_fake_model(
{
"title": HStoreField(uniqueness=["key1"]),
"cookies": models.CharField(max_length=255, null=True),
}
)
obj1 = model.objects.upsert_and_get(
conflict_target=[("title", "key1")],
fields=dict(title={"key1": "beer"}, cookies="cheers"),
)
obj1.refresh_from_db()
assert obj1.title["key1"] == "beer"
assert obj1.cookies == "cheers"
obj2 = model.objects.upsert_and_get(
conflict_target=[("title", "key1")],
fields=dict(title={"key1": "beer"}, cookies="choco"),
)
obj1.refresh_from_db()
obj2.refresh_from_db()
# assert both objects are the same
assert obj1.id == obj2.id
assert obj1.title["key1"] == "beer"
assert obj1.cookies == "choco"
assert obj2.title["key1"] == "beer"
assert obj2.cookies == "choco"
def test_upsert_explicit_pk():
"""Tests whether upserts works when the primary key is explicitly
specified."""
model = get_fake_model(
{
"name": models.CharField(max_length=255, primary_key=True),
"cookies": models.CharField(max_length=255, null=True),
}
)
obj1 = model.objects.upsert_and_get(
conflict_target=[("name")],
fields=dict(name="the-object", cookies="first-cheers"),
)
obj1.refresh_from_db()
assert obj1.name == "the-object"
assert obj1.cookies == "first-cheers"
obj2 = model.objects.upsert_and_get(
conflict_target=[("name")],
fields=dict(name="the-object", cookies="second-boo"),
)
obj1.refresh_from_db()
obj2.refresh_from_db()
# assert both objects are the same
assert obj1.pk == obj2.pk
assert obj1.name == "the-object"
assert obj1.cookies == "second-boo"
assert obj2.name == "the-object"
assert obj2.cookies == "second-boo"
def test_upsert_one_to_one_field():
model1 = get_fake_model({"title": models.TextField(unique=True)})
model2 = get_fake_model(
{"model1": models.OneToOneField(model1, on_delete=models.CASCADE)}
)
obj1 = model1.objects.create(title="hello world")
obj2_id = model2.objects.upsert(
conflict_target=["model1"], fields=dict(model1=obj1)
)
obj2 = model2.objects.get(id=obj2_id)
assert obj2.model1 == obj1
def test_upsert_with_update_condition():
"""Tests that an expression can be used as an upsert update condition."""
model = get_fake_model(
{
"name": models.TextField(unique=True),
"priority": models.IntegerField(),
"active": models.BooleanField(),
}
)
obj1 = model.objects.create(name="joe", priority=1, active=False)
# should not return anything because no rows were affected
assert not model.objects.upsert(
conflict_target=["name"],
update_condition=CombinedExpression(
model._meta.get_field("active").get_col(model._meta.db_table),
"=",
ExcludedCol("active"),
),
fields=dict(name="joe", priority=2, active=True),
)
obj1.refresh_from_db()
assert obj1.priority == 1
assert not obj1.active
# should return something because one row was affected
obj1_pk = model.objects.upsert(
conflict_target=["name"],
update_condition=CombinedExpression(
model._meta.get_field("active").get_col(model._meta.db_table),
"=",
Value(False),
),
fields=dict(name="joe", priority=2, active=True),
)
obj1.refresh_from_db()
assert obj1.pk == obj1_pk
assert obj1.priority == 2
assert obj1.active
@pytest.mark.parametrize("update_condition_value", [0, False])
def test_upsert_with_update_condition_false(update_condition_value):
"""Tests that an expression can be used as an upsert update condition."""
model = get_fake_model(
{
"name": models.TextField(unique=True),
"priority": models.IntegerField(),
"active": models.BooleanField(),
}
)
obj1 = model.objects.create(name="joe", priority=1, active=False)
with CaptureQueriesContext(connection) as ctx:
upsert_result = model.objects.upsert(
conflict_target=["name"],
update_condition=update_condition_value,
fields=dict(name="joe", priority=2, active=True),
)
assert upsert_result is None
assert len(ctx) == 1
assert 'ON CONFLICT ("name") DO NOTHING' in ctx[0]["sql"]
obj1.refresh_from_db()
assert obj1.priority == 1
assert not obj1.active
def test_upsert_with_update_values():
"""Tests that the default update values can be overriden with custom
expressions."""
model = get_fake_model(
{
"name": models.TextField(unique=True),
"count": models.IntegerField(default=0),
}
)
obj1 = model.objects.create(name="joe")
model.objects.upsert(
conflict_target=["name"],
fields=dict(name="joe"),
update_values=dict(
count=F("count") + 1,
),
)
obj1.refresh_from_db()
assert obj1.count == 1
def test_upsert_with_update_values_empty():
"""Tests that an upsert with an empty dict turns into ON CONFLICT DO
NOTHING."""
model = get_fake_model(
{
"name": models.TextField(unique=True),
"count": models.IntegerField(default=0),
}
)
obj1 = model.objects.create(name="joe")
model.objects.upsert(
conflict_target=["name"],
fields=dict(name="joe"),
update_values={},
)
obj1.refresh_from_db()
assert obj1.count == 0
@pytest.mark.skipif(
django.VERSION < (3, 1), reason="requires django 3.1 or newer"
)
def test_upsert_with_update_condition_with_q_object():
"""Tests that :see:Q objects can be used as an upsert update condition."""
model = get_fake_model(
{
"name": models.TextField(unique=True),
"priority": models.IntegerField(),
"active": models.BooleanField(),
}
)
obj1 = model.objects.create(name="joe", priority=1, active=False)
# should not return anything because no rows were affected
assert not model.objects.upsert(
conflict_target=["name"],
update_condition=Q(active=ExcludedCol("active")),
fields=dict(name="joe", priority=2, active=True),
)
obj1.refresh_from_db()
assert obj1.priority == 1
assert not obj1.active
# should return something because one row was affected
obj1_pk = model.objects.upsert(
conflict_target=["name"],
update_condition=Q(active=Value(False)),
fields=dict(name="joe", priority=2, active=True),
)
obj1.refresh_from_db()
assert obj1.pk == obj1_pk
assert obj1.priority == 2
assert obj1.active
def test_upsert_and_get_applies_converters():
"""Tests that converters are properly applied when using upsert_and_get."""
class MyCustomField(models.TextField):
def from_db_value(self, value, expression, connection):
return value.replace("hello", "bye")
model = get_fake_model({"title": MyCustomField(unique=True)})
obj = model.objects.upsert_and_get(
conflict_target=["title"], fields=dict(title="hello")
)
assert obj.title == "bye"
def test_bulk_upsert():
"""Tests whether bulk_upsert works properly."""
model = get_fake_model(
{
"first_name": models.CharField(
max_length=255, null=True, unique=True
),
"last_name": models.CharField(max_length=255, null=True),
}
)
model.objects.bulk_upsert(
conflict_target=["first_name"],
rows=[
dict(first_name="Swen", last_name="Kooij"),
dict(first_name="Henk", last_name="Test"),
],
)
row_a = model.objects.get(first_name="Swen")
row_b = model.objects.get(first_name="Henk")
model.objects.bulk_upsert(
conflict_target=["first_name"],
rows=[
dict(first_name="Swen", last_name="Test"),
dict(first_name="Henk", last_name="Kooij"),
],
)
row_a.refresh_from_db()
assert row_a.last_name == "Test"
row_b.refresh_from_db()
assert row_b.last_name == "Kooij"
def test_upsert_bulk_no_rows():
"""Tests whether bulk_upsert doesn't crash when specifying no rows or a
falsy value."""
model = get_fake_model(
{"name": models.CharField(max_length=255, null=True, unique=True)}
)
model.objects.on_conflict(ConflictAction.UPDATE, ["name"]).bulk_insert(
rows=[]
)
model.objects.bulk_upsert(conflict_target=["name"], rows=[])
model.objects.bulk_upsert(conflict_target=["name"], rows=None)
model.objects.on_conflict(ConflictAction.UPDATE, ["name"]).bulk_insert(
rows=None
)
def test_bulk_upsert_return_models():
"""Tests whether models are returned instead of dictionaries when
specifying the return_model=True argument."""
model = get_fake_model(
{
"id": models.BigAutoField(primary_key=True),
"name": models.CharField(max_length=255, unique=True),
}
)
rows = [dict(name="John Smith"), dict(name="Jane Doe")]
objs = model.objects.bulk_upsert(
conflict_target=["name"], rows=rows, return_model=True
)
for index, obj in enumerate(objs, 1):
assert isinstance(obj, model)
assert obj.id == index
def test_bulk_upsert_accepts_getitem_iterable():
"""Tests whether an iterable only implementing the __getitem__ method works
correctly."""
class GetItemIterable:
def __init__(self, items):
self.items = items
def __getitem__(self, key):
return self.items[key]
model = get_fake_model(
{
"id": models.BigAutoField(primary_key=True),
"name": models.CharField(max_length=255, unique=True),
}
)
rows = GetItemIterable([dict(name="John Smith"), dict(name="Jane Doe")])
objs = model.objects.bulk_upsert(
conflict_target=["name"], rows=rows, return_model=True
)
for index, obj in enumerate(objs, 1):
assert isinstance(obj, model)
assert obj.id == index
def test_bulk_upsert_accepts_iter_iterable():
"""Tests whether an iterable only implementing the __iter__ method works
correctly."""
class IterIterable:
def __init__(self, items):
self.items = items
def __iter__(self):
return iter(self.items)
model = get_fake_model(
{
"id": models.BigAutoField(primary_key=True),
"name": models.CharField(max_length=255, unique=True),
}
)
rows = IterIterable([dict(name="John Smith"), dict(name="Jane Doe")])
objs = model.objects.bulk_upsert(
conflict_target=["name"], rows=rows, return_model=True
)
for index, obj in enumerate(objs, 1):
assert isinstance(obj, model)
assert obj.id == index
def test_bulk_upsert_update_values():
model = get_fake_model(
{
"name": models.CharField(max_length=255, unique=True),
"count": models.IntegerField(default=0),
}
)
model.objects.bulk_create(
[
model(name="joe"),
model(name="john"),
]
)
objs = model.objects.bulk_upsert(
conflict_target=["name"],
rows=[],
return_model=True,
update_values=dict(count=F("count") + 1),
)
assert all([obj for obj in objs if obj.count == 1])
@pytest.mark.parametrize("return_model", [True])
def test_bulk_upsert_extra_columns_in_schema(return_model):
"""Tests that extra columns being returned by the database that aren't
known by Django don't make the bulk upsert crash."""
model = get_fake_model(
{
"name": models.CharField(max_length=255, unique=True),
}
)
with connection.cursor() as cursor:
cursor.execute(
f"ALTER TABLE {model._meta.db_table} ADD COLUMN new_name text NOT NULL DEFAULT %s",
("newjoe",),
)
objs = model.objects.bulk_upsert(
conflict_target=["name"],
rows=[
dict(name="joe"),
],
return_model=return_model,
)
assert len(objs) == 1
if return_model:
assert objs[0].name == "joe"
else:
assert objs[0]["name"] == "joe"
assert sorted(list(objs[0].keys())) == ["id", "name"]
def test_upsert_extra_columns_in_schema():
"""Tests that extra columns being returned by the database that aren't
known by Django don't make the upsert crash."""
model = get_fake_model(
{
"name": models.CharField(max_length=255, unique=True),
}
)
with connection.cursor() as cursor:
cursor.execute(
f"ALTER TABLE {model._meta.db_table} ADD COLUMN new_name text NOT NULL DEFAULT %s",
("newjoe",),
)
obj_id = model.objects.upsert(
conflict_target=["name"],
fields=dict(name="joe"),
)
assert obj_id == 1
obj = model.objects.upsert_and_get(
conflict_target=["name"],
fields=dict(name="joe"),
)
assert obj.name == "joe"
|