diff --git a/.changeset/29486-string-stored-filter-comparand.md b/.changeset/29486-string-stored-filter-comparand.md new file mode 100644 index 00000000000..29be7997a7e --- /dev/null +++ b/.changeset/29486-string-stored-filter-comparand.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +--- + +feat(objectql, spec): a number or boolean comparand on a text- or option-family field compares as its string, the form the write door stores (#29486) + +Clause-②: yes (widening) — a filter that compares a text-family field (`text`, `textarea`, `email`, `url`, `phone`, `password`, `markdown`, `html`, `richtext`, `code`, `signature`, `qrcode`) or an option-family field (`select`, `radio`, `multiselect`, `checkboxes`, `tags`) with a number or a boolean now matches the rows the write door stored for that value; before, it matched none on every driver, with no error. +Metadata-protocol: semantic +Skills-docs: `content/docs/deployment/cli.mdx` (`os migrate text-scalars`, `os migrate option-codes`) now says a filter on the number reads as the string. No `skills/**` page teaches how a filter reads a comparand on a text or option field. + +Maintainer ruling A on #29486: a number or boolean comparand on a text- or option-family field compares as `String(value)`, the form the write side stores since #29241 (text) and #29562 (options). + +**What answers differently.** + +- `{ code: 42 }`, `{ code: { $in: [42, true] } }` and `{ stage: 3 }` against a `text` / `select` field written `42` / `3`: FROM no row (InMemoryDriver and SQLite measured) TO the rows written `42` or `"42"` (`3` or `"3"`). `$ne` / `$nin` FROM every row TO every row but those. `true` / `false` read as `"true"` / `"false"`, and a `bigint` within ±2^53 as the number it names. +- A range is now a STRING range. `$gt` / `$gte` / `$lt` / `$lte` bounds and `$between` members are narrowed like any comparand, so a range on a text or option field compares strings in the column's order: `{ code: { $gt: 9 } }` does not match `"10"` (`"10"` < `"9"` as strings), and `{ code: { $between: [1, 10] } }` does not match `"5"` (`"5"` > `"10"`). Before, InMemoryDriver and MongoDB matched no row for a number bound (they do not order a number against a string), and SQLite compared by the column's affinity: measured, `{ $gt: 9 }` matched `"alpha"` and `{ $gt: 4, $lt: 5 }` matched `"5"` and `"42"`, where it now matches `"42"` alone. To range over numbers, declare the field as a number. +- Every engine verb that collects a filter (`find`, `findOne`, `count`, `aggregate`, `update`, `delete`), both spellings of `where` (the object form and the `FilterArray` sugar), the per-aggregation `filter` and `having`, and every REST door that reaches them. The comparand is narrowed at the engine's field-aware filter seam, beside the number and boolean doors, so every driver receives the string. +- Unchanged: a string comparand, `null` (the null test, never `"null"`), a `Date`, the text operators (`$contains: 42` is still refused), and every other field type. A scalar comparison on a multi-value option field is still refused by the drivers ("use `$contains`"); only the comparand they are handed changes. +- Rows written before #29241 / #29562 and not yet migrated: a raw `42` on driver-memory with persistence matched `{ code: 42 }` and no longer does, as `{ code: "42" }` never did. Run `os migrate text-scalars --apply` and `os migrate option-codes --apply` (tracked in #29643). + +**In-process APIs.** `@objectstack/spec/data` exports `stringStoredComparandDoorVerdict`, `stringStoredComparandFieldVerdict`, `STRING_STORED_COMPARAND_DOOR_FAMILIES`, `STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS`, `STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS`, the type `StringStoredComparandDoorFieldMeta` / `StringStoredComparandDoorVerdict`, and the cross-driver conformance table `FILTER_STRING_STORED_COMPARAND_CASES` with its fixture (`FILTER_STRING_STORED_COMPARAND_FIELDS`, `FILTER_STRING_STORED_COMPARAND_ROWS`, `StringStoredComparandRow`, `StringStoredComparandCase`). All additive. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index a1cbb3b6c42..2dea1f9b058 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1733,8 +1733,9 @@ by: `3` as `"3"`, `true` as `"true"`. Rows written before that rule keep the form the database stored: the raw number or boolean on driver-memory with persistence, the text `"3.0"`, `"1.0"` or `"0.0"` on SQLite, and raw elements inside a multi-value array on every driver. A filter on `"3"` does not find -those rows, a read hands back the old form, and a unique field admits a new -`"3"` beside an old `"3.0"`. +those rows, nor does a filter on `3`, which a filter reads as `"3"` (a number or +boolean compared with an option field compares as its string); a read hands +back the old form, and a unique field admits a new `"3"` beside an old `"3.0"`. ```bash os migrate option-codes # Dry run: counts per object and field, writes no rows @@ -1759,9 +1760,10 @@ A number or a boolean written to a text field (`text`, `textarea`, `email`, `signature`, `qrcode`) is stored as its string: `42` as `"42"`, `true` as `"true"`. Rows written before that rule keep the form the database stored: the raw number or boolean on driver-memory with persistence, the text `"42.0"`, -`"1.0"` or `"0.0"` on SQLite. A filter on `"42"` does not find those rows, a -read hands back the old form, and a unique field admits a new `"42"` beside an -old `42` or `"42.0"`. +`"1.0"` or `"0.0"` on SQLite. A filter on `"42"` does not find those rows, nor +does a filter on `42`, which a filter reads as `"42"` (a number or boolean +compared with a text field compares as its string); a read hands back the old +form, and a unique field admits a new `"42"` beside an old `42` or `"42.0"`. ```bash os migrate text-scalars # Dry run: counts per object and field, writes no rows diff --git a/packages/drivers/driver-memory/src/memory-comparand-type-conformance.test.ts b/packages/drivers/driver-memory/src/memory-comparand-type-conformance.test.ts index c429ea33161..07967ba5cfb 100644 --- a/packages/drivers/driver-memory/src/memory-comparand-type-conformance.test.ts +++ b/packages/drivers/driver-memory/src/memory-comparand-type-conformance.test.ts @@ -24,6 +24,9 @@ import { describe, it, expect, beforeAll } from 'vitest'; import { FILTER_COMPARAND_TYPE_CASES, FILTER_COMPARAND_TYPE_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_FIELDS, + FILTER_STRING_STORED_COMPARAND_ROWS, parseFilterAST, type FilterCondition, } from '@objectstack/spec/data'; @@ -101,3 +104,45 @@ describe('[#7872] InMemoryDriver.find — comparand-type conformance (behind the ).rejects.toThrow(/BigInt/); }); }); + +/** + * [#29486] `FILTER_STRING_STORED_COMPARAND_CASES`, the driver's half: a number + * or boolean comparand on a text- or option-family field reaches mingo already + * narrowed to the string the write door stored (the engine's declared-type + * door, pinned in `@objectstack/objectql`), so each case's `stored()` filter + * must select exactly its rows here — and the as-written filter, handed to the + * driver directly, still selects none of them: mingo compares `42` with `"42"` + * strictly, which is the cell the door stands in front of. + */ +describe('[#29486] InMemoryDriver.find — a number or boolean comparand on a string-stored field, as the door hands it', () => { + const STRING_TABLE = 'string_stored_conformance'; + let driver: InMemoryDriver; + + beforeAll(async () => { + driver = new InMemoryDriver({ persistence: false }); + await driver.connect(); + await driver.syncSchema(STRING_TABLE, { fields: FILTER_STRING_STORED_COMPARAND_FIELDS as never }); + for (const row of FILTER_STRING_STORED_COMPARAND_ROWS) await driver.create(STRING_TABLE, { ...row }); + }); + + const ids = async (where: FilterCondition | undefined): Promise => { + const rows = await driver.find(STRING_TABLE, { fields: ['id'], where }); + return (rows as Array>) + .map((r) => String(r.id)) + .sort((x, y) => x.localeCompare(y)); + }; + + it('the fixture really is every row', async () => { + expect(await ids(undefined)).toEqual(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => r.id)); + }); + + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, async () => { + expect(await ids(parseFilterAST(c.stored())), c.note).toEqual([...c.expected]); + }); + } + + it('the strict cell still exists on the direct path — { code: 42 } handed to mingo matches no row', async () => { + expect(await ids(parseFilterAST({ code: 42 }))).toEqual([]); + }); +}); diff --git a/packages/drivers/driver-mongodb/src/mongodb-comparand-type-conformance.test.ts b/packages/drivers/driver-mongodb/src/mongodb-comparand-type-conformance.test.ts index 6413c5c282e..f30c3090f78 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-comparand-type-conformance.test.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-comparand-type-conformance.test.ts @@ -35,8 +35,11 @@ import { BSON } from 'mongodb'; import { FILTER_COMPARAND_TYPE_CASES, FILTER_COMPARAND_TYPE_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_ROWS, parseFilterAST, type ComparandTypeRow, + type StringStoredComparandRow, type FilterCondition, } from '@objectstack/spec/data'; import { translateFilter } from './mongodb-filter.js'; @@ -106,7 +109,7 @@ function matchField(value: unknown, cond: unknown): boolean { return value === cond; } -function matchDoc(row: ComparandTypeRow, doc: Record): boolean { +function matchDoc(row: ComparandTypeRow | StringStoredComparandRow, doc: Record): boolean { for (const [key, value] of Object.entries(doc)) { switch (key) { case '$and': @@ -189,3 +192,24 @@ describe('[#7872] driver-mongodb — comparand-type conformance (server-free, be .toEqual(['1', '2']); }); }); + +/** + * [#29486] `FILTER_STRING_STORED_COMPARAND_CASES`, the driver's half: a number + * or boolean comparand on a text- or option-family field reaches + * `translateFilter` already narrowed to the string the write door stored (the + * engine's declared-type door, pinned in `@objectstack/objectql`), so each + * case's `stored()` filter, translated and wire-round-tripped, must select + * exactly its rows — judged by the same strict reader as the table above. + */ +describe('[#29486] driver-mongodb — a number or boolean comparand on a string-stored field, as the door hands it', () => { + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, () => { + const doc = translateFilter(parseFilterAST(c.stored()) as FilterCondition) as Record; + const wire = BSON.deserialize(BSON.serialize(doc)) as Record; + const selected = FILTER_STRING_STORED_COMPARAND_ROWS.filter((row) => matchDoc(row, wire)) + .map((row) => row.id) + .sort((x, y) => x.localeCompare(y)); + expect(selected, c.note).toEqual([...c.expected]); + }); + } +}); diff --git a/packages/drivers/driver-odata/src/odata-driver.conformance.test.ts b/packages/drivers/driver-odata/src/odata-driver.conformance.test.ts index 314fd52bd2b..0c0ec372b78 100644 --- a/packages/drivers/driver-odata/src/odata-driver.conformance.test.ts +++ b/packages/drivers/driver-odata/src/odata-driver.conformance.test.ts @@ -45,6 +45,8 @@ import { FILTER_COMPARAND_TYPE_ROWS, FILTER_LOGIC_CASES, FILTER_LOGIC_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_ROWS, FILTER_TEXT_CASES, FILTER_TEXT_ROWS, PAGINATION_ALL_IDS, @@ -204,6 +206,25 @@ for (const version of VERSIONS) { } }); + // [#29486] Through the engine, as written: the engine's declared-type door narrows a number + // or boolean comparand on the text and select fields to the stored string before the + // OData filter is built, so the as-written filter answers the case's rows end to end. + describe('FILTER_STRING_STORED_COMPARAND_CASES', () => { + const setup = () => boot({ + version, + collation, + properties: [STRING('id', false), STRING('code'), STRING('stage')], + rows: FILTER_STRING_STORED_COMPARAND_ROWS, + fields: { code: text, stage: { type: 'select' } }, + }); + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, async () => { + const { engine } = await setup(); + expect(sortedIds(await engine.find(OBJECT, { where: c.filter(), ...SYSTEM } as never)), c.note).toEqual([...c.expected]); + }); + } + }); + // Not a shared case-set: the shared filter rows negate text, which the driver never pushes // down. A negation on a number is pushed down, under `not`, to a service whose parser reads // OData's precedence (`not` binds tighter than `eq`) and refuses a non-Boolean operand. diff --git a/packages/drivers/driver-sql/src/sql-driver-comparand-type-conformance.test.ts b/packages/drivers/driver-sql/src/sql-driver-comparand-type-conformance.test.ts index 8797a8ee5ea..7279d2380aa 100644 --- a/packages/drivers/driver-sql/src/sql-driver-comparand-type-conformance.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-comparand-type-conformance.test.ts @@ -77,6 +77,8 @@ import type { Knex } from 'knex'; import { FILTER_COMPARAND_TYPE_CASES, FILTER_COMPARAND_TYPE_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_ROWS, parseFilterAST, type FilterCondition, } from '@objectstack/spec/data'; @@ -109,6 +111,55 @@ for (const cell of DIALECT_CELLS) { continue; } declareComparandTypeSweep(cell); + declareStringStoredSweep(cell); +} + +/** + * [#29486] `FILTER_STRING_STORED_COMPARAND_CASES`, the driver's half: a number + * or boolean comparand on a text- or option-family field reaches this driver + * already narrowed to the string the write door stored (the engine's + * declared-type door, pinned in `@objectstack/objectql`), so each case's + * `stored()` filter must select exactly its rows here. The columns are the + * ones `syncSchema` gives a `text` and a `select` field: strings. + */ +function declareStringStoredSweep(cell: DialectCell): void { + describe(`[#29486] SqlDriver — a number or boolean comparand on a string-stored field, as the door hands it (${cell.label})`, () => { + const STRING_TABLE = 'os29486_string_stored'; + let driver: SqlDriver; + let knexInstance: Knex; + + beforeAll(async () => { + driver = new SqlDriver(cell.config()); + knexInstance = driver.getKnex(); + await knexInstance.schema.dropTableIfExists(STRING_TABLE); + await knexInstance.schema.createTable(STRING_TABLE, (t: Knex.TableBuilder) => { + t.string('id').primary(); + t.string('code'); + t.string('stage'); + }); + await knexInstance(STRING_TABLE).insert(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => ({ ...r }))); + }); + + afterAll(async () => { + await knexInstance?.schema.dropTableIfExists(STRING_TABLE).catch(() => {}); + await driver?.disconnect?.(); + }); + + const ids = async (where: FilterCondition | undefined): Promise => { + const rows = await driver.find(STRING_TABLE, { fields: ['id'], where }); + return rows.map((r: any) => String(r.id)).sort((x, y) => x.localeCompare(y)); + }; + + it('the fixture really is every row', async () => { + expect(await ids(undefined)).toEqual(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => r.id)); + }); + + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, async () => { + expect(await ids(parseFilterAST(c.stored())), c.note).toEqual([...c.expected]); + }); + } + }); } function declareComparandTypeSweep(cell: DialectCell): void { diff --git a/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-comparand-type-conformance.test.ts b/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-comparand-type-conformance.test.ts index 8f1bc238877..0bc7bf66527 100644 --- a/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-comparand-type-conformance.test.ts +++ b/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-comparand-type-conformance.test.ts @@ -16,6 +16,8 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { FILTER_COMPARAND_TYPE_CASES, FILTER_COMPARAND_TYPE_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_ROWS, parseFilterAST, type FilterCondition, } from '@objectstack/spec/data'; @@ -84,3 +86,46 @@ describe('[#7872] SqliteWasmDriver — comparand-type conformance (behind the do expect(await ids(undefined)).toEqual(['1', '2']); }); }); + +/** + * [#29486] `FILTER_STRING_STORED_COMPARAND_CASES`, the driver's half: a number + * or boolean comparand on a text- or option-family field reaches this driver + * already narrowed to the string the write door stored (the engine's + * declared-type door, pinned in `@objectstack/objectql`), so each case's + * `stored()` filter must select exactly its rows here. + */ +describe('[#29486] SqliteWasmDriver — a number or boolean comparand on a string-stored field, as the door hands it', () => { + const STRING_TABLE = 'string_stored_conformance'; + let driver: SqliteWasmDriver; + + beforeAll(async () => { + driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.initObjects([ + { name: STRING_TABLE, fields: { code: { type: 'string' }, stage: { type: 'string' } } }, + ]); + for (const row of FILTER_STRING_STORED_COMPARAND_ROWS) { + await driver.create(STRING_TABLE, { ...row }, { bypassTenantAudit: true }); + } + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + const ids = async (where: FilterCondition | undefined): Promise => { + const rows = await driver.find(STRING_TABLE, { fields: ['id'], where }); + return (rows as Array>) + .map((r) => String(r.id)) + .sort((x, y) => x.localeCompare(y)); + }; + + it('the fixture really is every row', async () => { + expect(await ids(undefined)).toEqual(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => r.id)); + }); + + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, async () => { + expect(await ids(parseFilterAST(c.stored())), c.note).toEqual([...c.expected]); + }); + } +}); diff --git a/packages/drivers/driver-turso/src/turso-comparand-type-conformance.test.ts b/packages/drivers/driver-turso/src/turso-comparand-type-conformance.test.ts index f5cded80992..23fbb4ef533 100644 --- a/packages/drivers/driver-turso/src/turso-comparand-type-conformance.test.ts +++ b/packages/drivers/driver-turso/src/turso-comparand-type-conformance.test.ts @@ -19,6 +19,8 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { FILTER_COMPARAND_TYPE_CASES, FILTER_COMPARAND_TYPE_ROWS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_ROWS, parseFilterAST, type FilterCondition, } from '@objectstack/spec/data'; @@ -88,3 +90,46 @@ describe('[#7872] TursoDriver — comparand-type conformance (local mode, behind expect(await ids(undefined)).toEqual(['1', '2']); }); }); + +/** + * [#29486] `FILTER_STRING_STORED_COMPARAND_CASES`, the driver's half: a number + * or boolean comparand on a text- or option-family field reaches this driver + * already narrowed to the string the write door stored (the engine's + * declared-type door, pinned in `@objectstack/objectql`), so each case's + * `stored()` filter must select exactly its rows here. + */ +describe('[#29486] TursoDriver — a number or boolean comparand on a string-stored field, as the door hands it', () => { + const STRING_TABLE = 'string_stored_conformance'; + let driver: TursoDriver; + + beforeAll(async () => { + driver = new TursoDriver({ url: ':memory:' }); + await driver.initObjects([ + { name: STRING_TABLE, fields: { code: { type: 'string' }, stage: { type: 'string' } } }, + ]); + for (const row of FILTER_STRING_STORED_COMPARAND_ROWS) { + await driver.create(STRING_TABLE, { ...row }, { bypassTenantAudit: true }); + } + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + const ids = async (where: FilterCondition | undefined): Promise => { + const rows = await driver.find(STRING_TABLE, { fields: ['id'], where }); + return (rows as Array>) + .map((r) => String(r.id)) + .sort((x, y) => x.localeCompare(y)); + }; + + it('the fixture really is every row', async () => { + expect(await ids(undefined)).toEqual(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => r.id)); + }); + + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + it(c.name, async () => { + expect(await ids(parseFilterAST(c.stored())), c.note).toEqual([...c.expected]); + }); + } +}); diff --git a/packages/objectql/src/engine-boolean-comparand-declared-type-door.test.ts b/packages/objectql/src/engine-boolean-comparand-declared-type-door.test.ts index 553e8516c79..416e481cbfa 100644 --- a/packages/objectql/src/engine-boolean-comparand-declared-type-door.test.ts +++ b/packages/objectql/src/engine-boolean-comparand-declared-type-door.test.ts @@ -51,9 +51,14 @@ import { BOOLEAN_COMPARAND_DOOR_FIXTURE_OBJECT, BOOLEAN_COMPARAND_DOOR_LIST_OPERATORS, BOOLEAN_COMPARAND_DOOR_SCALAR_OPERATORS, + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_FIELDS, NON_BOOLEAN_STRING_FORMS, NON_BOOLEAN_VALUE_FORMS, + STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS, + STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS, lowerFilterCondition, + stringStoredComparandDoorVerdict, normalizeFilterComparandTypes, type BooleanComparandDoorCase, type BooleanComparandDoorNarrowsCase, @@ -217,7 +222,14 @@ describe('[#21333] the boolean-comparand arm at the engine collection point', () it('lets every passing case through UNCHANGED — a boolean, null, a non-boolean field, a flag, a reference', async () => { for (const c of PASSES) { const filter = c.filter(); - expect(await driverWhere(filter), c.name).toEqual(lowered(filter)); + // [#29486] …except where the walk's string-stored arm judges it: the + // table's number on `f_text` (not THIS arm's subject) reaches the + // driver as the string the write stores, by that arm's verdict. + const other = stringStoredComparandDoorVerdict({ type: c.declaredType }, c.comparand); + const expected = other.verdict === 'narrows' + ? JSON.parse(JSON.stringify(filter).replace(JSON.stringify(c.comparand), JSON.stringify(other.value))) + : filter; + expect(await driverWhere(filter), c.name).toEqual(lowered(expected)); } }); @@ -653,3 +665,142 @@ describe('[#21333] the boolean-comparand arm at the engine collection point', () }); }); }); + +/** + * [#29486] The walk's STRING-STORED arm: a number or boolean comparand against + * a declared text- or option-family field reaches the driver as `String(value)`, + * the string the write door stores for it (`@objectstack/spec/data`'s + * `filter-string-stored-comparand-declared-type.ts` is the verdict). The + * cross-driver table `FILTER_STRING_STORED_COMPARAND_CASES` is driven here + * end to end through a recording driver: the driver receives exactly each + * case's `stored()` filter, which every driver suite pins against real stored + * rows (memory, SQL, mongodb). Measured before the arm on InMemoryDriver and + * SQLite: `{ code: 42 }` and `{ stage: 3 }` matched no row written `42` / `3`. + */ +describe('[#29486] the string-stored arm at the engine collection point', () => { + const STRING_OBJECT = 'string_stored_probe'; + const FIXTURE = { + name: STRING_OBJECT, + label: 'String-stored comparand probe', + fields: { + ...FILTER_STRING_STORED_COMPARAND_FIELDS, + email: { name: 'email', type: 'email' }, + tags: { name: 'tags', type: 'multiselect' }, + qty: { name: 'qty', type: 'number' }, + flag: { name: 'flag', type: 'boolean' }, + at: { name: 'at', type: 'datetime' }, + }, + }; + let engine: ObjectQL; + let reads: SeenRead[]; + let writes: SeenRead[]; + + beforeEach(async () => { + const rec = makeRecordingDriver(); + reads = rec.reads; + writes = rec.writes; + engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + engine.registry.registerObject(FIXTURE as any, 'test'); + for (const row of [{ id: 'a', code: 42, stage: 3, qty: 1 }, { id: 'b', code: 'x', stage: true, qty: 2 }]) { + await engine.insert(STRING_OBJECT, { ...row }); + } + reads.length = 0; + writes.length = 0; + }); + + const driverWhere = async (where: unknown): Promise => { + reads.length = 0; + await engine.find(STRING_OBJECT, { where } as EngineQueryOptions); + expect(reads, JSON.stringify(where, (_k, v) => (typeof v === 'bigint' ? `${v}n` : v))).toHaveLength(1); + return reads[0]?.ast?.where; + }; + + it('the write side stored the strings the arm narrows to — the two halves read one value one way', async () => { + const rows = await engine.find(STRING_OBJECT, { where: { id: { $in: ['a', 'b'] } } }); + expect(rows.map((r) => [(r as any).code, (r as any).stage])).toEqual([['42', '3'], ['x', 'true']]); + }); + + it('FILTER_STRING_STORED_COMPARAND_CASES: the driver receives exactly each case\'s stored filter, the caller\'s is untouched', async () => { + expect(FILTER_STRING_STORED_COMPARAND_CASES.length).toBeGreaterThan(0); + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + const filter = c.filter(); + const asWritten = JSON.stringify(filter); + expect(await driverWhere(filter), c.name).toEqual(lowered(c.stored())); + expect(JSON.stringify(filter), `${c.name}: the caller's filter must not be edited`).toBe(asWritten); + } + }); + + it('narrows at every judged position, on every family member probed — implicit, each scalar operator, each list member', async () => { + for (const key of ['code', 'stage', 'email', 'tags']) { + expect(await driverWhere({ [key]: 7 }), key).toEqual(lowered({ [key]: '7' })); + for (const op of STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS) { + expect(await driverWhere({ [key]: { [op]: false } }), `${key}.${op}`).toEqual(lowered({ [key]: { [op]: 'false' } })); + } + for (const op of STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS) { + expect(await driverWhere({ [key]: { [op]: [1, 'z'] } }), `${key}.${op}`).toEqual(lowered({ [key]: { [op]: ['1', 'z'] } })); + } + } + }); + + it('leaves alone what is not a number or boolean, and every field outside the two families', async () => { + const at = new Date(Date.UTC(2026, 0, 1)); + for (const where of [ + { code: '42' }, + { code: null }, + { code: { $ne: null } }, + { code: { $null: true } }, + { code: { $eq: { $field: 'email' } } }, + { code: { $gt: at } }, + { qty: 42 }, + { flag: true }, + { at: { $gt: at } }, + ]) { + expect(await driverWhere(where), JSON.stringify(where)).toEqual(lowered(where)); + } + const schema = engine.registry.getObject(STRING_OBJECT); + for (const where of [{ code: '42' }, { code: null }, { qty: 42 }]) { + expect(narrowNumberComparands(STRING_OBJECT, 'find', schema, where), JSON.stringify(where)).toBe(where); + } + }); + + it('reads a bigint as the number it names on both spellings, and leaves one beyond 2^53 to the comparand-type door', async () => { + expect(await driverWhere({ code: BigInt(42) })).toEqual(lowered({ code: '42' })); + expect(await driverWhere([['code', '=', BigInt(42)]])).toEqual(lowered({ code: '42' })); + reads.length = 0; + const err = await refusalOf(engine.find(STRING_OBJECT, { where: { code: BigInt(2) ** BigInt(53) + BigInt(1) } } as unknown as EngineQueryOptions)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_FILTER', status: 400 }); + expect(reads).toHaveLength(0); + }); + + it('answers the FilterArray sugar and nested structure the same', async () => { + expect(await driverWhere([['code', '=', 42]])).toEqual(lowered({ code: '42' })); + expect(await driverWhere([['stage', '!=', true]])).toEqual(lowered({ stage: { $ne: 'true' } })); + expect(await driverWhere({ $or: [{ code: 42 }, { $not: { stage: { $in: [3] } } }] })) + .toEqual(lowered({ $or: [{ code: '42' }, { $not: { stage: { $in: ['3'] } } }] })); + }); + + it('reaches the write verbs and aggregate\'s `where`', async () => { + await engine.update(STRING_OBJECT, { code: 'y' }, { where: { code: 42 }, multi: true }); + await engine.delete(STRING_OBJECT, { where: { stage: { $in: [3, true] } }, multi: true }); + expect(writes.map((w) => w.ast?.where)).toEqual([lowered({ code: '42' }), lowered({ stage: { $in: ['3', 'true'] } })]); + reads.length = 0; + await engine.aggregate(STRING_OBJECT, { where: { code: 42 }, aggregations: [{ function: 'count', alias: 'n' }] } as EngineAggregateOptions); + expect(reads[0]?.ast?.where).toEqual(lowered({ code: '42' })); + }); + + it('a per-aggregation filter and `having` — the engine\'s own evaluator — count what the stored string counts', async () => { + const counted = async (filter: FilterCondition) => Number(((await engine.aggregate(STRING_OBJECT, { + aggregations: [{ function: 'count', alias: 'all' }, { function: 'count', alias: 'm', filter }], + } as EngineAggregateOptions))[0] as Record).m); + expect(await counted({ code: 42 })).toBe(1); + expect(await counted({ code: 42 })).toBe(await counted({ code: '42' })); + expect(await counted({ stage: { $in: [3, true] } })).toBe(2); + const groups = async (having: FilterCondition) => (await engine.aggregate(STRING_OBJECT, { + groupBy: ['stage'], aggregations: [{ function: 'count', alias: 'n' }], having, + } as EngineAggregateOptions)).map((r) => (r as Record).stage); + expect(await groups({ stage: 3 })).toEqual(['3']); + expect(await groups({ stage: { $ne: true } })).toEqual(['3']); + }); +}); diff --git a/packages/objectql/src/number-comparand-declared-type-door.ts b/packages/objectql/src/number-comparand-declared-type-door.ts index 84e9a0c96c6..acdfa13031d 100644 --- a/packages/objectql/src/number-comparand-declared-type-door.ts +++ b/packages/objectql/src/number-comparand-declared-type-door.ts @@ -166,6 +166,18 @@ * call them, run both arms. At `having` it reads each column's TYPE (a groupBy * of a boolean field), as the no-operator-object arm does. * + * ## [#29486] …and the string-stored arm, at all three positions + * + * The same walk narrows a NUMBER or BOOLEAN comparand against a declared + * text-family or option-family field (`@objectstack/spec/data`'s + * `filter-string-stored-comparand-declared-type.ts`) to `String(value)` — the + * string the write door stores for that value since #29241 / #29562 — so + * `{ code: 42 }` matches a row written `42` (stored `"42"`) on every driver, + * where it matched none. It never refuses. It is asked at every field key + * neither the number arm nor the boolean arm judges (the three classes are + * disjoint), at the same positions ({@link judgeFieldSpec}), so every engine + * site that runs the walk inherits it with no change of its own. + * * @see numberComparandDoorVerdict — the pure verdict (lane 1, `@objectstack/spec`). * @see https://github.com/objectstack-ai/objectstack/issues/20336 (the contract) * @see https://github.com/objectstack-ai/objectstack/issues/20351 (this door) @@ -178,9 +190,12 @@ import { numberComparandDoorVerdict, numberComparandFieldVerdict, numberComparandRefusalMessage, + stringStoredComparandDoorVerdict, + stringStoredComparandFieldVerdict, type BooleanComparandDoorFieldMeta, type NumberComparandDoorFieldMeta, type NumberComparandRefusalSite, + type StringStoredComparandDoorFieldMeta, } from '@objectstack/spec/data'; import { booleanArmFieldMeta, @@ -229,6 +244,12 @@ interface KeyFacts { * where the number arm does not judge. */ readonly boolean: BooleanComparandDoorFieldMeta | null; + /** + * [#29486] The string-stored arm's field meta — `null` when that arm has + * nothing to judge here. Disjoint from the two classes above; the walk asks + * this arm only where neither of them judges. + */ + readonly string: StringStoredComparandDoorFieldMeta | null; /** * [#20546] The column the no-operator-object arm judges — else `null`. * [#20745] Any of its three kinds (a scalar-valued, a relation or a @@ -362,6 +383,17 @@ const booleanArm = (meta: BooleanComparandDoorFieldMeta, ctx: RefusalSiteContext return answer.refused ? { ok: false, refusal: { arm: 'boolean', site: answer.site } } : kept(answer.value); }; +/** + * [#29486] The string-stored arm: a number or boolean comparand against a + * text- or option-family field is narrowed to the string the write stores. It + * never refuses — the spec's verdict answers `narrows` or `passes` only. + */ +const stringStoredArm = (meta: StringStoredComparandDoorFieldMeta): JudgeOne => + (_field, comparand) => { + const verdict = stringStoredComparandDoorVerdict(meta, comparand); + return kept(verdict.verdict === 'narrows' ? verdict.value : comparand); + }; + /** * One comparand at a judged position: the spec's verdict, routed. Whatever * the comparand is — a string, a boolean, a `Date`, an array (#20502) — the @@ -531,8 +563,15 @@ function walkCondition(factsOf: FactsOf, node: unknown, path: string, depth: num // [#21333] …and where the number arm does not judge, the boolean arm // may: the two classes are disjoint, so at most one arm judges a key. const booleanMeta = booleanArmFieldMeta(facts.boolean); - if (!booleanMeta) continue; - judged = judgeFieldSpec(booleanArm(booleanMeta, ctx), key, value, here); + if (booleanMeta) { + judged = judgeFieldSpec(booleanArm(booleanMeta, ctx), key, value, here); + } else { + // [#29486] …and where neither judges, the string-stored arm may: + // a number or boolean against a text- or option-family field. + const stringMeta = facts.string; + if (!stringMeta || stringStoredComparandFieldVerdict(stringMeta) !== 'judged') continue; + judged = judgeFieldSpec(stringStoredArm(stringMeta), key, value, here); + } } } } @@ -571,13 +610,14 @@ function declaredFactsOf(schema: unknown): FactsOf | null { // column all the same, and the arm judges it by the type it stores; // every other undeclared key keeps the registry-less tolerance. const provisioned = provisionedNoOperatorObjectColumn(key); - return provisioned === null ? null : { number: null, boolean: null, column: provisioned }; + return provisioned === null ? null : { number: null, boolean: null, string: null, column: provisioned }; } const meta = fieldMetaOf(fields[key]); if (!meta) return null; - // [#21333] The same declaration slice serves both comparand arms; each - // arm's field verdict decides whether it judges the key. - return { number: meta, boolean: meta, column: declaredNoOperatorObjectColumn(fields[key]) }; + // [#21333] The same declaration slice serves every comparand arm + // ([#29486] the string-stored one too); each arm's field verdict decides + // whether it judges the key. + return { number: meta, boolean: meta, string: meta, column: declaredNoOperatorObjectColumn(fields[key]) }; }; } @@ -734,6 +774,9 @@ export function narrowHavingNumberComparands( // [#21333] A groupBy projection (or a `min` / `max`) of a boolean // field carries that field's type; the boolean arm judges it by that. boolean: type === undefined ? null : { type }, + // [#29486] …and a groupBy (or `min` / `max`) of a text- or + // option-family field carries its stored string; judged by that type. + string: type === undefined ? null : { type }, column: kind === null ? null : { kind, type: type as string }, }; }, diff --git a/packages/rest/src/rest-data-option-scalar-value.test.ts b/packages/rest/src/rest-data-option-scalar-value.test.ts index 1085a77efc0..e1efd545fbc 100644 --- a/packages/rest/src/rest-data-option-scalar-value.test.ts +++ b/packages/rest/src/rest-data-option-scalar-value.test.ts @@ -25,8 +25,9 @@ * The first two rows are the narrowing; the third is SQLite's widening (base * stored `true` and `1` both as `'1.0'`), the same pair #29241 moved on text. * - * Filter face, recorded and NOT changed here (the number comparand on a - * string-stored field waits on #29486's decision): see the last block. + * Filter face: since #29486 (maintainer ruling A) a number or boolean + * comparand on an option field compares as its string reading, the code the + * write stored — see the last block. */ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; @@ -179,21 +180,36 @@ describe('a unique select compares the stored string (#29562, Clause-② narrowi }); /** - * The filter face, RECORDED, not changed: the number comparand on a - * string-stored field is #29486's decision box. This pins today's answer so a - * change there is seen here; it is not this card's contract. + * [#29486] The filter face: a number or boolean comparand on an option field + * compares as `String(value)`, the code the write door stored (maintainer + * ruling A). The engine's declared-type door narrows it before the driver, so + * `{ stage: 3 }` selects both rows the write stored as `"3"`. Before the + * ruling this block pinned `{ stage: 3 }` → no row (both rows hold the string + * `"3"`, and the number matched neither on SQLite or driver-memory). */ -describe('filter face on SQLite: a number comparand against a select written 3 (#29486 decides, recorded only)', () => { - it('{ stage: 3 } and { stage: "3" } against a row written 3 and a row written "3"', async () => { +describe('filter face on SQLite: a number or boolean comparand against a select matches the code the write stored (#29486)', () => { + it('{ stage: 3 } and { stage: "3" } select the same rows — the one written 3 and the one written "3"', async () => { const ctx = await boot(); await ctx.engine.insert('option_rest', { id: 'n', stage: 3 }); await ctx.engine.insert('option_rest', { id: 's', stage: '3' }); + await ctx.engine.insert('option_rest', { id: 't', stage: true }); const ids = async (where: Record) => ((await ctx.engine.find('option_rest', { where })) as Array<{ id: string }>).map((r) => r.id).sort(); expect(await ids({ stage: '3' })).toEqual(['n', 's']); - // Both rows now hold the string "3", and the number comparand matches - // neither (driver-memory answers the same). Base matched the row written - // 3 (stored "3.0") and not the row written "3". - expect(await ids({ stage: 3 })).toEqual([]); + expect(await ids({ stage: 3 })).toEqual(['n', 's']); + expect(await ids({ stage: true })).toEqual(['t']); + expect(await ids({ stage: { $in: [3, true] } })).toEqual(['n', 's', 't']); + expect(await ids({ stage: { $ne: 3 } })).toEqual(['t']); + }); + + it('the REST query door answers the same — POST …/query with a number comparand', async () => { + const ctx = await boot(); + await ctx.engine.insert('option_rest', { id: 'n', stage: 3 }); + await ctx.engine.insert('option_rest', { id: 'x', stage: 'other' }); + const route = '/api/v1/data/:object/query'; + const res = await ctx.call('POST', route, { object: 'option_rest' }, { where: { stage: 3 } }); + expect(res.status, JSON.stringify(res.body)).toBe(200); + const rows = (res.body?.records ?? res.body?.data ?? res.body?.value ?? res.body) as Array<{ id: string }>; + expect(Array.isArray(rows) ? rows.map((r) => r.id) : rows, JSON.stringify(res.body)).toEqual(['n']); }); }); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 3dd6a05f3f6..e896a280065 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -304,6 +304,9 @@ "FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS (const)", + "FILTER_STRING_STORED_COMPARAND_CASES (const)", + "FILTER_STRING_STORED_COMPARAND_FIELDS (const)", + "FILTER_STRING_STORED_COMPARAND_ROWS (const)", "FILTER_SUBTREE_PROVENANCE (const)", "FILTER_TEXT_CASES (const)", "FILTER_TEXT_ROWS (const)", @@ -742,6 +745,9 @@ "SSL_DETAIL_BELONGS_ON_DATASOURCE (const)", "STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS (const)", + "STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", + "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", + "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES (const)", @@ -816,6 +822,10 @@ "StateMachineValidationParsed (type)", "StateMachineValidationSchema (const)", "StringOperatorSchema (const)", + "StringStoredComparandCase (interface)", + "StringStoredComparandDoorFieldMeta (interface)", + "StringStoredComparandDoorVerdict (type)", + "StringStoredComparandRow (interface)", "SysActivityBuiltinType (type)", "TEMPORAL_CASES (const)", "TEMPORAL_NOW (const)", @@ -1086,6 +1096,8 @@ "resolveSearchFields (function)", "seedFile (function)", "sequenceWidth (function)", + "stringStoredComparandDoorVerdict (function)", + "stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods (function)", "suggestDefaultValueToken (function)", "suggestFieldTypeForSqlType (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 24f322456c9..5c3838ae513 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -299,6 +299,9 @@ "FILTER_LOGIC_CASES": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_CASES (const)", "FILTER_LOGIC_ROWS": "src/data/filter-logic-conformance.ts#FILTER_LOGIC_ROWS (const)", "FILTER_OPERATORS": "src/data/filter.zod.ts#FILTER_OPERATORS (const)", + "FILTER_STRING_STORED_COMPARAND_CASES": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_CASES (const)", + "FILTER_STRING_STORED_COMPARAND_FIELDS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_FIELDS (const)", + "FILTER_STRING_STORED_COMPARAND_ROWS": "src/data/filter-comparand-type-conformance.ts#FILTER_STRING_STORED_COMPARAND_ROWS (const)", "FILTER_SUBTREE_PROVENANCE": "src/data/filter-subtree-provenance.ts#FILTER_SUBTREE_PROVENANCE (const)", "FILTER_TEXT_CASES": "src/data/filter-text-conformance.ts#FILTER_TEXT_CASES (const)", "FILTER_TEXT_ROWS": "src/data/filter-text-conformance.ts#FILTER_TEXT_ROWS (const)", @@ -730,6 +733,9 @@ "SSL_DETAIL_BELONGS_ON_DATASOURCE": "src/data/driver/common.zod.ts#SSL_DETAIL_BELONGS_ON_DATASOURCE (const)", "STACK_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS": "src/data/authoring-key-lint.ts#STACK_RUNTIME_MEMBERS (const)", + "STRING_STORED_COMPARAND_DOOR_FAMILIES": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", + "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", + "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", "STRING_VALUE_TYPES": "src/data/field-value.zod.ts#STRING_VALUE_TYPES (const)", "STRUCTURED_JSON_TYPES": "src/data/field-value.zod.ts#STRUCTURED_JSON_TYPES (const)", "SYS_ACTIVITY_BUILTIN_TYPES": "src/data/feed.zod.ts#SYS_ACTIVITY_BUILTIN_TYPES (const)", @@ -804,6 +810,10 @@ "StateMachineValidationParsed": "src/data/validation.zod.ts#StateMachineValidationParsed (type)", "StateMachineValidationSchema": "src/data/validation.zod.ts#StateMachineValidationSchema (const)", "StringOperatorSchema": "src/data/filter.zod.ts#StringOperatorSchema (const)", + "StringStoredComparandCase": "src/data/filter-comparand-type-conformance.ts#StringStoredComparandCase (interface)", + "StringStoredComparandDoorFieldMeta": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorFieldMeta (interface)", + "StringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#StringStoredComparandDoorVerdict (type)", + "StringStoredComparandRow": "src/data/filter-comparand-type-conformance.ts#StringStoredComparandRow (interface)", "SysActivityBuiltinType": "src/data/feed.zod.ts#SysActivityBuiltinType (type)", "TEMPORAL_CASES": "src/data/temporal-conformance.ts#TEMPORAL_CASES (const)", "TEMPORAL_NOW": "src/data/temporal-conformance.ts#TEMPORAL_NOW (const)", @@ -1072,6 +1082,8 @@ "resolveSearchFields": "src/data/search-fields.ts#resolveSearchFields (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", + "stringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandDoorVerdict (function)", + "stringStoredComparandFieldVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandFieldVerdict (function)", "stripLegacyApiMethods": "src/data/object.zod.ts#stripLegacyApiMethods (function)", "suggestDefaultValueToken": "src/data/default-value-shape.ts#suggestDefaultValueToken (function)", "suggestFieldTypeForSqlType": "src/data/type-compat.ts#suggestFieldTypeForSqlType (function)", diff --git a/packages/spec/src/data/filter-comparand-type-conformance.ts b/packages/spec/src/data/filter-comparand-type-conformance.ts index 50de82ab711..2441df1f75c 100644 --- a/packages/spec/src/data/filter-comparand-type-conformance.ts +++ b/packages/spec/src/data/filter-comparand-type-conformance.ts @@ -302,3 +302,183 @@ export const FILTER_COMPARAND_TYPE_CASES: readonly ComparandTypeCase[] = [ mustMention: ['2^53', ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE], }, ] as const; + +/* ──────────────────────────────────────────────────────────────────────────── + * [#29486] A number or boolean comparand on a STRING-STORED field + * ──────────────────────────────────────────────────────────────────────────── */ + +/** + * The fixture's declared fields: a text-family field and an option-family + * field, each holding the string the write door stores for a number or a + * boolean (`42` → `"42"`, `3` → `"3"`, `true` → `"true"`; #29241, #29562), in + * the `{ name, type }` slice a driver's `syncSchema` and the engine's registry + * both take. + * + * `stage` declares no `options`, the shape the write door's own option pins + * register: a declared option code is a system identifier (a lower-case + * letter first), so `"3"` is never one, and the write door refuses `3` on a + * select that declares its codes. A number reaches an option field's storage + * only where the field declares none (an object registered in code, with no + * authoring parse) or from a row written before the rule; `"true"` / + * `"false"` are legal codes anywhere. `FieldSchema` refuses this `stage` at + * authoring for that reason; `code` is a legal `FieldSchema` input. + */ +export const FILTER_STRING_STORED_COMPARAND_FIELDS = { + id: { name: 'id', type: 'text' }, + code: { name: 'code', type: 'text' }, + stage: { name: 'stage', type: 'select' }, +} as const; + +/** A row in the string-stored fixture — every value is the STORED string. */ +export interface StringStoredComparandRow { + id: string; + /** text — the text family. */ + code: string; + /** select — the option family. */ + stage: string; +} + +/** + * The fixture: one row per stored reading (a number's, `true`'s, `false`'s) + * and one plain string, so a wrongly-widened or inverted predicate returns + * visibly wrong ids. No `null` cell: the NULL polarity of `$ne` / `$nin` is + * another table's subject. + */ +export const FILTER_STRING_STORED_COMPARAND_ROWS: readonly StringStoredComparandRow[] = [ + { id: '1', code: '42', stage: '3' }, + { id: '2', code: 'true', stage: 'true' }, + { id: '3', code: 'false', stage: 'false' }, + { id: '4', code: 'alpha', stage: 'open' }, +] as const; + +/** + * One case: the filter as an author writes it (a number or boolean comparand), + * the filter the engine's declared-type door hands every driver (each such + * comparand narrowed to `String(value)` — + * `filter-string-stored-comparand-declared-type.ts`), and the rows it matches. + * + * ## How the suites consume it + * + * - **The engine suite** (`@objectstack/objectql`, a recording driver): + * `engine.find` with {@link StringStoredComparandCase.filter} hands the + * driver exactly {@link StringStoredComparandCase.stored} (after the shared + * lowering), and the caller's filter is not edited. + * - **Each driver suite**: seed {@link FILTER_STRING_STORED_COMPARAND_ROWS} + * and assert `parseFilterAST(c.stored())` matches {@link + * StringStoredComparandCase.expected} — the driver's half of the promise, + * with no field-aware policy of its own. Together: the number `42` matches + * the row written `42` on every driver path. + */ +export interface StringStoredComparandCase { + /** Stable identifier, usable as a test name. */ + readonly name: string; + /** The filter as written — a factory, so no suite can edit what another judges. */ + readonly filter: () => FilterCondition; + /** The filter every driver receives once the engine's door has narrowed it. */ + readonly stored: () => FilterCondition; + /** Ids of matching rows, ascending. */ + readonly expected: readonly string[]; + /** Why the case is here — surfaced in failure output. */ + readonly note?: string; +} + +/** + * The cases: a number and a boolean comparand on the text field and on the + * option field, at the implicit slot, under `$eq` / `$ne`, and as members of + * `$in` / `$nin` mixed with other scalars (a string member passes as written). + * Then the ranges: a range bound is narrowed too, so a range on a string-stored + * field is a STRING range (`"42"` lies between `"4"` and `"5"`). Every bound is a + * single digit, which every collation orders before the fixture's letters and + * the same way among digits, so each answer is one on every driver. + */ +export const FILTER_STRING_STORED_COMPARAND_CASES: readonly StringStoredComparandCase[] = [ + { + name: 'a number on a text field — implicit equality (the card)', + filter: () => ({ code: 42 }), + stored: () => ({ code: '42' }), + expected: ['1'], + note: 'Before the door: no row on any driver, no error — the row holds the string "42".', + }, + { + name: 'a number on a text field — $eq', + filter: () => ({ code: { $eq: 42 } }), + stored: () => ({ code: { $eq: '42' } }), + expected: ['1'], + }, + { + name: 'a boolean on a text field — implicit equality', + filter: () => ({ code: true }), + stored: () => ({ code: 'true' }), + expected: ['2'], + }, + { + name: 'a number on a text field — $ne', + filter: () => ({ code: { $ne: 42 } }), + stored: () => ({ code: { $ne: '42' } }), + expected: ['2', '3', '4'], + note: 'Before the door: every row, the one written 42 included.', + }, + { + name: 'mixed scalars in $in on a text field — a number, a boolean and a string', + filter: () => ({ code: { $in: [42, false, 'alpha'] } }), + stored: () => ({ code: { $in: ['42', 'false', 'alpha'] } }), + expected: ['1', '3', '4'], + }, + { + name: 'mixed scalars in $nin on a text field', + filter: () => ({ code: { $nin: [42, true] } }), + stored: () => ({ code: { $nin: ['42', 'true'] } }), + expected: ['3', '4'], + }, + { + name: 'a number on an option field — implicit equality', + filter: () => ({ stage: 3 }), + stored: () => ({ stage: '3' }), + expected: ['1'], + note: 'Before the door: no row on any driver — the write stored the option code "3".', + }, + { + name: 'a boolean on an option field — $eq', + filter: () => ({ stage: { $eq: false } }), + stored: () => ({ stage: { $eq: 'false' } }), + expected: ['3'], + }, + { + name: 'a boolean on an option field — $ne', + filter: () => ({ stage: { $ne: true } }), + stored: () => ({ stage: { $ne: 'true' } }), + expected: ['1', '3', '4'], + }, + { + name: 'mixed scalars in $in on an option field — a number, a boolean and a string', + filter: () => ({ stage: { $in: [3, true, 'open'] } }), + stored: () => ({ stage: { $in: ['3', 'true', 'open'] } }), + expected: ['1', '2', '4'], + }, + { + name: 'mixed scalars in $nin on an option field', + filter: () => ({ stage: { $nin: [3, false] } }), + stored: () => ({ stage: { $nin: ['3', 'false'] } }), + expected: ['2', '4'], + }, + { + name: 'a range of numbers on a text field is a STRING range — $gt 4 and $lt 5 hold "42"', + filter: () => ({ code: { $gt: 4, $lt: 5 } }), + stored: () => ({ code: { $gt: '4', $lt: '5' } }), + expected: ['1'], + note: 'Read as strings, "4" < "42" < "5"; the number 42 lies outside 4..5. Every range bound is narrowed, ' + + 'so { code: { $gt: 9 } } does not match "10" either ("10" < "9").', + }, + { + name: 'a $between of numbers on a text field is a STRING range — [1, 5] holds "42"', + filter: () => ({ code: { $between: [1, 5] } }), + stored: () => ({ code: { $between: ['1', '5'] } }), + expected: ['1'], + }, + { + name: 'a $between of numbers on an option field — [1, 4] holds the code "3"', + filter: () => ({ stage: { $between: [1, 4] } }), + stored: () => ({ stage: { $between: ['1', '4'] } }), + expected: ['1'], + }, +] as const; diff --git a/packages/spec/src/data/filter-string-stored-comparand-declared-type.test.ts b/packages/spec/src/data/filter-string-stored-comparand-declared-type.test.ts new file mode 100644 index 00000000000..723327c50b4 --- /dev/null +++ b/packages/spec/src/data/filter-string-stored-comparand-declared-type.test.ts @@ -0,0 +1,147 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#29486] Pins for the string-stored comparand declared-type door's CONTRACT + * — the judged families, the positions, the pure verdict — and for the + * cross-driver case table it feeds (`FILTER_STRING_STORED_COMPARAND_CASES` in + * `filter-comparand-type-conformance.ts`). The door itself is + * `@objectstack/objectql`'s arm of the engine's field-aware walk. + */ + +import { describe, it, expect } from 'vitest'; +import { FieldSchema, FieldType, BOUNDED_STRING_FIELD_TYPES } from './field.zod'; +import { BOOLEAN_VALUE_TYPES, MULTI_OPTION_TYPES, NUMERIC_VALUE_TYPES, SINGLE_OPTION_TYPES } from './field-value.zod'; +import { parseFilterAST } from './filter.zod'; +import { FILTER_COMPARAND_BIGINT_EXACT_LIMIT } from './filter-comparand-type'; +import { + NUMBER_COMPARAND_DOOR_LIST_OPERATORS, + NUMBER_COMPARAND_DOOR_SCALAR_OPERATORS, +} from './filter-number-comparand-declared-type'; +import { + STRING_STORED_COMPARAND_DOOR_FAMILIES, + STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS, + STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS, + stringStoredComparandDoorVerdict, + stringStoredComparandFieldVerdict, +} from './filter-string-stored-comparand-declared-type'; +import { + FILTER_STRING_STORED_COMPARAND_CASES, + FILTER_STRING_STORED_COMPARAND_FIELDS, + FILTER_STRING_STORED_COMPARAND_ROWS, +} from './filter-comparand-type-conformance'; + +describe('the judged fields and positions', () => { + it('are the write side\'s three sets, by identity — never a re-listing', () => { + expect(STRING_STORED_COMPARAND_DOOR_FAMILIES).toHaveLength(3); + expect(STRING_STORED_COMPARAND_DOOR_FAMILIES[0]).toBe(BOUNDED_STRING_FIELD_TYPES); + expect(STRING_STORED_COMPARAND_DOOR_FAMILIES[1]).toBe(SINGLE_OPTION_TYPES); + expect(STRING_STORED_COMPARAND_DOOR_FAMILIES[2]).toBe(MULTI_OPTION_TYPES); + }); + + it('judges every member of those sets and nothing else, over the whole FieldType enum', () => { + for (const type of FieldType.options) { + const member = BOUNDED_STRING_FIELD_TYPES.has(type) || SINGLE_OPTION_TYPES.has(type) || MULTI_OPTION_TYPES.has(type); + expect(stringStoredComparandFieldVerdict({ type }), type).toBe(member ? 'judged' : 'not-judged'); + } + }); + + it('is disjoint from the number and boolean doors\' classes, so at most one arm judges a key', () => { + for (const type of [...NUMERIC_VALUE_TYPES, ...BOOLEAN_VALUE_TYPES]) { + expect(stringStoredComparandFieldVerdict({ type }), type).toBe('not-judged'); + } + expect(stringStoredComparandFieldVerdict({ type: 'formula' })).toBe('not-judged'); + }); + + it('judges the number door\'s positions, by identity', () => { + expect(STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS).toBe(NUMBER_COMPARAND_DOOR_SCALAR_OPERATORS); + expect(STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS).toBe(NUMBER_COMPARAND_DOOR_LIST_OPERATORS); + }); +}); + +describe('the verdict', () => { + const text = { type: 'text' }; + const select = { type: 'select' }; + + it('narrows a number or a boolean to String(value) — the write side\'s reading', () => { + for (const field of [text, select, { type: 'email' }, { type: 'multiselect' }]) { + for (const [comparand, value] of [[42, '42'], [0, '0'], [-3.5, '-3.5'], [1e21, '1e+21'], [true, 'true'], [false, 'false']] as const) { + expect(stringStoredComparandDoorVerdict(field, comparand), `${field.type} ${String(comparand)}`) + .toEqual({ verdict: 'narrows', value }); + expect(value).toBe(String(comparand)); + } + } + }); + + it('reads a bigint within ±2^53 as the number it names, and passes one beyond for the comparand-type door to refuse', () => { + expect(stringStoredComparandDoorVerdict(text, BigInt(42))).toEqual({ verdict: 'narrows', value: '42' }); + expect(stringStoredComparandDoorVerdict(text, -FILTER_COMPARAND_BIGINT_EXACT_LIMIT)) + .toEqual({ verdict: 'narrows', value: String(-(2 ** 53)) }); + expect(stringStoredComparandDoorVerdict(text, FILTER_COMPARAND_BIGINT_EXACT_LIMIT + BigInt(1))).toEqual({ verdict: 'passes' }); + }); + + it('passes a string, null (the null test — never "null"), a Date, an array and a non-literal', () => { + for (const comparand of ['42', '', null, undefined, new Date(0), ['42'], { $field: 'other' }, new Map()]) { + expect(stringStoredComparandDoorVerdict(text, comparand), String(comparand)).toEqual({ verdict: 'passes' }); + } + }); + + it('passes every comparand on a field outside the two families', () => { + for (const type of ['number', 'boolean', 'date', 'datetime', 'lookup', 'json', 'formula']) { + expect(stringStoredComparandDoorVerdict({ type }, 42), type).toEqual({ verdict: 'passes' }); + expect(stringStoredComparandDoorVerdict({ type }, true), type).toEqual({ verdict: 'passes' }); + } + }); +}); + +describe('FILTER_STRING_STORED_COMPARAND_CASES — the cross-driver table', () => { + it('declares fields from both families — the text field a legal FieldSchema input, the select the code-registered shape', () => { + expect(FieldSchema.safeParse(FILTER_STRING_STORED_COMPARAND_FIELDS.id).success).toBe(true); + expect(FieldSchema.safeParse(FILTER_STRING_STORED_COMPARAND_FIELDS.code).success).toBe(true); + // A select that declares no options is refused at authoring (its codes would be + // system identifiers, never "3"); the fixture is the shape the write door's + // option pins register in code, the one place a number code is stored today. + expect(FieldSchema.safeParse(FILTER_STRING_STORED_COMPARAND_FIELDS.stage).success).toBe(false); + expect(stringStoredComparandFieldVerdict(FILTER_STRING_STORED_COMPARAND_FIELDS.code)).toBe('judged'); + expect(stringStoredComparandFieldVerdict(FILTER_STRING_STORED_COMPARAND_FIELDS.stage)).toBe('judged'); + expect(BOUNDED_STRING_FIELD_TYPES.has(FILTER_STRING_STORED_COMPARAND_FIELDS.code.type)).toBe(true); + expect(SINGLE_OPTION_TYPES.has(FILTER_STRING_STORED_COMPARAND_FIELDS.stage.type)).toBe(true); + }); + + it('every stored filter is its written filter with each number or boolean comparand read by the verdict', () => { + const narrow = (field: string, v: unknown): unknown => { + const type = (FILTER_STRING_STORED_COMPARAND_FIELDS as Record)[field]!.type; + const verdict = stringStoredComparandDoorVerdict({ type }, v); + return verdict.verdict === 'narrows' ? verdict.value : v; + }; + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + const [[field, spec]] = Object.entries(c.filter()); + const expected = typeof spec === 'object' && spec !== null + ? Object.fromEntries(Object.entries(spec).map(([op, v]) => [op, Array.isArray(v) ? v.map((m) => narrow(field, m)) : narrow(field, v)])) + : narrow(field, spec); + expect(c.stored(), c.name).toEqual({ [field]: expected }); + // The written filter really carries a number or a boolean, else the case pins nothing. + expect(JSON.stringify(c.filter()), c.name).not.toBe(JSON.stringify(c.stored())); + } + }); + + it('covers both families, both comparand types, $eq / $ne / $in / $nin with mixed scalars, and the ranges', () => { + const written = FILTER_STRING_STORED_COMPARAND_CASES.map((c) => JSON.stringify(c.filter())); + for (const field of ['code', 'stage']) { + expect(written.some((w) => w.includes(`"${field}"`) && /[:\[,](-?\d|true|false)/.test(w)), field).toBe(true); + for (const op of ['$eq', '$ne', '$in', '$nin', '$between']) { + expect(written.some((w) => w.includes(`"${field}"`) && w.includes(`"${op}"`)), `${field} ${op}`).toBe(true); + } + } + // A range bound is narrowed too: the table pins the STRING range on a digits-only `$gt`. + expect(written.some((w) => w.includes('"code"') && w.includes('"$gt"'))).toBe(true); + }); + + it('every stored filter passes the shared door, and every expected id is a fixture row', () => { + const ids = new Set(FILTER_STRING_STORED_COMPARAND_ROWS.map((r) => r.id)); + for (const c of FILTER_STRING_STORED_COMPARAND_CASES) { + expect(() => parseFilterAST(c.stored()), c.name).not.toThrow(); + for (const id of c.expected) expect(ids.has(id), `${c.name}: ${id}`).toBe(true); + expect([...c.expected], c.name).toEqual([...c.expected].sort()); + } + }); +}); diff --git a/packages/spec/src/data/filter-string-stored-comparand-declared-type.ts b/packages/spec/src/data/filter-string-stored-comparand-declared-type.ts new file mode 100644 index 00000000000..b707d861600 --- /dev/null +++ b/packages/spec/src/data/filter-string-stored-comparand-declared-type.ts @@ -0,0 +1,184 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#29486] The STRING-STORED comparand **declared-type door** — what a number + * or boolean comparand means against a field whose stored value is a string: + * the text family and the option family. The third twin of + * `filter-number-comparand-declared-type.ts` (#20336) and + * `filter-boolean-comparand-declared-type.ts` (#21333), in the same two lanes: + * this module is lane (1), the CONTRACT — the judged types, the positions and + * the pure verdict. Lane (2), the door, is `@objectstack/objectql`'s, an arm of + * the one filter walk the engine runs at its field-aware seam. THIS MODULE + * WRITES NO DOOR, and `packages/spec` carries no runtime logic (Prime + * Directive #2). + * + * ## The direction this encodes (maintainer ruling A, recorded on #29486) + * + * A number or boolean comparand on a text- or option-family field compares as + * `String(value)`, the same form the write side stores (#29241 for the text + * family, #29562 for the option family) — the number and boolean doors' rule, + * "narrow what unambiguously names a value". It is a widening: a filter that + * matched nothing now matches what the write stored. + * + * ## What the door closes, measured before it (base `9499dcc53`) + * + * Three rows written through `engine.insert` — `42`, `"42"` and `true` on a + * `text` field, `3`, `"3"` and `true` on a `select` — on InMemoryDriver and on + * SqlDriver over SQLite. The write door stored `"42"`, `"42"`, `"true"` (and + * `"3"`, `"3"`, `"true"`), so a number comparand compared a number with a + * string: + * + * | filter | InMemoryDriver | SQLite | after the door | + * |:--|:--|:--|:--| + * | `{ title: 42 }`, `{ stage: 3 }` | no row | no row | the two rows written `42` / `3` and `"42"` / `"3"` | + * | `{ title: true }`, `{ stage: { $eq: true } }` | no row | no row | the row written `true` | + * | `{ title: { $in: [42, true] } }` | no row | no row | all three | + * | `{ title: { $ne: 42 } }` | all three | all three | the row written `true` | + * + * Every answer a 200, no error; `{ title: "42" }` matched both `42` rows. + * + * The ranges, a `text` field holding `"10"`, `"5"`, `"42"`, `"alpha"`, measured + * at the driver on the filter each received before the door (as written) and + * after it (narrowed). A range bound is narrowed like any comparand, so a range + * on a string-stored field is a STRING range, ordered as the column's strings: + * + * | filter | InMemoryDriver before | SQLite before | every driver after | + * |:--|:--|:--|:--| + * | `{ title: { $gt: 9 } }` | no row | `"alpha"` | `"alpha"` — `"10"` < `"9"` as strings | + * | `{ title: { $between: [1, 10] } }` | no row | `"10"` | `"10"` — `"5"` > `"10"` as strings | + * | `{ title: { $gt: 4, $lt: 5 } }` | no row | `"5"`, `"42"` | `"42"` | + * + * MongoDB orders a number and a string in different type brackets, so, like the + * memory matcher, it matched no row for a number bound. + * A multi-value option field (`multiselect`, …) is unchanged: both drivers + * refuse a scalar comparison against one (`INVALID_FILTER`, "use $contains"), + * whatever the comparand, before and after. + * + * ## The door's answers — NARROW a number or a boolean to its string reading + * + * - **A number or a boolean** narrows to `String(value)`, copy-on-write — the + * exact reading the record validator's string and option arms judge a + * written value by and the write door stores + * (`@objectstack/objectql`'s `record-validator.ts`): `42` → `"42"`, + * `true` → `"true"`, `false` → `"false"`, `0.5` → `"0.5"`. + * - **A `bigint` within ±2^53** narrows to the string of the number it names, + * the number the comparand-type door (`filter-comparand-type.ts`) rewrites it + * to. That door runs BEFORE this one on the `FilterArray` spelling and at + * `having` but AFTER it on the object spelling of `where` and on a + * per-aggregation `filter` (the boolean door records the same order), so only + * reading a `bigint` as its number gives one answer at every position. A + * `bigint` beyond ±2^53 passes, and that door refuses it in its own words. + * - **A string** passes, as written: it is already the stored form. + * - **`null`** passes: it is the null test (`{ code: null }`), never `"null"`. + * - **Everything else passes** — a `Date`, an array (the comparand-shape door's + * subject at a one-value slot), a `{ $field }` reference, and every value + * outside the comparand-type door's accepted set, which that door refuses. + * + * There is no refusal: every comparand this door judges names exactly one + * stored string. + * + * ## Which fields, which positions + * + * The write side's two families, by reference and never re-listed: + * `BOUNDED_STRING_FIELD_TYPES` (`field.zod.ts` — text, textarea, email, url, + * phone, password, markdown, html, richtext, code, signature, qrcode) and the + * option family, `SINGLE_OPTION_TYPES` and `MULTI_OPTION_TYPES` + * (`field-value.zod.ts` — select, radio, multiselect, checkboxes, tags). A + * multi-value option field stores an array of codes, and the write side reads + * each number or boolean ELEMENT by the same `String(value)`; a scalar + * comparand against one is such an element, so it is narrowed the same way. + * What a driver does with a scalar against an array column is unchanged (both + * measured drivers refuse it, as above); only the comparand it is handed is + * now the code the write stored. A `formula` is + * not judged: the write side stores no formula value, and the + * unmaterializable-field door refuses every formula filter first (#8296). + * + * The positions are the number door's, BY IDENTITY + * ({@link STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS}, + * {@link STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS}): the implicit + * comparand, the scalar operators and every member of the list operators. Not + * judged: the flags (`$null` / `$exists` / `$empty`), the text operators + * (`$contains: 42` is the text-comparand door's refusal), a `{ $field }` + * reference and a dotted key. + * + * ## Where the cases live + * + * The cross-driver cases are `FILTER_STRING_STORED_COMPARAND_CASES` in + * `filter-comparand-type-conformance.ts`: each carries the filter as written + * and the filter this door hands every driver, so the engine suite pins the + * narrowing and each driver suite pins that the narrowed filter matches the + * stored rows. + * + * @see NUMBER_COMPARAND_DOOR_CASES — the twin this module is shaped after. + * @see https://github.com/objectstack-ai/objectstack/issues/29486 (this door) + */ + +import { BOUNDED_STRING_FIELD_TYPES } from './field.zod'; +import { MULTI_OPTION_TYPES, SINGLE_OPTION_TYPES } from './field-value.zod'; +import { + NUMBER_COMPARAND_DOOR_LIST_OPERATORS, + NUMBER_COMPARAND_DOOR_SCALAR_OPERATORS, +} from './filter-number-comparand-declared-type'; +import { FILTER_COMPARAND_BIGINT_EXACT_LIMIT } from './filter-comparand-type'; + +/** + * The declared-type families the door judges — the write side's three sets, by + * identity (pinned), never a re-listing: the text family and the single- and + * multi-value option families. + */ +export const STRING_STORED_COMPARAND_DOOR_FAMILIES: readonly ReadonlySet[] = [ + BOUNDED_STRING_FIELD_TYPES, + SINGLE_OPTION_TYPES, + MULTI_OPTION_TYPES, +]; + +/** The operators whose single comparand the door judges — the number door's list, by identity. */ +export const STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS = NUMBER_COMPARAND_DOOR_SCALAR_OPERATORS; + +/** The list operators each of whose MEMBERS the door judges — the number door's list, by identity. */ +export const STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS = NUMBER_COMPARAND_DOOR_LIST_OPERATORS; + +/** The slice of a field definition the door reads. */ +export interface StringStoredComparandDoorFieldMeta { + type: string; +} + +/** Is the field one the door judges? `judged` for a member of a {@link STRING_STORED_COMPARAND_DOOR_FAMILIES} set. */ +export function stringStoredComparandFieldVerdict( + field: StringStoredComparandDoorFieldMeta, +): 'judged' | 'not-judged' { + return STRING_STORED_COMPARAND_DOOR_FAMILIES.some((family) => family.has(field.type)) ? 'judged' : 'not-judged'; +} + +/** + * The door's two answers for ONE comparand at a judged position. + * + * - `narrows` — a number, a boolean, or a `bigint` within ±2^53; the door + * replaces it with `value`, its string reading. + * - `passes` — not this door's subject (the field is not string-stored, or the + * comparand is a string, `null`, or anything else — see the module header); + * nothing changes. + */ +export type StringStoredComparandDoorVerdict = + | { readonly verdict: 'narrows'; readonly value: string } + | { readonly verdict: 'passes' }; + +/** + * The door's verdict for `comparand` at a judged position of a filter on + * `field` (an UNDOTTED key naming a declared field). Pure: two inputs, no I/O. + */ +export function stringStoredComparandDoorVerdict( + field: StringStoredComparandDoorFieldMeta, + comparand: unknown, +): StringStoredComparandDoorVerdict { + if (stringStoredComparandFieldVerdict(field) !== 'judged') return { verdict: 'passes' }; + if (typeof comparand === 'number' || typeof comparand === 'boolean') { + return { verdict: 'narrows', value: String(comparand) }; + } + if (typeof comparand === 'bigint') { + const magnitude = comparand < 0n ? -comparand : comparand; + if (magnitude > FILTER_COMPARAND_BIGINT_EXACT_LIMIT) return { verdict: 'passes' }; + return { verdict: 'narrows', value: String(Number(comparand)) }; + } + return { verdict: 'passes' }; +} diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 2f67885cbff..bfaa2ac4eaf 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -130,6 +130,12 @@ export * from './filter-number-comparand-declared-type'; // seam, and any other string is refused with INVALID_FILTER 400. The engine // door is objectql's; this module is the contract only. export * from './filter-boolean-comparand-declared-type'; +// [#29486] The STRING-STORED twin of the two doors above — the contract half of +// the maintainer's ruling: a number or boolean comparand against a declared +// text- or option-family field is narrowed to String(value), the form the write +// door stores, at the engine's field-aware seam. It never refuses. The engine +// arm is objectql's; this module is the contract only. +export * from './filter-string-stored-comparand-declared-type'; export * from './temporal-conformance'; // Canonical conformance cases for deterministic paged reads — the standard // every driver's `find()` is held to whenever `limit`/`offset` slice the result diff --git a/scripts/check-driver-conformance.mjs b/scripts/check-driver-conformance.mjs index e3ee841c234..2b9e1d5c61c 100644 --- a/scripts/check-driver-conformance.mjs +++ b/scripts/check-driver-conformance.mjs @@ -275,6 +275,11 @@ const CASE_SETS = [ marker: 'FILTER_COMPARAND_TYPE_CASES', what: 'the comparand-type door: the six accepted types compile everywhere, everything else is refused loudly — #7872', }, + { + file: 'filter-comparand-type-conformance.ts', + marker: 'FILTER_STRING_STORED_COMPARAND_CASES', + what: 'a number or boolean comparand on a text- or option-family field matches the string the write stored, as the engine door hands it — #29486', + }, { file: 'value-roundtrip-conformance.ts', marker: 'VALUE_ROUNDTRIP_CASES',