Open History to see the last commit
1import { describe, expect, it } from "vitest"
2import {
3 count,
4 createCollection,
5 createLiveQueryCollection,
6 createOptimisticAction,
7 eq,
8 gt,
9} from "@tanstack/db"
10import { nextTick, ref, watchEffect } from "vue"
11import { useLiveQuery } from "../src/useLiveQuery"
12import { mockSyncCollectionOptions } from "../../db/tests/utils"
13
14type Person = {
15 id: string
16 name: string
17 age: number
18 email: string
19 isActive: boolean
20 team: string
21}
22
23type Issue = {
24 id: string
25 title: string
26 description: string
27 userId: string
28}
29
30const initialPersons: Array<Person> = [
31 {
32 id: `1`,
33 name: `John Doe`,
34 age: 30,
35 email: `john.doe@example.com`,
36 isActive: true,
37 team: `team1`,
38 },
39 {
40 id: `2`,
41 name: `Jane Doe`,
42 age: 25,
43 email: `jane.doe@example.com`,
44 isActive: true,
45 team: `team2`,
46 },
47 {
48 id: `3`,
49 name: `John Smith`,
50 age: 35,
51 email: `john.smith@example.com`,
52 isActive: true,
53 team: `team1`,
54 },
55]
56
57const initialIssues: Array<Issue> = [
58 {
59 id: `1`,
60 title: `Issue 1`,
61 description: `Issue 1 description`,
62 userId: `1`,
63 },
64 {
65 id: `2`,
66 title: `Issue 2`,
67 description: `Issue 2 description`,
68 userId: `2`,
69 },
70 {
71 id: `3`,
72 title: `Issue 3`,
73 description: `Issue 3 description`,
74 userId: `1`,
75 },
76]
77
78// Helper function to wait for Vue reactivity
79async function waitForVueUpdate() {
80 await nextTick()
81 // Additional small delay to ensure collection updates are processed
82 await new Promise((resolve) => setTimeout(resolve, 50))
83}
84
85// Helper function to poll for a condition until it passes or times out
86async function waitFor(fn: () => void, timeout = 2000, interval = 20) {
87 const start = Date.now()
88
89 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
90 while (true) {
91 try {
92 fn()
93 return
94 } catch (err) {
95 if (Date.now() - start > timeout) throw err
96 await new Promise((resolve) => setTimeout(resolve, interval))
97 }
98 }
99}
100
101describe(`Query Collections`, () => {
102 it(`should work with basic collection and select`, async () => {
103 const collection = createCollection(
104 mockSyncCollectionOptions<Person>({
105 id: `test-persons`,
106 getKey: (person: Person) => person.id,
107 initialData: initialPersons,
108 })
109 )
110
111 const { state, data } = useLiveQuery((q) =>
112 q
113 .from({ persons: collection })
114 .where(({ persons }) => gt(persons.age, 30))
115 .select(({ persons }) => ({
116 id: persons.id,
117 name: persons.name,
118 age: persons.age,
119 }))
120 )
121
122 // Wait for Vue reactivity to update
123 await waitForVueUpdate()
124
125 expect(state.value.size).toBe(1) // Only John Smith (age 35)
126 expect(data.value).toHaveLength(1)
127
128 const johnSmith = data.value[0]
129 expect(johnSmith).toMatchObject({
130 id: `3`,
131 name: `John Smith`,
132 age: 35,
133 })
134 })
135
136 it(`should be able to query a collection with live updates`, async () => {
137 const collection = createCollection(
138 mockSyncCollectionOptions<Person>({
139 id: `test-persons-2`,
140 getKey: (person: Person) => person.id,
141 initialData: initialPersons,
142 })
143 )
144
145 const { state, data } = useLiveQuery((q) =>
146 q
147 .from({ collection })
148 .where(({ collection: c }) => gt(c.age, 30))
149 .select(({ collection: c }) => ({
150 id: c.id,
151 name: c.name,
152 }))
153 .orderBy(({ collection: c }) => c.id, `asc`)
154 )
155
156 // Wait for collection to sync
157 await waitForVueUpdate()
158
159 expect(state.value.size).toBe(1)
160 expect(state.value.get(`3`)).toMatchObject({
161 id: `3`,
162 name: `John Smith`,
163 })
164
165 expect(data.value.length).toBe(1)
166 expect(data.value[0]).toMatchObject({
167 id: `3`,
168 name: `John Smith`,
169 })
170
171 // Insert a new person using the proper utils pattern
172 collection.utils.begin()
173 collection.utils.write({
174 type: `insert`,
175 value: {
176 id: `4`,
177 name: `Kyle Doe`,
178 age: 40,
179 email: `kyle.doe@example.com`,
180 isActive: true,
181 team: `team1`,
182 },
183 })
184 collection.utils.commit()
185
186 await waitForVueUpdate()
187
188 expect(state.value.size).toBe(2)
189 expect(state.value.get(`3`)).toMatchObject({
190 id: `3`,
191 name: `John Smith`,
192 })
193 expect(state.value.get(`4`)).toMatchObject({
194 id: `4`,
195 name: `Kyle Doe`,
196 })
197
198 expect(data.value.length).toBe(2)
199 expect(data.value).toEqual(
200 expect.arrayContaining([
201 expect.objectContaining({
202 id: `3`,
203 name: `John Smith`,
204 }),
205 expect.objectContaining({
206 id: `4`,
207 name: `Kyle Doe`,
208 }),
209 ])
210 )
211
212 // Update the person
213 collection.utils.begin()
214 collection.utils.write({
215 type: `update`,
216 value: {
217 id: `4`,
218 name: `Kyle Doe 2`,
219 age: 40,
220 email: `kyle.doe@example.com`,
221 isActive: true,
222 team: `team1`,
223 },
224 })
225 collection.utils.commit()
226
227 await waitForVueUpdate()
228
229 expect(state.value.size).toBe(2)
230 expect(state.value.get(`4`)).toMatchObject({
231 id: `4`,
232 name: `Kyle Doe 2`,
233 })
234
235 expect(data.value.length).toBe(2)
236 expect(data.value).toEqual(
237 expect.arrayContaining([
238 expect.objectContaining({
239 id: `3`,
240 name: `John Smith`,
241 }),
242 expect.objectContaining({
243 id: `4`,
244 name: `Kyle Doe 2`,
245 }),
246 ])
247 )
248
249 // Delete the person
250 collection.utils.begin()
251 collection.utils.write({
252 type: `delete`,
253 value: {
254 id: `4`,
255 name: `Kyle Doe 2`,
256 age: 40,
257 email: `kyle.doe@example.com`,
258 isActive: true,
259 team: `team1`,
260 },
261 })
262 collection.utils.commit()
263
264 await waitForVueUpdate()
265
266 expect(state.value.size).toBe(1)
267 expect(state.value.get(`4`)).toBeUndefined()
268
269 expect(data.value.length).toBe(1)
270 expect(data.value[0]).toMatchObject({
271 id: `3`,
272 name: `John Smith`,
273 })
274 })
275
276 it(`should join collections and return combined results with live updates`, async () => {
277 // Create person collection
278 const personCollection = createCollection(
279 mockSyncCollectionOptions<Person>({
280 id: `person-collection-test`,
281 getKey: (person: Person) => person.id,
282 initialData: initialPersons,
283 })
284 )
285
286 // Create issue collection
287 const issueCollection = createCollection(
288 mockSyncCollectionOptions<Issue>({
289 id: `issue-collection-test`,
290 getKey: (issue: Issue) => issue.id,
291 initialData: initialIssues,
292 })
293 )
294
295 const { state } = useLiveQuery((q) =>
296 q
297 .from({ issues: issueCollection })
298 .join({ persons: personCollection }, ({ issues, persons }) =>
299 eq(issues.userId, persons.id)
300 )
301 .select(({ issues, persons }) => ({
302 id: issues.id,
303 title: issues.title,
304 name: persons.name,
305 }))
306 )
307
308 // Wait for collections to sync
309 await waitForVueUpdate()
310
311 // Verify that we have the expected joined results
312 expect(state.value.size).toBe(3)
313
314 expect(state.value.get(`[1,1]`)).toMatchObject({
315 id: `1`,
316 name: `John Doe`,
317 title: `Issue 1`,
318 })
319
320 expect(state.value.get(`[2,2]`)).toMatchObject({
321 id: `2`,
322 name: `Jane Doe`,
323 title: `Issue 2`,
324 })
325
326 expect(state.value.get(`[3,1]`)).toMatchObject({
327 id: `3`,
328 name: `John Doe`,
329 title: `Issue 3`,
330 })
331
332 // Add a new issue for user 2
333 issueCollection.utils.begin()
334 issueCollection.utils.write({
335 type: `insert`,
336 value: {
337 id: `4`,
338 title: `Issue 4`,
339 description: `Issue 4 description`,
340 userId: `2`,
341 },
342 })
343 issueCollection.utils.commit()
344
345 await waitForVueUpdate()
346
347 expect(state.value.size).toBe(4)
348 expect(state.value.get(`[4,2]`)).toMatchObject({
349 id: `4`,
350 name: `Jane Doe`,
351 title: `Issue 4`,
352 })
353
354 // Update an issue we're already joined with
355 issueCollection.utils.begin()
356 issueCollection.utils.write({
357 type: `update`,
358 value: {
359 id: `2`,
360 title: `Updated Issue 2`,
361 description: `Issue 2 description`,
362 userId: `2`,
363 },
364 })
365 issueCollection.utils.commit()
366
367 await waitForVueUpdate()
368
369 // The updated title should be reflected in the joined results
370 expect(state.value.get(`[2,2]`)).toMatchObject({
371 id: `2`,
372 name: `Jane Doe`,
373 title: `Updated Issue 2`,
374 })
375
376 // Delete an issue
377 issueCollection.utils.begin()
378 issueCollection.utils.write({
379 type: `delete`,
380 value: {
381 id: `3`,
382 title: `Issue 3`,
383 description: `Issue 3 description`,
384 userId: `1`,
385 },
386 })
387 issueCollection.utils.commit()
388
389 await waitForVueUpdate()
390
391 // After deletion, issue 3 should no longer have a joined result
392 expect(state.value.get(`[3,1]`)).toBeUndefined()
393 expect(state.value.size).toBe(3)
394 })
395
396 it(`should recompile query when parameters change and change results`, async () => {
397 const collection = createCollection(
398 mockSyncCollectionOptions<Person>({
399 id: `params-change-test`,
400 getKey: (person: Person) => person.id,
401 initialData: initialPersons,
402 })
403 )
404
405 const minAge = ref(30)
406
407 const { state } = useLiveQuery(
408 (q) =>
409 q
410 .from({ collection })
411 .where(({ collection: c }) => gt(c.age, minAge.value))
412 .select(({ collection: c }) => ({
413 id: c.id,
414 name: c.name,
415 age: c.age,
416 })),
417 [minAge]
418 )
419
420 // Wait for collection to sync
421 await waitForVueUpdate()
422
423 // Initially should return only people older than 30
424 expect(state.value.size).toBe(1)
425 expect(state.value.get(`3`)).toMatchObject({
426 id: `3`,
427 name: `John Smith`,
428 age: 35,
429 })
430
431 // Change the parameter to include more people
432 minAge.value = 20
433
434 await waitForVueUpdate()
435
436 // Now should return all people as they're all older than 20
437 expect(state.value.size).toBe(3)
438 expect(state.value.get(`1`)).toMatchObject({
439 id: `1`,
440 name: `John Doe`,
441 age: 30,
442 })
443 expect(state.value.get(`2`)).toMatchObject({
444 id: `2`,
445 name: `Jane Doe`,
446 age: 25,
447 })
448 expect(state.value.get(`3`)).toMatchObject({
449 id: `3`,
450 name: `John Smith`,
451 age: 35,
452 })
453
454 // Change to exclude everyone
455 minAge.value = 50
456
457 await waitForVueUpdate()
458
459 // Should now be empty
460 expect(state.value.size).toBe(0)
461 })
462
463 it(`should be able to query a result collection with live updates`, async () => {
464 const collection = createCollection(
465 mockSyncCollectionOptions<Person>({
466 id: `optimistic-changes-test`,
467 getKey: (person: Person) => person.id,
468 initialData: initialPersons,
469 })
470 )
471
472 // Initial query
473 const { state: _initialState, collection: initialCollection } =
474 useLiveQuery((q) =>
475 q
476 .from({ collection })
477 .where(({ collection: c }) => gt(c.age, 30))
478 .select(({ collection: c }) => ({
479 id: c.id,
480 name: c.name,
481 team: c.team,
482 }))
483 .orderBy(({ collection: c }) => c.id, `asc`)
484 )
485
486 // Wait for collection to sync
487 await waitForVueUpdate()
488
489 // Grouped query derived from initial query
490 const { state: groupedState } = useLiveQuery((q) =>
491 q
492 .from({ queryResult: initialCollection.value })
493 .groupBy(({ queryResult }) => queryResult.team)
494 .select(({ queryResult }) => ({
495 team: queryResult.team,
496 count: count(queryResult.id),
497 }))
498 )
499
500 // Wait for grouped query to sync
501 await waitForVueUpdate()
502
503 // Verify initial grouped results
504 expect(groupedState.value.size).toBe(1)
505 const teamResult = Array.from(groupedState.value.values())[0]
506 expect(teamResult).toMatchObject({
507 team: `team1`,
508 count: 1,
509 })
510
511 // Insert two new users in different teams
512 collection.utils.begin()
513 collection.utils.write({
514 type: `insert`,
515 value: {
516 id: `5`,
517 name: `Sarah Jones`,
518 age: 32,
519 email: `sarah.jones@example.com`,
520 isActive: true,
521 team: `team1`,
522 },
523 })
524 collection.utils.write({
525 type: `insert`,
526 value: {
527 id: `6`,
528 name: `Mike Wilson`,
529 age: 38,
530 email: `mike.wilson@example.com`,
531 isActive: true,
532 team: `team2`,
533 },
534 })
535 collection.utils.commit()
536
537 await waitForVueUpdate()
538
539 // Verify the grouped results include the new team members
540 expect(groupedState.value.size).toBe(2)
541
542 const groupedResults = Array.from(groupedState.value.values())
543 const team1Result = groupedResults.find((r) => r.team === `team1`)
544 const team2Result = groupedResults.find((r) => r.team === `team2`)
545
546 expect(team1Result).toMatchObject({
547 team: `team1`,
548 count: 2, // John Smith + Sarah Jones
549 })
550 expect(team2Result).toMatchObject({
551 team: `team2`,
552 count: 1, // Mike Wilson
553 })
554 })
555
556 it(`optimistic state is dropped after commit`, async () => {
557 // Track renders and states
558 const renderStates: Array<{
559 stateSize: number
560 hasTempKey: boolean
561 hasPermKey: boolean
562 timestamp: number
563 }> = []
564
565 // Create person collection
566 const personCollection = createCollection(
567 mockSyncCollectionOptions<Person>({
568 id: `person-collection-test-bug`,
569 getKey: (person: Person) => person.id,
570 initialData: initialPersons,
571 })
572 )
573
574 // Create issue collection
575 const issueCollection = createCollection(
576 mockSyncCollectionOptions<Issue>({
577 id: `issue-collection-test-bug`,
578 getKey: (issue: Issue) => issue.id,
579 initialData: initialIssues,
580 })
581 )
582
583 // Render the hook with a query that joins persons and issues
584 const queryResult = useLiveQuery((q) =>
585 q
586 .from({ issues: issueCollection })
587 .join({ persons: personCollection }, ({ issues, persons }) =>
588 eq(issues.userId, persons.id)
589 )
590 .select(({ issues, persons }) => ({
591 id: issues.id,
592 title: issues.title,
593 name: persons.name,
594 }))
595 )
596
597 const { state } = queryResult
598
599 // Track each state change like React does with useEffect
600 watchEffect(() => {
601 renderStates.push({
602 stateSize: state.value.size,
603 hasTempKey: state.value.has(`[temp-key,1]`),
604 hasPermKey: state.value.has(`[4,1]`),
605 timestamp: Date.now(),
606 })
607 })
608
609 // Wait for collections to sync and verify initial state
610 await waitForVueUpdate()
611
612 expect(state.value.size).toBe(3)
613
614 // Reset render states array for clarity in the remaining test
615 renderStates.length = 0
616
617 // Create an optimistic action for adding issues
618 type AddIssueInput = {
619 title: string
620 description: string
621 userId: string
622 }
623
624 const addIssue = createOptimisticAction<AddIssueInput>({
625 onMutate: (issueInput) => {
626 // Optimistically insert with temporary key
627 issueCollection.insert({
628 id: `temp-key`,
629 title: issueInput.title,
630 description: issueInput.description,
631 userId: issueInput.userId,
632 })
633 },
634 mutationFn: async (issueInput) => {
635 // Simulate server persistence - in a real app, this would be an API call
636 await new Promise((resolve) => setTimeout(resolve, 10)) // Simulate network delay
637
638 // After "server" responds, update the collection with permanent ID using utils
639 issueCollection.utils.begin()
640 issueCollection.utils.write({
641 type: `delete`,
642 value: {
643 id: `temp-key`,
644 title: issueInput.title,
645 description: issueInput.description,
646 userId: issueInput.userId,
647 },
648 })
649 issueCollection.utils.write({
650 type: `insert`,
651 value: {
652 id: `4`, // Use the permanent ID
653 title: issueInput.title,
654 description: issueInput.description,
655 userId: issueInput.userId,
656 },
657 })
658 issueCollection.utils.commit()
659
660 return { success: true, id: `4` }
661 },
662 })
663
664 // Perform optimistic insert of a new issue
665 const transaction = addIssue({
666 title: `New Issue`,
667 description: `New Issue Description`,
668 userId: `1`,
669 })
670
671 // Give Vue one tick to process the optimistic change
672 await nextTick()
673
674 // Verify optimistic state is immediately reflected (should be synchronous)
675 expect(state.value.size).toBe(4)
676 expect(state.value.get(`[temp-key,1]`)).toMatchObject({
677 id: `temp-key`,
678 name: `John Doe`,
679 title: `New Issue`,
680 })
681 expect(state.value.get(`[4,1]`)).toBeUndefined()
682
683 // Wait for the transaction to be committed
684 await transaction.isPersisted.promise
685
686 await waitForVueUpdate()
687
688 // Verify the temporary key is replaced by the permanent one
689 expect(state.value.size).toBe(4)
690 expect(state.value.get(`[temp-key,1]`)).toBeUndefined()
691 expect(state.value.get(`[4,1]`)).toMatchObject({
692 id: `4`,
693 name: `John Doe`,
694 title: `New Issue`,
695 })
696 })
697
698 it(`should accept pre-created live query collection`, async () => {
699 const collection = createCollection(
700 mockSyncCollectionOptions<Person>({
701 id: `pre-created-collection-test-vue`,
702 getKey: (person: Person) => person.id,
703 initialData: initialPersons,
704 })
705 )
706
707 // Create a live query collection beforehand
708 const liveQueryCollection = createLiveQueryCollection({
709 query: (q) =>
710 q
711 .from({ persons: collection })
712 .where(({ persons }) => gt(persons.age, 30))
713 .select(({ persons }) => ({
714 id: persons.id,
715 name: persons.name,
716 age: persons.age,
717 })),
718 startSync: true,
719 })
720
721 const {
722 state,
723 data,
724 collection: returnedCollection,
725 } = useLiveQuery(liveQueryCollection)
726
727 // Wait for collection to sync and state to update
728 await waitForVueUpdate()
729
730 expect(state.value.size).toBe(1) // Only John Smith (age 35)
731 expect(data.value).toHaveLength(1)
732
733 const johnSmith = data.value[0]
734 expect(johnSmith).toMatchObject({
735 id: `3`,
736 name: `John Smith`,
737 age: 35,
738 })
739
740 // Verify that the returned collection is the same instance
741 expect(returnedCollection.value).toBe(liveQueryCollection)
742 })
743
744 it(`should switch to a different pre-created live query collection when reactive ref changes`, async () => {
745 const collection1 = createCollection(
746 mockSyncCollectionOptions<Person>({
747 id: `collection-1-vue`,
748 getKey: (person: Person) => person.id,
749 initialData: initialPersons,
750 })
751 )
752
753 const collection2 = createCollection(
754 mockSyncCollectionOptions<Person>({
755 id: `collection-2-vue`,
756 getKey: (person: Person) => person.id,
757 initialData: [
758 {
759 id: `4`,
760 name: `Alice Cooper`,
761 age: 45,
762 email: `alice.cooper@example.com`,
763 isActive: true,
764 team: `team3`,
765 },
766 {
767 id: `5`,
768 name: `Bob Dylan`,
769 age: 50,
770 email: `bob.dylan@example.com`,
771 isActive: true,
772 team: `team3`,
773 },
774 ],
775 })
776 )
777
778 // Create two different live query collections
779 const liveQueryCollection1 = createLiveQueryCollection({
780 query: (q) =>
781 q
782 .from({ persons: collection1 })
783 .where(({ persons }) => gt(persons.age, 30))
784 .select(({ persons }) => ({
785 id: persons.id,
786 name: persons.name,
787 })),
788 startSync: true,
789 })
790
791 const liveQueryCollection2 = createLiveQueryCollection({
792 query: (q) =>
793 q
794 .from({ persons: collection2 })
795 .where(({ persons }) => gt(persons.age, 40))
796 .select(({ persons }) => ({
797 id: persons.id,
798 name: persons.name,
799 })),
800 startSync: true,
801 })
802
803 // Use a reactive ref that can change - this is the proper Vue pattern
804 const currentCollection = ref(liveQueryCollection1 as any)
805 const { state, collection: returnedCollection } =
806 useLiveQuery(currentCollection)
807
808 // Wait for first collection to sync
809 await waitForVueUpdate()
810
811 expect(state.value.size).toBe(1) // Only John Smith from collection1
812 expect(state.value.get(`3`)).toMatchObject({
813 id: `3`,
814 name: `John Smith`,
815 })
816 expect(returnedCollection.value.id).toBe(liveQueryCollection1.id)
817
818 // Switch to the second collection by updating the reactive ref
819 currentCollection.value = liveQueryCollection2 as any
820
821 // Wait for the reactive change to propagate
822 await waitForVueUpdate()
823
824 expect(state.value.size).toBe(2) // Alice and Bob from collection2
825 expect(state.value.get(`4`)).toMatchObject({
826 id: `4`,
827 name: `Alice Cooper`,
828 })
829 expect(state.value.get(`5`)).toMatchObject({
830 id: `5`,
831 name: `Bob Dylan`,
832 })
833 expect(returnedCollection.value.id).toBe(liveQueryCollection2.id)
834
835 // Verify we no longer have data from the first collection
836 expect(state.value.get(`3`)).toBeUndefined()
837 })
838
839 describe(`isReady property`, () => {
840 it(`should be false initially and true after collection is ready`, async () => {
841 let beginFn: (() => void) | undefined
842 let commitFn: (() => void) | undefined
843 let markReadyFn: (() => void) | undefined
844
845 // Create a collection that doesn't start sync immediately
846 const collection = createCollection<Person>({
847 id: `is-ready-test`,
848 getKey: (person: Person) => person.id,
849 startSync: false, // Don't start sync immediately
850 sync: {
851 sync: ({ begin, commit, markReady }) => {
852 beginFn = begin
853 commitFn = commit
854 markReadyFn = markReady
855 // Don't call begin/commit immediately
856 },
857 },
858 onInsert: () => Promise.resolve(),
859 onUpdate: () => Promise.resolve(),
860 onDelete: () => Promise.resolve(),
861 })
862
863 const { isReady } = useLiveQuery((q) =>
864 q
865 .from({ persons: collection })
866 .where(({ persons }) => gt(persons.age, 30))
867 .select(({ persons }) => ({
868 id: persons.id,
869 name: persons.name,
870 }))
871 )
872
873 // Initially isReady should be false (collection is in idle state)
874 expect(isReady.value).toBe(false)
875
876 // Start sync manually
877 collection.preload()
878
879 // Trigger the first commit to make collection ready
880 if (beginFn && commitFn && markReadyFn) {
881 beginFn()
882 commitFn()
883 markReadyFn()
884 }
885
886 // Insert data
887 collection.insert({
888 id: `1`,
889 name: `John Doe`,
890 age: 35,
891 email: `john.doe@example.com`,
892 isActive: true,
893 team: `team1`,
894 })
895
896 await waitFor(() => expect(isReady.value).toBe(true))
897 })
898
899 it(`should be true for pre-created collections that are already syncing`, async () => {
900 const collection = createCollection(
901 mockSyncCollectionOptions<Person>({
902 id: `pre-created-is-ready-test`,
903 getKey: (person: Person) => person.id,
904 initialData: initialPersons,
905 })
906 )
907
908 // Create a live query collection that's already syncing
909 const liveQueryCollection = createLiveQueryCollection({
910 query: (q) =>
911 q
912 .from({ persons: collection })
913 .where(({ persons }) => gt(persons.age, 30))
914 .select(({ persons }) => ({
915 id: persons.id,
916 name: persons.name,
917 })),
918 startSync: true,
919 })
920
921 await waitForVueUpdate()
922 const { isReady } = useLiveQuery(liveQueryCollection)
923 expect(isReady.value).toBe(true)
924 })
925
926 it(`should be false for pre-created collections that are not syncing`, () => {
927 const collection = createCollection<Person>({
928 id: `not-syncing-is-ready-test`,
929 getKey: (person: Person) => person.id,
930 startSync: false,
931 sync: {
932 sync: () => {
933 // Don't sync immediately
934 },
935 },
936 onInsert: () => Promise.resolve(),
937 onUpdate: () => Promise.resolve(),
938 onDelete: () => Promise.resolve(),
939 })
940
941 // Create a live query collection that's NOT syncing
942 const liveQueryCollection = createLiveQueryCollection({
943 query: (q) =>
944 q
945 .from({ persons: collection })
946 .where(({ persons }) => gt(persons.age, 30))
947 .select(({ persons }) => ({
948 id: persons.id,
949 name: persons.name,
950 })),
951 startSync: false, // Not syncing
952 })
953
954 const { isReady } = useLiveQuery(liveQueryCollection)
955 expect(isReady.value).toBe(false)
956 })
957
958 it(`should update isReady when collection status changes`, async () => {
959 let beginFn: (() => void) | undefined
960 let commitFn: (() => void) | undefined
961 let markReadyFn: (() => void) | undefined
962
963 const collection = createCollection<Person>({
964 id: `status-change-is-ready-test`,
965 getKey: (person: Person) => person.id,
966 startSync: false,
967 sync: {
968 sync: ({ begin, commit, markReady }) => {
969 beginFn = begin
970 commitFn = commit
971 markReadyFn = markReady
972 // Don't sync immediately
973 },
974 },
975 onInsert: () => Promise.resolve(),
976 onUpdate: () => Promise.resolve(),
977 onDelete: () => Promise.resolve(),
978 })
979
980 const { isReady } = useLiveQuery((q) =>
981 q
982 .from({ persons: collection })
983 .where(({ persons }) => gt(persons.age, 30))
984 .select(({ persons }) => ({
985 id: persons.id,
986 name: persons.name,
987 }))
988 )
989
990 expect(isReady.value).toBe(false)
991 collection.preload()
992 if (beginFn && commitFn && markReadyFn) {
993 beginFn()
994 commitFn()
995 markReadyFn()
996 }
997 collection.insert({
998 id: `1`,
999 name: `John Doe`,
1000 age: 35,
1001 email: `john.doe@example.com`,
1002 isActive: true,
1003 team: `team1`,
1004 })
1005 await waitFor(() => expect(isReady.value).toBe(true))
1006 })
1007
1008 it(`should update isLoading when collection status changes`, async () => {
1009 let beginFn: (() => void) | undefined
1010 let commitFn: (() => void) | undefined
1011 let markReadyFn: (() => void) | undefined
1012
1013 const collection = createCollection<Person>({
1014 id: `status-change-is-loading-test`,
1015 getKey: (person: Person) => person.id,
1016 startSync: false,
1017 sync: {
1018 sync: ({ begin, commit, markReady }) => {
1019 beginFn = begin
1020 commitFn = commit
1021 markReadyFn = markReady
1022 // Don't sync immediately
1023 },
1024 },
1025 onInsert: () => Promise.resolve(),
1026 onUpdate: () => Promise.resolve(),
1027 onDelete: () => Promise.resolve(),
1028 })
1029
1030 const { isLoading, isReady, status } = useLiveQuery((q) =>
1031 q
1032 .from({ persons: collection })
1033 .where(({ persons }) => gt(persons.age, 30))
1034 .select(({ persons }) => ({
1035 id: persons.id,
1036 name: persons.name,
1037 }))
1038 )
1039
1040 // Initially should be true
1041 expect(isLoading.value).toBe(true)
1042
1043 // Start sync manually
1044 collection.preload()
1045
1046 // Trigger the first commit to make collection ready
1047 if (beginFn && commitFn && markReadyFn) {
1048 beginFn()
1049 commitFn()
1050 markReadyFn()
1051 }
1052
1053 // Insert data
1054 collection.insert({
1055 id: `1`,
1056 name: `John Doe`,
1057 age: 35,
1058 email: `john.doe@example.com`,
1059 isActive: true,
1060 team: `team1`,
1061 })
1062
1063 await waitForVueUpdate()
1064
1065 expect(isLoading.value).toBe(false)
1066 expect(isReady.value).toBe(true)
1067
1068 // Wait for collection to become ready
1069 await waitFor(() => {
1070 expect(isLoading.value).toBe(false)
1071 })
1072 expect(status.value).toBe(`ready`)
1073 })
1074
1075 it(`should maintain isReady state during live updates`, async () => {
1076 const collection = createCollection(
1077 mockSyncCollectionOptions<Person>({
1078 id: `live-updates-is-ready-test`,
1079 getKey: (person: Person) => person.id,
1080 initialData: initialPersons,
1081 })
1082 )
1083
1084 const { isReady } = useLiveQuery((q) =>
1085 q
1086 .from({ persons: collection })
1087 .where(({ persons }) => gt(persons.age, 30))
1088 .select(({ persons }) => ({
1089 id: persons.id,
1090 name: persons.name,
1091 }))
1092 )
1093
1094 await waitForVueUpdate()
1095 const initialIsReady = isReady.value
1096 collection.utils.begin()
1097 collection.utils.write({
1098 type: `insert`,
1099 value: {
1100 id: `4`,
1101 name: `Kyle Doe`,
1102 age: 40,
1103 email: `kyle.doe@example.com`,
1104 isActive: true,
1105 team: `team1`,
1106 },
1107 })
1108 collection.utils.commit()
1109 await waitForVueUpdate()
1110 expect(isReady.value).toBe(true)
1111 expect(isReady.value).toBe(initialIsReady)
1112 })
1113
1114 it(`should handle isReady with complex queries including joins`, async () => {
1115 let personBeginFn: (() => void) | undefined
1116 let personCommitFn: (() => void) | undefined
1117 let personMarkReadyFn: (() => void) | undefined
1118 let issueBeginFn: (() => void) | undefined
1119 let issueCommitFn: (() => void) | undefined
1120 let issueMarkReadyFn: (() => void) | undefined
1121
1122 const personCollection = createCollection<Person>({
1123 id: `join-is-ready-persons`,
1124 getKey: (person: Person) => person.id,
1125 startSync: false,
1126 sync: {
1127 sync: ({ begin, commit, markReady }) => {
1128 personBeginFn = begin
1129 personCommitFn = commit
1130 personMarkReadyFn = markReady
1131 // Don't sync immediately
1132 },
1133 },
1134 onInsert: () => Promise.resolve(),
1135 onUpdate: () => Promise.resolve(),
1136 onDelete: () => Promise.resolve(),
1137 })
1138
1139 const issueCollection = createCollection<Issue>({
1140 id: `join-is-ready-issues`,
1141 getKey: (issue: Issue) => issue.id,
1142 startSync: false,
1143 sync: {
1144 sync: ({ begin, commit, markReady }) => {
1145 issueBeginFn = begin
1146 issueCommitFn = commit
1147 issueMarkReadyFn = markReady
1148 // Don't sync immediately
1149 },
1150 },
1151 onInsert: () => Promise.resolve(),
1152 onUpdate: () => Promise.resolve(),
1153 onDelete: () => Promise.resolve(),
1154 })
1155
1156 const { isReady } = useLiveQuery((q) =>
1157 q
1158 .from({ issues: issueCollection })
1159 .join({ persons: personCollection }, ({ issues, persons }) =>
1160 eq(issues.userId, persons.id)
1161 )
1162 .select(({ issues, persons }) => ({
1163 id: issues.id,
1164 title: issues.title,
1165 name: persons.name,
1166 }))
1167 )
1168
1169 expect(isReady.value).toBe(false)
1170 personCollection.preload()
1171 issueCollection.preload()
1172 if (personBeginFn && personCommitFn && personMarkReadyFn) {
1173 personBeginFn()
1174 personCommitFn()
1175 personMarkReadyFn()
1176 }
1177 if (issueBeginFn && issueCommitFn && issueMarkReadyFn) {
1178 issueBeginFn()
1179 issueCommitFn()
1180 issueMarkReadyFn()
1181 }
1182 personCollection.insert({
1183 id: `1`,
1184 name: `John Doe`,
1185 age: 30,
1186 email: `john.doe@example.com`,
1187 isActive: true,
1188 team: `team1`,
1189 })
1190 issueCollection.insert({
1191 id: `1`,
1192 title: `Issue 1`,
1193 description: `Issue 1 description`,
1194 userId: `1`,
1195 })
1196 await waitFor(() => expect(isReady.value).toBe(true))
1197 })
1198
1199 it(`should handle isReady with parameterized queries`, async () => {
1200 let beginFn: (() => void) | undefined
1201 let commitFn: (() => void) | undefined
1202
1203 const collection = createCollection<Person>({
1204 id: `params-is-ready-test`,
1205 getKey: (person: Person) => person.id,
1206 startSync: false,
1207 sync: {
1208 sync: ({ begin, commit, markReady }) => {
1209 beginFn = begin
1210 commitFn = () => {
1211 commit()
1212 markReady()
1213 }
1214 // Don't sync immediately
1215 },
1216 },
1217 onInsert: () => Promise.resolve(),
1218 onUpdate: () => Promise.resolve(),
1219 onDelete: () => Promise.resolve(),
1220 })
1221
1222 const minAge = ref(30)
1223 const { isReady } = useLiveQuery(
1224 (q) =>
1225 q
1226 .from({ collection })
1227 .where(({ collection: c }) => gt(c.age, minAge.value))
1228 .select(({ collection: c }) => ({
1229 id: c.id,
1230 name: c.name,
1231 })),
1232 [minAge]
1233 )
1234
1235 expect(isReady.value).toBe(false)
1236 collection.preload()
1237 if (beginFn && commitFn) {
1238 beginFn()
1239 commitFn()
1240 }
1241 collection.insert({
1242 id: `1`,
1243 name: `John Doe`,
1244 age: 35,
1245 email: `john.doe@example.com`,
1246 isActive: true,
1247 team: `team1`,
1248 })
1249 collection.insert({
1250 id: `2`,
1251 name: `Jane Doe`,
1252 age: 25,
1253 email: `jane.doe@example.com`,
1254 isActive: true,
1255 team: `team2`,
1256 })
1257 await waitFor(() => expect(isReady.value).toBe(true))
1258 minAge.value = 25
1259 await waitFor(() => expect(isReady.value).toBe(true))
1260 })
1261
1262 it(`should handle async status transitions correctly`, async () => {
1263 let beginFn: (() => void) | undefined
1264 let commitFn: (() => void) | undefined
1265 let markReadyFn: (() => void) | undefined
1266
1267 const collection = createCollection<Person>({
1268 id: `async-status-transition-test`,
1269 getKey: (person: Person) => person.id,
1270 startSync: false,
1271 sync: {
1272 sync: ({ begin, commit, markReady }) => {
1273 beginFn = begin
1274 commitFn = commit
1275 markReadyFn = markReady
1276 // Don't sync immediately
1277 },
1278 },
1279 onInsert: () => Promise.resolve(),
1280 onUpdate: () => Promise.resolve(),
1281 onDelete: () => Promise.resolve(),
1282 })
1283
1284 const { isLoading, isReady, status } = useLiveQuery((q) =>
1285 q
1286 .from({ collection })
1287 .where(({ collection: c }) => gt(c.age, 30))
1288 .select(({ collection: c }) => ({
1289 id: c.id,
1290 name: c.name,
1291 }))
1292 )
1293
1294 // Initially should be loading
1295 expect(isLoading.value).toBe(true)
1296 expect(isReady.value).toBe(false)
1297 expect(status.value).toBe(`loading`)
1298
1299 // Start sync manually
1300 collection.preload()
1301
1302 // Trigger the first commit to make collection ready
1303 if (beginFn && commitFn && markReadyFn) {
1304 beginFn()
1305 commitFn()
1306 // Simulate async delay before marking ready
1307 await new Promise((resolve) => setTimeout(resolve, 10))
1308 markReadyFn()
1309 }
1310
1311 // Insert data
1312 collection.insert({
1313 id: `1`,
1314 name: `John Doe`,
1315 age: 35,
1316 email: `john.doe@example.com`,
1317 isActive: true,
1318 team: `team1`,
1319 })
1320
1321 // Wait for the status to transition correctly
1322 await waitFor(() => {
1323 expect(isLoading.value).toBe(false)
1324 expect(isReady.value).toBe(true)
1325 expect(status.value).toBe(`ready`)
1326 })
1327 })
1328
1329 it(`should handle status transitions without change events`, async () => {
1330 // This test reproduces the bug where status gets stuck in 'initialCommit'
1331 // when the collection status changes without triggering change events
1332 let beginFn: (() => void) | undefined
1333 let commitFn: (() => void) | undefined
1334 let markReadyFn: (() => void) | undefined
1335
1336 const collection = createCollection<Person>({
1337 id: `status-stuck-test`,
1338 getKey: (person: Person) => person.id,
1339 startSync: false,
1340 sync: {
1341 sync: ({ begin, commit, markReady }) => {
1342 beginFn = begin
1343 commitFn = commit
1344 markReadyFn = markReady
1345 // Don't sync immediately
1346 },
1347 },
1348 onInsert: () => Promise.resolve(),
1349 onUpdate: () => Promise.resolve(),
1350 onDelete: () => Promise.resolve(),
1351 })
1352
1353 const { isLoading, isReady, status } = useLiveQuery((q) =>
1354 q
1355 .from({ collection })
1356 .where(({ collection: c }) => gt(c.age, 30))
1357 .select(({ collection: c }) => ({
1358 id: c.id,
1359 name: c.name,
1360 }))
1361 )
1362
1363 // Initially should be loading
1364 expect(isLoading.value).toBe(true)
1365 expect(isReady.value).toBe(false)
1366
1367 // Start sync manually
1368 collection.preload()
1369
1370 // Trigger the first commit to make collection ready
1371 if (beginFn && commitFn && markReadyFn) {
1372 beginFn()
1373 commitFn()
1374 // Simulate async delay before marking ready
1375 await new Promise((resolve) => setTimeout(resolve, 10))
1376 markReadyFn()
1377 }
1378
1379 // Insert data
1380 collection.insert({
1381 id: `1`,
1382 name: `John Doe`,
1383 age: 35,
1384 email: `john.doe@example.com`,
1385 isActive: true,
1386 team: `team1`,
1387 })
1388
1389 // Wait for the status to transition correctly
1390 // This should work even if no change events are fired
1391 await waitFor(() => {
1392 expect(isLoading.value).toBe(false)
1393 expect(isReady.value).toBe(true)
1394 expect(status.value).toBe(`ready`)
1395 })
1396 })
1397 })
1398
1399 it(`should accept config object with pre-built QueryBuilder instance`, async () => {
1400 const collection = createCollection(
1401 mockSyncCollectionOptions<Person>({
1402 id: `config-querybuilder-test-vue`,
1403 getKey: (person: Person) => person.id,
1404 initialData: initialPersons,
1405 })
1406 )
1407
1408 // Create a pre-built QueryBuilder instance
1409 const { Query } = await import(`@tanstack/db`)
1410 const queryBuilder = new Query()
1411 .from({ persons: collection })
1412 .where(({ persons }) => gt(persons.age, 30))
1413 .select(({ persons }) => ({
1414 id: persons.id,
1415 name: persons.name,
1416 age: persons.age,
1417 }))
1418
1419 const { state, data } = useLiveQuery({
1420 query: queryBuilder,
1421 })
1422
1423 // Wait for collection to sync and state to update
1424 await waitForVueUpdate()
1425
1426 expect(state.value.size).toBe(1) // Only John Smith (age 35)
1427 expect(data.value).toHaveLength(1)
1428
1429 const johnSmith = data.value[0]
1430 expect(johnSmith).toMatchObject({
1431 id: `3`,
1432 name: `John Smith`,
1433 age: 35,
1434 })
1435 })
1436})