@quereus/store 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +30 -4
  2. package/dist/src/common/encoding.d.ts +4 -3
  3. package/dist/src/common/encoding.d.ts.map +1 -1
  4. package/dist/src/common/encoding.js +17 -13
  5. package/dist/src/common/encoding.js.map +1 -1
  6. package/dist/src/common/events.d.ts +5 -1
  7. package/dist/src/common/events.d.ts.map +1 -1
  8. package/dist/src/common/events.js.map +1 -1
  9. package/dist/src/common/implicit-unique-index.d.ts +80 -0
  10. package/dist/src/common/implicit-unique-index.d.ts.map +1 -0
  11. package/dist/src/common/implicit-unique-index.js +148 -0
  12. package/dist/src/common/implicit-unique-index.js.map +1 -0
  13. package/dist/src/common/index.d.ts +7 -3
  14. package/dist/src/common/index.d.ts.map +1 -1
  15. package/dist/src/common/index.js +5 -2
  16. package/dist/src/common/index.js.map +1 -1
  17. package/dist/src/common/json-key.d.ts +2 -2
  18. package/dist/src/common/json-key.js +2 -2
  19. package/dist/src/common/key-builder.d.ts +33 -14
  20. package/dist/src/common/key-builder.d.ts.map +1 -1
  21. package/dist/src/common/key-builder.js +24 -17
  22. package/dist/src/common/key-builder.js.map +1 -1
  23. package/dist/src/common/kv-store.d.ts +10 -0
  24. package/dist/src/common/kv-store.d.ts.map +1 -1
  25. package/dist/src/common/pk-key-resolution.d.ts +275 -0
  26. package/dist/src/common/pk-key-resolution.d.ts.map +1 -0
  27. package/dist/src/common/pk-key-resolution.js +389 -0
  28. package/dist/src/common/pk-key-resolution.js.map +1 -0
  29. package/dist/src/common/store-module-access-plan.d.ts +32 -0
  30. package/dist/src/common/store-module-access-plan.d.ts.map +1 -0
  31. package/dist/src/common/store-module-access-plan.js +424 -0
  32. package/dist/src/common/store-module-access-plan.js.map +1 -0
  33. package/dist/src/common/store-module-alter-column.d.ts +23 -0
  34. package/dist/src/common/store-module-alter-column.d.ts.map +1 -0
  35. package/dist/src/common/store-module-alter-column.js +393 -0
  36. package/dist/src/common/store-module-alter-column.js.map +1 -0
  37. package/dist/src/common/store-module-alter.d.ts +55 -0
  38. package/dist/src/common/store-module-alter.d.ts.map +1 -0
  39. package/dist/src/common/store-module-alter.js +519 -0
  40. package/dist/src/common/store-module-alter.js.map +1 -0
  41. package/dist/src/common/store-module-base.d.ts +268 -0
  42. package/dist/src/common/store-module-base.d.ts.map +1 -0
  43. package/dist/src/common/store-module-base.js +362 -0
  44. package/dist/src/common/store-module-base.js.map +1 -0
  45. package/dist/src/common/store-module-catalog.d.ts +269 -0
  46. package/dist/src/common/store-module-catalog.d.ts.map +1 -0
  47. package/dist/src/common/store-module-catalog.js +462 -0
  48. package/dist/src/common/store-module-catalog.js.map +1 -0
  49. package/dist/src/common/store-module-index-build.d.ts +88 -0
  50. package/dist/src/common/store-module-index-build.d.ts.map +1 -0
  51. package/dist/src/common/store-module-index-build.js +280 -0
  52. package/dist/src/common/store-module-index-build.js.map +1 -0
  53. package/dist/src/common/store-module-index.d.ts +116 -0
  54. package/dist/src/common/store-module-index.d.ts.map +1 -0
  55. package/dist/src/common/store-module-index.js +373 -0
  56. package/dist/src/common/store-module-index.js.map +1 -0
  57. package/dist/src/common/store-module-rename.d.ts +49 -0
  58. package/dist/src/common/store-module-rename.d.ts.map +1 -0
  59. package/dist/src/common/store-module-rename.js +244 -0
  60. package/dist/src/common/store-module-rename.js.map +1 -0
  61. package/dist/src/common/store-module-schema-rewrite.d.ts +57 -0
  62. package/dist/src/common/store-module-schema-rewrite.d.ts.map +1 -0
  63. package/dist/src/common/store-module-schema-rewrite.js +140 -0
  64. package/dist/src/common/store-module-schema-rewrite.js.map +1 -0
  65. package/dist/src/common/store-module-schema-sync.d.ts +232 -0
  66. package/dist/src/common/store-module-schema-sync.d.ts.map +1 -0
  67. package/dist/src/common/store-module-schema-sync.js +529 -0
  68. package/dist/src/common/store-module-schema-sync.js.map +1 -0
  69. package/dist/src/common/store-module.d.ts +43 -909
  70. package/dist/src/common/store-module.d.ts.map +1 -1
  71. package/dist/src/common/store-module.js +184 -3276
  72. package/dist/src/common/store-module.js.map +1 -1
  73. package/dist/src/common/store-table-base.d.ts +523 -0
  74. package/dist/src/common/store-table-base.d.ts.map +1 -0
  75. package/dist/src/common/store-table-base.js +878 -0
  76. package/dist/src/common/store-table-base.js.map +1 -0
  77. package/dist/src/common/store-table-constraints.d.ts +237 -0
  78. package/dist/src/common/store-table-constraints.d.ts.map +1 -0
  79. package/dist/src/common/store-table-constraints.js +624 -0
  80. package/dist/src/common/store-table-constraints.js.map +1 -0
  81. package/dist/src/common/store-table-scan.d.ts +415 -0
  82. package/dist/src/common/store-table-scan.d.ts.map +1 -0
  83. package/dist/src/common/store-table-scan.js +821 -0
  84. package/dist/src/common/store-table-scan.js.map +1 -0
  85. package/dist/src/common/store-table.d.ts +71 -1144
  86. package/dist/src/common/store-table.d.ts.map +1 -1
  87. package/dist/src/common/store-table.js +166 -2383
  88. package/dist/src/common/store-table.js.map +1 -1
  89. package/dist/src/testing/index.d.ts +12 -0
  90. package/dist/src/testing/index.d.ts.map +1 -0
  91. package/dist/src/testing/index.js +12 -0
  92. package/dist/src/testing/index.js.map +1 -0
  93. package/dist/src/testing/kv-assert.d.ts +19 -0
  94. package/dist/src/testing/kv-assert.d.ts.map +1 -0
  95. package/dist/src/testing/kv-assert.js +25 -0
  96. package/dist/src/testing/kv-assert.js.map +1 -0
  97. package/dist/src/testing/kv-conformance.d.ts.map +1 -1
  98. package/dist/src/testing/kv-conformance.js +1 -15
  99. package/dist/src/testing/kv-conformance.js.map +1 -1
  100. package/dist/src/testing/kv-provider-conformance.d.ts +54 -0
  101. package/dist/src/testing/kv-provider-conformance.d.ts.map +1 -0
  102. package/dist/src/testing/kv-provider-conformance.js +183 -0
  103. package/dist/src/testing/kv-provider-conformance.js.map +1 -0
  104. package/package.json +8 -8
