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

expression-index-oracle.test.ts

1,451 lines47.7 KB

1/**
2 * # When does SQLite use a persisted expression index?
3 *
4 * Contract and source: RFC #1659 invariant 8 requires persisted index DDL and
5 * the indexed runtime predicate to have the same SQLite expression shape.
6 * SQLite requires syntactically matching expressions before an expression
7 * index can satisfy a predicate.
8 *
9 * History grammar and domain: every generated matrix reaches indexed string
10 * equality, ordinary and 901-value batched BigInt IN, numeric range, string
11 * conjunction, ordering, and lower(ref). Paths have a one-to-six-character
12 * identifier root and up to three identifier/0..3 tail segments. Numeric
13 * targets are -10_000..10_000; generated BigInts use the same bounds plus a
14 * 900-member suffix. Fixed cases cover constant-bearing coalesce indexes,
15 * BigInt ranges/IN within SQLite's signed-integer domain, and indexed numeric
16 * comparisons with tagged values, null, missing, and text controls. Numeric
17 * equality/IN, lower-wrapped BigInt IN, lone-surrogate coalesce, Date ranges,
18 * strftime, and add keep full reads where SQLite could exclude a JavaScript
19 * match. Integer threshold checks include adjacent fractional values.
20 * Fixed candidate-superset cases cover large Number versus BigInt bounds,
21 * numeric object keys and array indexes through three digit segments, and
22 * Unicode lowercase matches around NUL. The numeric-path cases also check
23 * named-index use; deeper digit paths retain a full candidate read.
24 * Native fixture families add EQ/IN, same-kind ranges, raw-ref NOT leaves,
25 * native field pairs, wrapper coalesce indexes, and numeric array/object paths.
26 * Rank/text expectations are independent of the SQL compiler. Mixed cases
27 * include NaN, null/missing, ordinary strings and alternate native kinds.
28 * SQL candidates must contain every expected match; exact native fixtures also
29 * check raw keys and supported index plans. NOT/coalesce and scalar
30 * eq(in(...), true) retain the safe classifier's full-read fallback.
31 * Explicitly qualified refs lower to the same JSON field expression
32 * without reinterpreting legacy nested paths. Known omissions: null, arbitrary
33 * raw SQL, and native-host planning. Generated BigInts stay inside SQLite's
34 * signed range. A fixed legacy-byte case checks read compatibility beyond it.
35 *
36 * Fixed scenarios whose expectations are literal, the replay-configuration and
37 * plan-classifier self-tests, and the cleanup self-test are ordinary unit tests in
38 * expression-index.test.ts, with the observer in expression-index-support.ts.
39 *
40 * Independent model: fixed keys encode the result of each generated relation;
41 * the equality witness also uses a full adapter scan, a small path walker, and
42 * strict scalar equality. Neither judgment calls the SQL compiler.
43 *
44 * Production path and checkpoint: the public SQLite-core adapter factory with
45 * the real BetterSqlite3SQLiteDriver. The exact SQL and bindings passed to the
46 * driver's predicate query are captured and executed directly before adapter
47 * re-filtering, then replayed through EXPLAIN QUERY PLAN. Result keys, ordering
48 * when promised, and named-index use are separate observations.
49 *
50 * Reach, challenge, replay, and cleanup: the expression-index matrix and both
51 * generated BigInt range checks run in fixed-seed and seedless-random campaigns.
52 * A path replay sets TANSTACK_DB_ORACLE_PATH, TANSTACK_DB_ORACLE_SEED, and
53 * TANSTACK_DB_ORACLE_PROPERTY to one of sqlite-persistence.expression-index,
54 * sqlite-persistence.bigint-roundtrip, or sqlite-persistence.bigint-rejection.
55 * That property's random campaign replays only its recorded history; the fixed
56 * campaigns and the other properties stand aside. A seed alone reseeds the
57 * random campaigns. Per-axis grammar ablations and same-path SQL/compiler faults must
58 * fail the expression-index property. The
59 * retained fixed campaign reconstructs the known valid matrix. The bounds
60 * above state its range; exact grammar checks reject missing, duplicate, and
61 * unexpected axes as nearby invalid matrices. The focused overbroad and former
62 * path-binding controls remain independent. In-memory SQLite teardown
63 * retains the semantic failure if cleanup also fails.
64 */
65import fc from 'fast-check'
66import { describe, expect, vi, it as vitestIt } from 'vitest'
67import { IR } from '@tanstack/db'
68import {
69 createPersistedTableName,
70 createSQLiteCorePersistenceAdapter,
71 decodePersistedStorageKey,
72} from '@tanstack/db-sqlite-persistence-core'
73import {
74 oraclePropertyOptions,
75 oracleReplayTest,
76 oracleRuns,
77} from '../../db/tests/oracle-config.js'
78import { declareOracle } from '../../db/tests/oracle-declaration.js'
79import {
80 Temporal,
81 temporalFamilies,
82 temporalQueryCases,
83 temporalValue,
84} from '../../db-sqlite-persistence-core/tests/temporal-value-oracle'
85import { BetterSqlite3SQLiteDriver } from '../src/node-driver'
86import {
87 SQLITE_BIGINT_MAX,
88 SQLITE_BIGINT_MIN,
89 bigintRangeError,
90 createNestedRow,
91 createQueryObservingDriver,
92 observeExpressionIndexScenario,
93 planScansTable,
94 planUsesNamedIndex,
95 planUsesNamedIndexForOrdering,
96 readPath,
97 sqliteJsonPath,
98 sqliteScalarParameter,
99 withFailurePreservingCleanup,
100} from './expression-index-support'
101import type { TemporalFamily } from '../../db-sqlite-persistence-core/tests/temporal-value-oracle'
102import type {
103 CapturedQuery,
104 ExpressionIndexObservation,
105 ExpressionIndexScenario,
106 OracleScalar,
107 QueryPlanRow,
108 QueryTransform,
109 ScanRow,
110} from './expression-index-support'
111​
112const DEFAULT_ORACLE_SEED = 1_659_005
113const DEFAULT_ORACLE_RUNS = 8
114​
115type OracleCase = {
116 path: Array<string>
117 target: OracleScalar
118 distractors: [OracleScalar, OracleScalar]
120​
121const identifierStart = [`a`, `m`, `p`, `t`, `x`] as const
122const identifierRest = [`a`, `b`, `e`, `i`, `n`, `r`, `s`, `0`, `1`] as const
123​
124const identifierArbitrary = fc
125 .tuple(
126 fc.constantFrom(...identifierStart),
127 fc.array(fc.constantFrom(...identifierRest), { maxLength: 5 }),
128 )
129 .map(([start, rest]) => `${start}${rest.join(``)}`)
130​
131const legalPathArbitrary = fc
132 .tuple(
133 identifierArbitrary,
134 fc.array(
135 fc.oneof(identifierArbitrary, fc.integer({ min: 0, max: 3 }).map(String)),
136 { maxLength: 3 },
137 ),
138 )
139 .map(([root, tail]) => [root, ...tail])
140​
141const EXPRESSION_INDEX_PROPERTY = `sqlite-persistence.expression-index`
142const BIGINT_ROUNDTRIP_PROPERTY = `sqlite-persistence.bigint-roundtrip`
143const BIGINT_REJECTION_PROPERTY = `sqlite-persistence.bigint-rejection`
144​
145type GeneratedPropertyCampaign = {
146 name: `fixed` | `random`
147 parameters: ReturnType<typeof oraclePropertyOptions>
149​
150// The fixed campaign pins its seed and stands aside on every path replay. The
151// random campaign runs in ordinary and seed-only runs, and as the replay of
152// its property, where oraclePropertyOptions returns the recorded path.
153const fixedGeneratedCampaign: GeneratedPropertyCampaign = {
154 name: `fixed`,
155 parameters: {
156 seed: DEFAULT_ORACLE_SEED,
157 numRuns: oracleRuns(DEFAULT_ORACLE_RUNS),
158 },
160​
161function randomGeneratedCampaign(property: string): GeneratedPropertyCampaign {
162 return {
163 name: `random`,
164 parameters: oraclePropertyOptions(DEFAULT_ORACLE_RUNS, property),
165 }
167​
168function generatedCampaignParameters(campaign: GeneratedPropertyCampaign) {
169 return { verbose: 2 as const, ...campaign.parameters }
171​
172function expectedKeysFromScan(
173 rows: ReadonlyArray<ScanRow>,
174 path: ReadonlyArray<string>,
175 target: OracleScalar,
176): Array<string> {
177 return rows
178 .filter((row) => readPath(row.value, path) === target)
179 .map((row) => String(row.key))
180 .sort()
182​
183const GENERATED_SCENARIO_KINDS = [
184 `eq`,
185 `in`,
186 `batched-in`,
187 `range`,
188 `and`,
189 `order-by`,
190 `wrapped-lower`,
191] as const
192​
193type GeneratedScenarioKind = (typeof GENERATED_SCENARIO_KINDS)[number]
194​
195const GENERATED_SCENARIO_FAULTS = [
196 { kind: `eq`, wrongAnswer: `inverted equality operator` },
197 { kind: `in`, wrongAnswer: `shifted first IN binding` },
198 { kind: `batched-in`, wrongAnswer: `replaced final batch member` },
199 { kind: `range`, wrongAnswer: `exclusive lower boundary` },
200 { kind: `and`, wrongAnswer: `wrong conjunct binding` },
201 { kind: `order-by`, wrongAnswer: `reversed ordering direction` },
202 { kind: `wrapped-lower`, wrongAnswer: `wrong expression wrapper` },
203] as const satisfies ReadonlyArray<{
204 kind: GeneratedScenarioKind
205 wrongAnswer: string
206}>
207​
208type GeneratedExpressionIndexScenario = ExpressionIndexScenario & {
209 kind: GeneratedScenarioKind
210 expectedKeys: Array<string>
211 expectedPlan: `search` | `ordered-scan`
213​
214const numericIndexCaseArbitrary = fc
215 .tuple(legalPathArbitrary, fc.integer({ min: -10_000, max: 10_000 }))
216 .map(([path, target]) => ({ path, target }))
217​
218const stringIndexCaseArbitrary = fc
219 .tuple(legalPathArbitrary, fc.integer({ min: 0, max: 10_000 }))
220 .map(([path, suffix]) => ({ path, target: `target-'${suffix}` }))
221​
222const generatedScenarioMatrixArbitrary = fc
223 .tuple(
224 stringIndexCaseArbitrary,
225 numericIndexCaseArbitrary,
226 numericIndexCaseArbitrary,
227 numericIndexCaseArbitrary,
228 stringIndexCaseArbitrary,
229 numericIndexCaseArbitrary,
230 stringIndexCaseArbitrary,
231 )
232 .map(
233 ([
234 eqCase,
235 inCase,
236 batchedCase,
237 rangeCase,
238 andCase,
239 orderCase,
240 lowerCase,
241 ]) => {
242 const eqRows = [
243 {
244 key: `eq-match-a`,
245 value: createNestedRow(eqCase.path, eqCase.target),
246 },
247 {
248 key: `eq-different`,
249 value: createNestedRow(eqCase.path, `${eqCase.target}-other`),
250 },
251 {
252 key: `eq-match-b`,
253 value: createNestedRow(eqCase.path, eqCase.target),
254 },
255 ]
256 const batchedValues = Array.from({ length: 901 }, (_unused, index) =>
257 BigInt(batchedCase.target + index),
258 )
259 const lowerTarget = lowerCase.target.toLowerCase()
260​
261 return [
262 {
263 kind: `eq`,
264 label: `generated-eq`,
265 indexExpression: new IR.PropRef(eqCase.path),
266 where: new IR.Func<boolean>(`eq`, [
267 new IR.PropRef(eqCase.path),
268 new IR.Value(eqCase.target),
269 ]),
270 rows: eqRows,
271 expectedKeys: [`eq-match-a`, `eq-match-b`],
272 expectedPlan: `search`,
273 },
274 {
275 kind: `in`,
276 label: `generated-in`,
277 indexExpression: new IR.PropRef(inCase.path),
278 where: new IR.Func<boolean>(`in`, [
279 new IR.PropRef(inCase.path),
280 new IR.Value([BigInt(inCase.target - 1), BigInt(inCase.target)]),
281 ]),
282 rows: [
283 {
284 key: `in-lower`,
285 value: createNestedRow(inCase.path, BigInt(inCase.target - 1)),
286 },
287 {
288 key: `in-match`,
289 value: createNestedRow(inCase.path, BigInt(inCase.target)),
290 },
291 {
292 key: `in-higher`,
293 value: createNestedRow(inCase.path, BigInt(inCase.target + 1)),
294 },
295 ],
296 expectedKeys: [`in-lower`, `in-match`],
297 expectedPlan: `search`,
298 },
299 {
300 kind: `batched-in`,
301 label: `generated-batched-in`,
302 indexExpression: new IR.PropRef(batchedCase.path),
303 where: new IR.Func<boolean>(`in`, [
304 new IR.PropRef(batchedCase.path),
305 new IR.Value(batchedValues),
306 ]),
307 rows: [
308 {
309 key: `batch-first`,
310 value: createNestedRow(
311 batchedCase.path,
312 BigInt(batchedCase.target),
313 ),
314 },
315 {
316 key: `batch-last`,
317 value: createNestedRow(
318 batchedCase.path,
319 BigInt(batchedCase.target + 900),
320 ),
321 },
322 {
323 key: `batch-outside`,
324 value: createNestedRow(
325 batchedCase.path,
326 BigInt(batchedCase.target - 1),
327 ),
328 },
329 ],
330 expectedKeys: [`batch-first`, `batch-last`],
331 expectedPlan: `search`,
332 },
333 {
334 kind: `range`,
335 label: `generated-range`,
336 indexExpression: new IR.PropRef(rangeCase.path),
337 where: new IR.Func<boolean>(`gte`, [
338 new IR.PropRef(rangeCase.path),
339 new IR.Value(rangeCase.target),
340 ]),
341 rows: [
342 {
343 key: `range-lower`,
344 value: createNestedRow(rangeCase.path, rangeCase.target - 1),
345 },
346 {
347 key: `range-match`,
348 value: createNestedRow(rangeCase.path, rangeCase.target),
349 },
350 {
351 key: `range-higher`,
352 value: createNestedRow(rangeCase.path, rangeCase.target + 1),
353 },
354 ],
355 expectedKeys: [`range-higher`, `range-match`],
356 expectedPlan: `search`,
357 },
358 {
359 kind: `and`,
360 label: `generated-and`,
361 indexExpression: new IR.PropRef(andCase.path),
362 where: new IR.Func<boolean>(`and`, [
363 new IR.Func(`eq`, [
364 new IR.PropRef(andCase.path),
365 new IR.Value(andCase.target),
366 ]),
367 new IR.Func(`eq`, [
368 new IR.PropRef([`status`]),
369 new IR.Value(`active`),
370 ]),
371 ]),
372 rows: [
373 {
374 key: `and-match`,
375 value: {
376 ...createNestedRow(andCase.path, andCase.target),
377 status: `active`,
378 },
379 },
380 {
381 key: `and-inactive`,
382 value: {
383 ...createNestedRow(andCase.path, andCase.target),
384 status: `inactive`,
385 },
386 },
387 {
388 key: `and-different`,
389 value: {
390 ...createNestedRow(andCase.path, `${andCase.target}-other`),
391 status: `active`,
392 },
393 },
394 ],
395 expectedKeys: [`and-match`],
396 expectedPlan: `search`,
397 },
398 {
399 kind: `order-by`,
400 label: `generated-order-by`,
401 indexExpression: new IR.PropRef(orderCase.path),
402 orderBy: [
403 {
404 expression: new IR.PropRef(orderCase.path),
405 compareOptions: {
406 direction: `asc`,
407 nulls: `last`,
408 },
409 },
410 ],
411 preserveResultOrder: true,
412 rows: [
413 {
414 key: `order-high`,
415 value: createNestedRow(orderCase.path, orderCase.target + 1),
416 },
417 {
418 key: `order-low`,
419 value: createNestedRow(orderCase.path, orderCase.target - 1),
420 },
421 {
422 key: `order-middle`,
423 value: createNestedRow(orderCase.path, orderCase.target),
424 },
425 ],
426 expectedKeys: [`order-low`, `order-middle`, `order-high`],
427 expectedPlan: `ordered-scan`,
428 },
429 {
430 kind: `wrapped-lower`,
431 label: `generated-wrapped-lower`,
432 indexExpression: new IR.Func(`lower`, [
433 new IR.PropRef(lowerCase.path),
434 ]),
435 where: new IR.Func<boolean>(`eq`, [
436 new IR.Func(`lower`, [new IR.PropRef(lowerCase.path)]),
437 new IR.Value(lowerTarget),
438 ]),
439 rows: [
440 {
441 key: `lower-upper`,
442 value: createNestedRow(
443 lowerCase.path,
444 lowerCase.target.toUpperCase(),
445 ),
446 },
447 {
448 key: `lower-lower`,
449 value: createNestedRow(lowerCase.path, lowerTarget),
450 },
451 {
452 key: `lower-other`,
453 value: createNestedRow(lowerCase.path, `${lowerTarget}-other`),
454 },
455 ],
456 expectedKeys: [`lower-lower`, `lower-upper`],
457 expectedPlan: `search`,
458 },
459 ] satisfies Array<GeneratedExpressionIndexScenario>
460 },
461 )
462​
463function assertGeneratedScenarioGrammar(
464 scenarios: ReadonlyArray<GeneratedExpressionIndexScenario>,
465): void {
466 const actualKinds = scenarios.map(({ kind }) => kind)
467 const missingKinds = GENERATED_SCENARIO_KINDS.filter(
468 (kind) => !actualKinds.includes(kind),
469 )
470 const unexpectedKinds = actualKinds.filter(
471 (kind) => !GENERATED_SCENARIO_KINDS.includes(kind),
472 )
473 const duplicateKinds = actualKinds.filter(
474 (kind, index) => actualKinds.indexOf(kind) !== index,
475 )
476​
477 if (
478 missingKinds.length > 0 ||
479 unexpectedKinds.length > 0 ||
480 duplicateKinds.length > 0
481 ) {
482 throw new Error(
483 `generated scenario grammar mismatch: missing=${missingKinds.join(`,`) || `none`}; unexpected=${unexpectedKinds.join(`,`) || `none`}; duplicate=${duplicateKinds.join(`,`) || `none`}`,
484 )
485 }
487​
488function mutateGeneratedScenarioQuery(
489 kind: GeneratedScenarioKind,
490): QueryTransform {
491 const unreached = (detail: string): never => {
492 throw new Error(`${kind} SQL/compiler fault did not reach ${detail}`)
493 }
494​
495 const numericInList = (
496 query: CapturedQuery,
497 length: number,
498 ): Array<number> => {
499 const boundList = query.params[0]
500 if (
501 !query.sql.includes(` IN (SELECT value FROM json_each(?))`) ||
502 query.params.length !== 1 ||
503 typeof boundList !== `string`
504 ) {
505 return unreached(`the ${length}-member IN list binding`)
506 }
507 let values: unknown
508 try {
509 values = JSON.parse(boundList) as unknown
510 } catch {
511 return unreached(`a JSON IN list binding`)
512 }
513 if (
514 !Array.isArray(values) ||
515 values.length !== length ||
516 !values.every(
517 (value: unknown) =>
518 typeof value === `number` && Number.isSafeInteger(value),
519 )
520 ) {
521 return unreached(`a ${length}-member numeric IN list binding`)
522 }
523 return values as Array<number>
524 }
525​
526 switch (kind) {
527 case `eq`:
528 return (query) => {
529 const sql = query.sql.replace(/ = \?/g, ` != ?`)
530 if (sql === query.sql) return unreached(`the equality operator`)
531 return { sql, params: query.params }
532 }
533 case `in`:
534 return (query) => {
535 const values = numericInList(query, 2)
536 values[0] = values[0]! + 2
537 return { sql: query.sql, params: [JSON.stringify(values)] }
538 }
539 case `batched-in`:
540 return (query) => {
541 const values = numericInList(query, 901)
542 values[values.length - 1] = values[0]! - 1
543 return { sql: query.sql, params: [JSON.stringify(values)] }
544 }
545 case `range`:
546 return (query) => {
547 const sql = query.sql.replace(/ >= \?/, ` > ?`)
548 if (sql === query.sql) return unreached(`the inclusive range operator`)
549 return { sql, params: query.params }
550 }
551 case `and`:
552 return (query) => {
553 const activeIndex = query.params.indexOf(`active`)
554 if (activeIndex === -1) return unreached(`the conjunction binding`)
555 const params = [...query.params]
556 params[activeIndex] = `inactive`
557 return { sql: query.sql, params }
558 }
559 case `order-by`:
560 return (query) => {
561 const sql = query.sql.replace(/\sASC\b/, ` DESC`)
562 if (sql === query.sql) return unreached(`the ascending order clause`)
563 return { sql, params: query.params }
564 }
565 case `wrapped-lower`:
566 return (query) => {
567 const sql = query.sql.replace(/\blower\(/gi, `upper(`)
568 if (sql === query.sql) return unreached(`the lower wrapper`)
569 return { sql, params: query.params }
570 }
571 }
573​
574function assertGeneratedScenarioObservation(
575 scenario: GeneratedExpressionIndexScenario,
576 observation: ExpressionIndexObservation,
577): void {
578 const diagnostic = JSON.stringify(
579 {
580 kind: scenario.kind,
581 sql: observation.predicateQuery.sql,
582 params: observation.predicateQuery.params,
583 plan: observation.plan.map((row) => row.detail),
584 adapterKeys: observation.adapterKeys,
585 directSqlKeys: observation.directSqlKeys,
586 },
587 null,
588 2,
589 )
590​
591 expect(observation.adapterKeys, diagnostic).toEqual(scenario.expectedKeys)
592 expect(observation.directSqlKeys, diagnostic).toEqual(scenario.expectedKeys)
593 if (scenario.expectedPlan === `ordered-scan`) {
594 expect(
595 planUsesNamedIndexForOrdering(
596 observation.plan,
597 observation.tableName,
598 observation.indexName,
599 ),
600 diagnostic,
601 ).toBe(true)
602 } else {
603 expect(
604 planUsesNamedIndex(
605 observation.plan,
606 observation.tableName,
607 observation.indexName,
608 ),
609 diagnostic,
610 ).toBe(true)
611 expect(
612 planScansTable(observation.plan, observation.tableName),
613 diagnostic,
614 ).toBe(false)
615 }
617​
618type GeneratedScenarioPropertyOptions = {
619 ablateKind?: GeneratedScenarioKind
620 faultKind?: GeneratedScenarioKind
621 onScenario?: (kind: GeneratedScenarioKind) => void
623​
624function generatedScenarioProperty({
625 ablateKind,
626 faultKind,
627 onScenario,
628}: GeneratedScenarioPropertyOptions = {}) {
629 return fc.asyncProperty(generatedScenarioMatrixArbitrary, async (matrix) => {
630 const scenarios =
631 ablateKind === undefined
632 ? matrix
633 : matrix.filter(({ kind }) => kind !== ablateKind)
634 assertGeneratedScenarioGrammar(scenarios)
635​
636 for (const scenario of scenarios) {
637 onScenario?.(scenario.kind)
638 const observation = await observeExpressionIndexScenario({
639 ...scenario,
640 ...(faultKind === scenario.kind
641 ? { transformQuery: mutateGeneratedScenarioQuery(scenario.kind) }
642 : {}),
643 })
644 assertGeneratedScenarioObservation(scenario, observation)
645 }
646 })
648​
649async function runGeneratedScenarioProperty(
650 campaign: GeneratedPropertyCampaign,
651) {
652 const reachedScenarios = new Set<GeneratedScenarioKind>()
653 const details = await fc.check(
654 generatedScenarioProperty({
655 onScenario: (kind) => reachedScenarios.add(kind),
656 }),
657 generatedCampaignParameters(campaign),
658 )
659​
660 if (details.failed) {
661 throw new Error(
662 fc.defaultReportMessage(details) ??
663 `generated expression-index property failed without a report`,
664 )
665 }
666 expect([...reachedScenarios].sort()).toEqual(
667 [...GENERATED_SCENARIO_KINDS].sort(),
668 )
669 return details
671​
672async function assertExpressionIndexHistory(
673 testCase: OracleCase,
674 label: string,
675): Promise<void> {
676 const baseDriver = new BetterSqlite3SQLiteDriver({ filename: `:memory:` })
677 const collectionId = `expression-index-${label}`
678 const signature = `generated-ref`
679 const tableName = createPersistedTableName(collectionId, `c`)
680 let predicateQuery: CapturedQuery | undefined
681​
682 const observingDriver = createQueryObservingDriver(baseDriver, (query) => {
683 if (
684 query.sql.includes(`FROM "${tableName}"`) &&
685 query.sql.includes(` WHERE `)
686 ) {
687 predicateQuery = query
688 }
689 })
690 const adapter = createSQLiteCorePersistenceAdapter({
691 driver: observingDriver,
692 })
693 const values = [
694 testCase.target,
695 testCase.distractors[0],
696 testCase.target,
697 testCase.distractors[1],
698 testCase.distractors[0],
699 testCase.target,
700 ]
701 const seededRows = values.map((value, index) => ({
702 key: `row-${index}`,
703 value: createNestedRow(testCase.path, value),
704 }))
705​
706 await withFailurePreservingCleanup(async () => {
707 await adapter.applyCommittedTx(
708 { kind: `eager`, collectionId: collectionId },
709 {
710 txId: `seed-${label}`,
711 term: 1,
712 seq: 1,
713 rowVersion: 1,
714 mutations: seededRows.map((row) => ({
715 type: `insert` as const,
716 key: row.key,
717 value: row.value,
718 })),
719 },
720 )
721​
722 await adapter.ensureIndex(
723 { kind: `eager`, collectionId: collectionId },
724 signature,
725 {
726 expressionSql: [JSON.stringify({ type: `ref`, path: testCase.path })],
727 },
728 )
729​
730 if (!adapter.scanRows) {
731 throw new Error(`real SQLite adapter did not expose scanRows`)
732 }
733 const scannedRows = await adapter.scanRows({
734 kind: `eager`,
735 collectionId: collectionId,
736 })
737 const expectedKeys = expectedKeysFromScan(
738 scannedRows,
739 testCase.path,
740 testCase.target,
741 )
742 const independentlySeededExpectedKeys = expectedKeysFromScan(
743 seededRows,
744 testCase.path,
745 testCase.target,
746 )
747​
748 expect(
749 expectedKeys,
750 `full-scan checkpoint must retain independently seeded values`,
751 ).toEqual(independentlySeededExpectedKeys)
752 expect(scannedRows).toHaveLength(seededRows.length)
753​
754 const indexedRows = await adapter.loadSubset(
755 { kind: `eager`, collectionId: collectionId },
756 {
757 where: new IR.Func(`eq`, [
758 new IR.PropRef(testCase.path),
759 new IR.Value(testCase.target),
760 ]),
761 },
762 )
763 const indexedKeys = indexedRows.map((row) => String(row.key)).sort()
764​
765 expect(
766 indexedKeys,
767 `indexed adapter results must equal the independent scan model`,
768 ).toEqual(expectedKeys)
769​
770 if (!predicateQuery) {
771 throw new Error(`predicate query checkpoint was not reached`)
772 }
773 expect(
774 predicateQuery.params,
775 `the filter value must remain a bound parameter`,
776 ).toContain(sqliteScalarParameter(testCase.target))
777​
778 const directSqlKeys = (
779 baseDriver
780 .getDatabase()
781 .prepare(predicateQuery.sql)
782 .all(...predicateQuery.params) as Array<{ key: string }>
783 )
784 .map((row) => String(decodePersistedStorageKey(row.key)))
785 .sort()
786 expect(
787 directSqlKeys,
788 `captured SQL must produce the independent keys before in-memory filtering`,
789 ).toEqual(expectedKeys)
790​
791 const registryRow = baseDriver
792 .getDatabase()
793 .prepare(
794 `SELECT index_name FROM persisted_index_registry
795 WHERE collection_id = ? AND signature = ?`,
796 )
797 .get(collectionId, signature) as { index_name: string } | undefined
798 if (!registryRow) {
799 throw new Error(`expression index registry checkpoint was not reached`)
800 }
801​
802 const indexDefinition = baseDriver
803 .getDatabase()
804 .prepare(
805 `SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?`,
806 )
807 .get(registryRow.index_name) as { sql: string } | undefined
808 if (!indexDefinition) {
809 throw new Error(`expression index DDL checkpoint was not reached`)
810 }
811​
812 const plan = baseDriver
813 .getDatabase()
814 .prepare(`EXPLAIN QUERY PLAN ${predicateQuery.sql}`)
815 .all(...predicateQuery.params) as Array<QueryPlanRow>
816 const checkpoint = {
817 name: `predicate-explain`,
818 path: sqliteJsonPath(testCase.path),
819 expectedKeys,
820 indexedKeys,
821 subsetSql: predicateQuery.sql,
822 subsetParams: predicateQuery.params,
823 indexName: registryRow.index_name,
824 indexSql: indexDefinition.sql,
825 plan: plan.map((row) => row.detail),
826 usedNamedExpressionIndex: planUsesNamedIndex(
827 plan,
828 tableName,
829 registryRow.index_name,
830 ),
831 scannedCollectionTable: planScansTable(plan, tableName),
832 }
833 const checkpointMessage = `predicate checkpoint must use only the matching expression index:\n${JSON.stringify(checkpoint, null, 2)}`
834​
835 expect(checkpoint.usedNamedExpressionIndex, checkpointMessage).toBe(true)
836 expect(checkpoint.scannedCollectionTable, checkpointMessage).toBe(false)
837 }, [() => baseDriver.close()])
839​
840// Pure JavaScript comparisons state which public rows satisfy a Number or
841// BigInt range predicate. The model is independent of SQLite and of the
842// adapter, so the SQL candidate set is judged against these keys.
843function expectedRangeKeys(
844 rows: ReadonlyArray<{ key: string; value: { n: number | bigint } }>,
845 operator: `gt` | `gte` | `lt` | `lte`,
846 fieldOnLeft: boolean,
847 bound: bigint,
848): Array<string> {
849 const matches = (
850 op: `gt` | `gte` | `lt` | `lte`,
851 left: number | bigint,
852 right: number | bigint,
853 ): boolean => {
854 switch (op) {
855 case `gt`:
856 return left > right
857 case `gte`:
858 return left >= right
859 case `lt`:
860 return left < right
861 case `lte`:
862 return left <= right
863 }
864 }
865 return rows
866 .filter(({ value }) =>
867 fieldOnLeft
868 ? matches(operator, value.n, bound)
869 : matches(operator, bound, value.n),
870 )
871 .map(({ key }) => key)
872 .sort()
874​
875// Fixture ranks give the semantic order of native values, and their kind and
876// canonical text give equality. Null and missing stamps match no ordering
877// predicate. This model is independent of SQLite, so SQL may keep extra
878// candidates that the row evaluator then removes.
879function expectedNativePolarityKeys(
880 family: TemporalFamily,
881 nullableRows: ReadonlyArray<{ key: string }>,
882 operator: `gt` | `gte` | `lt` | `lte`,
883 reverse: boolean,
884 negate: boolean,
885): Array<string> {
886 return nullableRows
887 .flatMap((row) => {
888 if (row.key === `null` || row.key === `missing`) return []
889 const rank =
890 row.key === `nan` ? Infinity : family.ranks[Number(row.key.slice(4))]!
891 const a = reverse ? family.ranks[1] : rank
892 const b = reverse ? rank : family.ranks[1]
893 const match =
894 operator === `gt`
895 ? a > b
896 : operator === `gte`
897 ? a >= b
898 : operator === `lt`
899 ? a < b
900 : a <= b
901 return match !== negate ? [row.key] : []
902 })
903 .sort()
905​
906declareOracle({
907 check: [assertExpressionIndexHistory],
908 model: [expectedKeysFromScan, expectedRangeKeys, expectedNativePolarityKeys],
909 grammar: [generatedScenarioMatrixArbitrary],
910})
911​
912describe(`SQLite expression-index oracle`, () => {
913 const it = oracleReplayTest(vitestIt)
914​
915 it(`keeps large Number matches across BigInt range directions and boolean wrappers`, async () => {
916 const field = new IR.PropRef([`n`])
917 const cases = [
918 {
919 name: `positive`,
920 number: 1000000000000000100,
921 bound: 1000000000000000120n,
922 },
923 {
924 name: `negative`,
925 number: -1000000000000000100,
926 bound: -1000000000000000120n,
927 },
928 ] as const
929 const operators = [`gt`, `gte`, `lt`, `lte`] as const
930​
931 for (const testCase of cases) {
932 const rows = [
933 { key: `rounded-number`, value: { n: testCase.number } },
934 { key: `exact-bigint`, value: { n: testCase.bound } },
935 ]
936 for (const operator of operators) {
937 for (const fieldOnLeft of [true, false]) {
938 const literal = new IR.Value(testCase.bound)
939 const predicate = new IR.Func<boolean>(
940 operator,
941 fieldOnLeft ? [field, literal] : [literal, field],
942 )
943 const expectedKeys = expectedRangeKeys(
944 rows,
945 operator,
946 fieldOnLeft,
947 testCase.bound,
948 )
949 for (const wrapper of [`direct`, `and`, `or`] as const) {
950 const observation = await observeExpressionIndexScenario({
951 label: `rounded-${testCase.name}-${operator}-${fieldOnLeft}-${wrapper}`,
952 indexExpression: field,
953 where:
954 wrapper === `direct`
955 ? predicate
956 : new IR.Func<boolean>(wrapper, [predicate]),
957 rows,
958 })
959 expect(observation.adapterKeys).toEqual(expectedKeys)
960 expect(observation.directSqlKeys).toEqual(
961 expect.arrayContaining(expectedKeys),
962 )
963 const greaterSide = fieldOnLeft
964 ? operator === `gt` || operator === `gte`
965 : operator === `lt` || operator === `lte`
966 if (greaterSide) {
967 expect(
968 planUsesNamedIndex(
969 observation.plan,
970 observation.tableName,
971 observation.indexName,
972 ),
973 `${testCase.name}-${operator}-${fieldOnLeft}-${wrapper}: ${observation.plan.map((row) => row.detail).join(`; `)}`,
974 ).toBe(true)
975 }
976 }
977 }
978 }
979 }
980 })
981​
982 async function roundTripGeneratedBigInt(campaign: GeneratedPropertyCampaign) {
983 await fc.assert(
984 fc.asyncProperty(
985 fc.bigInt({ min: SQLITE_BIGINT_MIN, max: SQLITE_BIGINT_MAX }),
986 async (value) => {
987 const driver = new BetterSqlite3SQLiteDriver({
988 filename: `:memory:`,
989 })
990 const adapter = createSQLiteCorePersistenceAdapter({ driver })
991 const collectionId = `generated-bigint-in-range`
992​
993 await withFailurePreservingCleanup(async () => {
994 await adapter.applyCommittedTx(
995 { kind: `eager`, collectionId: collectionId },
996 {
997 txId: `seed-${value}`,
998 term: 1,
999 seq: 1,
1000 rowVersion: 1,
1001 mutations: [
1003 type: `insert`,
1004 key: `match`,
1005 value: { nested: { count: value } },
1006 },
1007 ],
1008 },
1010​
1011 const rows = await adapter.loadSubset(
1012 { kind: `eager`, collectionId: collectionId },
1014 where: new IR.Func(`eq`, [
1015 new IR.PropRef([`nested`, `count`]),
1016 new IR.Value(value),
1017 ]),
1018 },
1020 expect(rows.map((row) => row.key)).toEqual([`match`])
1021 expect(rows[0]?.value).toEqual({ nested: { count: value } })
1022 }, [() => driver.close()])
1023 },
1024 ),
1025 generatedCampaignParameters(campaign),
1028 oracleReplayTest(vitestIt).each([fixedGeneratedCampaign])(
1029 `round-trips generated signed-64-bit BigInts through the real adapter in the $name campaign`,
1030 roundTripGeneratedBigInt,
1032 oracleReplayTest(vitestIt, BIGINT_ROUNDTRIP_PROPERTY).each([
1033 randomGeneratedCampaign(BIGINT_ROUNDTRIP_PROPERTY),
1034 ])(
1035 `round-trips generated signed-64-bit BigInts through the real adapter in the $name campaign`,
1036 roundTripGeneratedBigInt,
1038​
1039 async function rejectGeneratedBigInt(campaign: GeneratedPropertyCampaign) {
1040 const outOfRangeBigIntArbitrary = fc.oneof(
1041 fc
1042 .bigInt({ min: 1n, max: 1_000n })
1043 .map((distance) => SQLITE_BIGINT_MIN - distance),
1044 fc
1045 .bigInt({ min: 1n, max: 1_000n })
1046 .map((distance) => SQLITE_BIGINT_MAX + distance),
1048​
1049 await fc.assert(
1050 fc.asyncProperty(outOfRangeBigIntArbitrary, async (value) => {
1051 const driver = new BetterSqlite3SQLiteDriver({ filename: `:memory:` })
1052 const adapter = createSQLiteCorePersistenceAdapter({ driver })
1053​
1054 await withFailurePreservingCleanup(async () => {
1055 await expect(
1056 adapter.applyCommittedTx(
1058 kind: `eager`,
1059 collectionId: `generated-bigint-out-of-range`,
1060 },
1062 txId: `reject-${value}`,
1063 term: 1,
1064 seq: 1,
1065 rowVersion: 1,
1066 mutations: [
1068 type: `insert`,
1069 key: `rejected`,
1070 value: { nested: { count: value } },
1071 },
1072 ],
1073 },
1074 ),
1075 ).rejects.toThrow(bigintRangeError(value))
1076 }, [() => driver.close()])
1077 }),
1078 generatedCampaignParameters(campaign),
1081 oracleReplayTest(vitestIt).each([fixedGeneratedCampaign])(
1082 `rejects generated BigInts immediately outside the signed range in the $name campaign`,
1083 rejectGeneratedBigInt,
1085 oracleReplayTest(vitestIt, BIGINT_REJECTION_PROPERTY).each([
1086 randomGeneratedCampaign(BIGINT_REJECTION_PROPERTY),
1087 ])(
1088 `rejects generated BigInts immediately outside the signed range in the $name campaign`,
1089 rejectGeneratedBigInt,
1091​
1092 it(`uses the expression index for the fixed filter witness`, async () => {
1093 await assertExpressionIndexHistory(
1095 path: [`threadId`],
1096 target: `thread-'1`,
1097 distractors: [`thread-2`, `thread-3`],
1098 },
1099 `fixed-thread-filter`,
1101 })
1102​
1103 async function reachGeneratedExpressionIndex(
1104 campaign: GeneratedPropertyCampaign,
1105 ) {
1106 const details = await runGeneratedScenarioProperty(campaign)
1107 const parameters = generatedCampaignParameters(campaign)
1108​
1109 expect(details.numRuns).toBe(campaign.parameters.numRuns)
1110 expect(`seed` in parameters).toBe(campaign.parameters.seed !== undefined)
1111 expect(`path` in parameters).toBe(campaign.parameters.path !== undefined)
1112 if (campaign.parameters.seed !== undefined) {
1113 expect(details.seed).toBe(campaign.parameters.seed)
1115 if (campaign.parameters.path !== undefined) {
1116 expect(details.runConfiguration.path).toBe(campaign.parameters.path)
1118 expect(details.seed).toEqual(expect.any(Number))
1120 oracleReplayTest(vitestIt).each([fixedGeneratedCampaign])(
1121 `reaches every declared generated expression-index scenario in the $name campaign`,
1122 reachGeneratedExpressionIndex,
1124 oracleReplayTest(vitestIt, EXPRESSION_INDEX_PROPERTY).each([
1125 randomGeneratedCampaign(EXPRESSION_INDEX_PROPERTY),
1126 ])(
1127 `reaches every declared generated expression-index scenario in the $name campaign`,
1128 reachGeneratedExpressionIndex,
1130​
1131 const generatedControlTest = oracleReplayTest(vitestIt)
1132​
1133 generatedControlTest.each(GENERATED_SCENARIO_KINDS)(
1134 `rejects the generated grammar when the %s axis is ablated`,
1135 async (kind) => {
1136 const details = await fc.check(
1137 generatedScenarioProperty({ ablateKind: kind }),
1139 seed: DEFAULT_ORACLE_SEED,
1140 numRuns: 1,
1141 verbose: 2,
1142 },
1144 const evidence = JSON.stringify({
1145 seed: details.seed,
1146 path: details.counterexamplePath,
1147 error: details.error,
1148 })
1149​
1150 expect(details.failed, evidence).toBe(true)
1151 expect(details.seed, evidence).toBe(DEFAULT_ORACLE_SEED)
1152 expect(details.counterexamplePath, evidence).not.toBeNull()
1153 expect(details.error, evidence).toContain(`missing=${kind}`)
1154 },
1156​
1157 generatedControlTest(
1158 `reconstructs the retained generated grammar and rejects a nearby duplicate axis`,
1159 () => {
1160 const [matrix] = fc.sample(generatedScenarioMatrixArbitrary, {
1161 seed: DEFAULT_ORACLE_SEED,
1162 numRuns: 1,
1163 })
1164 if (!matrix) throw new Error(`fixed grammar witness was not generated`)
1165 assertGeneratedScenarioGrammar(matrix)
1166 expect(GENERATED_SCENARIO_FAULTS.map(({ kind }) => kind)).toEqual(
1167 GENERATED_SCENARIO_KINDS,
1169 const equalityScenario = matrix[0]
1170 if (!equalityScenario) {
1171 throw new Error(`fixed grammar witness omitted equality`)
1173 expect(() =>
1174 assertGeneratedScenarioGrammar([...matrix, equalityScenario]),
1175 ).toThrow(`duplicate=eq`)
1176 },
1178​
1179 generatedControlTest.each(GENERATED_SCENARIO_FAULTS)(
1180 `rejects the plausible $wrongAnswer for the $kind axis`,
1181 async ({ kind }) => {
1182 const details = await fc.check(
1183 generatedScenarioProperty({ faultKind: kind }),
1185 seed: DEFAULT_ORACLE_SEED,
1186 numRuns: 1,
1187 verbose: 2,
1188 },
1190 const evidence = JSON.stringify({
1191 seed: details.seed,
1192 path: details.counterexamplePath,
1193 error: details.error,
1194 })
1195​
1196 expect(details.failed, evidence).toBe(true)
1197 expect(details.seed, evidence).toBe(DEFAULT_ORACLE_SEED)
1198 expect(details.counterexamplePath, evidence).not.toBeNull()
1199 expect(details.error ?? ``, evidence).not.toContain(`did not reach`)
1200 expect(details.error, evidence).toContain(`"kind": "${kind}"`)
1201​
1202 if (details.counterexamplePath === null) {
1203 throw new Error(`${kind} wrong-answer control did not shrink to a path`)
1205 const replay = await fc.check(
1206 generatedScenarioProperty({ faultKind: kind }),
1208 seed: details.seed,
1209 path: details.counterexamplePath,
1210 numRuns: 1,
1211 verbose: 2,
1212 },
1214 const replayEvidence = JSON.stringify({
1215 seed: replay.seed,
1216 requestedPath: details.counterexamplePath,
1217 replayPath: replay.counterexamplePath,
1218 error: replay.error,
1219 })
1220 expect(replay.failed, replayEvidence).toBe(true)
1221 expect(replay.error ?? ``, replayEvidence).not.toContain(`did not reach`)
1222 expect(replay.error, replayEvidence).toContain(`"kind": "${kind}"`)
1223 },
1226​
1227// Native values add a bounded rank/text dimension to this SQL/plan owner.
1228// The common model is independent; this driver observes real SQL before cleanup.
1229describe(`Temporal expression-index refinement`, () => {
1230 const it = oracleReplayTest(vitestIt)
1231 it.each(temporalFamilies)(
1232 `uses native keys and identity for $kind / $name`,
1233 async (family) => {
1234 vi.stubGlobal(`Temporal`, Temporal)
1235 try {
1236 for (const query of temporalQueryCases(family)) {
1237 const result = await observeExpressionIndexScenario({
1238 label: `${family.name}-${query.name}`,
1239 indexExpression: new IR.PropRef([`stamp`]),
1240 where: query.where,
1241 rows: family.texts.map((_, i) => ({
1242 key: `row-${i}`,
1243 value: {
1244 stamp: temporalValue(family, i),
1245 target: temporalValue(family, 1),
1246 },
1247 })),
1248 })
1249 expect(result.adapterKeys, query.name).toEqual(query.expectedKeys)
1250 expect(result.directSqlKeys, query.name).toEqual(query.expectedKeys)
1251 if (query.name === `in` || query.name === `batched-in`)
1252 expect(result.predicateQuery.params).toHaveLength(1)
1253 if (
1255 `eq`,
1256 `in`,
1257 `batched-in`,
1258 `gt`,
1259 `gte`,
1260 `lt`,
1261 `lte`,
1262 `and`,
1263 ].includes(query.name)
1264 ) {
1265 expect(
1266 planUsesNamedIndex(
1267 result.plan,
1268 result.tableName,
1269 result.indexName,
1270 ),
1271 query.name,
1272 ).toBe(true)
1273 expect(
1274 planScansTable(result.plan, result.tableName),
1275 query.name,
1276 ).toBe(false)
1279 } finally {
1280 vi.unstubAllGlobals()
1282 },
1284​
1285 // Independent fixture rank/text rules also judge mixed-domain candidates.
1286 // SQL may retain extras, but NOT must never invert an approximate prefilter.
1287 it.each(temporalFamilies)(
1288 `retains mixed-domain matches under native predicate polarity / $name`,
1289 async (family) => {
1290 vi.stubGlobal(`Temporal`, Temporal)
1291 try {
1292 const ref = new IR.PropRef([`stamp`])
1293 const literal = new IR.Value(temporalValue(family, 1))
1294 const nativeRows = family.texts.map((_, i) => ({
1295 key: `row-${i}`,
1296 value: { stamp: temporalValue(family, i) },
1297 }))
1298 const nullableRows = [
1299 ...nativeRows,
1300 { key: `nan`, value: { stamp: NaN } },
1301 { key: `null`, value: { stamp: null } },
1302 { key: `missing`, value: {} },
1304 for (const operator of [`gt`, `gte`, `lt`, `lte`] as const) {
1305 for (const reverse of [false, true]) {
1306 for (const negate of [false, true]) {
1307 const comparison = new IR.Func<boolean>(
1308 operator,
1309 reverse ? [literal, ref] : [ref, literal],
1311 const where = negate
1312 ? new IR.Func<boolean>(`not`, [comparison])
1313 : comparison
1314 const expectedKeys = expectedNativePolarityKeys(
1315 family,
1316 nullableRows,
1317 operator,
1318 reverse,
1319 negate,
1321 const result = await observeExpressionIndexScenario({
1322 label: `native-polarity`,
1323 indexExpression: ref,
1324 where,
1325 rows: nullableRows,
1326 })
1327 expect(
1328 result.adapterKeys,
1329 `${operator}/${reverse}/${negate}`,
1330 ).toEqual(expectedKeys)
1331 expect(result.directSqlKeys).toEqual(
1332 expect.arrayContaining(expectedKeys),
1337 const otherKind =
1338 family.kind === `Instant`
1339 ? Temporal.PlainDate.from(`2026-01-02`)
1340 : Temporal.Instant.from(`2026-01-02T00:00:00Z`)
1341 const rows = [
1342 ...nullableRows,
1343 ...[
1344 otherKind,
1345 0,
1346 false,
1347 new Date(0),
1348 `10000000000000000000001`,
1349 `${family.kind === `Instant` ? `Temporal.Instant` : `Temporal.PlainDate`}:${family.texts[1]}`,
1350 `\u0000tanstack-db:temporal:Temporal.${family.kind}:${family.texts[1]}`,
1351 ].map((stamp, i) => ({ key: `other-${i}`, value: { stamp } })),
1353 for (const operator of [`eq`, `in`] as const) {
1354 const comparison = new IR.Func<boolean>(operator, [
1355 ref,
1356 operator === `eq`
1357 ? literal
1358 : new IR.Value([temporalValue(family, 1)]),
1359 ])
1360 for (const negate of [false, true]) {
1361 const where = negate
1362 ? new IR.Func<boolean>(`not`, [comparison])
1363 : comparison
1364 const expectedKeys = rows
1365 .filter(
1366 (row) =>
1367 ![`null`, `missing`].includes(row.key) &&
1368 (row.key === `row-1`) !== negate,
1370 .map((row) => row.key)
1371 .sort()
1372 const result = await observeExpressionIndexScenario({
1373 label: `native-equality-polarity`,
1374 indexExpression: ref,
1375 where,
1376 rows,
1377 })
1378 expect(result.adapterKeys).toEqual(expectedKeys)
1379 expect(result.directSqlKeys).toEqual(
1380 expect.arrayContaining(expectedKeys),
1384 // A string can equal a native SQL order key without equaling the native
1385 // value. The scalar candidate uses one binding and residual cleanup owns
1386 // that distinction; persisted Boolean expressions still retain identity.
1387 const orderKey = `10000000000000000000001`
1388 const stringEquality = new IR.Func<boolean>(`eq`, [
1389 ref,
1390 new IR.Value(orderKey),
1391 ])
1392 const scalar = await observeExpressionIndexScenario({
1393 label: `string-native-order-key`,
1394 indexExpression: stringEquality,
1395 where: stringEquality,
1396 rows,
1397 observeIndexValues: true,
1398 })
1399 expect(scalar.adapterKeys).toEqual([`other-4`])
1400 expect(scalar.directSqlKeys).toEqual(
1401 expect.arrayContaining([`other-4`]),
1403 expect(scalar.predicateQuery.params).toEqual([orderKey])
1404 expect(
1405 scalar.indexValues
1406 ?.filter((row) => row.value === 1)
1407 .map((row) => row.key),
1408 ).toEqual([`other-4`])
1409​
1410 const selected = new IR.Func(`coalesce`, [ref, literal])
1411 const equality = new IR.Func<boolean>(`eq`, [selected, literal])
1412 const fallback = await observeExpressionIndexScenario({
1413 label: `native-coalesce-negation`,
1414 indexExpression: selected,
1415 where: new IR.Func<boolean>(`not`, [equality]),
1416 rows: nullableRows,
1417 })
1418 expect(fallback.adapterKeys).toEqual([`nan`, `row-0`, `row-2`])
1419 expect(fallback.predicateQuery.sql).not.toContain(` WHERE `)
1420 const paired = await observeExpressionIndexScenario({
1421 label: `native-field-pairs`,
1422 indexExpression: ref,
1423 where: new IR.Func<boolean>(`eq`, [ref, new IR.PropRef([`target`])]),
1424 rows: [
1426 key: `native`,
1427 value: {
1428 stamp: temporalValue(family, 1),
1429 target: temporalValue(family, 1),
1430 },
1431 },
1433 key: `different`,
1434 value: {
1435 stamp: temporalValue(family, 0),
1436 target: temporalValue(family, 1),
1437 },
1438 },
1439 { key: `date-number`, value: { stamp: new Date(0), target: 0 } },
1440 ],
1441 })
1442 expect(paired.adapterKeys).toEqual([`date-number`, `native`])
1443 expect(paired.directSqlKeys).toEqual(
1444 expect.arrayContaining(paired.adapterKeys),
1446 } finally {
1447 vi.unstubAllGlobals()
1449 },