Open History to see the last commit
1/**
2 * Predicates Test Suite
3 *
4 * Tests basic where clause functionality with all comparison operators
5 * across different data types.
6 */
7
8import { describe, expect, it, vi } from 'vitest'
9import {
10 and,
11 createLiveQueryCollection,
12 eq,
13 gt,
14 gte,
15 ilike,
16 inArray,
17 isNull,
18 like,
19 lower,
20 lt,
21 lte,
22 not,
23 or,
24} from '@tanstack/db'
25import { assertAllItemsMatch, assertCollectionSize } from '../utils/assertions'
26import { waitForQueryData } from '../utils/helpers'
27import type { E2ETestConfig, Post, User } from '../types'
28
29type PredicateRow = User | Post
30
31function capturePredicateRows(
32 rows: Iterable<PredicateRow>,
33): Array<PredicateRow> {
34 return Array.from(rows, (row) =>
35 structuredClone(
36 'largeViewCount' in row
37 ? {
38 id: row.id,
39 userId: row.userId,
40 title: row.title,
41 content: row.content,
42 viewCount: row.viewCount,
43 largeViewCount: row.largeViewCount,
44 publishedAt: row.publishedAt,
45 deletedAt: row.deletedAt,
46 }
47 : {
48 id: row.id,
49 name: row.name,
50 email: row.email,
51 age: row.age,
52 isActive: row.isActive,
53 createdAt: row.createdAt,
54 metadata: row.metadata,
55 deletedAt: row.deletedAt,
56 },
57 ),
58 )
59}
60
61function assertPredicateRows(
62 actual: Array<PredicateRow>,
63 expected: Array<PredicateRow>,
64 ordered: boolean,
65) {
66 const byId = (a: PredicateRow, b: PredicateRow) =>
67 a.id < b.id ? -1 : a.id > b.id ? 1 : 0
68 expect(ordered ? actual : [...actual].sort(byId)).toStrictEqual(
69 ordered ? expected : [...expected].sort(byId),
70 )
71}
72
73function orderedAliceRows(users: Array<User>): Array<User> {
74 const expected = users
75 .filter((u) => u.name.toLowerCase().includes('alice'))
76 .sort((a, b) => a.name.localeCompare(b.name))
77 // The existing witness uses this host-default locale and distinct names.
78 // Reject a tied fixture before claiming an exact boundary identity/order.
79 for (let index = 1; index < expected.length; index++) {
80 expect(
81 expected[index - 1]!.name.localeCompare(expected[index]!.name),
82 ).not.toBe(0)
83 }
84 return expected
85}
86
87async function withPredicateRows(
88 query: { values: () => Iterable<PredicateRow>; cleanup: () => Promise<void> },
89 expectedRows: Array<PredicateRow>,
90 oldChecks: () => Promise<void>,
91 ordered = false,
92) {
93 const expected = structuredClone(expectedRows)
94 const errors: Array<unknown> = []
95 let observed: Array<PredicateRow> | undefined
96 try {
97 await oldChecks()
98 observed = await vi.waitFor(
99 () => {
100 const captured = capturePredicateRows(query.values())
101 assertPredicateRows(captured, expected, ordered)
102 return captured
103 },
104 { timeout: 5000 },
105 )
106 if (observed.length > 0) {
107 const metadataIndex = observed.findIndex(
108 (row) => 'metadata' in row && row.metadata !== null,
109 )
110 if (metadataIndex !== -1) {
111 const wrongMetadata = structuredClone(observed)
112 const row = wrongMetadata[metadataIndex]!
113 if (!('metadata' in row) || row.metadata === null) {
114 throw new Error('Captured metadata control did not reach a User')
115 }
116 expect(Object.hasOwn(row.metadata, 'unexpected')).toBe(false)
117 row.metadata.unexpected = undefined
118 expect(Object.hasOwn(row.metadata, 'unexpected')).toBe(true)
119 expect(() =>
120 assertPredicateRows(wrongMetadata, expected, ordered),
121 ).toThrow()
122 }
123 expect(() =>
124 assertPredicateRows(observed!.slice(1), expected, ordered),
125 ).toThrow()
126 const wrongKey = structuredClone(observed)
127 wrongKey[0]!.id += '-wrong'
128 expect(() => assertPredicateRows(wrongKey, expected, ordered)).toThrow()
129 const wrongValue = structuredClone(observed)
130 const first = wrongValue[0]!
131 if ('name' in first) first.name += '-wrong'
132 else first.title += '-wrong'
133 expect(() => assertPredicateRows(wrongValue, expected, ordered)).toThrow()
134 if (observed.length > 1) {
135 const duplicate = structuredClone(observed)
136 duplicate[0] = structuredClone(duplicate[1]!)
137 expect(() =>
138 assertPredicateRows(duplicate, expected, ordered),
139 ).toThrow()
140 if (ordered) {
141 expect(() =>
142 assertPredicateRows([...observed!].reverse(), expected, true),
143 ).toThrow()
144 }
145 }
146 }
147 } catch (error) {
148 errors.push(error)
149 } finally {
150 try {
151 await query.cleanup()
152 } catch (error) {
153 errors.push(error)
154 }
155 }
156 if (observed) {
157 try {
158 assertPredicateRows(observed, expected, ordered)
159 } catch (error) {
160 errors.push(error)
161 }
162 }
163 if (errors.length === 1) throw errors[0]
164 if (errors.length > 1)
165 throw new AggregateError(errors, 'Predicate history and cleanup failed')
166}
167
168export function createPredicatesTestSuite(
169 getConfig: () => Promise<E2ETestConfig>,
170) {
171 describe(`Predicates Suite`, () => {
172 describe(`Equality Operators`, () => {
173 it(`should filter with eq() on string field`, async () => {
174 const config = await getConfig()
175 const fixture = config.fixture()
176 const expected = fixture.users.filter((u) => u.name === `Alice 0`)
177 const usersCollection = config.collections.onDemand.users
178
179 const query = createLiveQueryCollection((q) =>
180 q
181 .from({ user: usersCollection })
182 .where(({ user }) => eq(user.name, `Alice 0`)),
183 )
184 await withPredicateRows(query, expected, async () => {
185 await query.preload()
186 await waitForQueryData(query, { minSize: 1 })
187
188 const results = Array.from(query.state.values())
189 expect(results.length).toBeGreaterThan(0)
190 expect(results.every((u) => u.name === `Alice 0`)).toBe(true)
191 })
192 })
193
194 it(`should filter with eq() on number field`, async () => {
195 const config = await getConfig()
196 const fixture = config.fixture()
197 const expected = fixture.users.filter((u) => u.age === 25)
198 const usersCollection = config.collections.onDemand.users
199
200 const query = createLiveQueryCollection((q) =>
201 q
202 .from({ user: usersCollection })
203 .where(({ user }) => eq(user.age, 25)),
204 )
205 await withPredicateRows(query, expected, async () => {
206 await query.preload()
207
208 assertAllItemsMatch(query, (u) => u.age === 25)
209 })
210 })
211
212 it(`should filter with eq() on boolean field`, async () => {
213 const config = await getConfig()
214 const fixture = config.fixture()
215 const expected = fixture.users.filter((u) => u.isActive === true)
216 const usersCollection = config.collections.onDemand.users
217
218 const query = createLiveQueryCollection((q) =>
219 q
220 .from({ user: usersCollection })
221 .where(({ user }) => eq(user.isActive, true)),
222 )
223 await withPredicateRows(query, expected, async () => {
224 await query.preload()
225 await waitForQueryData(query, { minSize: 1 })
226
227 const results = Array.from(query.state.values())
228 expect(results.length).toBeGreaterThan(0)
229 assertAllItemsMatch(query, (u) => u.isActive === true)
230 })
231 })
232
233 it(`should filter with eq() on UUID field`, async () => {
234 const config = await getConfig()
235 const fixture = config.fixture()
236 const expected = fixture.users.filter(
237 (u) => u.id === `00000000-0000-4000-8000-000000000000`,
238 )
239 const usersCollection = config.collections.onDemand.users
240
241 const testUserId = `00000000-0000-4000-8000-000000000000` // User ID for index 0
242
243 const query = createLiveQueryCollection((q) =>
244 q
245 .from({ user: usersCollection })
246 .where(({ user }) => eq(user.id, testUserId)),
247 )
248 await withPredicateRows(query, expected, async () => {
249 await query.preload()
250 await waitForQueryData(query, { minSize: 1 })
251
252 assertCollectionSize(query, 1)
253 const result = Array.from(query.state.values())[0]
254 expect(result?.id).toBe(testUserId)
255 })
256 })
257
258 it(`should filter with isNull() for null values`, async () => {
259 const config = await getConfig()
260 const fixture = config.fixture()
261 const expected = fixture.users.filter((u) => u.email === null)
262 const usersCollection = config.collections.onDemand.users
263
264 const query = createLiveQueryCollection((q) =>
265 q
266 .from({ user: usersCollection })
267 .where(({ user }) => isNull(user.email)),
268 )
269 await withPredicateRows(query, expected, async () => {
270 await query.preload()
271 await waitForQueryData(query, { minSize: 1 })
272
273 const results = Array.from(query.state.values())
274 expect(results.length).toBeGreaterThan(0)
275 assertAllItemsMatch(query, (u) => u.email === null)
276 })
277 })
278 })
279
280 describe(`Inequality Operators`, () => {
281 it(`should filter with not(eq()) on string field`, async () => {
282 const config = await getConfig()
283 const fixture = config.fixture()
284 const expected = fixture.users.filter((u) => u.name !== `Alice 0`)
285 const usersCollection = config.collections.onDemand.users
286
287 const query = createLiveQueryCollection((q) =>
288 q
289 .from({ user: usersCollection })
290 .where(({ user }) => not(eq(user.name, `Alice 0`))),
291 )
292 await withPredicateRows(query, expected, async () => {
293 await query.preload()
294 await waitForQueryData(query, { minSize: 1 })
295
296 const results = Array.from(query.state.values())
297 expect(results.length).toBeGreaterThan(0)
298 assertAllItemsMatch(query, (u) => u.name !== `Alice 0`)
299 })
300 })
301
302 it(`should filter with not(isNull()) for non-null values`, async () => {
303 const config = await getConfig()
304 const fixture = config.fixture()
305 const expected = fixture.users.filter((u) => u.email !== null)
306 const usersCollection = config.collections.onDemand.users
307
308 const query = createLiveQueryCollection((q) =>
309 q
310 .from({ user: usersCollection })
311 .where(({ user }) => not(isNull(user.email))),
312 )
313 await withPredicateRows(query, expected, async () => {
314 await query.preload()
315 await waitForQueryData(query, { minSize: 1 })
316
317 const results = Array.from(query.state.values())
318 expect(results.length).toBeGreaterThan(0)
319 assertAllItemsMatch(query, (u) => u.email !== null)
320 })
321 })
322 })
323
324 describe(`Comparison Operators`, () => {
325 it(`should filter with gt() on number field`, async () => {
326 const config = await getConfig()
327 const fixture = config.fixture()
328 const expected = fixture.users.filter((u) => u.age > 50)
329 const usersCollection = config.collections.onDemand.users
330
331 const query = createLiveQueryCollection((q) =>
332 q
333 .from({ user: usersCollection })
334 .where(({ user }) => gt(user.age, 50)),
335 )
336 await withPredicateRows(query, expected, async () => {
337 await query.preload()
338
339 assertAllItemsMatch(query, (u) => u.age > 50)
340 })
341 })
342
343 it(`should filter with gte() on number field`, async () => {
344 const config = await getConfig()
345 const fixture = config.fixture()
346 const expected = fixture.users.filter((u) => u.age >= 50)
347 const usersCollection = config.collections.onDemand.users
348
349 const query = createLiveQueryCollection((q) =>
350 q
351 .from({ user: usersCollection })
352 .where(({ user }) => gte(user.age, 50)),
353 )
354 await withPredicateRows(query, expected, async () => {
355 await query.preload()
356
357 assertAllItemsMatch(query, (u) => u.age >= 50)
358 })
359 })
360
361 it(`should filter with lt() on number field`, async () => {
362 const config = await getConfig()
363 const fixture = config.fixture()
364 const expected = fixture.users.filter((u) => u.age < 30)
365 const usersCollection = config.collections.onDemand.users
366
367 const query = createLiveQueryCollection((q) =>
368 q
369 .from({ user: usersCollection })
370 .where(({ user }) => lt(user.age, 30)),
371 )
372 await withPredicateRows(query, expected, async () => {
373 await query.preload()
374
375 assertAllItemsMatch(query, (u) => u.age < 30)
376 })
377 })
378
379 it(`should filter with lte() on number field`, async () => {
380 const config = await getConfig()
381 const fixture = config.fixture()
382 const expected = fixture.users.filter((u) => u.age <= 30)
383 const usersCollection = config.collections.onDemand.users
384
385 const query = createLiveQueryCollection((q) =>
386 q
387 .from({ user: usersCollection })
388 .where(({ user }) => lte(user.age, 30)),
389 )
390 await withPredicateRows(query, expected, async () => {
391 await query.preload()
392
393 assertAllItemsMatch(query, (u) => u.age <= 30)
394 })
395 })
396
397 it(`should filter with gt() on viewCount field`, async () => {
398 const config = await getConfig()
399 const fixture = config.fixture()
400 const expected = fixture.posts.filter((p) => p.viewCount > 100)
401 const postsCollection = config.collections.onDemand.posts
402
403 const query = createLiveQueryCollection((q) =>
404 q
405 .from({ post: postsCollection })
406 .where(({ post }) => gt(post.viewCount, 100)),
407 )
408 await withPredicateRows(query, expected, async () => {
409 await query.preload()
410
411 assertAllItemsMatch(query, (p) => p.viewCount > 100)
412 })
413 })
414
415 it(`should filter with eq() on BIGINT field using JavaScript BigInt`, async () => {
416 const config = await getConfig()
417 const fixture = config.fixture()
418 const expected = fixture.posts.filter(
419 (p) => p.largeViewCount === 9007199254740992n,
420 )
421 const postsCollection = config.collections.onDemand.posts
422
423 // Target the first post which has largeViewCount = 9007199254740992n (MAX_SAFE_INTEGER + 1)
424 const targetBigInt = BigInt(`9007199254740992`)
425
426 const query = createLiveQueryCollection((q) =>
427 q
428 .from({ post: postsCollection })
429 .where(({ post }) => eq(post.largeViewCount, targetBigInt)),
430 )
431 await withPredicateRows(query, expected, async () => {
432 await query.preload()
433 await waitForQueryData(query, { minSize: 1 })
434
435 const results = Array.from(query.state.values())
436 expect(results.length).toBe(1)
437 // Post 0 has largeViewCount = 9007199254740992n
438 // Database may return as bigint or string depending on driver
439 assertAllItemsMatch(query, (p) => {
440 const value = String(p.largeViewCount)
441 return value === targetBigInt.toString()
442 })
443 })
444 })
445
446 it(`should filter with gt() on BIGINT field using JavaScript BigInt`, async () => {
447 const config = await getConfig()
448 const fixture = config.fixture()
449 const expected = fixture.posts.filter(
450 (p) => p.largeViewCount > 9007199254740995n,
451 )
452 const postsCollection = config.collections.onDemand.posts
453
454 // Filter for posts with largeViewCount > 9007199254740995
455 // This should match posts 4-9 (indices 4,5,6,7,8,9 have values 9007199254740996-9007199254741001)
456 const thresholdBigInt = BigInt(`9007199254740995`)
457
458 const query = createLiveQueryCollection((q) =>
459 q
460 .from({ post: postsCollection })
461 .where(({ post }) => gt(post.largeViewCount, thresholdBigInt)),
462 )
463 await withPredicateRows(query, expected, async () => {
464 await query.preload()
465 await waitForQueryData(query, { minSize: 1 })
466
467 const results = Array.from(query.state.values())
468 expect(results.length).toBeGreaterThan(0)
469 // All results should have largeViewCount > threshold
470 assertAllItemsMatch(query, (p) => {
471 const value =
472 typeof p.largeViewCount === `bigint`
473 ? p.largeViewCount
474 : BigInt(p.largeViewCount)
475 return value > thresholdBigInt
476 })
477 })
478 })
479 })
480
481 describe(`String Pattern Matching Operators`, () => {
482 it(`should filter with like() operator (case-sensitive)`, async () => {
483 const config = await getConfig()
484 const fixture = config.fixture()
485 const expected = fixture.users.filter((u) => u.name.startsWith(`Alice`))
486 const usersCollection = config.collections.onDemand.users
487
488 const query = createLiveQueryCollection((q) =>
489 q
490 .from({ user: usersCollection })
491 .where(({ user }) => like(user.name, `Alice%`)),
492 )
493 await withPredicateRows(query, expected, async () => {
494 await query.preload()
495 await waitForQueryData(query, { minSize: 1 })
496
497 const results = Array.from(query.state.values())
498 expect(results.length).toBeGreaterThan(0)
499 // Should match names starting with "Alice" (case-sensitive)
500 assertAllItemsMatch(query, (u) => u.name.startsWith(`Alice`))
501 })
502 })
503
504 it(`should filter with ilike() operator (case-insensitive)`, async () => {
505 const config = await getConfig()
506 const fixture = config.fixture()
507 const expected = fixture.users.filter((u) =>
508 u.name.toLowerCase().startsWith(`alice`),
509 )
510 const usersCollection = config.collections.onDemand.users
511
512 const query = createLiveQueryCollection((q) =>
513 q
514 .from({ user: usersCollection })
515 .where(({ user }) => ilike(user.name, `alice%`)),
516 )
517 await withPredicateRows(query, expected, async () => {
518 await query.preload()
519 await waitForQueryData(query, { minSize: 1 })
520
521 const results = Array.from(query.state.values())
522 expect(results.length).toBeGreaterThan(0)
523 // Should match names starting with "Alice" (case-insensitive)
524 assertAllItemsMatch(query, (u) =>
525 u.name.toLowerCase().startsWith(`alice`),
526 )
527 })
528 })
529
530 it(`should filter with like() with wildcard pattern (% at end)`, async () => {
531 const config = await getConfig()
532 const fixture = config.fixture()
533 const expected = fixture.users.filter(
534 (u) => u.email?.endsWith(`@example.com`) ?? false,
535 )
536 const usersCollection = config.collections.onDemand.users
537
538 const query = createLiveQueryCollection((q) =>
539 q
540 .from({ user: usersCollection })
541 .where(({ user }) => like(user.email, `%@example.com`)),
542 )
543 await withPredicateRows(query, expected, async () => {
544 await query.preload()
545 await waitForQueryData(query, { minSize: 1 })
546
547 const results = Array.from(query.state.values())
548 expect(results.length).toBeGreaterThan(0)
549 // Should match emails ending with @example.com
550 assertAllItemsMatch(
551 query,
552 (u) => u.email?.endsWith(`@example.com`) ?? false,
553 )
554 })
555 })
556
557 it(`should filter with like() with wildcard pattern (% in middle)`, async () => {
558 const config = await getConfig()
559 const fixture = config.fixture()
560 const expected = fixture.users.filter(
561 (u) => u.email !== null && /^user.*0@example\.com$/.test(u.email),
562 )
563 const usersCollection = config.collections.onDemand.users
564
565 const query = createLiveQueryCollection((q) =>
566 q
567 .from({ user: usersCollection })
568 .where(({ user }) => like(user.email, `user%0@example.com`)),
569 )
570 await withPredicateRows(query, expected, async () => {
571 await query.preload()
572 await waitForQueryData(query, { minSize: 1 })
573
574 const results = Array.from(query.state.values())
575 expect(results.length).toBeGreaterThan(0)
576 // Should match emails like user0@example.com, user10@example.com, user20@example.com, etc.
577 assertAllItemsMatch(
578 query,
579 (u) => (u.email?.match(/^user.*0@example\.com$/) ?? null) !== null,
580 )
581 })
582 })
583
584 it(`should filter with like() with wildcard pattern matching newline`, async () => {
585 const config = await getConfig()
586 const fixture = config.fixture()
587 const expected = fixture.users.filter((u) =>
588 u.name.startsWith(`Ursula`),
589 )
590 const usersCollection = config.collections.onDemand.users
591
592 const query = createLiveQueryCollection((q) =>
593 q
594 .from({ user: usersCollection })
595 .where(({ user }) => like(user.name, `Ursula%`)),
596 )
597 await withPredicateRows(query, expected, async () => {
598 await query.preload()
599 await waitForQueryData(query, { minSize: 1 })
600
601 const results = Array.from(query.state.values())
602 expect(results.length).toBeGreaterThan(0)
603 // should match names starting with "Ursula" even if it contains a newline character
604 assertAllItemsMatch(query, (u) => u.name.startsWith(`Ursula`))
605 })
606 })
607
608 it(`should filter with like() with lower() function`, async () => {
609 const config = await getConfig()
610 const fixture = config.fixture()
611 const expected = fixture.users.filter((u) =>
612 u.name.toLowerCase().includes(`alice`),
613 )
614 const usersCollection = config.collections.onDemand.users
615
616 const query = createLiveQueryCollection((q) =>
617 q
618 .from({ user: usersCollection })
619 .where(({ user }) => like(lower(user.name), `%alice%`)),
620 )
621 await withPredicateRows(query, expected, async () => {
622 await query.preload()
623 await waitForQueryData(query, { minSize: 1 })
624
625 const results = Array.from(query.state.values())
626 expect(results.length).toBeGreaterThan(0)
627 // Should match names containing "alice" (case-insensitive via lower())
628 assertAllItemsMatch(query, (u) =>
629 u.name.toLowerCase().includes(`alice`),
630 )
631 })
632 })
633
634 it(`should filter with ilike() with lower() function`, async () => {
635 const config = await getConfig()
636 const fixture = config.fixture()
637 const expected = fixture.users.filter((u) =>
638 u.name.toLowerCase().includes(`bob`),
639 )
640 const usersCollection = config.collections.onDemand.users
641
642 const query = createLiveQueryCollection((q) =>
643 q
644 .from({ user: usersCollection })
645 .where(({ user }) => ilike(lower(user.name), `%bob%`)),
646 )
647 await withPredicateRows(query, expected, async () => {
648 await query.preload()
649 await waitForQueryData(query, { minSize: 1 })
650
651 const results = Array.from(query.state.values())
652 expect(results.length).toBeGreaterThan(0)
653 // Should match names containing "bob" (case-insensitive)
654 assertAllItemsMatch(query, (u) =>
655 u.name.toLowerCase().includes(`bob`),
656 )
657 })
658 })
659
660 it(`should filter with or() combining multiple like() conditions (search pattern)`, async () => {
661 const config = await getConfig()
662 const fixture = config.fixture()
663 const expected = fixture.posts.filter(
664 (p) =>
665 p.title.toLowerCase().includes(`introduction`) ||
666 (p.content?.toLowerCase().includes(`introduction`) ?? false),
667 )
668 const postsCollection = config.collections.onDemand.posts
669
670 // This mimics the user's exact query pattern with multiple fields
671 // User's pattern: like(lower(offers.title), `%${searchLower}%`) OR like(lower(offers.human_id), `%${searchLower}%`)
672 const searchTerm = `Introduction`
673 const searchLower = searchTerm.toLowerCase()
674
675 const query = createLiveQueryCollection((q) =>
676 q
677 .from({ post: postsCollection })
678 .where(({ post }) =>
679 or(
680 like(lower(post.title), `%${searchLower}%`),
681 like(lower(post.content ?? ``), `%${searchLower}%`),
682 ),
683 ),
684 )
685 await withPredicateRows(query, expected, async () => {
686 await query.preload()
687 await waitForQueryData(query, { minSize: 1 })
688
689 const results = Array.from(query.state.values())
690 expect(results.length).toBeGreaterThan(0)
691 // Should match posts with title or content containing "introduction" (case-insensitive)
692 assertAllItemsMatch(
693 query,
694 (p) =>
695 p.title.toLowerCase().includes(searchLower) ||
696 (p.content?.toLowerCase().includes(searchLower) ?? false),
697 )
698 })
699 })
700
701 it(`should filter with like() and orderBy`, async () => {
702 const config = await getConfig()
703 const fixture = config.fixture()
704 const expected = orderedAliceRows(fixture.users)
705 const usersCollection = config.collections.onDemand.users
706
707 const query = createLiveQueryCollection((q) =>
708 q
709 .from({ user: usersCollection })
710 .where(({ user }) => like(lower(user.name), `%alice%`))
711 .orderBy(({ user }) => user.name, `asc`),
712 )
713 await withPredicateRows(
714 query,
715 expected,
716 async () => {
717 await query.preload()
718 await waitForQueryData(query, { minSize: 1 })
719
720 const results = Array.from(query.state.values())
721 expect(results.length).toBeGreaterThan(0)
722 assertAllItemsMatch(query, (u) =>
723 u.name.toLowerCase().includes(`alice`),
724 )
725
726 // Verify ordering
727 const names = results.map((u) => u.name)
728 const sortedNames = [...names].sort((a, b) => a.localeCompare(b))
729 expect(names).toEqual(sortedNames)
730 },
731 true,
732 )
733 })
734
735 it(`should filter with like() and limit`, async () => {
736 const config = await getConfig()
737 const fixture = config.fixture()
738 const expected = orderedAliceRows(fixture.users).slice(0, 5)
739 const usersCollection = config.collections.onDemand.users
740
741 const query = createLiveQueryCollection((q) =>
742 q
743 .from({ user: usersCollection })
744 .where(({ user }) => like(lower(user.name), `%alice%`))
745 .orderBy(({ user }) => user.name, `asc`) // Required when using LIMIT
746 .limit(5),
747 )
748 await withPredicateRows(
749 query,
750 expected,
751 async () => {
752 await query.preload()
753 await waitForQueryData(query, { minSize: 1 })
754
755 const results = Array.from(query.state.values())
756 // Should respect limit
757 expect(results.length).toBeLessThanOrEqual(5)
758 assertAllItemsMatch(query, (u) =>
759 u.name.toLowerCase().includes(`alice`),
760 )
761 },
762 true,
763 )
764 })
765
766 it(`should handle like() with pattern matching no records`, async () => {
767 const config = await getConfig()
768 const fixture = config.fixture()
769 const expected = fixture.users.filter((u) =>
770 u.name.startsWith(`NonExistent`),
771 )
772 const usersCollection = config.collections.onDemand.users
773
774 const query = createLiveQueryCollection((q) =>
775 q
776 .from({ user: usersCollection })
777 .where(({ user }) => like(user.name, `NonExistent%`)),
778 )
779 await withPredicateRows(query, expected, async () => {
780 await query.preload()
781
782 assertCollectionSize(query, 0)
783 })
784 })
785 })
786
787 describe(`In Operator`, () => {
788 it(`should filter with inArray() on string array`, async () => {
789 const config = await getConfig()
790 const fixture = config.fixture()
791 const expected = fixture.users.filter((u) =>
792 [`Alice 0`, `bob 1`, `Charlie 2`].includes(u.name),
793 )
794 const usersCollection = config.collections.onDemand.users
795
796 const query = createLiveQueryCollection((q) =>
797 q
798 .from({ user: usersCollection })
799 .where(({ user }) =>
800 inArray(user.name, [`Alice 0`, `bob 1`, `Charlie 2`]),
801 ),
802 )
803 await withPredicateRows(query, expected, async () => {
804 await query.preload()
805
806 const validNames = new Set([`Alice 0`, `bob 1`, `Charlie 2`])
807 assertAllItemsMatch(query, (u) => validNames.has(u.name))
808 })
809 })
810
811 it(`should filter with inArray() on number array`, async () => {
812 const config = await getConfig()
813 const fixture = config.fixture()
814 const expected = fixture.users.filter((u) =>
815 [25, 30, 35].includes(u.age),
816 )
817 const usersCollection = config.collections.onDemand.users
818
819 const query = createLiveQueryCollection((q) =>
820 q
821 .from({ user: usersCollection })
822 .where(({ user }) => inArray(user.age, [25, 30, 35])),
823 )
824 await withPredicateRows(query, expected, async () => {
825 await query.preload()
826
827 const validAges = new Set([25, 30, 35])
828 assertAllItemsMatch(query, (u) => validAges.has(u.age))
829 })
830 })
831
832 it(`should filter with inArray() on UUID array`, async () => {
833 const config = await getConfig()
834 const fixture = config.fixture()
835 const expected = fixture.users.filter((u) =>
836 [
837 `00000000-0000-4000-8000-000000000000`,
838 `00000001-0000-4000-8000-000000000001`,
839 `00000002-0000-4000-8000-000000000002`,
840 ].includes(u.id),
841 )
842 const usersCollection = config.collections.onDemand.users
843
844 const userIds = [
845 `00000000-0000-4000-8000-000000000000`, // User ID for index 0
846 `00000001-0000-4000-8000-000000000001`, // User ID for index 1
847 `00000002-0000-4000-8000-000000000002`, // User ID for index 2
848 ]
849
850 const query = createLiveQueryCollection((q) =>
851 q
852 .from({ user: usersCollection })
853 .where(({ user }) => inArray(user.id, userIds)),
854 )
855 await withPredicateRows(query, expected, async () => {
856 await query.preload()
857
858 const validIds = new Set(userIds)
859 assertAllItemsMatch(query, (u) => validIds.has(u.id))
860 })
861 })
862
863 it(`should handle empty inArray()`, async () => {
864 const config = await getConfig()
865 const fixture = config.fixture()
866 const expectedIds = new Set<string>()
867 const expected = fixture.users.filter((u) => expectedIds.has(u.id))
868 const usersCollection = config.collections.onDemand.users
869
870 const query = createLiveQueryCollection((q) =>
871 q
872 .from({ user: usersCollection })
873 .where(({ user }) => inArray(user.id, [])),
874 )
875 await withPredicateRows(query, expected, async () => {
876 await query.preload()
877
878 assertCollectionSize(query, 0)
879 })
880 })
881
882 it(`should filter with inArray() on BIGINT array using JavaScript BigInt`, async () => {
883 const config = await getConfig()
884 const fixture = config.fixture()
885 const expected = fixture.posts.filter((p) =>
886 [9007199254740992n, 9007199254740993n].includes(p.largeViewCount),
887 )
888 const postsCollection = config.collections.onDemand.posts
889
890 // Target posts 0 and 1 which have largeViewCount values:
891 // Post 0: 9007199254740992n, Post 1: 9007199254740993n
892 const targetBigInts = [
893 BigInt(`9007199254740992`),
894 BigInt(`9007199254740993`),
895 ]
896
897 const query = createLiveQueryCollection((q) =>
898 q
899 .from({ post: postsCollection })
900 .where(({ post }) => inArray(post.largeViewCount, targetBigInts)),
901 )
902 await withPredicateRows(query, expected, async () => {
903 await query.preload()
904 await waitForQueryData(query, { minSize: 2 })
905
906 const results = Array.from(query.state.values())
907 expect(results.length).toBe(2)
908
909 // Verify both matching posts are returned
910 const targetStrings = targetBigInts.map((b) => b.toString())
911 assertAllItemsMatch(query, (p) => {
912 const value =
913 typeof p.largeViewCount === `bigint`
914 ? p.largeViewCount.toString()
915 : String(p.largeViewCount)
916 return targetStrings.includes(value)
917 })
918 })
919 })
920 })
921
922 describe(`Null Operators`, () => {
923 it(`should filter with isNull() on nullable field`, async () => {
924 const config = await getConfig()
925 const fixture = config.fixture()
926 const expected = fixture.users.filter((u) => u.email === null)
927 const usersCollection = config.collections.onDemand.users
928
929 const query = createLiveQueryCollection((q) =>
930 q
931 .from({ user: usersCollection })
932 .where(({ user }) => isNull(user.email)),
933 )
934 await withPredicateRows(query, expected, async () => {
935 await query.preload()
936 await waitForQueryData(query, { minSize: 1 })
937
938 const results = Array.from(query.state.values())
939 expect(results.length).toBeGreaterThan(0)
940 assertAllItemsMatch(query, (u) => u.email === null)
941 })
942 })
943
944 it(`should filter with not(isNull()) on nullable field`, async () => {
945 const config = await getConfig()
946 const fixture = config.fixture()
947 const expected = fixture.users.filter((u) => u.email !== null)
948 const usersCollection = config.collections.onDemand.users
949
950 const query = createLiveQueryCollection((q) =>
951 q
952 .from({ user: usersCollection })
953 .where(({ user }) => not(isNull(user.email))),
954 )
955 await withPredicateRows(query, expected, async () => {
956 await query.preload()
957 await waitForQueryData(query, { minSize: 1 })
958
959 const results = Array.from(query.state.values())
960 expect(results.length).toBeGreaterThan(0)
961 assertAllItemsMatch(query, (u) => u.email !== null)
962 })
963 })
964
965 it(`should filter with isNull() on deletedAt (soft delete pattern)`, async () => {
966 const config = await getConfig()
967 const fixture = config.fixture()
968 const expected = fixture.users.filter((u) => u.deletedAt === null)
969 const usersCollection = config.collections.onDemand.users
970
971 const query = createLiveQueryCollection((q) =>
972 q
973 .from({ user: usersCollection })
974 .where(({ user }) => isNull(user.deletedAt)),
975 )
976 await withPredicateRows(query, expected, async () => {
977 await query.preload()
978 await waitForQueryData(query, { minSize: 1 })
979
980 const results = Array.from(query.state.values())
981 expect(results.length).toBeGreaterThan(0)
982 assertAllItemsMatch(query, (u) => u.deletedAt === null)
983 })
984 })
985 })
986
987 describe(`Boolean Logic`, () => {
988 it(`should combine predicates with and()`, async () => {
989 const config = await getConfig()
990 const fixture = config.fixture()
991 const expected = fixture.users.filter(
992 (u) => u.age > 25 && u.isActive === true,
993 )
994 const usersCollection = config.collections.onDemand.users
995
996 const query = createLiveQueryCollection((q) =>
997 q
998 .from({ user: usersCollection })
999 .where(({ user }) =>
1000 and(gt(user.age, 25), eq(user.isActive, true)),
1001 ),
1002 )
1003 await withPredicateRows(query, expected, async () => {
1004 await query.preload()
1005
1006 assertAllItemsMatch(query, (u) => u.age > 25 && u.isActive === true)
1007 })
1008 })
1009
1010 it(`should combine predicates with or()`, async () => {
1011 const config = await getConfig()
1012 const fixture = config.fixture()
1013 const expected = fixture.users.filter(
1014 (u) => u.age === 25 || u.age === 30,
1015 )
1016 const usersCollection = config.collections.onDemand.users
1017
1018 const query = createLiveQueryCollection((q) =>
1019 q
1020 .from({ user: usersCollection })
1021 .where(({ user }) => or(eq(user.age, 25), eq(user.age, 30))),
1022 )
1023 await withPredicateRows(query, expected, async () => {
1024 await query.preload()
1025
1026 assertAllItemsMatch(query, (u) => u.age === 25 || u.age === 30)
1027 })
1028 })
1029
1030 it(`should handle complex nested logic`, async () => {
1031 const config = await getConfig()
1032 const fixture = config.fixture()
1033 const expected = fixture.users.filter(
1034 (u) => (u.age === 25 || u.age === 30) && u.isActive === true,
1035 )
1036 const usersCollection = config.collections.onDemand.users
1037
1038 const query = createLiveQueryCollection((q) =>
1039 q
1040 .from({ user: usersCollection })
1041 .where(({ user }) =>
1042 and(
1043 or(eq(user.age, 25), eq(user.age, 30)),
1044 eq(user.isActive, true),
1045 ),
1046 ),
1047 )
1048 await withPredicateRows(query, expected, async () => {
1049 await query.preload()
1050
1051 assertAllItemsMatch(
1052 query,
1053 (u) => (u.age === 25 || u.age === 30) && u.isActive === true,
1054 )
1055 })
1056 })
1057
1058 it(`should handle NOT operator`, async () => {
1059 const config = await getConfig()
1060 const fixture = config.fixture()
1061 const expected = fixture.users.filter((u) => u.isActive !== true)
1062 const usersCollection = config.collections.onDemand.users
1063
1064 const query = createLiveQueryCollection((q) =>
1065 q
1066 .from({ user: usersCollection })
1067 .where(({ user }) => not(eq(user.isActive, true))),
1068 )
1069 await withPredicateRows(query, expected, async () => {
1070 await query.preload()
1071
1072 assertAllItemsMatch(query, (u) => u.isActive !== true)
1073 })
1074 })
1075 })
1076
1077 describe(`Predicate Result Verification`, () => {
1078 it(`should return only data matching the predicate`, async () => {
1079 const config = await getConfig()
1080 const fixture = config.fixture()
1081 const expected = fixture.users.filter((u) => u.age === 25)
1082 const usersCollection = config.collections.onDemand.users
1083
1084 const query = createLiveQueryCollection((q) =>
1085 q
1086 .from({ user: usersCollection })
1087 .where(({ user }) => eq(user.age, 25)),
1088 )
1089 await withPredicateRows(query, expected, async () => {
1090 await query.preload()
1091 await waitForQueryData(query, { minSize: 1 })
1092
1093 // This checks query output, not physical backend acquisition.
1094 const results = Array.from(query.state.values())
1095 expect(results.length).toBeGreaterThan(0)
1096 expect(results.length).toBeLessThan(100) // Filtered output, not backend work
1097 })
1098 })
1099
1100 it(`should exclude deleted records from filtered results`, async () => {
1101 const config = await getConfig()
1102 const fixture = config.fixture()
1103 const expected = fixture.users.filter((u) => u.deletedAt === null)
1104 const usersCollection = config.collections.onDemand.users
1105
1106 const query = createLiveQueryCollection((q) =>
1107 q
1108 .from({ user: usersCollection })
1109 .where(({ user }) => isNull(user.deletedAt)),
1110 )
1111 await withPredicateRows(query, expected, async () => {
1112 await query.preload()
1113 await waitForQueryData(query, { minSize: 1 })
1114
1115 const results = Array.from(query.state.values())
1116 expect(results.length).toBeGreaterThan(0)
1117 assertAllItemsMatch(query, (u) => u.deletedAt === null)
1118 })
1119 })
1120 })
1121
1122 describe(`Multiple where() Calls`, () => {
1123 it(`should AND multiple where() calls together`, async () => {
1124 const config = await getConfig()
1125 const fixture = config.fixture()
1126 const expected = fixture.users.filter(
1127 (u) => u.age > 25 && u.isActive === true,
1128 )
1129 const usersCollection = config.collections.onDemand.users
1130
1131 const query = createLiveQueryCollection((q) =>
1132 q
1133 .from({ user: usersCollection })
1134 .where(({ user }) => gt(user.age, 25))
1135 .where(({ user }) => eq(user.isActive, true)),
1136 )
1137 await withPredicateRows(query, expected, async () => {
1138 await query.preload()
1139
1140 assertAllItemsMatch(query, (u) => u.age > 25 && u.isActive === true)
1141 })
1142 })
1143 })
1144
1145 describe(`Edge Cases`, () => {
1146 it(`should handle query with no where clause on on-demand collection`, async () => {
1147 // NOTE: Electric has a bug where empty subset requests don't load data
1148 // We work around this by injecting "true = true" when there's no where clause
1149 // This is always true so doesn't filter data, just tricks Electric into loading
1150
1151 const config = await getConfig()
1152 const fixture = config.fixture()
1153 const expected = fixture.users
1154 const usersCollection = config.collections.onDemand.users
1155
1156 // Query with NO where clause - loads all data
1157 const query = createLiveQueryCollection(
1158 (q) => q.from({ user: usersCollection }),
1159 // No where, no limit, no orderBy
1160 )
1161 await withPredicateRows(query, expected, async () => {
1162 await query.preload()
1163 await waitForQueryData(query, { minSize: 50 })
1164
1165 // Should load significant data (true = true workaround for Electric)
1166 expect(query.size).toBeGreaterThan(0)
1167 expect(query.size).toBe(usersCollection.size) // Query shows all collection data
1168 })
1169 })
1170
1171 it(`should handle predicate matching no records`, async () => {
1172 const config = await getConfig()
1173 const fixture = config.fixture()
1174 const expected = fixture.users.filter((u) => u.age === 999)
1175 const usersCollection = config.collections.onDemand.users
1176
1177 const query = createLiveQueryCollection((q) =>
1178 q
1179 .from({ user: usersCollection })
1180 .where(({ user }) => eq(user.age, 999)),
1181 )
1182 await withPredicateRows(query, expected, async () => {
1183 await query.preload()
1184
1185 assertCollectionSize(query, 0)
1186 })
1187 })
1188
1189 it(`should handle complex AND with no matches`, async () => {
1190 const config = await getConfig()
1191 const fixture = config.fixture()
1192 const expected = fixture.users.filter((u) =>
1193 [25, 30].every((age) => u.age === age),
1194 )
1195 const usersCollection = config.collections.onDemand.users
1196
1197 const query = createLiveQueryCollection((q) =>
1198 q.from({ user: usersCollection }).where(({ user }) =>
1199 and(
1200 eq(user.age, 25),
1201 eq(user.age, 30), // Impossible: age can't be both 25 and 30
1202 ),
1203 ),
1204 )
1205 await withPredicateRows(query, expected, async () => {
1206 await query.preload()
1207
1208 assertCollectionSize(query, 0)
1209 })
1210 })
1211 })
1212 })
1213}