@@ -0,0 +1,821 @@
1
+ /**
2
+ * The read path of the KVStore-backed virtual table: turning a pushed predicate
3
+ * into a byte window over the data store or a secondary index, iterating that
4
+ * window, and re-checking every pushed constraint under the column's real
5
+ * collation.
6
+ *
7
+ * Second layer of the store-table chain:
8
+ * StoreTableBase -> StoreTableScan -> StoreTableConstraints -> StoreTable
9
+ */
10
+ import { IndexConstraintOp, QuereusError, StatusCode, compareSqlValuesFast, createTypedComparator, hasSemanticOrdering, BINARY_COLLATION, decodeIdxStr, planKindFromCode, } from '@quereus/quereus';
11
+ import { bytesToHex, compareBytes } from './bytes.js';
12
+ import { buildIndexPrefixBounds, buildFullScanBounds, } from './key-builder.js';
13
+ import { deserializeRow, } from './serialization.js';
14
+ import { indexLeadingRangeIsOrderSafe, indexPrefixSeekIsCollationExact, pkOrderPreservingPrefixLength, resolveIndexKeyCollations } from './pk-key-resolution.js';
15
+ import { StoreTableBase } from './store-table-base.js';
16
+ /**
17
+ * Read-path layer of the generic KVStore-backed virtual table.
18
+ *
19
+ * Every arm below reads the EFFECTIVE row state (see
20
+ * {@link StoreTableBase.iterateEffective}), so a byte window narrowed here still
21
+ * honors read-your-own-writes.
22
+ */
23
+ export class StoreTableScan extends StoreTableBase {
24
+ /**
25
+ * Query the table with optional filters.
26
+ *
27
+ * All three access arms read the EFFECTIVE row state: the committed store
28
+ * merged with this table's coordinator's pending ops when a transaction is
29
+ * active (read-your-own-writes — see {@link iterateEffective} /
30
+ * {@link readLiveRowByPk}). Merged emission stays in encoded-PK-key order,
31
+ * preserving the module's `providesOrdering` / `monotonicOn` advertisements.
32
+ */
33
+ async *query(filterInfo) {
34
+ const store = await this.ensureStore();
35
+ // Multi-seek (`plan=5`, an IN-list served as N point seeks) dispatches FIRST —
36
+ // before analyzePKAccess: the FilterInfo carries N*W EQ constraints, so on a
37
+ // table whose PK column is also the leading column of the chosen index,
38
+ // analyzePKAccess would match the FIRST equality and answer a single-value
39
+ // point lookup — one list value's rows, a silent wrong result.
40
+ const idxSpec = decodeIdxStr(filterInfo.idxStr);
41
+ if (idxSpec && planKindFromCode(idxSpec.plan) === 'multiSeek') {
42
+ yield* this.scanMultiSeek(idxSpec, filterInfo);
43
+ return;
44
+ }
45
+ const pkAccess = this.analyzePKAccess(filterInfo);
46
+ if (pkAccess.type === 'point') {
47
+ const row = await this.readLiveRowByPk(pkAccess.values);
48
+ if (row && this.matchesFilters(row, filterInfo, this.resolveFilterCollations(filterInfo))) {
49
+ yield row;
50
+ }
51
+ return;
52
+ }
53
+ if (pkAccess.type === 'range') {
54
+ yield* this.scanPKRange(store, pkAccess, filterInfo);
55
+ return;
56
+ }
57
+ // Secondary-index scan arm — reached only when the predicate did NOT resolve
58
+ // to a PK point/range (PK access is cheaper and already handled above). When
59
+ // the planner chose a secondary index (idxStr carries `idx=<name>(…)`), derive
60
+ // its byte window and iterate it instead of full-scanning.
61
+ const indexAccess = this.analyzeIndexAccess(filterInfo);
62
+ if (indexAccess) {
63
+ const indexStore = await this.ensureIndexStore(indexAccess.index.name);
64
+ yield* this.scanIndex(indexStore, indexAccess, filterInfo);
65
+ return;
66
+ }
67
+ // Full table scan
68
+ const collations = this.resolveFilterCollations(filterInfo);
69
+ const bounds = buildFullScanBounds();
70
+ for await (const entry of this.iterateEffective(store, bounds)) {
71
+ const row = deserializeRow(entry.value);
72
+ if (this.matchesFilters(row, filterInfo, collations)) {
73
+ yield row;
74
+ }
75
+ }
76
+ }
77
+ /**
78
+ * True when a byte window over the LEADING PK column reproduces the comparator's order
79
+ * — the precondition {@link buildPKRangeBounds} needs, and the exact condition
80
+ * `computeBestAccessPlan` (store-module-access-plan.ts) uses before claiming the range filters handled.
81
+ * When false, the range arm degrades to a full scan + `matchesFilters` residual.
82
+ */
83
+ leadingPkRangeIsOrderSafe() {
84
+ return pkOrderPreservingPrefixLength(this.db, this.tableSchema, this.pkKeyCollations, this.encodeOptions.collation ?? 'NOCASE') >= 1;
85
+ }
86
+ /**
87
+ * True when some PK member's logical type carries semantic ordering (TIMESPAN,
88
+ * JSON). Such PKs decline the point arm and full-scan, where
89
+ * {@link matchesFilters} applies the type's compare. Historically required —
90
+ * byte-key equality was a strict subset of the type's equality ('PT1H' ≡
91
+ * 'PT60M' elapsed-time-equal, byte-distinct) and a point window under-fetched
92
+ * with no residual able to resurrect a skipped row. Both types' key transforms
93
+ * (see {@link storeSemanticKeyTransform}) now make byte equality the type's
94
+ * equality, so the decline is conservative; re-opening is tracked in backlog
95
+ * `feat-reopen-timespan-store-seeks`. (Range windows and ordering
96
+ * advertisements are already declined by {@link keyOrderMatchesCollation}.)
97
+ */
98
+ pkHasSemanticOrderingMember() {
99
+ const schema = this.tableSchema;
100
+ return schema.primaryKeyDefinition.some(def => hasSemanticOrdering(schema.columns[def.index]?.logicalType));
101
+ }
102
+ /** Analyze filter info to determine PK access pattern. */
103
+ analyzePKAccess(filterInfo) {
104
+ const schema = this.tableSchema;
105
+ const pkColumns = schema.primaryKeyDefinition.map(pk => pk.index);
106
+ if (pkColumns.length === 0) {
107
+ return { type: 'scan' };
108
+ }
109
+ // Check for equality on all PK columns
110
+ const eqValues = new Array(pkColumns.length);
111
+ let allEq = true;
112
+ for (let i = 0; i < pkColumns.length; i++) {
113
+ const pkColIdx = pkColumns[i];
114
+ const eqConstraintEntry = filterInfo.constraints?.find(c => c.constraint.iColumn === pkColIdx && c.constraint.op === IndexConstraintOp.EQ);
115
+ if (eqConstraintEntry && eqConstraintEntry.argvIndex > 0) {
116
+ eqValues[i] = filterInfo.args[eqConstraintEntry.argvIndex - 1];
117
+ }
118
+ else {
119
+ allEq = false;
120
+ break;
121
+ }
122
+ }
123
+ if (allEq && !this.pkHasSemanticOrderingMember()) {
124
+ return { type: 'point', values: eqValues };
125
+ }
126
+ // Check for range constraints on first PK column
127
+ const firstPkCol = pkColumns[0];
128
+ const rangeOps = [IndexConstraintOp.LT, IndexConstraintOp.LE, IndexConstraintOp.GT, IndexConstraintOp.GE];
129
+ const rangeConstraints = filterInfo.constraints?.filter(c => c.constraint.iColumn === firstPkCol && rangeOps.includes(c.constraint.op)) || [];
130
+ // A range window is only sound when the leading PK column's key bytes order the way
131
+ // its comparator does; otherwise fall through to the full scan, where matchesFilters
132
+ // applies the range under the real comparator.
133
+ if (rangeConstraints.length > 0 && this.leadingPkRangeIsOrderSafe()) {
134
+ return {
135
+ type: 'range',
136
+ columnIndex: firstPkCol,
137
+ constraints: rangeConstraints.map(c => ({
138
+ columnIndex: c.constraint.iColumn,
139
+ op: c.constraint.op,
140
+ value: c.argvIndex > 0 ? filterInfo.args[c.argvIndex - 1] : undefined,
141
+ })),
142
+ };
143
+ }
144
+ return { type: 'scan' };
145
+ }
146
+ /**
147
+ * Convert a leading-PK-column range access into one seek + early-terminate
148
+ * iterate window.
149
+ *
150
+ * Each LT/LE/GT/GE constraint's bound value is encoded under the SAME
151
+ * per-column DESC direction and key collation as the data keys (via
152
+ * {@link encodePkPrefixBounds}), giving the byte region `[lo, hi)` whose
153
+ * leading column equals that value (`lo = encode([x])`,
154
+ * `hi = incrementLastByte(lo)`). The op maps that region's endpoints onto a
155
+ * `gte`/`lt` window; because a DESC column bit-inverts its bytes (larger value
156
+ * ⇒ smaller bytes), the lower/upper assignment swaps with direction:
157
+ *
158
+ * | op | ASC | DESC |
159
+ * |----|----------|----------|
160
+ * | GE | gte = lo | lt = hi |
161
+ * | GT | gte = hi | lt = lo |
162
+ * | LE | lt = hi | gte = lo |
163
+ * | LT | lt = lo | gte = hi |
164
+ *
165
+ * Across constraints (BETWEEN ⇒ one lower + one upper; a redundant same-side
166
+ * pair ⇒ the tighter wins) we keep the MAX lower candidate for `gte` and the
167
+ * MIN upper candidate for `lt`. A candidate that resolves to `undefined` (an
168
+ * `hi` whose increment overflowed all-0xff) leaves that side unbounded — a safe
169
+ * SUPERSET, since {@link matchesFilters} stays the authoritative collation-aware
170
+ * row filter. A NULL/missing bound value is likewise skipped (the planner never
171
+ * pushes `= NULL`, and a range op against NULL rejects every row in matchesFilters).
172
+ *
173
+ * NOTE: a range window over a text PK column is sound only when the column's key
174
+ * normalizer is ORDER-preserving with respect to its comparator — i.e. the comparator
175
+ * orders two strings the way memcmp orders their normalized bytes. That is NOT implied
176
+ * by `db.registerCollation`'s normalizer contract, which promises only an equality
177
+ * partition, and a built-in NAME may be re-registered with a comparator + normalizer
178
+ * pair that preserves equality while inverting order. This method is therefore only
179
+ * ever reached under {@link leadingPkRangeIsOrderSafe} — enforced by
180
+ * {@link analyzePKAccess} here and mirrored by `computeBestAccessPlan` (store-module-access-plan.ts)
181
+ * before it claims the range filters handled. A collation without the
182
+ * `orderPreserving` assertion costs the seek, never a row.
183
+ */
184
+ buildPKRangeBounds(access) {
185
+ const full = buildFullScanBounds();
186
+ const constraints = access.constraints;
187
+ if (!constraints || constraints.length === 0)
188
+ return full;
189
+ const dir = this.pkDirections[0];
190
+ let gte = full.gte;
191
+ let lt;
192
+ for (const c of constraints) {
193
+ if (c.value === undefined || c.value === null)
194
+ continue;
195
+ const { gte: lo, lt: hi } = this.encodePkPrefixBounds([c.value]);
196
+ const lower = !dir
197
+ ? (c.op === IndexConstraintOp.GE ? lo : c.op === IndexConstraintOp.GT ? hi : undefined)
198
+ : (c.op === IndexConstraintOp.LE ? lo : c.op === IndexConstraintOp.LT ? hi : undefined);
199
+ const upper = !dir
200
+ ? (c.op === IndexConstraintOp.LE ? hi : c.op === IndexConstraintOp.LT ? lo : undefined)
201
+ : (c.op === IndexConstraintOp.GE ? hi : c.op === IndexConstraintOp.GT ? lo : undefined);
202
+ if (lower && compareBytes(lower, gte) > 0)
203
+ gte = lower;
204
+ if (upper && (lt === undefined || compareBytes(upper, lt) < 0))
205
+ lt = upper;
206
+ }
207
+ return lt === undefined ? { gte } : { gte, lt };
208
+ }
209
+ /**
210
+ * Scan a leading-PK-column range, seeking to the window start and
211
+ * early-terminating at its end.
212
+ *
213
+ * {@link buildPKRangeBounds} converts the LT/LE/GT/GE constraints into one
214
+ * encoded-byte `gte`/`lt` window under the same per-column DESC directions and
215
+ * key collations the data keys use, so the iterate visits a SUPERSET of the
216
+ * qualifying rows (a collation widening or the bound-byte increment can
217
+ * over-fetch, never under-fetch). {@link matchesFilters} stays the authoritative
218
+ * collation-aware row filter. {@link iterateEffective} restricts the pending
219
+ * merge to the same `bounds`, so read-your-own-writes holds on the narrowed window.
220
+ */
221
+ async *scanPKRange(store, access, filterInfo) {
222
+ const collations = this.resolveFilterCollations(filterInfo);
223
+ const bounds = this.buildPKRangeBounds(access);
224
+ for await (const entry of this.iterateEffective(store, bounds)) {
225
+ const row = deserializeRow(entry.value);
226
+ if (this.matchesFilters(row, filterInfo, collations)) {
227
+ yield row;
228
+ }
229
+ }
230
+ }
231
+ /**
232
+ * Resolve the secondary index chosen by the planner from `filterInfo.idxStr`.
233
+ *
234
+ * The planner emits `idx=<name>(<n>);plan=…` when its access plan set both an
235
+ * `indexName` and `seekColumnIndexes` (see `getBestAccessPlan` and
236
+ * rule-select-access-path.ts). Decoding goes through the engine's shared
237
+ * `decodeIdxStr`, so the store, the in-memory vtab, and the isolation overlay all
238
+ * read one format. Returns null for the PK/scan sentinels (`_primary_`, `fullscan`,
239
+ * `empty`), an idxStr that names no index, or a name absent from `schema.indexes` —
240
+ * every one of which routes back to a PK/full-scan arm.
241
+ */
242
+ resolveIndexFromIdxStr(idxStr) {
243
+ const spec = decodeIdxStr(idxStr);
244
+ if (!spec)
245
+ return null;
246
+ const name = spec.indexName;
247
+ if (!name || name === '_primary_')
248
+ return null;
249
+ const indexes = this.tableSchema?.indexes ?? [];
250
+ return indexes.find(i => i.name.toLowerCase() === name.toLowerCase()) ?? null;
251
+ }
252
+ /**
253
+ * Analyze filter info to determine a secondary-index access pattern, mirroring
254
+ * {@link analyzePKAccess} but over the index chosen in `idxStr`.
255
+ *
256
+ * A contiguous leading-prefix EQ on the index columns yields a `point` window
257
+ * (the prefix covers every entry sharing those leading values — an index seek
258
+ * is a PREFIX scan, not a single row, since the index need not be unique and
259
+ * the PK suffix varies); otherwise a range (LT/LE/GT/GE) on the LEADING index
260
+ * column yields a `range` window. Returns null when neither applies or when the
261
+ * index is unresolved. {@link matchesFilters} stays the authoritative row filter,
262
+ * so the window need only be a SUPERSET.
263
+ *
264
+ * Index-column bytes are encoded under each column's own key collation
265
+ * ({@link indexKeyCollations}); {@link matchesFilters} re-checks a fetched row under the
266
+ * index column's `COLLATE` else the table column's declared collation. The EQ/prefix
267
+ * window is EXACTLY the qualifying set when those two agree, which
268
+ * {@link indexPrefixSeekIsCollationExact} decides; the RANGE window additionally equates
269
+ * memcmp of the key bytes with the residual's comparison ORDER, which
270
+ * {@link indexRangeIsOrderSafe} decides. `tryIndexAccessPlan`
271
+ * (store-module-access-plan.ts) consults the SAME two predicates before claiming the
272
+ * filters handled, so the two decisions cannot disagree. Either failing returns null and
273
+ * the caller full-scans, where the residual is authoritative.
274
+ */
275
+ analyzeIndexAccess(filterInfo) {
276
+ const index = this.resolveIndexFromIdxStr(filterInfo.idxStr);
277
+ if (!index)
278
+ return null;
279
+ const indexCols = index.columns.map(c => c.index);
280
+ const indexDirections = index.columns.map(c => !!c.desc);
281
+ const indexCollations = this.indexKeyCollations(index);
282
+ // Contiguous leading-prefix EQ → point/prefix window. A prefix member whose
283
+ // logical type carries semantic ordering stops the prefix: its byte-equality
284
+ // window under-fetches the type's equality (see pkHasSemanticOrderingMember),
285
+ // and a skipped row cannot be resurrected by the residual.
286
+ const eqValues = [];
287
+ for (let i = 0; i < indexCols.length; i++) {
288
+ if (hasSemanticOrdering(this.tableSchema.columns[indexCols[i]]?.logicalType))
289
+ break;
290
+ const eq = filterInfo.constraints?.find(c => c.constraint.iColumn === indexCols[i]
291
+ && c.constraint.op === IndexConstraintOp.EQ
292
+ && c.argvIndex > 0);
293
+ if (!eq)
294
+ break;
295
+ eqValues.push(filterInfo.args[eq.argvIndex - 1]);
296
+ }
297
+ if (eqValues.length > 0) {
298
+ // Decline rather than fall through to the range arm: an EQ prefix whose key
299
+ // collation differs from the residual's comparison collation would under-fetch,
300
+ // and the planner declined the same shape, so the residual Filter is still there.
301
+ if (!indexPrefixSeekIsCollationExact(this.tableSchema.columns, index, indexCollations, eqValues.length)) {
302
+ return null;
303
+ }
304
+ const bounds = buildIndexPrefixBounds(eqValues, this.encodeOptions, indexDirections.slice(0, eqValues.length), indexCollations.slice(0, eqValues.length));
305
+ return { index, type: 'point', bounds };
306
+ }
307
+ // Else a range on the LEADING index column.
308
+ const leadingCol = indexCols[0];
309
+ const rangeOps = [IndexConstraintOp.LT, IndexConstraintOp.LE, IndexConstraintOp.GT, IndexConstraintOp.GE];
310
+ const rangeConstraints = (filterInfo.constraints ?? []).filter(c => c.constraint.iColumn === leadingCol && rangeOps.includes(c.constraint.op));
311
+ if (rangeConstraints.length > 0 && this.indexRangeIsOrderSafe(index)) {
312
+ const bounds = this.buildIndexRangeBounds(rangeConstraints.map(c => ({
313
+ op: c.constraint.op,
314
+ value: c.argvIndex > 0 ? filterInfo.args[c.argvIndex - 1] : undefined,
315
+ })), indexDirections[0], indexCollations[0]);
316
+ return { index, type: 'range', bounds };
317
+ }
318
+ return null;
319
+ }
320
+ /**
321
+ * Lazy cache behind {@link indexKeyCollations}: one resolved array per index-schema
322
+ * object, invalidated when the column array it was resolved against is replaced (an
323
+ * ALTER can retype a column without minting new index objects, so the index identity
324
+ * alone is not a safe key).
325
+ */
326
+ indexKeyCollationsCache = new WeakMap();
327
+ /**
328
+ * Per-column KEY collation for `index`'s own columns, memoized — see
329
+ * {@link resolveIndexKeyCollations}. The one resolution every scan-side encode site
330
+ * ({@link analyzeIndexAccess}, {@link buildIndexRangeBounds}, {@link scanMultiSeek})
331
+ * threads into `buildIndexPrefixBounds`, so a scan window can never address
332
+ * different bytes than the maintenance writes.
333
+ */
334
+ indexKeyCollations(index) {
335
+ const columns = this.tableSchema.columns;
336
+ const cached = this.indexKeyCollationsCache.get(index);
337
+ if (cached && cached.columns === columns)
338
+ return cached.collations;
339
+ const collations = resolveIndexKeyCollations(index, columns);
340
+ this.indexKeyCollationsCache.set(index, { columns, collations });
341
+ return collations;
342
+ }
343
+ /**
344
+ * Per-column comparators stating the store's actual index-key BYTE order for
345
+ * `indexName` — the `VirtualTable.getIndexComparator` isolation hook, mirroring
346
+ * `MemoryTable.getIndexComparator`. The isolation layer merges the overlay's pending
347
+ * rows against this table's index scan by `(indexKey, PK)` sort key and prefers these
348
+ * over its descriptor-derived fallback, so each column's comparator must reproduce
349
+ * the order {@link scanIndex} emits in:
350
+ * - the column's KEY collation ({@link indexKeyCollations}: index COLLATE, else the
351
+ * table column's declared collation, else BINARY) for text;
352
+ * - the logical type's `compare` for a semantic-ordering column (its key bytes
353
+ * encode through an order-preserving transform — see `storeSemanticKeyTransform`);
354
+ * - negated for a DESC column (its key bytes are bit-inverted).
355
+ * Resolved against the MATERIALIZED schema so a hidden `_uc_*` name resolves too.
356
+ *
357
+ * NOTE: for a text column this states the COMPARATOR's order, which is the byte order
358
+ * only while the collation's key normalizer preserves order (`_isCollationOrderPreserving`
359
+ * — asserted by the built-ins, opt-in for a custom one; see keyOrderMatchesCollation).
360
+ * Under an equality-only custom collation the emitted byte order and this comparator can
361
+ * disagree, misplacing an overlay row within an index-key-equal group. Same exposure the
362
+ * isolation layer's descriptor fallback carried before this method existed, so nothing
363
+ * regressed; if a custom equality-only collation on an INDEX column ever ships, gate this
364
+ * on the assertion (returning undefined declines to the fallback, which is no better —
365
+ * the real fix is to make the store emit in comparator order or the merge tolerate it).
366
+ */
367
+ getIndexComparator(indexName) {
368
+ const schema = this.materializedSchema;
369
+ const index = schema.indexes?.find(ix => ix.name.toLowerCase() === indexName.toLowerCase());
370
+ if (!index)
371
+ return undefined;
372
+ const keyCollations = this.indexKeyCollations(index);
373
+ return index.columns.map((col, i) => {
374
+ const columnSchema = schema.columns[col.index];
375
+ const name = keyCollations[i];
376
+ const collationFunc = name ? this.collationResolver(name) : undefined;
377
+ const typedComparator = createTypedComparator(columnSchema.logicalType, collationFunc);
378
+ return col.desc
379
+ ? (a, b) => -typedComparator(a, b)
380
+ : typedComparator;
381
+ });
382
+ }
383
+ /**
384
+ * True when a byte window over the LEADING column of `index` reproduces the order the
385
+ * residual comparison uses. Delegates to {@link indexLeadingRangeIsOrderSafe} — the SAME
386
+ * call the range arm of `tryIndexAccessPlan` (store-module-access-plan.ts) makes before
387
+ * it marks the range filters handled, so the "build a window" and "mark handled"
388
+ * decisions cannot disagree. The memoized {@link indexKeyCollations} is passed as the
389
+ * key side, so the predicate judges the bytes this scan actually addresses.
390
+ */
391
+ indexRangeIsOrderSafe(index) {
392
+ return indexLeadingRangeIsOrderSafe(this.db, this.tableSchema.columns, index, this.indexKeyCollations(index));
393
+ }
394
+ /**
395
+ * Convert leading-index-column LT/LE/GT/GE constraints into one encoded-byte
396
+ * `gte`/`lt` window — the secondary-index analogue of {@link buildPKRangeBounds}.
397
+ *
398
+ * Each bound value is encoded under the leading index column's own key `collation`
399
+ * ({@link indexKeyCollations}) and DESC `dir` — exactly as {@link buildIndexKey}
400
+ * encodes that column — via {@link buildIndexPrefixBounds}, giving the byte region
401
+ * `[lo, hi)` whose leading column equals that value. The op maps that region's
402
+ * endpoints onto `gte`/`lt`, with the same DESC lower/upper SWAP as the PK path:
403
+ *
404
+ * | op | ASC | DESC |
405
+ * |----|----------|----------|
406
+ * | GE | gte = lo | lt = hi |
407
+ * | GT | gte = hi | lt = lo |
408
+ * | LE | lt = hi | gte = lo |
409
+ * | LT | lt = lo | gte = hi |
410
+ *
411
+ * Across constraints keep the MAX lower and MIN upper. An `undefined` upper (an
412
+ * `hi` whose increment overflowed all-0xff) leaves that side unbounded — a safe
413
+ * SUPERSET. A NULL/missing bound value is skipped (the planner never pushes
414
+ * `= NULL`, and a range op against NULL rejects every row in matchesFilters).
415
+ */
416
+ buildIndexRangeBounds(constraints, dir, collation) {
417
+ const full = buildFullScanBounds();
418
+ let gte = full.gte;
419
+ let lt;
420
+ for (const c of constraints) {
421
+ if (c.value === undefined || c.value === null)
422
+ continue;
423
+ const { gte: lo, lt: hi } = buildIndexPrefixBounds([c.value], this.encodeOptions, [dir], [collation]);
424
+ const lower = !dir
425
+ ? (c.op === IndexConstraintOp.GE ? lo : c.op === IndexConstraintOp.GT ? hi : undefined)
426
+ : (c.op === IndexConstraintOp.LE ? lo : c.op === IndexConstraintOp.LT ? hi : undefined);
427
+ const upper = !dir
428
+ ? (c.op === IndexConstraintOp.LE ? hi : c.op === IndexConstraintOp.LT ? lo : undefined)
429
+ : (c.op === IndexConstraintOp.GE ? hi : c.op === IndexConstraintOp.GT ? lo : undefined);
430
+ if (lower && compareBytes(lower, gte) > 0)
431
+ gte = lower;
432
+ if (upper && (lt === undefined || compareBytes(upper, lt) < 0))
433
+ lt = upper;
434
+ }
435
+ return lt === undefined ? { gte } : { gte, lt };
436
+ }
437
+ /**
438
+ * Scan a secondary index over `access.bounds`, resolving each index entry to its
439
+ * base row and re-filtering.
440
+ *
441
+ * {@link iterateEffective} yields the committed index entries merged with this
442
+ * transaction's pending index puts/deletes (read-your-own-writes over the
443
+ * index), in index-key byte order — the order the isolation overlay merge relies
444
+ * on (`isolated-table.ts` § buildSortKey). We resolve each entry to its row via
445
+ * its stored data-key value WITHOUT reordering, so index-key order is preserved.
446
+ *
447
+ * Defense in depth mirroring the memory layer's live-recheck: a resolved-null
448
+ * row (the entry's row was deleted — a pending index delete would normally
449
+ * suppress the entry, but a committed entry can lag) is skipped, and every
450
+ * resolved row is re-checked by {@link matchesFilters} (the byte window is only
451
+ * a superset, and a stale entry whose indexed column no longer matches is
452
+ * dropped).
453
+ */
454
+ async *scanIndex(indexStore, access, filterInfo, multi) {
455
+ // Re-check each resolved row under the INDEX's per-column collation (see
456
+ // matchesFilters): the planner dropped the residual based on the index
457
+ // column's collation, which an explicit index `COLLATE` can make differ from
458
+ // the table column's declared collation.
459
+ const indexCollations = multi?.collations
460
+ ?? this.resolveFilterCollations(filterInfo, this.indexColumnCollations(access.index));
461
+ for await (const entry of this.iterateEffective(indexStore, access.bounds)) {
462
+ // NOTE: a legacy index store (written before index values carried the data
463
+ // key) holds EMPTY values; a zero-length data key is not a row key, so skip
464
+ // it rather than resolve it to the wrong row. Because the access plan marked
465
+ // the filter handled and dropped the residual, an indexed query over such a
466
+ // store returns NOTHING rather than the matching rows — a silent wrong
467
+ // result, not an error. Backwards compatibility is waived project-wide
468
+ // (AGENTS.md) and no test provider carries on-disk data, so nothing exercises
469
+ // this today. If real persisted stores predating this format come into play,
470
+ // their indexes must be dropped + recreated (or the table rebuilt); the
471
+ // durable fix is to version-stamp the index store and rebuild on open, or to
472
+ // fall back to a full scan the first time an empty value is seen.
473
+ if (entry.value.length === 0)
474
+ continue;
475
+ // Cross-window dedup for a multi-seek: a data key an earlier window already
476
+ // YIELDED is skipped before the data-store read, so a duplicate costs no
477
+ // extra `get`. The seen-set is only ever ADDED to on a yield (below) — adding
478
+ // at visit time would let a stale index entry that fails its residual poison
479
+ // the set and suppress the row's live entry in a later window.
480
+ const dataKeyHex = multi ? bytesToHex(entry.value) : undefined;
481
+ if (dataKeyHex !== undefined && multi.seen.has(dataKeyHex))
482
+ continue;
483
+ // NOTE: one extra data-store `get` per matched index entry — the row lives
484
+ // in the data store, not the index (the index value carries only the data
485
+ // key, no covering payload). Fine now; if index-covered scans ever dominate
486
+ // a profile, consider storing the serialized row as a covering index value,
487
+ // at the cost of an index rewrite on EVERY column change (not just indexed
488
+ // columns) — deliberately not done here.
489
+ const row = await this.readEffectiveRowByKey(entry.value);
490
+ if (!row)
491
+ continue;
492
+ if (this.matchesFilters(row, filterInfo, indexCollations)
493
+ || (multi !== undefined && multi.extraTuples.some(fi => this.matchesFilters(row, fi, indexCollations)))) {
494
+ if (dataKeyHex !== undefined)
495
+ multi.seen.add(dataKeyHex);
496
+ yield row;
497
+ }
498
+ }
499
+ }
500
+ /**
501
+ * Fail loudly on a multi-seek FilterInfo this table cannot serve. The plan already
502
+ * dropped the residual Filter, and {@link matchesFilters} ANDs every pushed
503
+ * constraint — so falling through to the scan arm would AND N mutually-exclusive
504
+ * equalities and return zero rows: a silent wrong answer, not a slow one.
505
+ */
506
+ multiSeekMalformed(filterInfo, why) {
507
+ throw new QuereusError(`Malformed multi-seek FilterInfo (idxStr '${filterInfo.idxStr}') on ${this.schemaName}.${this.tableName}: ${why}`, StatusCode.INTERNAL);
508
+ }
509
+ /**
510
+ * Decode a multi-seek FilterInfo into its N seek tuples of width W. Tuple i pairs
511
+ * `args[i*W … i*W+W-1]` with the same slice of `constraints` (argvIndex runs
512
+ * 1…N*W in order — see rule-select-access-path's multiSeek emission). A tuple with
513
+ * a NULL/undefined component is dropped: IN is set membership and a NULL component
514
+ * matches nothing. The planner pre-reduces literal lists, but a parameter-bound /
515
+ * mixed-binding list reaches here unreduced, so this skip is the only line of
516
+ * defense for those.
517
+ */
518
+ decodeMultiSeekTuples(spec, filterInfo) {
519
+ const seekWidth = Number.parseInt(spec.params.get('seekWidth') ?? '1', 10);
520
+ const inCount = Number.parseInt(spec.params.get('inCount') ?? '0', 10);
521
+ if (!Number.isInteger(seekWidth) || seekWidth < 1) {
522
+ this.multiSeekMalformed(filterInfo, `seekWidth=${spec.params.get('seekWidth')}`);
523
+ }
524
+ if (!Number.isInteger(inCount) || inCount < 1) {
525
+ this.multiSeekMalformed(filterInfo, `inCount=${spec.params.get('inCount')}`);
526
+ }
527
+ const constraints = filterInfo.constraints ?? [];
528
+ if (constraints.length < inCount * seekWidth) {
529
+ this.multiSeekMalformed(filterInfo, `${constraints.length} constraints for ${inCount}×${seekWidth} seek keys`);
530
+ }
531
+ if (filterInfo.args.length < inCount * seekWidth) {
532
+ this.multiSeekMalformed(filterInfo, `${filterInfo.args.length} args for ${inCount}×${seekWidth} seek keys`);
533
+ }
534
+ const tuples = [];
535
+ for (let t = 0; t < inCount; t++) {
536
+ const entries = constraints.slice(t * seekWidth, (t + 1) * seekWidth);
537
+ if (entries.some(e => e.constraint.op !== IndexConstraintOp.EQ || e.argvIndex <= 0)) {
538
+ this.multiSeekMalformed(filterInfo, `seek tuple ${t} carries a non-EQ or unbound constraint`);
539
+ }
540
+ const values = entries.map(e => filterInfo.args[e.argvIndex - 1]);
541
+ if (values.some(v => v === null || v === undefined))
542
+ continue;
543
+ tuples.push({ entries, values });
544
+ }
545
+ return { tuples, seekWidth };
546
+ }
547
+ /**
548
+ * Order one tuple's values to match `keyCols` (the leading index columns, or the
549
+ * PK definition) using each constraint entry's column. The plan's seek columns and
550
+ * the constraint list must agree; a tuple that does not cover exactly those
551
+ * columns is malformed.
552
+ */
553
+ orderTupleValues(tuple, keyCols, filterInfo) {
554
+ const byCol = new Map();
555
+ tuple.entries.forEach((e, i) => byCol.set(e.constraint.iColumn, tuple.values[i]));
556
+ if (byCol.size !== keyCols.length) {
557
+ this.multiSeekMalformed(filterInfo, `seek tuple covers ${byCol.size} columns, expected ${keyCols.length}`);
558
+ }
559
+ return keyCols.map(colIdx => {
560
+ if (!byCol.has(colIdx))
561
+ this.multiSeekMalformed(filterInfo, `seek tuple missing column ${colIdx}`);
562
+ return byCol.get(colIdx);
563
+ });
564
+ }
565
+ /**
566
+ * Serve a multi-seek (`plan=5`) FilterInfo: one point window per distinct
567
+ * IN-list tuple, scanned in ascending encoded-key order.
568
+ *
569
+ * Window order is not cosmetic. Encoded-byte order IS index-key order (per-column
570
+ * DESC inversion is baked into the bytes), and the isolation overlay merges an
571
+ * index scan with its pending rows by (indexKey, PK) — an out-of-order underlying
572
+ * stream misplaces overlay rows in the output. Two overlap hazards are folded
573
+ * away before scanning:
574
+ * - Tuples whose encoded prefix byte-matches (duplicate bound parameters, or
575
+ * case variants under a NOCASE key collation C) share ONE window, each kept
576
+ * as a residual alternative — see {@link MultiSeekWindowContext}.
577
+ * - A window with no finite upper bound (all-0xff prefix — see
578
+ * buildIndexPrefixBounds) contains every later-sorting window outright (any
579
+ * key ≥ an all-0xff prefix necessarily starts with it), so those windows fold
580
+ * into it instead of re-scanning an overlapping range out of order.
581
+ *
582
+ * Emission is lazy per window — `… in (…) limit 1` stops after the first yielded
583
+ * row without materializing the remaining windows. Each window goes through
584
+ * {@link scanIndex} → {@link iterateEffective}, so read-your-own-writes and the
585
+ * stale-entry / deleted-row defenses hold per seek key.
586
+ */
587
+ async *scanMultiSeek(spec, filterInfo) {
588
+ const { tuples, seekWidth } = this.decodeMultiSeekTuples(spec, filterInfo);
589
+ if (spec.indexName === '_primary_') {
590
+ yield* this.scanMultiSeekPrimary(tuples, seekWidth, filterInfo);
591
+ return;
592
+ }
593
+ const index = this.resolveIndexFromIdxStr(filterInfo.idxStr);
594
+ if (!index)
595
+ this.multiSeekMalformed(filterInfo, `no index named '${spec.indexName}'`);
596
+ const indexCols = index.columns.map(c => c.index);
597
+ const indexDirections = index.columns.map(c => !!c.desc);
598
+ if (seekWidth > indexCols.length) {
599
+ this.multiSeekMalformed(filterInfo, `seekWidth ${seekWidth} exceeds ${index.name}'s ${indexCols.length} columns`);
600
+ }
601
+ const seekCols = indexCols.slice(0, seekWidth);
602
+ // The encoded byte windows below carry no residual able to resurrect a
603
+ // skipped row, so a seek column whose byte equality under-fetches the type's
604
+ // equality (TIMESPAN, JSON — see pkHasSemanticOrderingMember) cannot be
605
+ // multi-seeked. `tryIndexAccessPlan` (store-module-access-plan.ts) declines such plans; one
606
+ // arriving anyway is malformed.
607
+ if (seekCols.some(colIdx => hasSemanticOrdering(this.tableSchema.columns[colIdx]?.logicalType))) {
608
+ this.multiSeekMalformed(filterInfo, 'semantic-ordering seek column');
609
+ }
610
+ // Same rationale for the collation gate: the merged windows drop any tuple the
611
+ // bytes exclude, so a prefix whose key collation differs from the one the residual
612
+ // re-compares under would under-fetch with nothing left to repair it.
613
+ // `tryIndexAccessPlan` declines such plans through this same predicate; one
614
+ // arriving anyway is malformed. {@link analyzeIndexAccess} makes the point-window
615
+ // twin of this check.
616
+ const indexKeyCollations = this.indexKeyCollations(index);
617
+ if (!indexPrefixSeekIsCollationExact(this.tableSchema.columns, index, indexKeyCollations, seekWidth)) {
618
+ this.multiSeekMalformed(filterInfo, 'index key collation differs from the comparison collation');
619
+ }
620
+ // One window per distinct encoded tuple prefix (each column under its own key
621
+ // collation C — see indexKeyCollations); C-equal tuples merge into one window,
622
+ // each kept as a residual alternative.
623
+ const seekCollations = indexKeyCollations.slice(0, seekWidth);
624
+ const windows = new Map();
625
+ for (const tuple of tuples) {
626
+ const ordered = this.orderTupleValues(tuple, seekCols, filterInfo);
627
+ const bounds = buildIndexPrefixBounds(ordered, this.encodeOptions, indexDirections.slice(0, seekWidth), seekCollations);
628
+ const hex = bytesToHex(bounds.gte);
629
+ const info = { ...filterInfo, constraints: tuple.entries };
630
+ const existing = windows.get(hex);
631
+ if (existing)
632
+ existing.infos.push(info);
633
+ else
634
+ windows.set(hex, { bounds, infos: [info] });
635
+ }
636
+ if (windows.size === 0)
637
+ return; // every tuple had a NULL component — nothing matches
638
+ const sorted = [...windows.values()].sort((a, b) => compareBytes(a.bounds.gte, b.bounds.gte));
639
+ const disjoint = [];
640
+ for (const w of sorted) {
641
+ const last = disjoint[disjoint.length - 1];
642
+ if (last && last.bounds.lt === undefined)
643
+ last.infos.push(...w.infos);
644
+ else
645
+ disjoint.push(w);
646
+ }
647
+ const indexStore = await this.ensureIndexStore(index.name);
648
+ // Identical for every window (resolveFilterCollations dedups by column), so
649
+ // resolve once and thread it through.
650
+ const collations = this.resolveFilterCollations(filterInfo, this.indexColumnCollations(index));
651
+ const seen = new Set();
652
+ for (const w of disjoint) {
653
+ yield* this.scanIndex(indexStore, { index, type: 'point', bounds: w.bounds }, w.infos[0], { seen, collations, extraTuples: w.infos.slice(1) });
654
+ }
655
+ }
656
+ /**
657
+ * Multi-seek over the PRIMARY key: each tuple is a full PK, resolved by a point
658
+ * read in ascending encoded-data-key order (the table's native emission order).
659
+ *
660
+ * NOT reachable from this module's own plans today: `computeBestAccessPlan` (store-module-access-plan.ts)
661
+ * claims IN-list filters only for secondary indexes (see its EQ_OPS vs EQ_OR_IN_OPS
662
+ * split and tickets/backlog/feat-store-pk-in-list-multiseek). The branch exists so
663
+ * a `_primary_` multi-seek arriving from a future plan gets a correct answer rather
664
+ * than the scan arm's silent zero rows, and it is what PK-IN enablement will build on.
665
+ */
666
+ async *scanMultiSeekPrimary(tuples, seekWidth, filterInfo) {
667
+ const pkColumns = this.tableSchema.primaryKeyDefinition.map(pk => pk.index);
668
+ if (pkColumns.length === 0) {
669
+ this.multiSeekMalformed(filterInfo, 'primary-key multi-seek on a table with no primary key');
670
+ }
671
+ if (seekWidth !== pkColumns.length) {
672
+ this.multiSeekMalformed(filterInfo, `seekWidth ${seekWidth} does not cover the ${pkColumns.length}-column primary key`);
673
+ }
674
+ // Mirrors analyzePKAccess's conservative decline of the point arm for such PKs
675
+ // (see pkHasSemanticOrderingMember); with the residual gone there is no scan to
676
+ // degrade to, so fail loudly rather than risk an under-fetch.
677
+ if (this.pkHasSemanticOrderingMember()) {
678
+ this.multiSeekMalformed(filterInfo, 'semantic-ordering primary-key member');
679
+ }
680
+ // Dedup by encoded data key (collapses K-equal tuples), keeping every merged
681
+ // tuple's residual as an alternative — same rationale as the index branch.
682
+ const points = new Map();
683
+ for (const tuple of tuples) {
684
+ const ordered = this.orderTupleValues(tuple, pkColumns, filterInfo);
685
+ const key = this.encodeDataKey(ordered);
686
+ const hex = bytesToHex(key);
687
+ const info = { ...filterInfo, constraints: tuple.entries };
688
+ const existing = points.get(hex);
689
+ if (existing)
690
+ existing.infos.push(info);
691
+ else
692
+ points.set(hex, { key, infos: [info] });
693
+ }
694
+ const collations = this.resolveFilterCollations(filterInfo);
695
+ for (const p of [...points.values()].sort((a, b) => compareBytes(a.key, b.key))) {
696
+ const row = await this.readEffectiveRowByKey(p.key);
697
+ if (row && p.infos.some(fi => this.matchesFilters(row, fi, collations))) {
698
+ yield row;
699
+ }
700
+ }
701
+ }
702
+ /**
703
+ * Check if a row matches the filter constraints.
704
+ *
705
+ * `collations` maps a constrained column index to the comparison function that
706
+ * column must be re-checked under; every caller builds it once per scan with
707
+ * {@link resolveFilterCollations}, whose doc comment explains how the name is
708
+ * chosen. A column absent from the map compares BINARY — the same result
709
+ * {@link resolveFilterCollations} produces for an undeclared collation, and the
710
+ * only reachable absence, since both walk the constraint list under identical
711
+ * skip conditions.
712
+ */
713
+ matchesFilters(row, filterInfo, collations) {
714
+ if (!filterInfo.constraints || filterInfo.constraints.length === 0) {
715
+ return true;
716
+ }
717
+ for (const constraintEntry of filterInfo.constraints) {
718
+ const { constraint, argvIndex } = constraintEntry;
719
+ if (constraint.iColumn < 0 || argvIndex <= 0) {
720
+ continue;
721
+ }
722
+ const rowValue = row[constraint.iColumn];
723
+ const filterValue = filterInfo.args[argvIndex - 1];
724
+ const collation = collations.get(constraint.iColumn) ?? BINARY_COLLATION;
725
+ // A semantic-ordering column (TIMESPAN, JSON) must filter under the type's
726
+ // compare — the same order the engine's operators and Sort use — or a pushed
727
+ // `d > 'PT90M'` would text-compare and drop rows the predicate admits. The
728
+ // comparator is built per row only on this rare column kind; if a profile
729
+ // ever shows it, resolve it once per scan alongside the collations.
730
+ const logicalType = this.tableSchema.columns[constraint.iColumn]?.logicalType;
731
+ const compare = hasSemanticOrdering(logicalType)
732
+ ? createTypedComparator(logicalType, collation)
733
+ : undefined;
734
+ if (!this.compareValues(rowValue, constraint.op, filterValue, collation, compare)) {
735
+ return false;
736
+ }
737
+ }
738
+ return true;
739
+ }
740
+ /**
741
+ * Resolve, ONCE per scan, the comparison collation function for every pushed
742
+ * constraint column, keyed by column index.
743
+ *
744
+ * The name for a column is its DECLARED collation (absent ⇒ BINARY) — the same
745
+ * resolution the access path's collation-cover analysis uses
746
+ * (indexColumnCollationLookup / primaryKeyCollationLookup) when it decides a
747
+ * pushed constraint is fully covered, and the same source `StoreTableConstraints`'
748
+ * UNIQUE checks compare under. On a collation MATCH the planner drops the residual
749
+ * Filter, so {@link matchesFilters} alone must reproduce the predicate.
750
+ *
751
+ * `indexCollationNames` (from {@link indexColumnCollations}) overrides the
752
+ * declared name for the secondary-index scan arm: the planner's MATCH there is
753
+ * against the INDEX column's collation, which an explicit `COLLATE` on the index
754
+ * can make differ from the table column's.
755
+ *
756
+ * Names resolve against {@link collationResolver}, so an unregistered collation
757
+ * raises `no such collation sequence` at scan setup rather than byte-ordering
758
+ * every row.
759
+ *
760
+ * NOTE: rebuilt on every `query()` / `scanPKRange()` / `scanIndex()` call — one
761
+ * registry lookup per distinct constrained column, dwarfed by the scan's I/O. If a
762
+ * point-lookup-heavy profile ever shows it, memoize on the `FilterInfo`.
763
+ */
764
+ resolveFilterCollations(filterInfo, indexCollationNames) {
765
+ const resolved = new Map();
766
+ if (!filterInfo.constraints)
767
+ return resolved;
768
+ for (const { constraint, argvIndex } of filterInfo.constraints) {
769
+ if (constraint.iColumn < 0 || argvIndex <= 0)
770
+ continue;
771
+ if (resolved.has(constraint.iColumn))
772
+ continue;
773
+ const name = indexCollationNames?.has(constraint.iColumn)
774
+ ? indexCollationNames.get(constraint.iColumn)
775
+ : this.tableSchema.columns[constraint.iColumn]?.collation;
776
+ resolved.set(constraint.iColumn, name ? this.collationResolver(name) : BINARY_COLLATION);
777
+ }
778
+ return resolved;
779
+ }
780
+ /**
781
+ * Effective per-column comparison collation for a secondary index's columns:
782
+ * the index column's own `COLLATE` when present, else the underlying table
783
+ * column's declared collation. Mirrors the resolution `StoreModule`'s
784
+ * index-maintenance UNIQUE dedup uses (`indexCol.collation ?? tableColumn`), so
785
+ * a re-checked index-scan row compares under the same collation the planner used
786
+ * to justify dropping (or keeping) the residual Filter.
787
+ */
788
+ indexColumnCollations(index) {
789
+ const cols = this.tableSchema.columns;
790
+ const map = new Map();
791
+ for (const c of index.columns) {
792
+ map.set(c.index, c.collation ?? cols[c.index]?.collation);
793
+ }
794
+ return map;
795
+ }
796
+ /**
797
+ * Compare two values according to an operator, under `collationFunc` (already
798
+ * resolved by {@link resolveFilterCollations} against this database's collation
799
+ * registry). So the LT/LE/GT/GE range bounds honour a NOCASE/RTRIM/custom column
800
+ * collation rather than a raw BINARY JS comparison — the capability
801
+ * `StoreModule.getBestAccessPlan` advertises via `honorsCollatedRangeBounds`.
802
+ * NULL on either side fails every operator except EQ-with-both-NULL (the
803
+ * internal point-lookup convention; the planner never pushes `= NULL`).
804
+ */
805
+ compareValues(a, op, b, collationFunc, semanticCompare) {
806
+ if (a === null || b === null) {
807
+ return op === IndexConstraintOp.EQ ? a === b : false;
808
+ }
809
+ const cmp = semanticCompare ? semanticCompare(a, b) : compareSqlValuesFast(a, b, collationFunc);
810
+ switch (op) {
811
+ case IndexConstraintOp.EQ: return cmp === 0;
812
+ case IndexConstraintOp.NE: return cmp !== 0;
813
+ case IndexConstraintOp.LT: return cmp < 0;
814
+ case IndexConstraintOp.LE: return cmp <= 0;
815
+ case IndexConstraintOp.GT: return cmp > 0;
816
+ case IndexConstraintOp.GE: return cmp >= 0;
817
+ default: return true;
818
+ }
819
+ }
820
+ }
821
+ //# sourceMappingURL=store-table-scan.js.map