Open History to see the last commit
1/**
2 * Joins Test Suite
3 *
4 * Tests multi-collection joins with various syncMode combinations
5 */
6
7import { randomUUID } from 'node:crypto'
8import { describe, expect, it, vi } from 'vitest'
9import { createLiveQueryCollection, eq, gt, isNull } from '@tanstack/db'
10import { waitFor, waitForQueryData } from '../utils/helpers'
11import type {
12 Comment,
13 E2ETestConfig,
14 Post,
15 SeedDataResult,
16 User,
17} from '../types'
18
19type UserPost = { user: User; post: Post | undefined }
20type JoinProjection = Record<string, string | number | undefined>
21type JoinQuery = {
22 values: () => Iterable<object>
23 cleanup: () => Promise<void>
24}
25type OwnQuery = (query: JoinQuery) => void
26type OwnCleanup = (cleanup: () => Promise<void>) => void
27type Archive = (check: () => void) => void
28
29function userPostPairs(
30 users: Array<User>,
31 posts: Array<Post>,
32): Array<UserPost> {
33 const pairs: Array<UserPost> = []
34 for (const user of users) {
35 const children = posts.filter((post) => post.userId === user.id)
36 if (children.length === 0) pairs.push({ user, post: undefined })
37 else for (const post of children) pairs.push({ user, post })
38 }
39 return pairs
40}
41
42function withComments(pairs: Array<UserPost>, comments: Array<Comment>) {
43 const triples: Array<UserPost & { comment: Comment | undefined }> = []
44 for (const pair of pairs) {
45 const children = comments.filter(
46 (comment) => comment.postId === pair.post?.id,
47 )
48 if (children.length === 0) triples.push({ ...pair, comment: undefined })
49 else for (const comment of children) triples.push({ ...pair, comment })
50 }
51 return triples
52}
53
54function compareProjectedValue(
55 left: string | number | undefined,
56 right: string | number | undefined,
57): number {
58 if (left === right) return 0
59 if (left === undefined) return -1
60 if (right === undefined) return 1
61 if (typeof left === 'number' && typeof right === 'number') return left - right
62 if (typeof left === 'string' && typeof right === 'string')
63 return left < right ? -1 : 1
64 throw new Error('Mixed scalar kinds in the fixed join projection')
65}
66
67function orderJoinedFixture<T extends JoinProjection>(
68 rows: Array<T>,
69 key: 'id' | 'viewCount',
70 direction: 'asc' | 'desc',
71): Array<T> {
72 // These two old ordered witnesses use defined, distinct seed Post keys.
73 // Do not invent an ordering/boundary identity for missing fields or ties.
74 expect(rows.every((row) => row[key] !== undefined)).toBe(true)
75 expect(new Set(rows.map((row) => row[key])).size).toBe(rows.length)
76 return [...rows].sort((left, right) => {
77 const a = left[key]!
78 const b = right[key]!
79 const rank =
80 typeof a === 'string' && typeof b === 'string'
81 ? a.localeCompare(b)
82 : compareProjectedValue(a, b)
83 return direction === 'asc' ? rank : -rank
84 })
85}
86
87function createJoinOracle(
88 expectedRows: Array<JoinProjection>,
89 fields: Array<string>,
90 archive: Archive,
91 ordered = false,
92) {
93 const expected = structuredClone(expectedRows)
94 const compare = (left: JoinProjection, right: JoinProjection) => {
95 for (const field of fields) {
96 const rank = compareProjectedValue(left[field], right[field])
97 if (rank !== 0) return rank
98 }
99 return 0
100 }
101 const assert = (actual: Array<JoinProjection>) => {
102 expect(ordered ? actual : [...actual].sort(compare)).toStrictEqual(
103 ordered ? expected : [...expected].sort(compare),
104 )
105 }
106 return {
107 assert,
108 async check(query: { values: () => Iterable<object> }) {
109 const captured = await vi.waitFor(
110 () => {
111 const rows = Array.from(query.values(), (value) => {
112 const row: JoinProjection = {}
113 for (const field of fields) {
114 const item: unknown = Reflect.get(value, field)
115 if (
116 item !== undefined &&
117 typeof item !== 'string' &&
118 typeof item !== 'number'
119 )
120 throw new Error('Unexpected joined projection value kind')
121 row[field] = item
122 }
123 return structuredClone(row)
124 })
125 assert(rows)
126 return rows
127 },
128 { timeout: 5000 },
129 )
130 archive(() => assert(captured))
131 if (captured.length > 0) {
132 expect(() => assert(captured.slice(1))).toThrow()
133 const wrongKey = structuredClone(captured)
134 wrongKey[0]!.id = `${wrongKey[0]!.id}-wrong`
135 expect(() => assert(wrongKey)).toThrow()
136 const wrongValue = structuredClone(captured)
137 wrongValue[0]!.userName = `${wrongValue[0]!.userName}-wrong`
138 expect(() => assert(wrongValue)).toThrow()
139 if (captured.length > 1) {
140 const duplicate = structuredClone(captured)
141 duplicate[0] = structuredClone(duplicate[1]!)
142 expect(() => assert(duplicate)).toThrow()
143 if (ordered) expect(() => assert([...captured].reverse())).toThrow()
144 }
145 }
146 return captured
147 },
148 }
149}
150
151async function withJoinHistory(
152 run: (
153 own: OwnQuery,
154 ownCleanup: OwnCleanup,
155 archive: Archive,
156 ) => Promise<void>,
157) {
158 const queries: Array<JoinQuery> = []
159 const cleanup: Array<() => Promise<void>> = []
160 const archived: Array<() => void> = []
161 const errors: Array<unknown> = []
162 try {
163 await run(
164 (query) => queries.push(query),
165 (action) => cleanup.push(action),
166 (check) => archived.push(check),
167 )
168 } catch (error) {
169 errors.push(error)
170 } finally {
171 // Owned rows are removed while their actual source/query owners stay live.
172 for (const action of [
173 ...cleanup,
174 ...queries.map((query) => () => query.cleanup()),
175 ]) {
176 try {
177 await action()
178 } catch (error) {
179 errors.push(error)
180 }
181 }
182 for (const check of archived) {
183 try {
184 check()
185 } catch (error) {
186 errors.push(error)
187 }
188 }
189 }
190 if (errors.length === 1) throw errors[0]
191 if (errors.length > 1)
192 throw new AggregateError(errors, 'Join history and cleanup failed')
193}
194
195function capturePosts(rows: Iterable<Post>): Array<Post> {
196 return Array.from(rows, (row) =>
197 structuredClone({
198 id: row.id,
199 userId: row.userId,
200 title: row.title,
201 content: row.content,
202 viewCount: row.viewCount,
203 largeViewCount: row.largeViewCount,
204 publishedAt: row.publishedAt,
205 deletedAt: row.deletedAt,
206 }),
207 )
208}
209
210function assertPosts(actual: Array<Post>, expected: Array<Post>) {
211 const byId = (left: Post, right: Post) =>
212 left.id < right.id ? -1 : left.id > right.id ? 1 : 0
213 expect([...actual].sort(byId)).toStrictEqual([...expected].sort(byId))
214}
215
216async function ownedLeftJoinContinuation(
217 config: E2ETestConfig,
218 fixture: SeedDataResult,
219 query: JoinQuery,
220 seedProjection: Array<JoinProjection>,
221 own: OwnQuery,
222 ownCleanup: OwnCleanup,
223 archive: Archive,
224) {
225 const mutations = config.mutations
226 if (!mutations)
227 throw new Error('Owned join history requires mutation drivers')
228 const parents: Array<User> = ['multiple children', 'unmatched parent'].map(
229 (name) => ({
230 id: randomUUID(),
231 name,
232 email: null,
233 age: 43,
234 isActive: true,
235 createdAt: new Date('2024-03-04T05:06:07.123Z'),
236 metadata: { owned: name },
237 deletedAt: null,
238 }),
239 )
240 const children: Array<Post> = ['first owned child', 'second owned child'].map(
241 (title, index) => ({
242 id: randomUUID(),
243 userId: parents[0]!.id,
244 title,
245 content: `owned content ${index}`,
246 viewCount: 71 + index,
247 largeViewCount: 9007199254740993n + BigInt(index),
248 publishedAt: new Date('2024-06-07T08:09:10.321Z'),
249 deletedAt: null,
250 }),
251 )
252 const expectedPosts = structuredClone([...fixture.posts, ...children])
253 const expectedJoined = structuredClone([
254 ...seedProjection,
255 {
256 id: parents[0]!.id,
257 userName: 'multiple children',
258 postTitle: 'first owned child',
259 },
260 {
261 id: parents[0]!.id,
262 userName: 'multiple children',
263 postTitle: 'second owned child',
264 },
265 { id: parents[1]!.id, userName: 'unmatched parent', postTitle: undefined },
266 ])
267 const postOwner = createLiveQueryCollection((q) =>
268 q.from({ post: config.collections.eager.posts }),
269 )
270 own(postOwner)
271 await postOwner.preload()
272 await vi.waitFor(
273 () => assertPosts(capturePosts(postOwner.values()), fixture.posts),
274 { timeout: 5000 },
275 )
276
277 // Register all exact child and parent IDs before the first provider write.
278 for (const child of children)
279 ownCleanup(async () => {
280 await mutations.deletePost(child.id)
281 await vi.waitFor(
282 () => {
283 expect(config.collections.eager.posts.has(child.id)).toBe(false)
284 expect(config.collections.onDemand.posts.has(child.id)).toBe(false)
285 },
286 { timeout: 5000 },
287 )
288 })
289 for (const parent of parents)
290 ownCleanup(async () => {
291 await mutations.deleteUser(parent.id)
292 await vi.waitFor(
293 () =>
294 expect(config.collections.onDemand.users.has(parent.id)).toBe(false),
295 { timeout: 5000 },
296 )
297 })
298 ownCleanup(async () => {
299 await vi.waitFor(
300 () => assertPosts(capturePosts(postOwner.values()), fixture.posts),
301 { timeout: 5000 },
302 )
303 await createJoinOracle(
304 seedProjection,
305 ['id', 'userName', 'postTitle'],
306 archive,
307 ).check(query)
308 })
309 for (const parent of parents)
310 await mutations.insertUser(structuredClone(parent))
311 for (const child of children)
312 await mutations.insertPost(structuredClone(child))
313 const observedPosts = await vi.waitFor(
314 () => {
315 const rows = capturePosts(postOwner.values())
316 assertPosts(rows, expectedPosts)
317 return rows
318 },
319 { timeout: 5000 },
320 )
321 archive(() => assertPosts(observedPosts, expectedPosts))
322 const wrongPostEdge = structuredClone(observedPosts)
323 const observedChild = wrongPostEdge.find((row) => row.id === children[0]!.id)
324 expect(observedChild).toBeDefined()
325 if (!observedChild)
326 throw new Error('Owned Post driver control was not reached')
327 observedChild.userId = parents[1]!.id
328 expect(() => assertPosts(wrongPostEdge, expectedPosts)).toThrow()
329
330 const oracle = createJoinOracle(
331 expectedJoined,
332 ['id', 'userName', 'postTitle'],
333 archive,
334 )
335 const captured = await oracle.check(query)
336 const first = captured.findIndex(
337 (row) => row.id === parents[0]!.id && row.postTitle === children[0]!.title,
338 )
339 const second = captured.findIndex(
340 (row) => row.id === parents[0]!.id && row.postTitle === children[1]!.title,
341 )
342 const unmatched = captured.findIndex(
343 (row) => row.id === parents[1]!.id && row.postTitle === undefined,
344 )
345 expect(first).toBeGreaterThanOrEqual(0)
346 expect(second).toBeGreaterThanOrEqual(0)
347 expect(unmatched).toBeGreaterThanOrEqual(0)
348 const duplicateChild = structuredClone(captured)
349 duplicateChild[first] = structuredClone(duplicateChild[second]!)
350 expect(() => oracle.assert(duplicateChild)).toThrow()
351 const wrongJoinedEdge = structuredClone(captured)
352 wrongJoinedEdge[first]!.id = parents[1]!.id
353 expect(() => oracle.assert(wrongJoinedEdge)).toThrow()
354 expect(() =>
355 oracle.assert(captured.filter((_, index) => index !== unmatched)),
356 ).toThrow()
357}
358
359export function createJoinsTestSuite(getConfig: () => Promise<E2ETestConfig>) {
360 describe(`Joins Suite`, () => {
361 describe(`Two-Collection Joins`, () => {
362 it(`should join Users and Posts`, async () => {
363 const config = await getConfig()
364 const usersCollection = config.collections.onDemand.users
365 const postsCollection = config.collections.onDemand.posts
366
367 const fixture = config.fixture()
368 const expected = userPostPairs(fixture.users, fixture.posts).map(
369 ({ user, post }) => ({
370 id: post?.id,
371 userName: user.name,
372 postTitle: post?.title,
373 }),
374 )
375 await withJoinHistory(async (own, ownCleanup, archive) => {
376 const oracle = createJoinOracle(
377 expected,
378 ['id', 'userName', 'postTitle'],
379 archive,
380 false,
381 )
382 const query = createLiveQueryCollection((q) =>
383 q
384 .from({ user: usersCollection })
385 .join({ post: postsCollection }, ({ user, post }) =>
386 eq(user.id, post.userId),
387 )
388 .select(({ user, post }) => ({
389 id: post.id,
390 userName: user.name,
391 postTitle: post.title,
392 })),
393 )
394 own(query)
395
396 await query.preload()
397 await waitForQueryData(query, { minSize: 1 })
398
399 const results = Array.from(query.state.values())
400 expect(results.length).toBeGreaterThan(0)
401 expect(results[0]!).toHaveProperty(`userName`)
402 expect(results[0]!).toHaveProperty(`postTitle`)
403
404 await oracle.check(query)
405 })
406 })
407
408 it(`should join with predicates on both collections`, async () => {
409 const config = await getConfig()
410 const usersCollection = config.collections.onDemand.users
411 const postsCollection = config.collections.onDemand.posts
412
413 const fixture = config.fixture()
414 const expected = userPostPairs(fixture.users, fixture.posts)
415 .filter(
416 ({ user, post }) =>
417 user.isActive === true &&
418 post !== undefined &&
419 post.viewCount > 10,
420 )
421 .map(({ user, post }) => ({
422 id: post?.id,
423 userName: user.name,
424 postTitle: post?.title,
425 viewCount: post?.viewCount,
426 }))
427 await withJoinHistory(async (own, ownCleanup, archive) => {
428 const oracle = createJoinOracle(
429 expected,
430 ['id', 'userName', 'postTitle', 'viewCount'],
431 archive,
432 false,
433 )
434 const query = createLiveQueryCollection((q) =>
435 q
436 .from({ user: usersCollection })
437 .where(({ user }) => eq(user.isActive, true))
438 .join({ post: postsCollection }, ({ user, post }) =>
439 eq(user.id, post.userId),
440 )
441 .where(({ post }) => gt(post.viewCount, 10))
442 .select(({ user, post }) => ({
443 id: post.id,
444 userName: user.name,
445 postTitle: post.title,
446 viewCount: post.viewCount,
447 })),
448 )
449 own(query)
450
451 await query.preload()
452
453 const results = Array.from(query.state.values())
454 // Verify predicates applied
455 results.forEach((r) => {
456 expect(r.viewCount).toBeGreaterThan(10)
457 })
458
459 await oracle.check(query)
460 })
461 })
462
463 it(
464 `should join with one eager, one on-demand`,
465 { timeout: 60000 },
466 async () => {
467 const config = await getConfig()
468 const usersEager = config.collections.eager.users
469 const postsOnDemand = config.collections.onDemand.posts
470
471 const fixture = config.fixture()
472 const expected = userPostPairs(fixture.users, fixture.posts).map(
473 ({ user, post }) => ({
474 id: post?.id,
475 userName: user.name,
476 postTitle: post?.title,
477 }),
478 )
479 await withJoinHistory(async (own, ownCleanup, archive) => {
480 const oracle = createJoinOracle(
481 expected,
482 ['id', 'userName', 'postTitle'],
483 archive,
484 false,
485 )
486 const query = createLiveQueryCollection((q) =>
487 q
488 .from({ user: usersEager })
489 .join({ post: postsOnDemand }, ({ user, post }) =>
490 eq(user.id, post.userId),
491 )
492 .select(({ user, post }) => ({
493 id: post.id,
494 userName: user.name,
495 postTitle: post.title,
496 })),
497 )
498 own(query)
499
500 await query.preload()
501 // Joins with eager + on-demand collections may need more time to load data from multiple sources
502 // Use longer timeout for CI environments which can be slower
503 await waitForQueryData(query, { minSize: 1, timeout: 50000 })
504
505 const results = Array.from(query.state.values())
506 expect(results.length).toBeGreaterThan(0)
507
508 await oracle.check(query)
509 })
510 },
511 )
512
513 it(`should join with ordering across collections`, async () => {
514 const config = await getConfig()
515 const usersCollection = config.collections.onDemand.users
516 const postsCollection = config.collections.onDemand.posts
517
518 const fixture = config.fixture()
519 const expected = orderJoinedFixture(
520 userPostPairs(fixture.users, fixture.posts).map(({ user, post }) => ({
521 id: post?.id,
522 userName: user.name,
523 postTitle: post?.title,
524 viewCount: post?.viewCount,
525 })),
526 'viewCount',
527 'desc',
528 )
529 await withJoinHistory(async (own, ownCleanup, archive) => {
530 const oracle = createJoinOracle(
531 expected,
532 ['id', 'userName', 'postTitle', 'viewCount'],
533 archive,
534 true,
535 )
536 const query = createLiveQueryCollection((q) =>
537 q
538 .from({ user: usersCollection })
539 .join({ post: postsCollection }, ({ user, post }) =>
540 eq(user.id, post.userId),
541 )
542 .orderBy(({ post }) => post.viewCount, `desc`)
543 .select(({ user, post }) => ({
544 id: post.id,
545 userName: user.name,
546 postTitle: post.title,
547 viewCount: post.viewCount,
548 })),
549 )
550 own(query)
551
552 await query.preload()
553
554 // For joins with ordering, we need to wait for sufficient data in BOTH collections
555 // Wait for the posts collection to load enough data (not just the query results)
556 await waitFor(() => postsCollection.size >= 100, {
557 timeout: 5000,
558 interval: 50,
559 message: `Posts collection did not fully load (got ${postsCollection.size}/100)`,
560 })
561
562 // Also wait for query to have data
563 await waitForQueryData(query, { minSize: 50, timeout: 5000 })
564
565 const results = Array.from(query.state.values())
566 expect(results.length).toBeGreaterThan(0)
567
568 // All results MUST have viewCount field (verifies join completed successfully)
569 expect(results.every((r) => typeof r.viewCount === `number`)).toBe(
570 true,
571 )
572
573 // Verify sorting by viewCount (descending)
574 for (let i = 1; i < results.length; i++) {
575 const prevCount = results[i - 1]!.viewCount
576 const currCount = results[i]!.viewCount
577 expect(prevCount!).toBeGreaterThanOrEqual(currCount!)
578 }
579
580 await oracle.check(query)
581 })
582 })
583
584 it(`should join with pagination`, async () => {
585 const config = await getConfig()
586 const usersCollection = config.collections.onDemand.users
587 const postsCollection = config.collections.onDemand.posts
588
589 const fixture = config.fixture()
590 const expected = orderJoinedFixture(
591 userPostPairs(fixture.users, fixture.posts).map(({ user, post }) => ({
592 id: post?.id,
593 userName: user.name,
594 postTitle: post?.title,
595 })),
596 'id',
597 'asc',
598 ).slice(5, 15)
599 await withJoinHistory(async (own, ownCleanup, archive) => {
600 const oracle = createJoinOracle(
601 expected,
602 ['id', 'userName', 'postTitle'],
603 archive,
604 true,
605 )
606 const query = createLiveQueryCollection((q) =>
607 q
608 .from({ user: usersCollection })
609 .join({ post: postsCollection }, ({ user, post }) =>
610 eq(user.id, post.userId),
611 )
612 .orderBy(({ post }) => post.id, `asc`)
613 .limit(10)
614 .offset(5)
615 .select(({ user, post }) => ({
616 id: post.id,
617 userName: user.name,
618 postTitle: post.title,
619 })),
620 )
621 own(query)
622
623 await query.preload()
624
625 expect(query.size).toBeLessThanOrEqual(10)
626
627 await oracle.check(query)
628 })
629 })
630 })
631
632 describe(`Three-Collection Joins`, () => {
633 it(`should join Users + Posts + Comments`, async () => {
634 const config = await getConfig()
635 const { users, posts, comments } = config.collections.onDemand
636
637 const fixture = config.fixture()
638 const expected = withComments(
639 userPostPairs(fixture.users, fixture.posts),
640 fixture.comments,
641 ).map(({ user, post, comment }) => ({
642 id: comment?.id,
643 userName: user.name,
644 postTitle: post?.title,
645 commentText: comment?.text,
646 }))
647 await withJoinHistory(async (own, ownCleanup, archive) => {
648 const oracle = createJoinOracle(
649 expected,
650 ['id', 'userName', 'postTitle', 'commentText'],
651 archive,
652 false,
653 )
654 const query = createLiveQueryCollection((q) =>
655 q
656 .from({ user: users })
657 .join({ post: posts }, ({ user, post }) =>
658 eq(user.id, post.userId),
659 )
660 .join({ comment: comments }, ({ post, comment }) =>
661 eq(post.id, comment.postId),
662 )
663 .select(({ user, post, comment }) => ({
664 id: comment.id,
665 userName: user.name,
666 postTitle: post.title,
667 commentText: comment.text,
668 })),
669 )
670 own(query)
671
672 await query.preload()
673 await waitForQueryData(query, { minSize: 1 })
674
675 const results = Array.from(query.state.values())
676 expect(results.length).toBeGreaterThan(0)
677 expect(results[0]!).toHaveProperty(`userName`)
678 expect(results[0]!).toHaveProperty(`postTitle`)
679 expect(results[0]!).toHaveProperty(`commentText`)
680
681 await oracle.check(query)
682 })
683 })
684
685 it(`should handle predicates on all three collections`, async () => {
686 const config = await getConfig()
687 const { users, posts, comments } = config.collections.onDemand
688
689 const fixture = config.fixture()
690 const expected = withComments(
691 userPostPairs(fixture.users, fixture.posts).filter(
692 ({ user, post }) =>
693 user.isActive === true && post?.deletedAt === null,
694 ),
695 fixture.comments,
696 )
697 .filter(({ comment }) => comment?.deletedAt === null)
698 .map(({ user, post, comment }) => ({
699 id: comment?.id,
700 userName: user.name,
701 postTitle: post?.title,
702 commentText: comment?.text,
703 }))
704 await withJoinHistory(async (own, ownCleanup, archive) => {
705 const oracle = createJoinOracle(
706 expected,
707 ['id', 'userName', 'postTitle', 'commentText'],
708 archive,
709 false,
710 )
711 const query = createLiveQueryCollection((q) =>
712 q
713 .from({ user: users })
714 .where(({ user }) => eq(user.isActive, true))
715 .join({ post: posts }, ({ user, post }) =>
716 eq(user.id, post.userId),
717 )
718 .where(({ post }) => isNull(post.deletedAt))
719 .join({ comment: comments }, ({ post, comment }) =>
720 eq(post.id, comment.postId),
721 )
722 .where(({ comment }) => isNull(comment.deletedAt))
723 .select(({ user, post, comment }) => ({
724 id: comment.id,
725 userName: user.name,
726 postTitle: post.title,
727 commentText: comment.text,
728 })),
729 )
730 own(query)
731
732 await query.preload()
733 await waitForQueryData(query, { minSize: 1 })
734
735 const results = Array.from(query.state.values())
736 // All results should match all predicates and return some rows
737 expect(results.length).toBeGreaterThan(0)
738
739 await oracle.check(query)
740 })
741 })
742
743 it(
744 `should handle mixed syncModes in 3-way join`,
745 { timeout: 60000 },
746 async () => {
747 const config = await getConfig()
748 const usersEager = config.collections.eager.users
749 const postsOnDemand = config.collections.onDemand.posts
750 const commentsOnDemand = config.collections.onDemand.comments
751
752 const fixture = config.fixture()
753 const expected = withComments(
754 userPostPairs(fixture.users, fixture.posts),
755 fixture.comments,
756 ).map(({ user, post, comment }) => ({
757 id: comment?.id,
758 userName: user.name,
759 postTitle: post?.title,
760 commentText: comment?.text,
761 }))
762 await withJoinHistory(async (own, ownCleanup, archive) => {
763 const oracle = createJoinOracle(
764 expected,
765 ['id', 'userName', 'postTitle', 'commentText'],
766 archive,
767 false,
768 )
769 const query = createLiveQueryCollection((q) =>
770 q
771 .from({ user: usersEager })
772 .join({ post: postsOnDemand }, ({ user, post }) =>
773 eq(user.id, post.userId),
774 )
775 .join({ comment: commentsOnDemand }, ({ post, comment }) =>
776 eq(post.id, comment.postId),
777 )
778 .select(({ user, post, comment }) => ({
779 id: comment.id,
780 userName: user.name,
781 postTitle: post.title,
782 commentText: comment.text,
783 })),
784 )
785 own(query)
786
787 await query.preload()
788 // 3-way joins with mixed eager + on-demand collections need more time
789 // Use longer timeout for CI environments which can be slower
790 await waitForQueryData(query, { minSize: 1, timeout: 50000 })
791
792 const results = Array.from(query.state.values())
793 expect(results.length).toBeGreaterThan(0)
794
795 await oracle.check(query)
796 })
797 },
798 )
799 })
800
801 describe(`Predicates in Joined Results`, () => {
802 it(`should apply predicates to the selected joined fields`, async () => {
803 const config = await getConfig()
804 const { users, posts } = config.collections.onDemand
805
806 const fixture = config.fixture()
807 const expected = userPostPairs(fixture.users, fixture.posts)
808 .filter(({ post }) => post !== undefined && post.viewCount > 50)
809 .map(({ user, post }) => ({
810 id: post?.id,
811 userName: user.name,
812 postTitle: post?.title,
813 viewCount: post?.viewCount,
814 }))
815 await withJoinHistory(async (own, ownCleanup, archive) => {
816 const oracle = createJoinOracle(
817 expected,
818 ['id', 'userName', 'postTitle', 'viewCount'],
819 archive,
820 false,
821 )
822 const query = createLiveQueryCollection((q) =>
823 q
824 .from({ user: users })
825 .join({ post: posts }, ({ user, post }) =>
826 eq(user.id, post.userId),
827 )
828 .where(({ post }) => gt(post.viewCount, 50))
829 .select(({ user, post }) => ({
830 id: post.id,
831 userName: user.name,
832 postTitle: post.title,
833 viewCount: post.viewCount,
834 })),
835 )
836 own(query)
837
838 await query.preload()
839
840 const results = Array.from(query.state.values())
841 // Verify predicate applied
842 results.forEach((r) => {
843 expect(r.viewCount).toBeGreaterThan(50)
844 })
845
846 await oracle.check(query)
847 })
848 })
849
850 it(`should exclude joined rows outside the user predicate`, async () => {
851 const config = await getConfig()
852 const { users, posts } = config.collections.onDemand
853
854 const fixture = config.fixture()
855 const expected = userPostPairs(fixture.users, fixture.posts)
856 .filter(({ user }) => user.age > 30)
857 .map(({ user, post }) => ({
858 id: post?.id,
859 userName: user.name,
860 userAge: user.age,
861 postTitle: post?.title,
862 }))
863 await withJoinHistory(async (own, ownCleanup, archive) => {
864 const oracle = createJoinOracle(
865 expected,
866 ['id', 'userName', 'userAge', 'postTitle'],
867 archive,
868 false,
869 )
870 const query = createLiveQueryCollection((q) =>
871 q
872 .from({ user: users })
873 .where(({ user }) => gt(user.age, 30))
874 .join({ post: posts }, ({ user, post }) =>
875 eq(user.id, post.userId),
876 )
877 .select(({ user, post }) => ({
878 id: post.id,
879 userName: user.name,
880 userAge: user.age,
881 postTitle: post.title,
882 })),
883 )
884 own(query)
885
886 await query.preload()
887
888 const results = Array.from(query.state.values())
889 // All users should be > 30
890 results.forEach((r) => {
891 expect(r.userAge).toBeGreaterThan(30)
892 })
893
894 await oracle.check(query)
895 })
896 })
897 })
898
899 describe(`Left Joins`, () => {
900 it(`should handle left joins correctly`, async () => {
901 const config = await getConfig()
902 const { users, posts } = config.collections.onDemand
903
904 const fixture = config.fixture()
905 const expected = userPostPairs(fixture.users, fixture.posts).map(
906 ({ user, post }) => ({
907 id: user.id,
908 userName: user.name,
909 postTitle: post?.title,
910 }),
911 )
912 await withJoinHistory(async (own, ownCleanup, archive) => {
913 const oracle = createJoinOracle(
914 expected,
915 ['id', 'userName', 'postTitle'],
916 archive,
917 false,
918 )
919 const query = createLiveQueryCollection((q) =>
920 q
921 .from({ user: users })
922 .leftJoin({ post: posts }, ({ user, post }) =>
923 eq(user.id, post.userId),
924 )
925 .select(({ user, post }) => ({
926 id: user.id,
927 userName: user.name,
928 postTitle: post.title, // Missing joined fields are undefined for unmatched users
929 })),
930 )
931 own(query)
932
933 await query.preload()
934 await waitForQueryData(query, { minSize: 1 })
935
936 const results = Array.from(query.state.values())
937 expect(results.length).toBeGreaterThan(0)
938
939 await oracle.check(query)
940 await ownedLeftJoinContinuation(
941 config,
942 fixture,
943 query,
944 expected,
945 own,
946 ownCleanup,
947 archive,
948 )
949 })
950 })
951 })
952 })
953}