-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cache.py
More file actions
1417 lines (1084 loc) · 48.1 KB
/
test_cache.py
File metadata and controls
1417 lines (1084 loc) · 48.1 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 the caching functionality in SQLiter."""
from __future__ import annotations
from collections import OrderedDict
from typing import TYPE_CHECKING, Any
from unittest.mock import patch
import pytest
from sqliter import SqliterDB
from sqliter.model import BaseDBModel
if TYPE_CHECKING:
from pathlib import Path
class User(BaseDBModel):
"""Test model for caching tests."""
name: str
age: int
class TestCacheDisabledByDefault:
"""Test that caching is disabled by default."""
def test_cache_disabled_by_default(self, tmp_path: Path) -> None:
"""Verify caching is off unless explicitly enabled."""
db = SqliterDB(str(tmp_path / "test.db"))
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache should be disabled by default
assert not db._cache_enabled
# Queries should not be cached
assert db._cache == {}
db.close()
class TestCacheParameterValidation:
"""Test validation of cache configuration parameters."""
def test_cache_max_size_must_be_positive(self, tmp_path: Path) -> None:
"""cache_max_size must be greater than 0."""
with pytest.raises(
ValueError, match="cache_max_size must be greater than 0"
):
SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_size=0
)
with pytest.raises(
ValueError, match="cache_max_size must be greater than 0"
):
SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_size=-1
)
def test_cache_ttl_must_be_non_negative(self, tmp_path: Path) -> None:
"""cache_ttl must be non-negative."""
with pytest.raises(ValueError, match="cache_ttl must be non-negative"):
SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_ttl=-1
)
def test_cache_max_memory_mb_must_be_positive(self, tmp_path: Path) -> None:
"""cache_max_memory_mb must be greater than 0."""
with pytest.raises(
ValueError, match="cache_max_memory_mb must be greater than 0"
):
SqliterDB(
str(tmp_path / "test.db"),
cache_enabled=True,
cache_max_memory_mb=0,
)
with pytest.raises(
ValueError, match="cache_max_memory_mb must be greater than 0"
):
SqliterDB(
str(tmp_path / "test.db"),
cache_enabled=True,
cache_max_memory_mb=-1,
)
class TestCacheHitOnRepeatedQuery:
"""Test cache hits on repeated queries."""
def test_cache_hit_on_repeated_query(self, tmp_path: Path) -> None:
"""Repeated queries return cached result and increment hit counter."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# First query - hits DB
result1 = db.select(User).filter(name="Alice").fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 1
# Second query - hits cache
result2 = db.select(User).filter(name="Alice").fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 1
assert stats["misses"] == 1
# Results should be equivalent (same content)
assert len(result1) == 1
assert len(result2) == 1
assert result1[0].name == result2[0].name
assert result1[0].age == result2[0].age
db.close()
def test_cache_key_stable_with_partial_fields(self, tmp_path: Path) -> None:
"""Partial-field queries should not mutate query state or cache key."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
query = db.select(User, fields=["name"]) # partial select
key_before = query._make_cache_key(fetch_one=False)
result = query.fetch_all()
assert len(result) == 1
assert result[0].name == "Alice"
assert result[0].pk == 1
key_after = query._make_cache_key(fetch_one=False)
assert query._fields == ["name"]
assert key_before == key_after
db.close()
class TestGetCacheControls:
"""Test caching behavior for get() calls."""
def test_get_cache_hits(self, tmp_path: Path) -> None:
"""get() uses cache on repeated lookups."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
result1 = db.get(User, user.pk)
stats = db.get_cache_stats()
assert result1 is not None
assert stats["hits"] == 0
assert stats["misses"] == 1
result2 = db.get(User, user.pk)
stats = db.get_cache_stats()
assert result2 is not None
assert stats["hits"] == 1
assert stats["misses"] == 1
db.close()
def test_get_bypass_cache(self, tmp_path: Path) -> None:
"""get(bypass_cache=True) skips cache read/write."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
db.get(User, user.pk, bypass_cache=True)
stats = db.get_cache_stats()
assert stats["total"] == 0
assert db._cache == {}
db.close()
def test_get_cache_ttl_override(self, tmp_path: Path) -> None:
"""get(cache_ttl=...) overrides global TTL."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_ttl=100
)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
with patch("sqliter.sqliter.time.time", return_value=0):
db.get(User, user.pk, cache_ttl=1)
with patch("sqliter.sqliter.time.time", return_value=10):
db.get(User, user.pk)
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 2
db.close()
def test_get_cache_ttl_negative(self, tmp_path: Path) -> None:
"""get(cache_ttl=...) rejects negative values."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
with pytest.raises(ValueError, match="cache_ttl must be non-negative"):
db.get(User, 1, cache_ttl=-1)
db.close()
class TestCacheInvalidation:
"""Test cache invalidation on write operations."""
def test_cache_invalidation_on_insert(self, tmp_path: Path) -> None:
"""Insert clears table cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache the query
result1 = db.select(User).fetch_all()
assert len(result1) == 1
# Insert new record
db.insert(User(name="Bob", age=25))
# Cache should be invalidated, should hit DB
result2 = db.select(User).fetch_all()
assert len(result2) == 2
db.close()
def test_cache_invalidation_on_update(self, tmp_path: Path) -> None:
"""Update clears table cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
# Cache the query
result1 = db.select(User).filter(name="Alice").fetch_all()
assert len(result1) == 1
# Update the record
user.age = 31
db.update(user)
# Cache should be invalidated
result2 = db.select(User).filter(name="Alice").fetch_all()
assert result2[0].age == 31
db.close()
def test_cache_invalidation_on_delete_by_pk(self, tmp_path: Path) -> None:
"""Delete by primary key clears table cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
# Cache the query
result1 = db.select(User).fetch_all()
assert len(result1) == 1
# Delete the record
db.delete(User, str(user.pk))
# Cache should be invalidated
result2 = db.select(User).fetch_all()
assert len(result2) == 0
db.close()
def test_cache_invalidation_on_delete_by_query(
self, tmp_path: Path
) -> None:
"""Delete by query clears table cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
# Cache the query
result1 = db.select(User).fetch_all()
assert len(result1) == 2
# Delete records by query
deleted_count = db.select(User).filter(age__gte=30).delete()
assert deleted_count == 1
# Cache should be invalidated
result2 = db.select(User).fetch_all()
assert len(result2) == 1
db.close()
class TestCacheClearedOnClose:
"""Test that cache is cleared when connection is closed."""
def test_cache_cleared_on_close(self, tmp_path: Path) -> None:
"""Cache cleared when connection closed."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query to populate cache
db.select(User).fetch_all()
assert len(db._cache) > 0
# Close connection
db.close()
# Cache should be cleared
assert len(db._cache) == 0
def test_cache_context_manager(self, tmp_path: Path) -> None:
"""Cache persists when using context manager."""
with SqliterDB(str(tmp_path / "test.db"), cache_enabled=True) as db:
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query to populate cache
db.select(User).fetch_all()
assert len(db._cache) > 0
# Cache should remain available after exiting context
assert len(db._cache) > 0
db.close()
class TestCacheTtlExpiration:
"""Test TTL-based cache expiration."""
def test_cache_ttl_expiration(self, tmp_path: Path) -> None:
"""Entries expire after TTL."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_ttl=1
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query to populate cache at time=0
with patch("sqliter.sqliter.time.time", return_value=0):
result1 = db.select(User).fetch_all()
assert len(result1) == 1
# Mock time advancing past TTL (time=100, TTL was 1 second)
with patch("sqliter.sqliter.time.time", return_value=100):
# Query should hit DB again (cache expired)
result2 = db.select(User).fetch_all()
assert len(result2) == 1
db.close()
class TestCacheMaxSizeLru:
"""Test LRU eviction when cache is full."""
def test_cache_max_size_lru(self, tmp_path: Path) -> None:
"""Oldest entries evicted when max size reached."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_size=2
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
db.insert(User(name="Charlie", age=35))
# Fill cache with 3 different queries (max is 2)
db.select(User).filter(name="Alice").fetch_all()
db.select(User).filter(name="Bob").fetch_all()
db.select(User).filter(name="Charlie").fetch_all()
# Cache should only have 2 entries (LRU eviction)
assert len(db._cache[User.get_table_name()]) == 2
db.close()
class TestCacheClear:
"""Test manual cache clearing functionality."""
def test_clear_cache_removes_all_entries(self) -> None:
"""clear_cache() removes all cached entries from all tables."""
db = SqliterDB(memory=True, cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
# Cache some queries
db.select(User).filter(name="Alice").fetch_all()
db.select(User).filter(name="Bob").fetch_all()
db.select(User).fetch_all()
# Verify cache is populated
table_name = User.get_table_name()
assert len(db._cache.get(table_name, {})) == 3
# Clear cache
db.clear_cache()
# Verify all entries are cleared
assert len(db._cache.get(table_name, {})) == 0
db.close()
def test_clear_cache_with_multiple_tables(self) -> None:
"""clear_cache() clears cache for all tables."""
class Product(BaseDBModel):
name: str
price: float
db = SqliterDB(memory=True, cache_enabled=True)
db.create_table(User)
db.create_table(Product)
# Insert and cache data for both tables
db.insert(User(name="Alice", age=30))
db.insert(Product(name="Widget", price=9.99))
db.select(User).fetch_all()
db.select(Product).fetch_all()
# Verify both tables have cached entries
user_table = User.get_table_name()
product_table = Product.get_table_name()
assert len(db._cache.get(user_table, {})) == 1
assert len(db._cache.get(product_table, {})) == 1
# Clear cache
db.clear_cache()
# Verify all tables are cleared
assert len(db._cache.get(user_table, {})) == 0
assert len(db._cache.get(product_table, {})) == 0
db.close()
def test_clear_cache_preserves_statistics(self) -> None:
"""clear_cache() preserves cache statistics."""
db = SqliterDB(memory=True, cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Generate some cache activity
db.select(User).fetch_all() # miss
db.select(User).fetch_all() # hit
stats_before = db.get_cache_stats()
assert stats_before["hits"] > 0 or stats_before["misses"] > 0
# Clear cache doesn't reset statistics
db.clear_cache()
stats_after = db.get_cache_stats()
assert stats_after["hits"] == stats_before["hits"]
assert stats_after["misses"] == stats_before["misses"]
# But subsequent queries will hit DB again
db.select(User).fetch_all() # miss (cache was cleared)
stats_final = db.get_cache_stats()
assert stats_final["misses"] > stats_before["misses"]
db.close()
def test_clear_cache_when_cache_disabled(self) -> None:
"""clear_cache() works even when cache is disabled."""
db = SqliterDB(memory=True, cache_enabled=False)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache should be empty
assert len(db._cache) == 0
# clear_cache() should not raise an error
db.clear_cache()
# Cache should still be empty
assert len(db._cache) == 0
db.close()
def test_clear_cache_allows_fresh_queries(self) -> None:
"""Queries after clear_cache() hit the database."""
db = SqliterDB(memory=True, cache_enabled=True)
db.create_table(User)
user = db.insert(User(name="Alice", age=30))
# Query and cache
result1 = db.select(User).filter(name="Alice").fetch_one()
assert result1 is not None
assert result1.age == 30
stats_before = db.get_cache_stats()
assert stats_before["misses"] == 1
# Update the record directly (bypass ORM to avoid cache invalidation)
conn = db.conn
assert conn is not None
conn.execute("UPDATE users SET age = 31 WHERE pk = ?", (user.pk,))
# Query again - should return cached result (age=30)
result2 = db.select(User).filter(name="Alice").fetch_one()
assert result2 is not None
assert result2.age == 30 # Still cached value
# Clear cache
db.clear_cache()
# Query again - should hit database and get fresh data (age=31)
result3 = db.select(User).filter(name="Alice").fetch_one()
assert result3 is not None
assert result3.age == 31 # Fresh from database
db.close()
class TestCacheKeyVariations:
"""Test that different query parameters create different cache keys."""
def test_cache_key_includes_filters(self, tmp_path: Path) -> None:
"""Different filters create different cache entries."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
# Different filters should create different cache entries
result1 = db.select(User).filter(name="Alice").fetch_all()
result2 = db.select(User).filter(name="Bob").fetch_all()
assert len(result1) == 1
assert len(result2) == 1
assert result1[0].name == "Alice"
assert result2[0].name == "Bob"
# Should have 2 cache entries for the table
assert len(db._cache[User.get_table_name()]) == 2
db.close()
def test_cache_key_includes_limit_offset(self, tmp_path: Path) -> None:
"""Different pagination creates different cache entries."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
db.insert(User(name="Charlie", age=35))
# Different pagination should create different cache entries
result1 = db.select(User).limit(1).fetch_all()
result2 = db.select(User).limit(1).offset(1).fetch_all()
assert len(result1) == 1
assert len(result2) == 1
# Should have 2 cache entries for the table
assert len(db._cache[User.get_table_name()]) == 2
db.close()
def test_cache_key_includes_order_by(self, tmp_path: Path) -> None:
"""Different order by creates different cache entries."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
db.insert(User(name="Bob", age=25))
db.insert(User(name="Charlie", age=35))
# Different order by should create different cache entries
result1 = db.select(User).order("age").fetch_all()
result2 = db.select(User).order("age", reverse=True).fetch_all()
assert len(result1) == 3
assert len(result2) == 3
assert result1[0].age == 25 # Ascending
assert result2[0].age == 35 # Descending
# Should have 2 cache entries for the table
assert len(db._cache[User.get_table_name()]) == 2
db.close()
class TestCacheEmptyResults:
"""Test caching of empty results."""
def test_cache_empty_single_result(self, tmp_path: Path) -> None:
"""Empty single results are cached and retrieved from cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query that returns no results
result1 = db.select(User).filter(name="Bob").fetch_one()
assert result1 is None
# Verify first query was a cache miss
stats = db.get_cache_stats()
assert stats["misses"] == 1
assert stats["hits"] == 0
# Should return cached None
result2 = db.select(User).filter(name="Bob").fetch_one()
assert result2 is None
# Verify second query was a cache hit
stats = db.get_cache_stats()
assert stats["hits"] == 1
assert stats["misses"] == 1
# Should have 1 cache entry
assert len(db._cache[User.get_table_name()]) == 1
db.close()
def test_cache_empty_list_result(self, tmp_path: Path) -> None:
"""Empty list results are cached and retrieved from cache."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query that returns no results
result1 = db.select(User).filter(name="Bob").fetch_all()
assert result1 == []
# Verify first query was a cache miss
stats = db.get_cache_stats()
assert stats["misses"] == 1
assert stats["hits"] == 0
# Should return cached empty list
result2 = db.select(User).filter(name="Bob").fetch_all()
assert result2 == []
# Verify second query was a cache hit
stats = db.get_cache_stats()
assert stats["hits"] == 1
assert stats["misses"] == 1
# Should have 1 cache entry
assert len(db._cache[User.get_table_name()]) == 1
db.close()
class TestCacheWithFields:
"""Test caching with field selection."""
def test_cache_with_field_selection(self, tmp_path: Path) -> None:
"""Different field selections create different cache entries."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query with specific fields
result1 = db.select(User).only("name").fetch_all()
result2 = db.select(User).fetch_all()
assert len(result1) == 1
assert len(result2) == 1
# Fields should be different
assert hasattr(result1[0], "name")
assert hasattr(result2[0], "age")
# Should have 2 cache entries for the table
assert len(db._cache[User.get_table_name()]) == 2
db.close()
class TestCacheStatistics:
"""Test cache statistics tracking."""
def test_cache_stats_initial_state(self, tmp_path: Path) -> None:
"""Cache stats start at zero."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 0
assert stats["total"] == 0
assert stats["hit_rate"] == 0.0
db.close()
def test_cache_stats_track_hits(self, tmp_path: Path) -> None:
"""Cache stats track hits correctly."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# First query - cache miss
db.select(User).filter(name="Alice").fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 1
# Second query - cache hit
db.select(User).filter(name="Alice").fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 1
assert stats["misses"] == 1
assert stats["hit_rate"] == 50.0
db.close()
def test_cache_stats_track_misses(self, tmp_path: Path) -> None:
"""Cache stats track misses correctly."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Three different queries - all misses
db.select(User).filter(name="Alice").fetch_all()
db.select(User).filter(name="Bob").fetch_all()
db.select(User).filter(age=30).fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 3
assert stats["hit_rate"] == 0.0
db.close()
def test_cache_stats_with_invalidation(self, tmp_path: Path) -> None:
"""Cache stats continue after invalidation."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query - miss
db.select(User).fetch_all()
# Query - hit
db.select(User).fetch_all()
stats_before = db.get_cache_stats()
assert stats_before["hits"] == 1
# Invalidate cache
db.insert(User(name="Bob", age=25))
# Query - miss again (was invalidated)
db.select(User).fetch_all()
stats_after = db.get_cache_stats()
assert stats_after["hits"] == 1
assert stats_after["misses"] == 2
db.close()
def test_cache_stats_disabled_cache(self, tmp_path: Path) -> None:
"""Cache stats don't increment when cache is disabled."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=False)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Queries with cache disabled
db.select(User).fetch_all()
db.select(User).fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 0
assert stats["misses"] == 0
assert stats["total"] == 0
db.close()
def test_cache_stats_with_ttl_expiration(self, tmp_path: Path) -> None:
"""Expired cache entries count as misses."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_ttl=1
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Query at time=0 - miss
with patch("sqliter.sqliter.time.time", return_value=0):
db.select(User).fetch_all()
stats = db.get_cache_stats()
assert stats["misses"] == 1
# Query at time=0.5 - hit
with patch("sqliter.sqliter.time.time", return_value=0.5):
db.select(User).fetch_all()
stats = db.get_cache_stats()
assert stats["hits"] == 1
assert stats["misses"] == 1
# Query at time=100 (past TTL) - should be a cache miss
with patch("sqliter.sqliter.time.time", return_value=100):
db.select(User).fetch_all()
stats = db.get_cache_stats()
assert stats["misses"] == 2
assert stats["hits"] == 1
db.close()
def test_cache_stats_hit_rate_calculation(self, tmp_path: Path) -> None:
"""Hit rate is calculated correctly."""
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Execute 10 queries: 1 unique, 9 repeats
for _ in range(10):
db.select(User).filter(name="Alice").fetch_all()
stats = db.get_cache_stats()
assert stats["total"] == 10
assert stats["hits"] == 9
assert stats["misses"] == 1
assert stats["hit_rate"] == 90.0
db.close()
class TestCacheMemoryLimit:
"""Test memory-based cache limiting."""
def test_memory_usage_with_set_fields(self, tmp_path: Path) -> None:
"""Memory usage calculation works with set fields."""
class ModelWithSet(BaseDBModel):
name: str
tags: set[str]
db = SqliterDB(str(tmp_path / "test.db"), cache_enabled=True)
db.create_table(ModelWithSet)
db.insert(
ModelWithSet(name="test", tags={"python", "database", "caching"})
)
# Cache the query - this should trigger set measurement
db.select(ModelWithSet).fetch_all()
# Memory usage should be calculable
memory_usage = db._get_table_memory_usage(ModelWithSet.get_table_name())
assert memory_usage > 0
db.close()
def test_memory_limit_enforcement(self, tmp_path: Path) -> None:
"""Cache enforces memory limit by evicting entries."""
# Create a model with large fields to consume memory quickly
class LargeData(BaseDBModel):
name: str
data: str
# Set a very low memory limit (1MB)
db = SqliterDB(
str(tmp_path / "test.db"),
cache_enabled=True,
cache_max_memory_mb=1,
)
db.create_table(LargeData)
# Insert data with large payloads
large_data = "x" * 50000 # 50KB of data per entry
for i in range(50):
db.insert(LargeData(name=f"User{i}", data=large_data))
# Cache queries - eviction should be triggered due to memory limit
for i in range(50):
db.select(LargeData).filter(name=f"User{i}").fetch_all()
table_cache: OrderedDict[Any, Any] = db._cache.get(
LargeData.get_table_name(), OrderedDict()
)
# With 1MB limit and ~50KB per entry, only ~15-20 entries should fit
assert len(table_cache) < 50 # Many entries were evicted
# Verify memory usage is under the limit
memory_usage = db._get_table_memory_usage(LargeData.get_table_name())
max_bytes = 1 * 1024 * 1024 # 1MB
# Should be at or slightly over limit (eviction check after insert)
assert memory_usage <= max_bytes + 100000 # Allow buffer
db.close()
def test_memory_usage_tracking(self, tmp_path: Path) -> None:
"""Memory usage is calculated on-demand per table."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_memory_mb=1
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Initial memory usage should be 0 (no cached entries)
assert db._get_table_memory_usage(User.get_table_name()) == 0
# After caching, memory usage should be > 0
db.select(User).filter(name="Alice").fetch_all()
assert db._get_table_memory_usage(User.get_table_name()) > 0
db.close()
def test_memory_tracking_cleared_on_invalidation(
self,
tmp_path: Path,
) -> None:
"""Memory usage is 0 when cache is invalidated."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_memory_mb=1
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache a query
db.select(User).filter(name="Alice").fetch_all()
initial_memory = db._get_table_memory_usage(User.get_table_name())
assert initial_memory > 0
# Invalidate cache (this clears all cached entries)
db.insert(User(name="Bob", age=25))
# Memory usage should be 0 (cache was cleared)
assert db._get_table_memory_usage(User.get_table_name()) == 0
db.close()
def test_memory_tracking_cleared_on_close(self, tmp_path: Path) -> None:
"""Memory usage is 0 when connection is closed."""
db = SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_memory_mb=1
)
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache a query
db.select(User).filter(name="Alice").fetch_all()
assert db._get_table_memory_usage(User.get_table_name()) > 0
# Close connection
db.close()
# Memory usage should be 0 (cache was cleared)
assert db._get_table_memory_usage(User.get_table_name()) == 0
def test_memory_tracking_cleared_on_context_exit(
self, tmp_path: Path
) -> None:
"""Memory tracking remains until the connection is explicitly closed."""
with SqliterDB(
str(tmp_path / "test.db"), cache_enabled=True, cache_max_memory_mb=1
) as db:
db.create_table(User)
db.insert(User(name="Alice", age=30))
# Cache a query
db.select(User).filter(name="Alice").fetch_all()
assert db._get_table_memory_usage(User.get_table_name()) > 0
assert db._get_table_memory_usage(User.get_table_name()) > 0
db.close()
assert db._get_table_memory_usage(User.get_table_name()) == 0
def test_memory_limit_with_both_limits(self, tmp_path: Path) -> None:
"""Both cache_max_size and cache_max_memory_mb are respected."""
# Set both limits: 10 entries OR 1MB (whichever hit first)
db = SqliterDB(
str(tmp_path / "test.db"),
cache_enabled=True,
cache_max_size=10,
cache_max_memory_mb=1,
)
db.create_table(User)
# Insert 20 users
for i in range(20):
db.insert(User(name=f"User{i}", age=20 + i))
# Cache 15 different queries
for i in range(15):
db.select(User).filter(name=f"User{i}").fetch_all()
# Cache should be limited by both size and memory
# Actual count depends on object sizes and memory pressure
assert len(db._cache[User.get_table_name()]) <= 10
db.close()
def test_no_memory_limit_when_none(self, tmp_path: Path) -> None:
"""When cache_max_memory_mb is None, only size limit applies."""
db = SqliterDB(
str(tmp_path / "test.db"),
cache_enabled=True,
cache_max_size=5,
cache_max_memory_mb=None,
)
db.create_table(User)
# Insert all users first
for i in range(10):
db.insert(User(name=f"User{i}", age=20 + i))
# Now cache multiple queries (each query is different)
for i in range(10):
db.select(User).filter(name=f"User{i}").fetch_all()
# Should respect cache_max_size only (5 entries max)
assert len(db._cache[User.get_table_name()]) == 5
# Memory usage should still be calculable
assert db._get_table_memory_usage(User.get_table_name()) >= 0