File: test_upsert_bulk.py

package info (click to toggle)
python-django-postgres-extra 2.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,096 kB
  • sloc: python: 9,057; makefile: 17; sh: 7; sql: 1
file content (68 lines) | stat: -rw-r--r-- 1,763 bytes parent folder | download | duplicates (3)
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
import uuid

import pytest

from django.db import models

from psqlextra.query import ConflictAction

from ..fake_model import get_fake_model

ROW_COUNT = 10000


@pytest.mark.benchmark()
def test_upsert_bulk_naive(benchmark):
    model = get_fake_model(
        {"field": models.CharField(max_length=255, unique=True)}
    )

    rows = []
    random_values = []
    for i in range(0, ROW_COUNT):
        random_value = str(uuid.uuid4())
        random_values.append(random_value)
        rows.append(model(field=random_value))

    model.objects.bulk_create(rows)

    def _native_upsert(model, random_values):
        """Performs a concurrency safe upsert using the native PostgreSQL
        upsert."""

        rows = [dict(field=random_value) for random_value in random_values]

        for row in rows:
            model.objects.on_conflict(["field"], ConflictAction.UPDATE).insert(
                **row
            )

    benchmark(_native_upsert, model, random_values)


@pytest.mark.benchmark()
def test_upsert_bulk_native(benchmark):
    model = get_fake_model(
        {"field": models.CharField(max_length=255, unique=True)}
    )

    rows = []
    random_values = []
    for i in range(0, ROW_COUNT):
        random_value = str(uuid.uuid4())
        random_values.append(random_value)
        rows.append(model(field=random_value))

    model.objects.bulk_create(rows)

    def _native_upsert(model, random_values):
        """Performs a concurrency safe upsert using the native PostgreSQL
        upsert."""

        rows = [dict(field=random_value) for random_value in random_values]

        model.objects.on_conflict(["field"], ConflictAction.UPDATE).bulk_insert(
            rows
        )

    benchmark(_native_upsert, model, random_values)