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
|
import uuid
import pytest
from django.db import models, transaction
from django.db.utils import IntegrityError
from ..fake_model import get_fake_model
@pytest.mark.benchmark()
def test_upsert_traditional(benchmark):
model = get_fake_model(
{"field": models.CharField(max_length=255, unique=True)}
)
random_value = str(uuid.uuid4())[:8]
model.objects.create(field=random_value)
def _traditional_upsert(model, random_value):
"""Performs a concurrency safe upsert the traditional way."""
try:
with transaction.atomic():
return model.objects.create(field=random_value)
except IntegrityError:
model.objects.update(field=random_value)
return model.objects.get(field=random_value)
benchmark(_traditional_upsert, model, random_value)
@pytest.mark.benchmark()
def test_upsert_native(benchmark):
model = get_fake_model(
{"field": models.CharField(max_length=255, unique=True)}
)
random_value = str(uuid.uuid4())[:8]
model.objects.create(field=random_value)
def _native_upsert(model, random_value):
"""Performs a concurrency safe upsert using the native PostgreSQL
upsert."""
return model.objects.upsert_and_get(
conflict_target=["field"], fields=dict(field=random_value)
)
benchmark(_native_upsert, model, random_value)
|