forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection-indexes.test.ts
More file actions
1338 lines (1147 loc) · 41.9 KB
/
collection-indexes.test.ts
File metadata and controls
1338 lines (1147 loc) · 41.9 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
import { beforeEach, describe, expect, it } from "vitest"
import mitt from "mitt"
import { createCollection } from "../src/collection"
import { createTransaction } from "../src/transactions"
import {
and,
eq,
gt,
gte,
inArray,
length,
lt,
lte,
or,
} from "../src/query/builder/functions"
import { expectIndexUsage, withIndexTracking } from "./utils"
import type { Collection } from "../src/collection"
import type { MutationFn, PendingMutation } from "../src/types"
interface TestItem {
id: string
name: string
age: number
status: `active` | `inactive` | `pending`
score?: number
createdAt: Date
}
describe(`Collection Indexes`, () => {
let collection: Collection<TestItem, string>
let testData: Array<TestItem>
let mutationFn: MutationFn
let emitter: any
beforeEach(async () => {
testData = [
{
id: `1`,
name: `Alice`,
age: 25,
status: `active`,
score: 95,
createdAt: new Date(`2023-01-01`),
},
{
id: `2`,
name: `Bob`,
age: 30,
status: `inactive`,
score: 80,
createdAt: new Date(`2023-01-02`),
},
{
id: `3`,
name: `Charlie`,
age: 35,
status: `active`,
score: 90,
createdAt: new Date(`2023-01-03`),
},
{
id: `4`,
name: `Diana`,
age: 28,
status: `pending`,
score: 85,
createdAt: new Date(`2023-01-04`),
},
{
id: `5`,
name: `Eve`,
age: 22,
status: `active`,
score: undefined,
createdAt: new Date(`2023-01-05`),
},
]
emitter = mitt()
// Create mutation handler that syncs changes back via emitter
mutationFn = ({ transaction }) => {
emitter.emit(`sync`, transaction.mutations)
return Promise.resolve()
}
collection = createCollection<TestItem, string>({
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// Provide initial data through sync
begin()
for (const item of testData) {
write({
type: `insert`,
value: item,
})
}
commit()
// Listen for mutations and sync them back (only register once)
if (!emitter.all.has(`sync`)) {
emitter.on(`sync`, (changes: Array<PendingMutation>) => {
begin()
changes.forEach((change) => {
write({
type: change.type,
value: change.modified as unknown as TestItem,
})
})
commit()
})
}
},
},
})
// Wait for sync to complete
await collection.stateWhenReady()
// Verify data was loaded
expect(collection.size).toBe(5)
})
describe(`Index Creation`, () => {
it(`should create an index on a simple field`, () => {
const index = collection.createIndex((row) => row.status)
expect(typeof index.id).toBe(`number`)
expect(index.id).toBeGreaterThan(0)
expect(index.name).toBeUndefined()
expect(index.expression.type).toBe(`ref`)
expect(index.indexedKeysSet.size).toBe(5)
})
it(`should create a named index`, () => {
const index = collection.createIndex((row) => row.age, {
name: `ageIndex`,
})
expect(index.name).toBe(`ageIndex`)
expect(index.indexedKeysSet.size).toBe(5)
})
it(`should create multiple indexes`, () => {
const statusIndex = collection.createIndex((row) => row.status)
const ageIndex = collection.createIndex((row) => row.age)
expect(statusIndex.id).not.toBe(ageIndex.id)
expect(statusIndex.indexedKeysSet.size).toBe(5)
expect(ageIndex.indexedKeysSet.size).toBe(5)
})
it(`should maintain ordered entries`, () => {
const ageIndex = collection.createIndex((row) => row.age)
// Ages should be ordered: 22, 25, 28, 30, 35
const orderedAges = ageIndex.orderedEntriesArray.map(([age]) => age)
expect(orderedAges).toEqual([22, 25, 28, 30, 35])
})
it(`should handle duplicate values in index`, () => {
const statusIndex = collection.createIndex((row) => row.status)
// Should have 3 unique status values
expect(statusIndex.orderedEntriesArray.length).toBe(3)
// "active" status should have 3 items
const activeKeys = statusIndex.valueMapData.get(`active`)
expect(activeKeys?.size).toBe(3)
})
it(`should handle undefined/null values`, () => {
const scoreIndex = collection.createIndex((row) => row.score)
// Should include the item with undefined score
expect(scoreIndex.indexedKeysSet.size).toBe(5)
// undefined should be first in ordered entries
const firstValue = scoreIndex.orderedEntriesArray[0]?.[0]
expect(firstValue).toBeUndefined()
})
})
describe(`Index Maintenance`, () => {
beforeEach(() => {
collection.createIndex((row) => row.status)
collection.createIndex((row) => row.age)
})
it(`should reflect mutations in collection state and subscriptions`, async () => {
const changes: Array<any> = []
// Subscribe to all changes
const unsubscribe = collection.subscribeChanges((items) => {
changes.push(...items)
})
const newItem: TestItem = {
id: `6`,
name: `Frank`,
age: 40,
status: `active`,
createdAt: new Date(`2023-01-06`),
}
const tx = createTransaction({ mutationFn })
tx.mutate(() => collection.insert(newItem))
await tx.isPersisted.promise
// Item should be in collection state
expect(collection.size).toBe(6)
expect(collection.get(`6`)).toEqual(newItem)
// Should trigger subscription
expect(changes).toHaveLength(1)
expect(changes[0]?.type).toBe(`insert`)
expect(changes[0]?.value.name).toBe(`Frank`)
unsubscribe()
})
it(`should reflect updates in collection state and subscriptions`, async () => {
const changes: Array<any> = []
const unsubscribe = collection.subscribeChanges((items) => {
changes.push(...items)
})
const tx = createTransaction({ mutationFn })
tx.mutate(() =>
collection.update(`1`, (draft) => {
draft.status = `inactive`
draft.age = 26
})
)
await tx.isPersisted.promise
// Updated item should be in collection state
const updatedItem = collection.get(`1`)
expect(updatedItem?.status).toBe(`inactive`)
expect(updatedItem?.age).toBe(26)
// Should trigger subscription
expect(changes).toHaveLength(1)
expect(changes[0]?.type).toBe(`update`)
expect(changes[0]?.value.status).toBe(`inactive`)
unsubscribe()
})
it(`should reflect deletions in collection state and subscriptions`, async () => {
const changes: Array<any> = []
const unsubscribe = collection.subscribeChanges((items) => {
changes.push(...items)
})
const tx = createTransaction({ mutationFn })
tx.mutate(() => collection.delete(`1`))
await tx.isPersisted.promise
// Item should be removed from collection state
expect(collection.size).toBe(4)
expect(collection.get(`1`)).toBeUndefined()
// Should trigger subscription (may be called multiple times in test environment)
expect(changes.length).toBeGreaterThanOrEqual(1)
expect(changes[0]?.type).toBe(`delete`)
expect(changes[0]?.key).toBe(`1`)
// Ensure all events are the same delete event
const deleteEvents = changes.filter(
(c) => c.type === `delete` && c.key === `1`
)
expect(deleteEvents.length).toBe(changes.length) // All events should be the same delete
unsubscribe()
})
it(`should handle filtered subscriptions correctly with mutations`, async () => {
const activeChanges: Array<any> = []
const unsubscribe = collection.subscribeChanges(
(items) => {
activeChanges.push(...items)
},
{
where: (row) => eq(row.status, `active`),
}
)
// Change inactive item to active (should trigger)
const tx1 = createTransaction({ mutationFn })
tx1.mutate(() =>
collection.update(`2`, (draft) => {
draft.status = `active`
})
)
await tx1.isPersisted.promise
expect(activeChanges).toHaveLength(1)
expect(activeChanges[0]?.value.name).toBe(`Bob`)
// Change active item to inactive (should trigger delete event for item leaving filter)
activeChanges.length = 0
const tx2 = createTransaction({ mutationFn })
tx2.mutate(() =>
collection.update(`1`, (draft) => {
draft.status = `inactive`
})
)
await tx2.isPersisted.promise
// Should trigger delete event for item that no longer matches filter
expect(activeChanges).toHaveLength(1)
expect(activeChanges[0]?.type).toBe(`delete`)
expect(activeChanges[0]?.key).toBe(`1`)
expect(activeChanges[0]?.value.status).toBe(`active`) // Should be the previous value
unsubscribe()
})
})
describe(`Range Queries`, () => {
beforeEach(() => {
collection.createIndex((row) => row.age)
})
it(`should perform equality queries`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => eq(row.age, 25),
})
expect(result).toHaveLength(1)
expect(result[0]?.value.name).toBe(`Alice`)
// Verify 100% index usage
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should perform greater than queries`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => gt(row.age, 28),
})
expect(result).toHaveLength(2)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Bob`, `Charlie`])
// Verify 100% index usage
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should perform greater than or equal queries`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => gte(row.age, 28),
})
expect(result).toHaveLength(3)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Bob`, `Charlie`, `Diana`])
// Verify 100% index usage
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should perform less than queries`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => lt(row.age, 28),
})
expect(result).toHaveLength(2)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Eve`])
// Verify 100% index usage
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should perform less than or equal queries`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => lte(row.age, 28),
})
expect(result).toHaveLength(3)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Diana`, `Eve`])
// Verify 100% index usage
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should fall back to full scan for complex expressions`, () => {
withIndexTracking(collection, (tracker) => {
// This should work but use full scan since it's not a simple comparison
// Using a complex expression that can't be optimized with indexes
const result = collection.currentStateAsChanges({
where: (row) => gt(length(row.name), 3),
})
expect(result).toHaveLength(3) // Alice, Charlie, Diana (names longer than 3 chars)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`, `Diana`])
// Verify full scan is used, no index
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
it(`should verify index optimization is being used for simple queries`, () => {
withIndexTracking(collection, (tracker) => {
// This should use index optimization
const result = collection.currentStateAsChanges({
where: (row) => eq(row.age, 25),
})
expect(result).toHaveLength(1)
expect(result[0]?.value.name).toBe(`Alice`)
// Verify 100% index usage, no full scan
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
// Verify the specific index was used
expect(tracker.stats.indexesUsed[0]).toMatch(/^\d+$/)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `eq`,
field: `age`,
value: 25,
})
})
})
it(`should verify different range operations use indexes`, () => {
withIndexTracking(collection, (tracker) => {
// Test multiple range operations
const eqResult = collection.currentStateAsChanges({
where: (row) => eq(row.age, 25),
})
const gtResult = collection.currentStateAsChanges({
where: (row) => gt(row.age, 30),
})
const lteResult = collection.currentStateAsChanges({
where: (row) => lte(row.age, 28),
})
expect(eqResult).toHaveLength(1)
expect(gtResult).toHaveLength(1) // Charlie (35)
expect(lteResult).toHaveLength(3) // Alice (25), Diana (28), Eve (22)
// Should have used index 3 times, no full scans
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 3,
fullScanCallCount: 0,
})
// Verify all operations used indexes
expect(tracker.stats.queriesExecuted).toHaveLength(3)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `eq`,
})
expect(tracker.stats.queriesExecuted[1]).toMatchObject({
type: `index`,
operation: `gt`,
})
expect(tracker.stats.queriesExecuted[2]).toMatchObject({
type: `index`,
operation: `lte`,
})
})
})
it(`should verify complex expressions fall back to full scan`, () => {
withIndexTracking(collection, (tracker) => {
// This should fall back to full scan
const result = collection.currentStateAsChanges({
where: (row) => gt(length(row.name), 3),
})
expect(result).toHaveLength(3) // Alice, Charlie, Diana
// Should use full scan, no index
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `fullScan`,
})
})
})
it(`should verify queries without matching indexes use full scan`, () => {
withIndexTracking(collection, (tracker) => {
// Query on a field without an index (status)
const result = collection.currentStateAsChanges({
where: (row) => eq(row.status, `active`),
})
expect(result).toHaveLength(3) // Alice, Charlie, Eve
// Should use full scan since no status index exists
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
})
describe(`Complex Query Optimization`, () => {
beforeEach(() => {
collection.createIndex((row) => row.age)
collection.createIndex((row) => row.status)
})
it(`should optimize AND queries with range conditions using indexes`, () => {
withIndexTracking(collection, (tracker) => {
// Test the key case: range query with AND
const result = collection.currentStateAsChanges({
where: (row) => and(gt(row.age, 25), lt(row.age, 35)),
})
expect(result).toHaveLength(2) // Bob (30), Diana (28)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Bob`, `Diana`])
// Verify 100% index usage - should use age index once with compound range query
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1, // Single compound range query (gt and lt combined)
fullScanCallCount: 0,
})
// Verify compound range query was used
expect(tracker.stats.queriesExecuted).toHaveLength(1)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `gt AND lt`,
field: `age`,
value: { from: 25, fromInclusive: false, to: 35, toInclusive: false },
})
})
})
it(`should optimize AND queries with multiple field conditions`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => and(eq(row.status, `active`), gte(row.age, 25)),
})
expect(result).toHaveLength(2) // Alice (25, active), Charlie (35, active)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`])
// Verify 100% index usage - should use both status and age indexes
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 2, // eq and gte operations
fullScanCallCount: 0,
})
// Verify different indexes were used
expect(tracker.stats.queriesExecuted).toHaveLength(2)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `eq`,
field: `status`,
value: `active`,
})
expect(tracker.stats.queriesExecuted[1]).toMatchObject({
type: `index`,
operation: `gte`,
field: `age`,
value: { from: 25, fromInclusive: true },
})
})
})
it(`should optimize OR queries using indexes`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => or(eq(row.age, 25), eq(row.age, 35)),
})
expect(result).toHaveLength(2) // Alice (25), Charlie (35)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`])
// Verify 100% index usage - should use age index twice
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 2, // Two eq operations
fullScanCallCount: 0,
})
// Verify both operations used the age index
expect(tracker.stats.queriesExecuted).toHaveLength(2)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `eq`,
field: `age`,
value: 25,
})
expect(tracker.stats.queriesExecuted[1]).toMatchObject({
type: `index`,
operation: `eq`,
field: `age`,
value: 35,
})
})
})
it(`should optimize inArray queries using indexes`, () => {
withIndexTracking(collection, (tracker) => {
const result = collection.currentStateAsChanges({
where: (row) => inArray(row.status, [`active`, `pending`]),
})
expect(result).toHaveLength(4) // Alice, Charlie, Eve (active), Diana (pending)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`, `Diana`, `Eve`])
// Verify 100% index usage - should use status index once with IN operation
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1, // One IN operation for the array values
fullScanCallCount: 0,
})
// Verify the IN operation was used
expect(tracker.stats.queriesExecuted).toHaveLength(1)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `in`,
field: `status`,
value: [`active`, `pending`],
})
})
})
it(`should optimize complex nested AND/OR expressions`, () => {
withIndexTracking(collection, (tracker) => {
// (age >= 25 AND age <= 30) OR status = 'pending'
const result = collection.currentStateAsChanges({
where: (row) =>
or(
and(gte(row.age, 25), lte(row.age, 30)),
eq(row.status, `pending`)
),
})
expect(result).toHaveLength(3) // Alice (25), Bob (30), Diana (28, pending)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Bob`, `Diana`])
// Verify 100% index usage - should use age index once (compound) + status index once
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 2, // Compound range query + status equality
fullScanCallCount: 0,
})
// Verify the operations
expect(tracker.stats.queriesExecuted).toHaveLength(2)
expect(tracker.stats.queriesExecuted[0]).toMatchObject({
type: `index`,
operation: `gte AND lte`,
field: `age`,
value: { from: 25, fromInclusive: true, to: 30, toInclusive: true },
})
expect(tracker.stats.queriesExecuted[1]).toMatchObject({
type: `index`,
operation: `eq`,
field: `status`,
value: `pending`,
})
})
})
it(`should partially optimize when some conditions can be optimized`, () => {
withIndexTracking(collection, (tracker) => {
// Mix of optimizable and non-optimizable conditions
const result = collection.currentStateAsChanges({
where: (row) =>
and(
eq(row.status, `active`), // Can optimize with index
gt(row.age, 24) // Can also optimize - will be AND combined
),
})
expect(result).toHaveLength(2) // Alice (25), Charlie (35) - both active and age > 24
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`])
// Should use optimization: both conditions can use indexes
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 2,
fullScanCallCount: 0,
})
})
})
it(`should optimize queries with missing indexes by using partial optimization`, () => {
withIndexTracking(collection, (tracker) => {
// Query on a field without an index (name)
const result = collection.currentStateAsChanges({
where: (row) =>
and(
eq(row.age, 25), // Has index
eq(row.name, `Alice`) // No index on name
),
})
expect(result).toHaveLength(1) // Alice (25, name Alice)
expect(result[0]?.value.name).toBe(`Alice`)
// Should use partial optimization: age index, then filter by name
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
})
it(`should fall back to full scan when no conditions can be optimized`, () => {
withIndexTracking(collection, (tracker) => {
// Only complex expressions that can't be optimized
const result = collection.currentStateAsChanges({
where: (row) => gt(length(row.name), 3),
})
expect(result).toHaveLength(3) // Alice, Charlie, Diana (names > 3 chars)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Alice`, `Charlie`, `Diana`])
// Should fall back to full scan since no conditions can be optimized
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
it(`should fall back to full scan for complex nested expressions`, () => {
withIndexTracking(collection, (tracker) => {
// Complex expression involving function calls - no simple field comparisons
const result = collection.currentStateAsChanges({
where: (row) =>
and(
gt(length(row.name), 4), // Complex - can't optimize (Alice=5, Charlie=7, Diana=5)
gt(length(row.status), 6) // Complex - can't optimize (only "inactive" = 8 > 6)
),
})
expect(result).toHaveLength(1) // Only Diana has name>4 AND status>6 (Diana name=5, status="pending"=7)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Diana`])
// Should fall back to full scan for complex expressions
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
it(`should fall back to full scan when OR conditions can't be optimized`, () => {
withIndexTracking(collection, (tracker) => {
// OR with complex conditions that can't be optimized
const result = collection.currentStateAsChanges({
where: (row) =>
or(
gt(length(row.name), 6), // Complex - can't optimize (only Charlie has name length 7 > 6)
gt(length(row.status), 7) // Complex - can't optimize (only Bob has status "inactive" = 8 > 7)
),
})
expect(result).toHaveLength(2) // Charlie (name length 7 > 6), Bob (status length 8 > 7)
const names = result.map((r) => r.value.name).sort()
expect(names).toEqual([`Bob`, `Charlie`])
// Should fall back to full scan when no OR branches can be optimized
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
it(`should fall back to full scan when querying non-indexed fields only`, () => {
withIndexTracking(collection, (tracker) => {
// Query only on fields without indexes (name and score fields don't have indexes)
const result = collection.currentStateAsChanges({
where: (row) => and(eq(row.name, `Alice`), eq(row.score, 95)),
})
expect(result).toHaveLength(1) // Alice
expect(result[0]?.value.name).toBe(`Alice`)
// Should fall back to full scan since no indexed fields are used
expectIndexUsage(tracker.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
it(`should handle mixed optimization scenarios within same query`, () => {
// Test two separate queries to show different optimization strategies
// First: partial optimization (age index + name filter)
withIndexTracking(collection, (tracker1) => {
const result1 = collection.currentStateAsChanges({
where: (row) =>
and(
eq(row.age, 25), // Can optimize - has index
eq(row.name, `Alice`) // Can't optimize - no index
),
})
expect(result1).toHaveLength(1) // Alice via partial optimization
expectIndexUsage(tracker1.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 1,
fullScanCallCount: 0,
})
})
// Second: full scan (no optimizable conditions)
withIndexTracking(collection, (tracker2) => {
const result2 = collection.currentStateAsChanges({
where: (row) =>
and(
eq(row.name, `Alice`), // Can't optimize - no index
gt(length(row.name), 3) // Can't optimize - complex expression
),
})
expect(result2).toHaveLength(1) // Alice via full scan
expectIndexUsage(tracker2.stats, {
shouldUseIndex: false,
shouldUseFullScan: true,
indexCallCount: 0,
fullScanCallCount: 1,
})
})
})
})
describe(`Index Usage Verification`, () => {
it(`should track multiple indexes and their usage patterns`, () => {
// Create multiple indexes
collection.createIndex((row) => row.age, {
name: `ageIndex`,
})
collection.createIndex((row) => row.status, {
name: `statusIndex`,
})
collection.createIndex((row) => row.name, {
name: `nameIndex`,
})
withIndexTracking(collection, (tracker) => {
// Query using age index
const ageQuery = collection.currentStateAsChanges({
where: (row) => gte(row.age, 30),
})
// Query using status index
const statusQuery = collection.currentStateAsChanges({
where: (row) => eq(row.status, `active`),
})
// Query using name index
const nameQuery = collection.currentStateAsChanges({
where: (row) => eq(row.name, `Alice`),
})
expect(ageQuery).toHaveLength(2) // Bob (30), Charlie (35)
expect(statusQuery).toHaveLength(3) // Alice, Charlie, Eve
expect(nameQuery).toHaveLength(1) // Alice
// Verify all queries used indexes
expectIndexUsage(tracker.stats, {
shouldUseIndex: true,
shouldUseFullScan: false,
indexCallCount: 3,
fullScanCallCount: 0,
})
// Verify specific indexes were used
expect(tracker.stats.indexesUsed).toHaveLength(3)
expect(tracker.stats.queriesExecuted).toEqual([
{
type: `index`,
operation: `gte`,
field: `age`,
value: { from: 30, fromInclusive: true },
},
{ type: `index`, operation: `eq`, field: `status`, value: `active` },
{ type: `index`, operation: `eq`, field: `name`, value: `Alice` },
])
// Test that we can identify which specific index was used
const usedIndexes = new Set(tracker.stats.indexesUsed)
expect(usedIndexes.size).toBe(3) // Three different indexes used
})
})
it(`should verify 100% index usage for subscriptions`, () => {
collection.createIndex((row) => row.status)
withIndexTracking(collection, (tracker) => {
const changes: Array<any> = []
// Subscribe with a where clause that should use index
const unsubscribe = collection.subscribeChanges(
(items) => changes.push(...items),
{
includeInitialState: true,
where: (row) => eq(row.status, `active`),
}
)
expect(changes).toHaveLength(3) // Initial active items
// Verify initial state query used index