File: test_on_conflict_update.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 (170 lines) | stat: -rw-r--r-- 4,650 bytes parent folder | download
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
import django
import pytest

from django.db import models

from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction

from .fake_model import get_fake_model


def test_on_conflict_update():
    """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.on_conflict(
        [("title", "key1")], ConflictAction.UPDATE
    ).insert_and_get(title={"key1": "beer"}, cookies="cheers")

    obj1.refresh_from_db()
    assert obj1.title["key1"] == "beer"
    assert obj1.cookies == "cheers"

    obj2 = model.objects.on_conflict(
        [("title", "key1")], ConflictAction.UPDATE
    ).insert_and_get(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"


@pytest.mark.skipif(
    django.VERSION < (2, 2),
    reason="Django < 2.2 doesn't implement constraints",
)
def test_on_conflict_update_by_unique_constraint():
    model = get_fake_model(
        {
            "title": models.CharField(max_length=255, null=True),
        },
        meta_options={
            "constraints": [
                models.UniqueConstraint(name="test_uniq", fields=["title"]),
            ],
        },
    )

    constraint = next(
        (
            constraint
            for constraint in model._meta.constraints
            if constraint.name == "test_uniq"
        )
    )

    model.objects.on_conflict(constraint, ConflictAction.UPDATE).insert_and_get(
        title="title"
    )


def test_on_conflict_update_foreign_key_by_object():
    """Tests whether simple upsert works correctly when the conflicting field
    is a foreign key specified as an object."""

    other_model = get_fake_model({})

    model = get_fake_model(
        {
            "other": models.OneToOneField(
                other_model, on_delete=models.CASCADE
            ),
            "data": models.CharField(max_length=255),
        }
    )

    other_obj = other_model.objects.create()

    obj1 = model.objects.on_conflict(
        ["other"], ConflictAction.UPDATE
    ).insert_and_get(other=other_obj, data="some data")

    assert obj1.other == other_obj
    assert obj1.data == "some data"

    obj1.refresh_from_db()
    assert obj1.other == other_obj
    assert obj1.data == "some data"

    with pytest.raises(ValueError):
        (
            model.objects.on_conflict(
                ["other"], ConflictAction.UPDATE
            ).insert_and_get(other=obj1)
        )

    obj2 = model.objects.on_conflict(
        ["other"], ConflictAction.UPDATE
    ).insert_and_get(other=other_obj, data="different data")

    assert obj2.other == other_obj
    assert obj2.data == "different data"

    obj1.refresh_from_db()
    obj2.refresh_from_db()

    # assert that the 'other' field didn't change
    assert obj1.id == obj2.id
    assert obj1.other == other_obj
    assert obj2.other == other_obj
    assert obj1.data == "different data"
    assert obj2.data == "different data"


def test_on_conflict_update_foreign_key_by_id():
    """Tests whether simple upsert works correctly when the conflicting field
    is a foreign key specified as an id."""

    other_model = get_fake_model({})

    model = get_fake_model(
        {
            "other": models.OneToOneField(
                other_model, on_delete=models.CASCADE
            ),
            "data": models.CharField(max_length=255),
        }
    )

    other_obj = other_model.objects.create()

    obj1 = model.objects.on_conflict(
        ["other_id"], ConflictAction.UPDATE
    ).insert_and_get(other_id=other_obj.pk, data="some data")

    assert obj1.other == other_obj
    assert obj1.data == "some data"

    obj1.refresh_from_db()
    assert obj1.other == other_obj
    assert obj1.data == "some data"

    obj2 = model.objects.on_conflict(
        ["other_id"], ConflictAction.UPDATE
    ).insert_and_get(other_id=other_obj.pk, data="different data")

    assert obj2.other == other_obj
    assert obj2.data == "different data"

    obj1.refresh_from_db()
    obj2.refresh_from_db()

    # assert that the 'other' field didn't change
    assert obj1.id == obj2.id
    assert obj1.other == other_obj
    assert obj2.other == other_obj
    assert obj1.data == "different data"
    assert obj2.data == "different data"