Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

predicates-oracle.suite.ts

1,216 lines43.2 KB

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