File: test_default_through_relation_order.py

package info (click to toggle)
ormar 0.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,952 kB
  • sloc: python: 24,085; makefile: 34; sh: 14
file content (321 lines) | stat: -rw-r--r-- 11,086 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
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
from typing import Any, Dict, List, Optional, Tuple, Type, cast
from uuid import UUID, uuid4

import ormar
import pytest
from ormar import (
    Model,
    ModelDefinitionError,
    QuerySet,
    pre_relation_remove,
    pre_save,
    pre_update,
)

from tests.lifespan import init_tests
from tests.settings import create_config

base_ormar_config = create_config()


class Animal(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="animals")

    id: UUID = ormar.UUID(primary_key=True, default=uuid4)
    name: str = ormar.Text(default="")
    # favoriteHumans


class Link(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="link_table")

    id: UUID = ormar.UUID(primary_key=True, default=uuid4)
    animal_order: Optional[int] = ormar.Integer(nullable=True)
    human_order: Optional[int] = ormar.Integer(nullable=True)


class Human(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="humans")

    id: UUID = ormar.UUID(primary_key=True, default=uuid4)
    name: str = ormar.Text(default="")
    favoriteAnimals: List[Animal] = ormar.ManyToMany(
        Animal,
        through=Link,
        related_name="favoriteHumans",
        orders_by=["link__animal_order"],
        related_orders_by=["link__human_order"],
    )


class Human2(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="humans2")

    id: UUID = ormar.UUID(primary_key=True, default=uuid4)
    name: str = ormar.Text(default="")
    favoriteAnimals: List[Animal] = ormar.ManyToMany(
        Animal, related_name="favoriteHumans2", orders_by=["link__animal_order__fail"]
    )


create_test_database = init_tests(base_ormar_config)


@pytest.mark.asyncio
async def test_ordering_by_through_fail():
    async with base_ormar_config.database:
        alice = await Human2(name="Alice").save()
        spot = await Animal(name="Spot").save()
        await alice.favoriteAnimals.add(spot)
        with pytest.raises(ModelDefinitionError):
            await alice.load_all()


def _get_filtered_query(
    sender: Type[Model], instance: Model, to_class: Type[Model]
) -> QuerySet:
    """
    Helper function.
    Gets the query filtered by the appropriate class name.
    """
    pk = getattr(instance, f"{to_class.get_name()}").pk
    filter_kwargs = {f"{to_class.get_name()}": pk}
    query = sender.objects.filter(**filter_kwargs)
    return query


def _get_through_model_relations(
    sender: Type[Model], instance: Model
) -> Tuple[Type[Model], Type[Model]]:
    relations = list(instance.extract_related_names())
    rel_one = sender.ormar_config.model_fields[relations[0]].to
    rel_two = sender.ormar_config.model_fields[relations[1]].to
    return rel_one, rel_two


async def _populate_order_on_insert(
    sender: Type[Model], instance: Model, from_class: Type[Model], to_class: Type[Model]
):
    """
    Helper function.

    Get max values from database for both orders and adds 1 (0 if max is None) if the
    order is not provided. If the order is provided it reorders the existing links
    to match the newly defined order.

    Assumes names f"{model.get_name()}_order" like for Animal: animal_order.
    """
    order_column = f"{from_class.get_name()}_order"
    if getattr(instance, order_column) is None:
        query = _get_filtered_query(sender, instance, to_class)
        max_order = await query.max(order_column)
        max_order = max_order + 1 if max_order is not None else 0
        setattr(instance, order_column, max_order)
    else:
        await _reorder_on_update(
            sender=sender,
            instance=instance,
            from_class=from_class,
            to_class=to_class,
            passed_args={order_column: getattr(instance, order_column)},
        )


async def _reorder_on_update(
    sender: Type[Model],
    instance: Model,
    from_class: Type[Model],
    to_class: Type[Model],
    passed_args: Dict,
):
    """
    Helper function.
    Actually reorders links by given order passed in add/update query to the link
    model.

    Assumes names f"{model.get_name()}_order" like for Animal: animal_order.
    """
    order = f"{from_class.get_name()}_order"
    if order in passed_args:
        query = _get_filtered_query(sender, instance, to_class)
        to_reorder = await query.exclude(pk=instance.pk).order_by(order).all()
        new_order = passed_args.get(order)
        if to_reorder and new_order is not None:
            # can be more efficient - here we renumber all even if not needed.
            for ind, link in enumerate(to_reorder):
                if ind < new_order:
                    setattr(link, order, ind)
                else:
                    setattr(link, order, ind + 1)
            await sender.objects.bulk_update(
                cast(List[Model], to_reorder), columns=[order]
            )


@pre_save(Link)
async def order_link_on_insert(sender: Type[Model], instance: Model, **kwargs: Any):
    """
    Signal receiver registered on Link model, triggered every time before one is created
    by calling save() on a model. Note that signal functions for pre_save signal accepts
    sender class, instance and have to accept **kwargs even if it's empty as of now.
    """
    rel_one, rel_two = _get_through_model_relations(sender, instance)
    await _populate_order_on_insert(
        sender=sender, instance=instance, from_class=rel_one, to_class=rel_two
    )
    await _populate_order_on_insert(
        sender=sender, instance=instance, from_class=rel_two, to_class=rel_one
    )


