-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_asyncio_orm.py
More file actions
1417 lines (1135 loc) · 44.5 KB
/
test_asyncio_orm.py
File metadata and controls
1417 lines (1135 loc) · 44.5 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for async ORM support."""
from __future__ import annotations
from types import SimpleNamespace
from typing import TYPE_CHECKING, cast
import pytest
from sqliter.asyncio import AsyncSqliterDB
from sqliter.asyncio.orm import (
AsyncBaseDBModel,
AsyncForeignKey,
AsyncLazyLoader,
AsyncManyToMany,
AsyncManyToManyManager,
AsyncPrefetchedM2MResult,
AsyncPrefetchedResult,
AsyncReverseManyToMany,
AsyncReverseQuery,
)
from sqliter.asyncio.orm.query import AsyncReverseRelationship
from sqliter.exceptions import ManyToManyIntegrityError, RecordFetchError
from sqliter.orm.m2m import ManyToManyOptions
from sqliter.orm.registry import ModelRegistry
if TYPE_CHECKING:
from sqliter.asyncio.orm.m2m import HasPKAndContext as AsyncM2MContext
from sqliter.asyncio.orm.query import HasPKAndContext as AsyncReverseContext
from sqliter.model.model import BaseDBModel
@pytest.mark.asyncio
async def test_async_fk_lazy_fetch_and_select_related() -> None:
"""Async FK access supports explicit lazy fetch and eager cache use."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async FK tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async FK tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
on_delete="CASCADE",
related_name="books",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
author = await db.insert(Author(name="Ada"))
book = await db.insert(Book(title="Notes", author_id=author.pk))
fetched = await db.get(Book, book.pk)
assert fetched is not None
loader = fetched.author
assert isinstance(loader, AsyncLazyLoader)
loaded = await loader.fetch()
assert loaded is not None
assert loaded.name == "Ada"
eager = await db.select(Book).select_related("author").fetch_one()
assert eager is not None
assert isinstance(eager.author, Author)
assert eager.author.name == "Ada"
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_fk_loader_descriptor_and_model_edge_paths(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Async FK helpers cover null, cache, error, and refresh paths."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async loader edge tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async loader edge tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
null=True,
on_delete="CASCADE",
related_name="books",
)
assert isinstance(Book.author, AsyncForeignKey)
assert isinstance(Author.__dict__["books"], AsyncReverseRelationship)
draft = Book(title="Draft", author_id=None)
assert draft.author is None
draft.author_id = 1
unloaded = cast("AsyncLazyLoader[Author]", draft.author)
assert unloaded.db_context is None
assert "unloaded" in repr(unloaded)
with pytest.raises(AttributeError, match=r"await relation\.fetch"):
_ = unloaded.name
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
author = await db.insert(Author(name="Ada"))
draft.author_id = author.pk
draft.db_context = db
refreshed = cast("AsyncLazyLoader[Author]", draft.author)
assert refreshed.db_context is db
loaded = await refreshed.fetch()
assert loaded is not None
assert loaded.name == "Ada"
assert "loaded" in repr(refreshed)
draft.__dict__.setdefault("_fk_cache", {})["author"] = loaded
assert draft.author is loaded
async def broken_get(
model: type[AsyncBaseDBModel],
pk: int | None,
) -> None:
raise RecordFetchError(model.get_table_name(), pk or 0)
monkeypatch.setattr(db, "get", broken_get)
failing = AsyncLazyLoader(
instance=draft,
to_model=Author,
fk_id=author.pk,
db_context=db,
)
with pytest.raises(RecordFetchError):
await failing.fetch()
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_fk_missing_relation_is_cached(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Missing async FK lookups should not re-query after first fetch."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for missing async FK cache tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for missing async FK cache tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
null=True,
on_delete="CASCADE",
related_name="books",
)
db = AsyncSqliterDB(memory=True)
loader = AsyncLazyLoader(
instance=Book(title="Draft", author_id=99),
to_model=Author,
fk_id=99,
db_context=db,
)
calls = {"count": 0}
async def missing_get(
model: type[AsyncBaseDBModel],
pk: int,
) -> None:
calls["count"] += 1
monkeypatch.setattr(db, "get", missing_get)
assert await loader.fetch() is None
assert await loader.fetch() is None
assert calls["count"] == 1
assert "loaded" in repr(loader)
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_fk_zero_fk_id_is_missing() -> None:
"""Async FK with unsaved value 0 should behave as a missing relation."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async unsaved FK tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async unsaved FK tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
null=True,
on_delete="CASCADE",
related_name="books",
)
draft = Book(title="Draft", author_id=0)
assert draft.author is None
assert draft.__dict__.get("_fk_cache", {}) == {}
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_fk_cache_refreshes_when_fk_id_changes() -> None:
"""Changing FK id invalidates stale async FK cache entries."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async cache refresh tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async cache refresh tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
null=True,
on_delete="CASCADE",
related_name="books",
)
book = Book(title="Draft", author_id=1)
first_loader = cast("AsyncLazyLoader[Author]", book.author)
assert first_loader._fk_id == 1
object.__setattr__(book, "author_id", 2)
second_loader = cast("AsyncLazyLoader[Author]", book.author)
assert second_loader is not first_loader
assert second_loader._fk_id == 2
cached_author = Author(name="Loaded")
cached_author.pk = 2
book.__dict__.setdefault("_fk_cache", {})["author"] = cached_author
object.__setattr__(book, "author_id", 3)
stale_cache = book.__dict__["_fk_cache"]["author"]
assert stale_cache is not second_loader
refresh_loader = cast("AsyncLazyLoader[Author]", book.author)
assert refresh_loader is not stale_cache
assert refresh_loader._fk_id == 3
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_fk_descriptor_direct_paths() -> None:
"""Direct descriptor access covers null, cached, and new loader branches."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for direct descriptor tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for direct descriptor tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
null=True,
related_name="books",
)
descriptor = cast("AsyncForeignKey[Author]", Book.__dict__["author"])
empty_loader = AsyncLazyLoader(
instance=object(),
to_model=Author,
fk_id=None,
db_context=None,
)
assert await empty_loader.fetch() is None
draft = Book(title="Draft", author_id=None)
assert descriptor.__get__(draft, Book) is None
cached = AsyncLazyLoader(
instance=draft,
to_model=Author,
fk_id=1,
db_context=None,
)
draft.author_id = 1
draft.__dict__["_fk_cache"] = {"author": cached}
cached_value = descriptor.__get__(draft, Book)
assert isinstance(cached_value, AsyncLazyLoader)
assert cached_value is cached
fresh = Book(title="Fresh", author_id=2)
loader = descriptor.__get__(fresh, Book)
assert isinstance(loader, AsyncLazyLoader)
assert fresh.__dict__["_fk_cache"]["author"] is loader
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_reverse_relationship_and_prefetch() -> None:
"""Async reverse descriptors support lazy queries and prefetched reads."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async reverse tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async reverse tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
on_delete="CASCADE",
related_name="books",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
author = await db.insert(Author(name="Jane"))
await db.insert(Book(title="One", author_id=author.pk))
await db.insert(Book(title="Two", author_id=author.pk))
fetched_author = await db.get(Author, author.pk)
assert fetched_author is not None
reverse = fetched_author.books
assert isinstance(reverse, AsyncReverseQuery)
assert await reverse.count() == 2
book_items = cast("list[Book]", await reverse.fetch_all())
titles = {book.title for book in book_items}
assert titles == {"One", "Two"}
prefetched = await (
db.select(Author).prefetch_related("books").fetch_one()
)
assert prefetched is not None
prefetched_books = prefetched.books
assert isinstance(prefetched_books, AsyncPrefetchedResult)
assert await prefetched_books.exists() is True
assert await prefetched_books.count() == 2
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_reverse_query_and_prefetched_result_edge_paths() -> None:
"""Async reverse wrappers handle empty, prefetched, and paged paths."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for async reverse edge tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for async reverse edge tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
on_delete="CASCADE",
related_name="books",
)
empty_author = Author(name="No DB")
empty_reverse = AsyncReverseQuery(
instance=cast("AsyncReverseContext", empty_author),
to_model=Book,
fk_field="author",
db_context=None,
)
assert await empty_reverse.fetch_all() == []
assert await empty_reverse.fetch_one() is None
assert await empty_reverse.count() == 0
assert await empty_reverse.exists() is False
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
author = await db.insert(Author(name="Grace"))
await db.insert(Book(title="One", author_id=author.pk))
await db.insert(Book(title="Two", author_id=author.pk))
fetched_author = await db.get(Author, author.pk)
assert fetched_author is not None
reverse = cast("AsyncReverseQuery", fetched_author.books)
second = cast(
"Book | None",
await reverse.offset(1).limit(1).fetch_one(),
)
assert second is not None
assert second.title == "Two"
prefetched = AsyncPrefetchedResult(
cached_items=cast("list[BaseDBModel]", [author]),
instance=cast("AsyncReverseContext", fetched_author),
to_model=Author,
fk_field="author",
db_context=db,
)
assert await prefetched.fetch_all() == [author]
assert await prefetched.fetch_one() == author
assert await prefetched.count() == 1
assert await prefetched.exists() is True
filtered = prefetched.filter(name="Grace")
assert isinstance(filtered, AsyncReverseQuery)
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_reverse_query_skips_unsaved_parent(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Unsaved parent with pk=0 should skip reverse query execution."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for unsaved reverse skip tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for unsaved reverse skip tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
on_delete="CASCADE",
related_name="books",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
def guarded_select(*args: object, **kwargs: object) -> object:
msg = (
"reverse queries should be skipped for unsaved parent instances"
)
raise AssertionError(msg)
monkeypatch.setattr(db, "select", guarded_select)
unsaved_author = Author(name="Unsaved")
unsaved_author.db_context = db
reverse = cast("AsyncReverseQuery", unsaved_author.books)
assert unsaved_author.pk == 0
assert await reverse.fetch_all() == []
assert await reverse.fetch_one() is None
assert await reverse.count() == 0
assert await reverse.exists() is False
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_reverse_query_filter_and_model_registry_skip_paths() -> (
None
):
"""Filtered reverse queries and async registry skip branches behave."""
state = ModelRegistry.snapshot()
try:
class Author(AsyncBaseDBModel):
"""Author model for reverse filter tests."""
name: str
class Book(AsyncBaseDBModel):
"""Book model for reverse filter tests."""
title: str
author: AsyncForeignKey[Author] = AsyncForeignKey(
Author,
on_delete="CASCADE",
related_name="books",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Author)
await db.create_table(Book)
author = await db.insert(Author(name="Lin"))
await db.insert(Book(title="One", author_id=author.pk))
await db.insert(Book(title="Two", author_id=author.pk))
fetched = await db.get(Author, author.pk)
assert fetched is not None
filtered = cast("AsyncReverseQuery", fetched.books).filter(title="Two")
match = cast("Book | None", await filtered.fetch_one())
assert match is not None
assert match.title == "Two"
draft = Book(title="Draft", author_id=author.pk)
first = cast("AsyncLazyLoader[Author]", draft.author)
draft.db_context = db
second = cast("AsyncLazyLoader[Author]", draft.author)
assert second is not first
assert second.db_context is db
cached_author = await db.get(Author, author.pk)
assert cached_author is not None
draft.__dict__["_fk_cache"] = {"author": cached_author}
assert draft.author is cached_author
Author._install_async_fk_reverse_accessors(
{
Book.get_table_name(): [
{
"to_model": Author,
"fk_field": "author",
"related_name": "written_books",
},
{"to_model": Author, "fk_field": "author"},
]
}
)
assert isinstance(
Author.__dict__["written_books"],
AsyncReverseRelationship,
)
Author._install_async_m2m_reverse_accessors(
{
Book.get_table_name(): [
{
"to_model": Author,
"junction_table": "book_author",
"related_name": "linked_books",
"symmetrical": False,
},
{
"to_model": Author,
"junction_table": "book_author",
"symmetrical": False,
},
]
}
)
assert isinstance(
Author.__dict__["linked_books"],
AsyncReverseManyToMany,
)
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_many_to_many_manager_and_prefetch() -> None:
"""Async M2M descriptors support manager writes and prefetched reads."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for async M2M tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for async M2M tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Tag)
await db.create_table(Article)
tag_a = await db.insert(Tag(name="python"))
tag_b = await db.insert(Tag(name="sqlite"))
article = await db.insert(Article(title="Guide"))
manager = article.tags
assert isinstance(manager, AsyncManyToManyManager)
await manager.add(tag_a, tag_b)
assert await manager.count() == 2
fetched_tags = await manager.fetch_all()
assert {tag.name for tag in fetched_tags} == {"python", "sqlite"}
reverse_manager = tag_a.articles
assert isinstance(reverse_manager, AsyncManyToManyManager)
article_manager = cast(
"AsyncManyToManyManager[Article]",
reverse_manager,
)
reverse_articles = await article_manager.fetch_all()
assert [item.title for item in reverse_articles] == ["Guide"]
prefetched = await (
db.select(Article).prefetch_related("tags").fetch_one()
)
assert prefetched is not None
prefetched_tags = prefetched.tags
assert isinstance(prefetched_tags, AsyncPrefetchedM2MResult)
assert await prefetched_tags.count() == 2
await manager.remove(tag_b)
assert await manager.count() == 1
await manager.clear()
assert await manager.count() == 0
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_m2m_manager_and_prefetched_edge_paths() -> None:
"""Async M2M helpers cover empty, delegated, and descriptor paths."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for async M2M edge tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for async M2M edge tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
assert isinstance(Article.tags, AsyncManyToMany)
draft = Article(title="Draft")
unresolved = AsyncManyToManyManager(
instance=cast("AsyncM2MContext", draft),
to_model=Tag,
from_model=Article,
junction_table="article_tags",
db_context=None,
)
assert unresolved.sql_metadata.junction_table == "article_tags"
assert await unresolved.fetch_all() == []
assert await unresolved.fetch_one() is None
assert await unresolved.count() == 0
assert await unresolved.exists() is False
with pytest.raises(
ManyToManyIntegrityError,
match="No database context",
):
await unresolved.filter(name="python")
db = AsyncSqliterDB(memory=True)
await db.create_table(Tag)
await db.create_table(Article)
article = await db.insert(Article(title="Guide"))
tag = await db.insert(Tag(name="python"))
manager = cast("AsyncManyToManyManager[Tag]", article.tags)
assert await manager.fetch_one() is None
empty_query = await manager.filter(name="python")
assert await empty_query.exists() is False
prefetched = AsyncPrefetchedM2MResult([tag], manager)
assert prefetched.sql_metadata == manager.sql_metadata
assert await prefetched.fetch_all() == [tag]
assert await prefetched.fetch_one() == tag
assert await prefetched.count() == 1
assert await prefetched.exists() is True
await prefetched.add(tag)
assert await manager.count() == 1
found = await manager.fetch_one()
assert found is not None
assert found.name == "python"
await prefetched.remove(Tag(name="missing"))
await prefetched.set(tag)
filtered = await prefetched.filter(name="python")
assert await filtered.exists() is True
await prefetched.clear()
assert await manager.count() == 0
with pytest.raises(
ManyToManyIntegrityError,
match="Related instance has no primary key",
):
await manager.add(Tag(name="unsaved"))
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_prefetched_wrapper_refreshes_after_writes() -> None:
"""Async prefetched wrapper reflects delegated write operations."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for async prefetched wrapper tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for async prefetched wrapper tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Tag)
await db.create_table(Article)
article = await db.insert(Article(title="Guide"))
tag1 = await db.insert(Tag(name="python"))
tag2 = await db.insert(Tag(name="tutorial"))
manager = cast("AsyncManyToManyManager[Tag]", article.tags)
await manager.add(tag1)
prefetched = AsyncPrefetchedM2MResult(
await manager.fetch_all(), manager
)
assert await prefetched.count() == 1
await prefetched.add(tag2)
assert await prefetched.count() == 2
assert {tag.name for tag in await prefetched.fetch_all()} == {
"python",
"tutorial",
}
await prefetched.remove(Tag(name="missing"))
assert await prefetched.count() == 2
await prefetched.set(tag2)
fetched = await prefetched.fetch_one()
assert fetched is not None
assert fetched.name == "tutorial"
await prefetched.clear()
assert await prefetched.fetch_all() == []
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_m2m_write_invalidates_cached_prefetch_queries() -> None:
"""M2M writes should invalidate cached prefetched query results."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for cached async M2M query tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for cached async M2M query tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
db = AsyncSqliterDB(memory=True, cache_enabled=True)
await db.create_table(Tag)
await db.create_table(Article)
article = await db.insert(Article(title="Guide"))
tag = await db.insert(Tag(name="python"))
manager = cast("AsyncManyToManyManager[Tag]", article.tags)
initial_article = await (
db.select(Article).prefetch_related("tags").fetch_one()
)
assert initial_article is not None
initial_article_tags = cast(
"AsyncPrefetchedM2MResult[Tag]",
initial_article.tags,
)
assert await initial_article_tags.fetch_all() == []
initial_tag = await (
db.select(Tag).prefetch_related("articles").fetch_one()
)
assert initial_tag is not None
initial_tag_articles = cast(
"AsyncPrefetchedM2MResult[Article]",
initial_tag.articles,
)
assert await initial_tag_articles.fetch_all() == []
await manager.add(tag)
refreshed_article = await (
db.select(Article).prefetch_related("tags").fetch_one()
)
assert refreshed_article is not None
refreshed_article_tags = cast(
"AsyncPrefetchedM2MResult[Tag]",
refreshed_article.tags,
)
refreshed_tags = await refreshed_article_tags.fetch_all()
assert [item.name for item in refreshed_tags] == ["python"]
refreshed_tag = await (
db.select(Tag).prefetch_related("articles").fetch_one()
)
assert refreshed_tag is not None
refreshed_tag_articles = cast(
"AsyncPrefetchedM2MResult[Article]",
refreshed_tag.articles,
)
refreshed_articles = await refreshed_tag_articles.fetch_all()
assert [item.title for item in refreshed_articles] == ["Guide"]
await manager.clear()
cleared_article = await (
db.select(Article).prefetch_related("tags").fetch_one()
)
assert cleared_article is not None
cleared_article_tags = cast(
"AsyncPrefetchedM2MResult[Tag]",
cleared_article.tags,
)
assert await cleared_article_tags.fetch_all() == []
cleared_tag = await (
db.select(Tag).prefetch_related("articles").fetch_one()
)
assert cleared_tag is not None
cleared_tag_articles = cast(
"AsyncPrefetchedM2MResult[Article]",
cleared_tag.articles,
)
assert await cleared_tag_articles.fetch_all() == []
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_m2m_write_invalidates_instance_prefetch_caches() -> None:
"""M2M writes should clear stale in-memory prefetched relationship data."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for async M2M instance cache tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for async M2M instance cache tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Tag)
await db.create_table(Article)
await db.insert(Article(title="Guide"))
await db.insert(Tag(name="python"))
prefetched_article = await (
db.select(Article).prefetch_related("tags").fetch_one()
)
assert prefetched_article is not None
prefetched_article_tags = cast(
"AsyncPrefetchedM2MResult[Tag]",
prefetched_article.tags,
)
assert await prefetched_article_tags.fetch_all() == []
prefetched_tag = await (
db.select(Tag).prefetch_related("articles").fetch_one()
)
assert prefetched_tag is not None
prefetched_tag_articles = cast(
"AsyncPrefetchedM2MResult[Article]",
prefetched_tag.articles,
)
assert await prefetched_tag_articles.fetch_all() == []
prefetched_tags = cast(
"AsyncPrefetchedM2MResult[Tag]",
prefetched_article.tags,
)
manager = prefetched_tags._manager
await manager.add(prefetched_tag)
refreshed_article_rel = prefetched_article.tags
refreshed_tags = await refreshed_article_rel.fetch_all()
assert [item.name for item in refreshed_tags] == ["python"]
refreshed_tag_rel = cast(
"AsyncManyToManyManager[Article]"
" | AsyncPrefetchedM2MResult[Article]",
prefetched_tag.articles,
)
refreshed_articles = await refreshed_tag_rel.fetch_all()
assert [item.title for item in refreshed_articles] == ["Guide"]
await manager.clear()
cleared_article_rel = prefetched_article.tags
assert await cleared_article_rel.fetch_all() == []
cleared_tag_rel = cast(
"AsyncManyToManyManager[Article]"
" | AsyncPrefetchedM2MResult[Article]",
prefetched_tag.articles,
)
assert await cleared_tag_rel.fetch_all() == []
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_prefetched_wrapper_updates_cached_list_in_place() -> None:
"""Async wrapper writes should mutate the cached prefetch list in place."""
state = ModelRegistry.snapshot()
try:
class Tag(AsyncBaseDBModel):
"""Tag model for async prefetched wrapper cache tests."""
name: str
class Article(AsyncBaseDBModel):
"""Article model for async prefetched wrapper cache tests."""
title: str
tags: AsyncManyToMany[Tag] = AsyncManyToMany(
Tag,
related_name="articles",
)
db = AsyncSqliterDB(memory=True)
await db.create_table(Tag)
await db.create_table(Article)
article = await db.insert(Article(title="Guide"))
tag1 = await db.insert(Tag(name="python"))
tag2 = await db.insert(Tag(name="tutorial"))