Open History to see the last commit
1// @vitest-environment node
2/**
3 * Scenario checks for SQLite boolean-arity reads: a large string-ID OR scope
4 * stays selective, and bound string membership avoids discarded quoting. The
5 * boolean-arity oracle in `sqlite-boolean-arity-oracle.test.ts` owns the law.
6 */
7import { expect, it, vi } from 'vitest'
8import { IR } from '@tanstack/db'
9import { SQLiteCorePersistenceAdapter, createPersistedTableName } from '../src'
10import { CountingDriver } from './sqlite-boolean-arity-support'
11β
12it('keeps large string-ID OR scopes selective at the SQLite boundary', async () => {
13 const driver = new CountingDriver()
14 const adapter = new SQLiteCorePersistenceAdapter({ driver })
15 const collectionId = 'string-id-scope'
16 const scopeRows = Array.from({ length: 20 }, (_, index) => ({
17 issueId: `issue-${index}`,
18 relatedIssueId:
19 ['related-\uD800', 'related-\u0000', 'related-π'][index] ??
20 `related-${index}`,
21 }))
22 const ids = Array.from({ length: 50_582 }, (_, index) => `other-${index}`)
23 ids[5_001] = 'related-\uD800'
24 ids[25_291] = 'issue-1'
25 ids[35_001] = 'related-\u0000'
26 ids[45_001] = 'related-π'
27 const allowed = new Set(ids)
28β
29 try {
30 await adapter.applyCommittedTx(
31 { kind: `eager`, collectionId: collectionId },
32 {
33 txId: 'seed-string-scope',
34 term: 1,
35 seq: 1,
36 rowVersion: 1,
37 mutations: scopeRows.map((row) => ({
38 type: 'insert' as const,
39 key: row.issueId,
40 value: structuredClone(row),
41 })),
42 },
43 )
44 for (const field of ['issueId', 'relatedIssueId']) {
45 await adapter.ensureIndex(
46 { kind: `eager`, collectionId: collectionId },
47 field,
48 {
49 expressionSql: [JSON.stringify(new IR.PropRef([field]))],
50 },
51 )
52 }
53β
54 driver.reads = []
55 const rows = await adapter.loadSubset(
56 { kind: `eager`, collectionId: collectionId },
57 {
58 where: new IR.Func('and', [
59 new IR.Func('or', [
60 new IR.Func('in', [new IR.PropRef(['issueId']), new IR.Value(ids)]),
61 new IR.Func('in', [
62 new IR.PropRef(['relatedIssueId']),
63 new IR.Value(ids),
64 ]),
65 ]),
66 ]),
67 },
68 )
69 const expected = scopeRows
70 .filter(
71 (row) => allowed.has(row.issueId) || allowed.has(row.relatedIssueId),
72 )
73 .map((row) => row.issueId)
74 expect(rows.map((row) => row.key).sort()).toEqual(expected.sort())
75 expect(driver.reads).toHaveLength(1)
76 expect(driver.reads[0]?.rawRows).toBe(expected.length)
77 expect(driver.reads[0]?.parameters).toBe(2)
78 const plan = driver.db
79 .prepare(`EXPLAIN QUERY PLAN ${driver.reads[0]!.sql}`)
80 .all(JSON.stringify(ids), JSON.stringify(ids)) as Array<{
81 detail: string
82 }>
83 const tableName = createPersistedTableName(collectionId, 'c')
84 expect(
85 plan.some(
86 ({ detail }) =>
87 detail.startsWith(`SCAN ${tableName}`) ||
88 detail.startsWith(`SCAN "${tableName}"`),
89 ),
90 ).toBe(false)
91 for (const field of ['issueId', 'relatedIssueId']) {
92 const index = driver.db
93 .prepare(
94 `SELECT index_name FROM persisted_index_registry WHERE collection_id = ? AND signature = ?`,
95 )
96 .get(collectionId, field) as { index_name: string }
97 expect(
98 plan.some(
99 ({ detail }) =>
100 detail.startsWith('SEARCH') && detail.includes(index.index_name),
101 ),
102 ).toBe(true)
103 }
104 } finally {
105 driver.db.close()
106 }
107})
108β
109// Ordinary runtime membership transports its list through one JSON binding.
110// The independent work rule therefore permits zero SQL-literal quoting of list
111// values. Counting the quoting primitive detects discarded construction that
112// cannot be seen in the final SQL. The original compiler performs two quotes
113// per value; exact result and binding checks retain the receiving contract.
114// A sequential index-expression control proves the sensor still sees quoting
115// before the bound-path counter resets; changing the primitive cannot pass silently.
116it.sequential.each([0, 1, 32, 1_025])(
117 'avoids discarded literal quoting for bound string membership / %i',
118 async (size) => {
119 const driver = new CountingDriver()
120 const adapter = new SQLiteCorePersistenceAdapter({ driver })
121 const values = Array.from({ length: size }, (_, index) => `work-${index}`)
122 const control = 'quote-probe-control'
123 const observedValues = new Set([...values, control])
124 let quotedValues = 0
125 const replace = String.prototype.replace
126 const quoteProbe = vi
127 .spyOn(String.prototype, 'replace')
128 .mockImplementation(function (
129 this: string,
130 ...args: Parameters<typeof replace>
131 ) {
132 if (observedValues.has(String(this))) quotedValues++
133 return Reflect.apply(replace, this, args)
134 })
135 try {
136 await adapter.applyCommittedTx(
137 { kind: `eager`, collectionId: 'string-membership-work' },
138 {
139 txId: 'seed',
140 term: 1,
141 seq: 1,
142 rowVersion: 1,
143 mutations: [
144 { type: 'insert', key: 'match', value: { value: 'work-0' } },
145 { type: 'insert', key: 'other', value: { value: 'outside' } },
146 ],
147 },
148 )
149 // An index literal must reach the probe, even for an empty bound list.
150 await adapter.ensureIndex(
151 { kind: `eager`, collectionId: 'string-membership-work' },
152 'quote-control',
153 {
154 expressionSql: [
155 JSON.stringify(
156 new IR.Func('coalesce', [
157 new IR.PropRef(['value']),
158 new IR.Value(control),
159 ]),
160 ),
161 ],
162 },
163 )
164 expect(quotedValues).toBeGreaterThan(0)
165 quotedValues = 0
166 driver.reads = []
167 const rows = await adapter.loadSubset(
168 { kind: `eager`, collectionId: 'string-membership-work' },
169 {
170 where: new IR.Func('in', [
171 new IR.PropRef(['value']),
172 new IR.Value(values),
173 ]),
174 },
175 )
176 expect(rows.map((row) => row.key)).toEqual(size === 0 ? [] : ['match'])
177 expect(driver.reads).toHaveLength(1)
178 expect(driver.reads[0]?.parameters).toBe(size === 0 ? 0 : 1)
179 expect(quotedValues).toBe(0)
180 } finally {
181 quoteProbe.mockRestore()
182 driver.db.close()
183 }
184 },
185)