@pre_update(Link)
async def reorder_links_on_update(
    sender: Type[ormar.Model], instance: ormar.Model, passed_args: Dict, **kwargs: Any
):
    """
    Signal receiver registered on Link model, triggered every time before one is updated
    by calling update() on a model. Note that signal functions for pre_update signal
    accepts sender class, instance, passed_args which is a dict of kwargs passed to
    update and have to accept **kwargs even if it's empty as of now.
    """

    rel_one, rel_two = _get_through_model_relations(sender, instance)
    await _reorder_on_update(
        sender=sender,
        instance=instance,
        from_class=rel_one,
        to_class=rel_two,
        passed_args=passed_args,
    )
    await _reorder_on_update(
        sender=sender,
        instance=instance,
        from_class=rel_two,
        to_class=rel_one,
        passed_args=passed_args,
    )


@pre_relation_remove([Animal, Human])
async def reorder_links_on_remove(
    sender: Type[ormar.Model],
    instance: ormar.Model,
    child: ormar.Model,
    relation_name: str,
    **kwargs: Any,
):
    """
    Signal receiver registered on Anima and Human models, triggered every time before
    relation on a model is removed. Note that signal functions for pre_relation_remove
    signal accepts sender class, instance, child, relation_name and have to accept
    **kwargs even if it's empty as of now.

    Note that if classes have many relations you need to check if current one is ordered
    """
    through_class = sender.ormar_config.model_fields[relation_name].through
    through_instance = getattr(instance, through_class.get_name())
    if not through_instance:
        parent_pk = instance.pk
        child_pk = child.pk
        filter_kwargs = {f"{sender.get_name()}": parent_pk, child.get_name(): child_pk}
        through_instance = await through_class.objects.get(**filter_kwargs)
    rel_one, rel_two = _get_through_model_relations(through_class, through_instance)
    await _reorder_on_update(
        sender=through_class,
        instance=through_instance,
        from_class=rel_one,
        to_class=rel_two,
        passed_args={f"{rel_one.get_name()}_order": 999999},
    )
    await _reorder_on_update(
        sender=through_class,
        instance=through_instance,
        from_class=rel_two,
        to_class=rel_one,
        passed_args={f"{rel_two.get_name()}_order": 999999},
    )


@pytest.mark.asyncio
async def test_ordering_by_through_on_m2m_field():
    async with base_ormar_config.database:

        def verify_order(instance, expected):
            field_name = (
                "favoriteAnimals" if isinstance(instance, Human) else "favoriteHumans"
            )
            order_field_name = (
                "animal_order" if isinstance(instance, Human) else "human_order"
            )
            assert [x.name for x in getattr(instance, field_name)] == expected
            assert [
                getattr(x.link, order_field_name) for x in getattr(instance, field_name)
            ] == [i for i in range(len(expected))]

        alice = await Human(name="Alice").save()
        bob = await Human(name="Bob").save()
        charlie = await Human(name="Charlie").save()

        spot = await Animal(name="Spot").save()
        kitty = await Animal(name="Kitty").save()
        noodle = await Animal(name="Noodle").save()

        await alice.favoriteAnimals.add(noodle)
        await alice.favoriteAnimals.add(spot)
        await alice.favoriteAnimals.add(kitty)

        await alice.load_all()
        verify_order(alice, ["Noodle", "Spot", "Kitty"])

        await bob.favoriteAnimals.add(noodle)
        await bob.favoriteAnimals.add(kitty)
        await bob.favoriteAnimals.add(spot)

        await bob.load_all()
        verify_order(bob, ["Noodle", "Kitty", "Spot"])

        await charlie.favoriteAnimals.add(kitty)
        await charlie.favoriteAnimals.add(noodle)
        await charlie.favoriteAnimals.add(spot)

        await charlie.load_all()
        verify_order(charlie, ["Kitty", "Noodle", "Spot"])

        animals = [noodle, kitty, spot]
        for animal in animals:
            await animal.load_all()
            verify_order(animal, ["Alice", "Bob", "Charlie"])

        zack = await Human(name="Zack").save()

        await noodle.favoriteHumans.add(zack, human_order=0)
        await noodle.load_all()
        verify_order(noodle, ["Zack", "Alice", "Bob", "Charlie"])

        await zack.load_all()
        verify_order(zack, ["Noodle"])

        await noodle.favoriteHumans.filter(name="Zack").update(link=dict(human_order=1))
        await noodle.load_all()
        verify_order(noodle, ["Alice", "Zack", "Bob", "Charlie"])

        await noodle.favoriteHumans.filter(name="Zack").update(link=dict(human_order=2))
        await noodle.load_all()
        verify_order(noodle, ["Alice", "Bob", "Zack", "Charlie"])

        await noodle.favoriteHumans.filter(name="Zack").update(link=dict(human_order=3))
        await noodle.load_all()
        verify_order(noodle, ["Alice", "Bob", "Charlie", "Zack"])

        await kitty.favoriteHumans.remove(bob)
        await kitty.load_all()
        assert [x.name for x in kitty.favoriteHumans] == ["Alice", "Charlie"]

        bob = await noodle.favoriteHumans.get(pk=bob.pk)
        assert bob.link.human_order == 1

        await noodle.favoriteHumans.remove(
            await noodle.favoriteHumans.filter(link__human_order=2).get()
        )
        await noodle.load_all()
        verify_order(noodle, ["Alice", "Bob", "Zack"])