-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathlive-query-collection.test.ts
More file actions
2910 lines (2491 loc) · 94.3 KB
/
live-query-collection.test.ts
File metadata and controls
2910 lines (2491 loc) · 94.3 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Temporal } from 'temporal-polyfill'
import { createCollection } from '../../src/collection/index.js'
import {
and,
coalesce,
createLiveQueryCollection,
eq,
ilike,
liveQueryCollectionOptions,
} from '../../src/query/index.js'
import { Query } from '../../src/query/builder/index.js'
import {
flushPromises,
mockSyncCollectionOptions,
mockSyncCollectionOptionsNoInitialState,
stripVirtualProps,
} from '../utils.js'
import { createDeferred } from '../../src/deferred'
import { BTreeIndex } from '../../src/indexes/btree-index'
import { Func, Value } from '../../src/query/ir.js'
import type { ChangeMessage, LoadSubsetOptions } from '../../src/types.js'
// Sample user type for tests
type User = {
id: number
name: string
active: boolean
}
// Sample data for tests
const sampleUsers: Array<User> = [
{ id: 1, name: `Alice`, active: true },
{ id: 2, name: `Bob`, active: true },
{ id: 3, name: `Charlie`, active: false },
]
function createUsersCollection() {
return createCollection(
mockSyncCollectionOptions<User>({
id: `test-users`,
getKey: (user) => user.id,
initialData: sampleUsers,
}),
)
}
describe(`createLiveQueryCollection`, () => {
let usersCollection: ReturnType<typeof createUsersCollection>
beforeEach(() => {
usersCollection = createUsersCollection()
})
it(`should accept a callback function`, async () => {
const activeUsers = createLiveQueryCollection((q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true)),
)
await activeUsers.preload()
expect(activeUsers).toBeDefined()
expect(activeUsers.size).toBe(2) // Only Alice and Bob are active
})
it(`should accept a QueryBuilder instance via config object`, async () => {
const queryBuilder = new Query()
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true))
const activeUsers = createLiveQueryCollection({
query: queryBuilder,
})
await activeUsers.preload()
expect(activeUsers).toBeDefined()
expect(activeUsers.size).toBe(2) // Only Alice and Bob are active
})
it(`should work with both callback and QueryBuilder instance via config`, async () => {
// Test with callback
const activeUsers1 = createLiveQueryCollection((q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true)),
)
// Test with QueryBuilder instance via config
const queryBuilder = new Query()
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true))
const activeUsers2 = createLiveQueryCollection({
query: queryBuilder,
})
await activeUsers1.preload()
await activeUsers2.preload()
expect(activeUsers1).toBeDefined()
expect(activeUsers2).toBeDefined()
expect(activeUsers1.size).toBe(2)
expect(activeUsers2.size).toBe(2)
})
describe(`compareOptions inheritance`, () => {
it(`should inherit compareOptions from FROM collection`, () => {
// Create a collection with non-default compareOptions
const sourceCollection = createCollection(
mockSyncCollectionOptions<User>({
id: `source-with-lexical`,
getKey: (user) => user.id,
initialData: sampleUsers,
defaultStringCollation: {
stringSort: `lexical`,
},
}),
)
// Create a live query collection from the source collection
const liveQuery = createLiveQueryCollection((q) =>
q.from({ user: sourceCollection }),
)
// The live query should inherit the compareOptions from the source collection
expect(liveQuery.compareOptions).toEqual({
stringSort: `lexical`,
})
expect(sourceCollection.compareOptions).toEqual({
stringSort: `lexical`,
})
})
it(`should inherit compareOptions from FROM collection via subquery`, () => {
// Create a collection with non-default compareOptions
const sourceCollection = createCollection(
mockSyncCollectionOptions<User>({
id: `source-with-locale`,
getKey: (user) => user.id,
initialData: sampleUsers,
defaultStringCollation: {
stringSort: `locale`,
locale: `de-DE`,
},
}),
)
// Create a live query collection with a subquery
const liveQuery = createLiveQueryCollection((q) => {
// Build the subquery first
const filteredUsers = q
.from({ user: sourceCollection })
.where(({ user }) => eq(user.active, true))
// Use the subquery in the main query
return q.from({ filteredUser: filteredUsers })
})
// The live query should inherit the compareOptions from the source collection
// (which is the FROM collection of the subquery)
expect(liveQuery.compareOptions).toEqual({
stringSort: `locale`,
locale: `de-DE`,
})
expect(sourceCollection.compareOptions).toEqual({
stringSort: `locale`,
locale: `de-DE`,
})
})
it(`should use default compareOptions when FROM collection has no compareOptions`, () => {
// Create a collection without compareOptions (uses defaults)
const sourceCollection = createCollection(
mockSyncCollectionOptions<User>({
id: `source-with-defaults`,
getKey: (user) => user.id,
initialData: sampleUsers,
// No compareOptions specified - uses defaults
}),
)
// Create a live query collection with a subquery
const liveQuery = createLiveQueryCollection((q) => {
// Build the subquery first
const filteredUsers = q
.from({ user: sourceCollection })
.where(({ user }) => eq(user.active, true))
// Use the subquery in the main query
return q.from({ filteredUser: filteredUsers })
})
// The live query should use default compareOptions (locale)
// when the source collection doesn't specify compareOptions
expect(liveQuery.compareOptions).toEqual({
stringSort: `locale`,
})
expect(sourceCollection.compareOptions).toEqual({
stringSort: `locale`,
})
})
it(`should use explicitly provided compareOptions instead of inheriting from FROM collection`, () => {
// Create a collection with non-default compareOptions
const sourceCollection = createCollection(
mockSyncCollectionOptions<User>({
id: `source-with-lexical`,
getKey: (user) => user.id,
initialData: sampleUsers,
defaultStringCollation: {
stringSort: `lexical`,
},
}),
)
// Create a live query collection with explicitly provided compareOptions
// that differ from the source collection's compareOptions
const liveQuery = createLiveQueryCollection({
query: (q) => q.from({ user: sourceCollection }),
defaultStringCollation: {
stringSort: `locale`,
locale: `en-US`,
},
})
// The live query should use the explicitly provided compareOptions,
// not the inherited ones from the source collection
expect(liveQuery.compareOptions).toEqual({
stringSort: `locale`,
locale: `en-US`,
})
// The source collection should still have its original compareOptions
expect(sourceCollection.compareOptions).toEqual({
stringSort: `lexical`,
})
})
})
it(`should call markReady when source collection returns empty array`, async () => {
// Create an empty source collection using the mock sync options
const emptyUsersCollection = createCollection(
mockSyncCollectionOptions<User>({
id: `empty-test-users`,
getKey: (user) => user.id,
initialData: [], // Empty initial data
}),
)
// Create a live query collection that depends on the empty source collection
const liveQuery = createLiveQueryCollection((q) =>
q
.from({ user: emptyUsersCollection })
.where(({ user }) => eq(user.active, true)),
)
// This should resolve and not hang, even though the source collection is empty
await liveQuery.preload()
expect(liveQuery.status).toBe(`ready`)
expect(liveQuery.size).toBe(0)
})
it(`should call markReady when source collection sync doesn't call begin/commit (without WHERE clause)`, async () => {
// Create a collection with sync that only calls markReady (like the reproduction case)
const problemCollection = createCollection<User>({
id: `problem-collection`,
sync: {
sync: ({ markReady }) => {
// Simulate async operation without begin/commit (like empty queryFn case)
setTimeout(() => {
markReady()
}, 50)
return () => {} // cleanup function
},
},
getKey: (user) => user.id,
})
// Create a live query collection that depends on the problematic source collection
const liveQuery = createLiveQueryCollection((q) =>
q.from({ user: problemCollection }),
)
// This should resolve and not hang, even though the source collection doesn't commit data
await liveQuery.preload()
expect(liveQuery.status).toBe(`ready`)
expect(liveQuery.size).toBe(0)
})
it(`should call markReady when source collection sync doesn't call begin/commit (with WHERE clause)`, async () => {
// Create a collection with sync that only calls markReady (like the reproduction case)
const problemCollection = createCollection<User>({
id: `problem-collection-where`,
sync: {
sync: ({ markReady }) => {
// Simulate async operation without begin/commit (like empty queryFn case)
setTimeout(() => {
markReady()
}, 50)
return () => {} // cleanup function
},
},
getKey: (user) => user.id,
})
// Create a live query collection that depends on the problematic source collection
const liveQuery = createLiveQueryCollection((q) =>
q
.from({ user: problemCollection })
.where(({ user }) => eq(user.active, true)),
)
// This should resolve and not hang, even though the source collection doesn't commit data
await liveQuery.preload()
expect(liveQuery.status).toBe(`ready`)
expect(liveQuery.size).toBe(0)
})
it(`shouldn't call markReady when source collection sync doesn't call markReady`, () => {
const collection = createCollection<{ id: string }>({
sync: {
sync({ begin, commit }) {
begin()
commit()
},
},
getKey: (item) => item.id,
startSync: true,
})
const liveQuery = createLiveQueryCollection({
query: (q) => q.from({ collection }),
startSync: true,
})
expect(liveQuery.isReady()).toBe(false)
})
it(`should update after source collection is loaded even when not preloaded before rendering`, async () => {
// Create a source collection that doesn't start sync immediately
let beginCallback: (() => void) | undefined
let writeCallback:
| ((message: Omit<ChangeMessage<User, string | number>, `key`>) => void)
| undefined
let markReadyCallback: (() => void) | undefined
let commitCallback: (() => void) | undefined
const sourceCollection = createCollection<User>({
id: `delayed-source-collection`,
getKey: (user) => user.id,
startSync: false, // Don't start sync immediately
sync: {
sync: ({ begin, commit, write, markReady }) => {
beginCallback = begin
commitCallback = commit
markReadyCallback = markReady
writeCallback = write
return () => {} // cleanup function
},
},
onInsert: ({ transaction }) => {
const newItem = transaction.mutations[0].modified
// We need to call begin, write, and commit to properly sync the data
beginCallback!()
writeCallback!({
type: `insert`,
value: newItem,
})
commitCallback!()
return Promise.resolve()
},
onUpdate: () => Promise.resolve(),
onDelete: () => Promise.resolve(),
})
// Create a live query collection BEFORE the source collection is preloaded
// This simulates the scenario where the live query is created during rendering
// but the source collection hasn't been preloaded yet
const liveQuery = createLiveQueryCollection((q) =>
q
.from({ user: sourceCollection })
.where(({ user }) => eq(user.active, true)),
)
// Initially, the live query should be in idle state (default startSync: false)
expect(liveQuery.status).toBe(`idle`)
expect(liveQuery.size).toBe(0)
// Now preload the source collection (simulating what happens after rendering)
sourceCollection.preload()
// Store the promise so we can wait for it later
const preloadPromise = liveQuery.preload()
// Trigger the initial data load first
if (beginCallback && writeCallback && commitCallback && markReadyCallback) {
beginCallback()
// Write initial data
writeCallback({
type: `insert`,
value: { id: 1, name: `Alice`, active: true },
})
writeCallback({
type: `insert`,
value: { id: 2, name: `Bob`, active: false },
})
writeCallback({
type: `insert`,
value: { id: 3, name: `Charlie`, active: true },
})
commitCallback()
markReadyCallback()
}
// Wait for the preload to complete
await preloadPromise
// The live query should be ready and have the initial data
expect(liveQuery.size).toBe(2) // Alice and Charlie are active
expect(stripVirtualProps(liveQuery.get(1))).toEqual({
id: 1,
name: `Alice`,
active: true,
})
expect(stripVirtualProps(liveQuery.get(3))).toEqual({
id: 3,
name: `Charlie`,
active: true,
})
expect(liveQuery.get(2)).toBeUndefined() // Bob is not active
expect(liveQuery.status).toBe(`ready`)
// Now add some new data to the source collection (this should work as per the original report)
sourceCollection.insert({ id: 4, name: `David`, active: true })
// Wait for the mutation to propagate
await new Promise((resolve) => setTimeout(resolve, 10))
// The live query should update to include the new data
expect(liveQuery.size).toBe(3) // Alice, Charlie, and David are active
expect(stripVirtualProps(liveQuery.get(4))).toEqual({
id: 4,
name: `David`,
active: true,
})
})
it(`should not reuse finalized graph after GC cleanup (resubscribe is safe)`, async () => {
const liveQuery = createLiveQueryCollection({
query: (q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true)),
gcTime: 1,
})
const subscription = liveQuery.subscribeChanges(() => {})
await liveQuery.preload()
expect(liveQuery.status).toBe(`ready`)
// Unsubscribe and wait for GC to run and cleanup to complete
subscription.unsubscribe()
const deadline = Date.now() + 500
while (liveQuery.status !== `cleaned-up` && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 1))
}
expect(liveQuery.status).toBe(`cleaned-up`)
// Resubscribe should not throw (would throw "Graph already finalized" without the fix)
expect(() => liveQuery.subscribeChanges(() => {})).not.toThrow()
})
it(`nested live query should not go blank after GC and resubscribe`, async () => {
type Thread = { id: string; last_email_id: string; last_sent_at: number }
type LabelByEmail = { email_id: string; label: string }
const threads = createCollection(
mockSyncCollectionOptions<Thread>({
id: `threads-for-nested-gc-repro-collection`,
getKey: (t) => t.id,
initialData: [
{ id: `t1`, last_email_id: `e1`, last_sent_at: 3 },
{ id: `t2`, last_email_id: `e2`, last_sent_at: 2 },
],
}),
)
const labelsByEmail = createCollection(
mockSyncCollectionOptions<LabelByEmail>({
id: `labels-for-nested-gc-repro-collection`,
getKey: (l) => l.email_id,
initialData: [
{ email_id: `e1`, label: `inbox` },
{ email_id: `e2`, label: `work` },
],
}),
)
// Source live query (pre-created)
const sourceLQ = createCollection({
...liveQueryCollectionOptions({
query: (q: any) =>
q
.from({ thread: threads })
.orderBy(({ thread }: any) => thread.last_sent_at, {
direction: `desc`,
}),
startSync: true,
gcTime: 5,
}),
id: `source-lq`,
})
// Nested live query built from the source live query
const nestedLQ = createCollection({
...liveQueryCollectionOptions({
query: (q: any) =>
q
.from({ thread: sourceLQ })
.join(
{ label: labelsByEmail },
({ thread, label }: any) =>
eq(thread.last_email_id, label.email_id),
`inner`,
)
.orderBy(({ thread }: any) => thread.last_sent_at, {
direction: `desc`,
}),
startSync: true,
gcTime: 5,
}),
id: `nested-lq`,
})
// Wait for initial sync
await nestedLQ.preload()
expect(nestedLQ.size).toBe(2)
expect(nestedLQ.status).toBe(`ready`)
// First subscription cycle
const subscription1 = nestedLQ.subscribeChanges(() => {})
// Verify we still have data after subscribing
expect(nestedLQ.size).toBe(2)
expect(nestedLQ.status).toBe(`ready`)
// Unsubscribe and wait for GC
subscription1.unsubscribe()
const deadline1 = Date.now() + 500
while (nestedLQ.status !== `cleaned-up` && Date.now() < deadline1) {
await new Promise((r) => setTimeout(r, 1))
}
expect(nestedLQ.status).toBe(`cleaned-up`)
// Try multiple resubscribe cycles to increase chance of reproduction
for (let i = 0; i < 3; i++) {
// Resubscribe
const subscription2 = nestedLQ.subscribeChanges(() => {})
// Wait for the collection to potentially recover
await new Promise((r) => setTimeout(r, 50))
expect(nestedLQ.status).toBe(`ready`)
expect(nestedLQ.size).toBe(2)
// Unsubscribe and wait for GC again
subscription2.unsubscribe()
const deadline2 = Date.now() + 500
while (nestedLQ.status !== `cleaned-up` && Date.now() < deadline2) {
await new Promise((r) => setTimeout(r, 1))
}
expect(nestedLQ.status).toBe(`cleaned-up`)
// Small delay between cycles
await new Promise((r) => setTimeout(r, 20))
}
// Final verification - resubscribe one more time and ensure data is available
const finalSubscription = nestedLQ.subscribeChanges(() => {})
// Wait for the collection to become ready
const finalDeadline = Date.now() + 1000
while (nestedLQ.status !== `ready` && Date.now() < finalDeadline) {
await new Promise((r) => setTimeout(r, 10))
}
expect(nestedLQ.status).toBe(`ready`)
expect(nestedLQ.size).toBe(2)
finalSubscription.unsubscribe()
})
it(`should handle temporal values correctly in live queries`, async () => {
// Define a type with temporal values
type Task = {
id: number
name: string
duration: Temporal.Duration
}
// Initial data with temporal duration
const initialTask: Task = {
id: 1,
name: `Test Task`,
duration: Temporal.Duration.from({ hours: 1 }),
}
// Create a collection with temporal values
const taskCollection = createCollection(
mockSyncCollectionOptions<Task>({
id: `test-tasks`,
getKey: (task) => task.id,
initialData: [initialTask],
}),
)
// Create a live query collection that includes the temporal value
const liveQuery = createLiveQueryCollection((q) =>
q.from({ task: taskCollection }),
)
await liveQuery.preload()
// After initial sync, the live query should see the row with the temporal value
expect(liveQuery.size).toBe(1)
const initialResult = liveQuery.get(1)
expect(initialResult).toBeDefined()
expect(initialResult!.duration).toBeInstanceOf(Temporal.Duration)
expect(initialResult!.duration.hours).toBe(1)
// Simulate backend change: update the temporal value to 10 hours
const updatedTask: Task = {
id: 1,
name: `Test Task`,
duration: Temporal.Duration.from({ hours: 10 }),
}
// Update the task in the collection (simulating backend sync)
taskCollection.utils.begin()
taskCollection.utils.write({
type: `update`,
value: updatedTask,
})
taskCollection.utils.commit()
// The live query should now contain the new temporal value
const updatedResult = liveQuery.get(1)
expect(updatedResult).toBeDefined()
expect(updatedResult!.duration).toBeInstanceOf(Temporal.Duration)
expect(updatedResult!.duration.hours).toBe(10)
expect(updatedResult!.duration.total({ unit: `hours` })).toBe(10)
})
for (const autoIndex of [`eager`, `off`] as const) {
it(`should not send the initial state twice on joins with autoIndex: ${autoIndex}`, async () => {
type Player = { id: number; name: string }
type Challenge = { id: number; value: number }
const playerCollection = createCollection(
mockSyncCollectionOptionsNoInitialState<Player>({
id: `player`,
getKey: (post) => post.id,
autoIndex,
}),
)
const challenge1Collection = createCollection(
mockSyncCollectionOptionsNoInitialState<Challenge>({
id: `challenge1`,
getKey: (post) => post.id,
autoIndex,
}),
)
const challenge2Collection = createCollection(
mockSyncCollectionOptionsNoInitialState<Challenge>({
id: `challenge2`,
getKey: (post) => post.id,
autoIndex,
}),
)
const liveQuery = createLiveQueryCollection((q) =>
q
.from({ player: playerCollection })
.leftJoin(
{ challenge1: challenge1Collection },
({ player, challenge1 }) => eq(player.id, challenge1.id),
)
.leftJoin(
{ challenge2: challenge2Collection },
({ player, challenge2 }) => eq(player.id, challenge2.id),
),
)
// Start the query, but don't wait it, we are doing to write the data to the
// source collections while the query is loading the initial state
const preloadPromise = liveQuery.preload()
// Write player
playerCollection.utils.begin()
playerCollection.utils.write({
type: `insert`,
value: { id: 1, name: `Alice` },
})
playerCollection.utils.commit()
playerCollection.utils.markReady()
// Write challenge1
challenge1Collection.utils.begin()
challenge1Collection.utils.write({
type: `insert`,
value: { id: 1, value: 100 },
})
challenge1Collection.utils.commit()
challenge1Collection.utils.markReady()
// Write challenge2
challenge2Collection.utils.begin()
challenge2Collection.utils.write({
type: `insert`,
value: { id: 1, value: 200 },
})
challenge2Collection.utils.commit()
challenge2Collection.utils.markReady()
await preloadPromise
// With a failed test the results show more than 1 item
// It returns both an unjoined player with no joined challenges, and a joined
// player with the challenges
const results = liveQuery.toArray
expect(results.length).toBe(1)
const result = results[0]!
expect(result.player.name).toBe(`Alice`)
expect(result.challenge1?.value).toBe(100)
expect(result.challenge2?.value).toBe(200)
})
}
it(`should handle updates in live queries with custom getKey correctly`, async () => {
type Task = {
id: number
name: string
}
const initialTask: Task = {
id: 1,
name: `Test Task`,
}
const taskCollection = createCollection(
mockSyncCollectionOptions<Task>({
id: `test-tasks`,
getKey: (task) => `source:${task.id}`,
initialData: [initialTask],
}),
)
const liveQuery = createLiveQueryCollection({
query: (q) => q.from({ task: taskCollection }),
getKey: (task) => `live:${task.id}`, // return a different key from the source
})
await liveQuery.preload()
// After initial sync, the live query should see the row with the value
expect(liveQuery.size).toBe(1)
const initialResult = liveQuery.get(`live:1`)
expect(initialResult).toBeDefined()
expect(initialResult!.name).toBe(`Test Task`)
// Simulate backend change
const updatedTask: Task = {
id: 1,
name: `Updated Task`,
}
// Update the task in the collection (simulating backend sync)
taskCollection.utils.begin()
taskCollection.utils.write({
type: `update`,
value: updatedTask,
})
taskCollection.utils.commit()
// The live query should now contain the new value
expect(liveQuery.size).toBe(1)
const updatedResult = liveQuery.get(`live:1`)
expect(updatedResult).toBeDefined()
expect(updatedResult!.name).toBe(`Updated Task`)
})
describe(`optimistic reconciliation`, () => {
describe(`with delayed inserts`, () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it(`keeps emitting changes while sync catches up`, async () => {
let changeEventCount = 0
let syncBegin!: () => void
let syncWrite!: (change: ChangeMessage<any>) => void
let syncCommit!: () => void
const base = createCollection<{ id: string; created_at: number }>({
id: `delayed-inserts`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit, markReady }) => {
syncBegin = begin
syncWrite = write
syncCommit = commit
begin()
commit()
markReady()
},
},
onInsert: async ({ transaction }) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
syncBegin()
transaction.mutations.forEach((mutation) => {
syncWrite({
type: mutation.type,
value: mutation.modified,
key: mutation.key,
})
})
syncCommit()
},
})
const live = createLiveQueryCollection({
query: (q) =>
q
.from({ todo: base })
.orderBy(({ todo }) => todo.created_at, `asc`),
startSync: true,
})
await live.preload()
live.subscribeChanges(() => {
changeEventCount++
})
const tx1 = base.insert({ id: `1`, created_at: Date.now() })
const tx2 = base.insert({ id: `2`, created_at: Date.now() + 1 })
await vi.advanceTimersByTimeAsync(2000)
await Promise.all([tx1.isPersisted.promise, tx2.isPersisted.promise])
expect(base.size).toBe(2)
expect(live.size).toBe(2)
expect(changeEventCount).toBeGreaterThanOrEqual(2)
expect((base as any)._changes.shouldBatchEvents).toBe(false)
})
it(`stays in sync with many queued inserts`, async () => {
let syncBegin!: () => void
let syncWrite!: (change: ChangeMessage<any>) => void
let syncCommit!: () => void
const base = createCollection<{ id: string; created_at: number }>({
id: `delayed-inserts-many`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit, markReady }) => {
syncBegin = begin
syncWrite = write
syncCommit = commit
begin()
commit()
markReady()
},
},
onInsert: async ({ transaction }) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
syncBegin()
transaction.mutations.forEach((mutation) => {
syncWrite({
type: mutation.type,
value: mutation.modified,
key: mutation.key,
})
})
syncCommit()
},
})
const live = createLiveQueryCollection({
query: (q) =>
q
.from({ todo: base })
.orderBy(({ todo }) => todo.created_at, `asc`),
startSync: true,
})
await live.preload()
const transactions = Array.from({ length: 5 }, (_, index) =>
base.insert({
id: `${index + 1}`,
created_at: Date.now() + index,
}),
)
await vi.advanceTimersByTimeAsync(5000)
await Promise.all(transactions.map((tx) => tx.isPersisted.promise))
expect(base.size).toBe(5)
expect(live.size).toBe(5)
expect((base as any)._changes.shouldBatchEvents).toBe(false)
})
})
describe(`with queued optimistic updates`, () => {
it(`keeps live query results aligned while persist is delayed`, async () => {
const pendingPersists: Array<ReturnType<typeof createDeferred<void>>> =
[]
let syncBegin: (() => void) | undefined
let syncWrite: ((change: ChangeMessage<any>) => void) | undefined
let syncCommit: (() => void) | undefined
const todos = createCollection<{
id: string
createdAt: number
completed: boolean
}>({
id: `queued-optimistic-updates`,
getKey: (todo) => todo.id,
sync: {
sync: ({ begin, write, commit, markReady }) => {
syncBegin = begin
syncWrite = (change) => write({ ...change })
syncCommit = commit
begin()
;[
{ id: `1`, createdAt: 1, completed: false },
{ id: `2`, createdAt: 2, completed: false },
{ id: `3`, createdAt: 3, completed: false },
{ id: `4`, createdAt: 4, completed: false },
{ id: `5`, createdAt: 5, completed: false },
].forEach((todo) =>
write({
type: `insert`,
value: todo,
}),
)
commit()
markReady()
},
},
onUpdate: async ({ transaction }) => {
const deferred = createDeferred<void>()
pendingPersists.push(deferred)
await deferred.promise
syncBegin?.()
transaction.mutations.forEach((mutation) => {
syncWrite?.({
type: mutation.type,
key: mutation.key,
value: mutation.modified as {
id: string
createdAt: number
completed: boolean
},
})
})
syncCommit?.()
},
})
await todos.preload()
const live = createLiveQueryCollection({
query: (q) =>
q
.from({ todo: todos })
.orderBy(({ todo }) => todo.createdAt, `desc`),
startSync: true,