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 psqlextra.query import ConflictAction
from ..fake_model import get_fake_model
@pytest.mark.benchmark()
def test_insert_nothing_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_insert(model, random_value):
"""Performs a concurrency safe insert the traditional way."""
try:
with transaction.atomic():
return model.objects.create(field=random_value)
except IntegrityError:
return model.objects.filter(field=random_value).first()
benchmark(_traditional_insert, model, random_value)
@pytest.mark.benchmark()
def test_insert_nothing_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_insert(model, random_value):
"""Performs a concurrency safeinsert using the native PostgreSQL
conflict resolution."""
return model.objects.on_conflict(
["field"], ConflictAction.NOTHING
).insert_and_get(field=random_value)
benchmark(_native_insert, model, random_value)
|