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