From 2d71b8631b9bd61bacf4a4c2875a96d3a3666d39 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:51:32 +0000 Subject: [PATCH 1/3] fix(driver-sql): a boolean field is stored as a boolean whatever spelling the caller sends WIP: write arm, shared spelling table, remote bulkCreate preflight, pins. Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- ...sql-driver-boolean-write-spellings.test.ts | 155 +++++++++++++ .../driver-sql/src/sql-driver-schema-sync.ts | 21 +- .../src/sql-driver-sqlite-serialisation.ts | 102 +++++++- .../drivers/driver-turso/src/turso-driver.ts | 5 + ...-local-remote-boolean-write-parity.test.ts | 164 +++++++++++++ ...boolean-written-spelling-row-scope.test.ts | 217 ++++++++++++++++++ 6 files changed, 658 insertions(+), 6 deletions(-) create mode 100644 packages/drivers/driver-sql/src/sql-driver-boolean-write-spellings.test.ts create mode 100644 packages/drivers/driver-turso/src/turso-local-remote-boolean-write-parity.test.ts create mode 100644 packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-boolean-write-spellings.test.ts b/packages/drivers/driver-sql/src/sql-driver-boolean-write-spellings.test.ts new file mode 100644 index 00000000000..e0646d9b4e6 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-boolean-write-spellings.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A declared scalar `Field.boolean` / `Field.toggle` is stored as a boolean on + * SQLite whatever spelling the caller hands a write door, and a value that + * spells no boolean is refused instead of stored. + * + * The engine writes the boolean its validator judged, but a caller that writes + * through the driver itself (a plugin, a migration, a `beforeInsert` hook's + * assignment, which lands after the engine's rewrite) reached `formatInput` + * with the text `'true'` / `'false'`, and SQLite kept that TEXT beside rows + * holding the INTEGER `1` / `0`. Every filter, sort and group then ran against + * the raw cell: `'true' <> 1` holds in SQLite, so a row written as `'true'` + * satisfied `$ne: true`. Any other text (`'yes'`) was stored as itself and read + * back as `Boolean('yes')`. + * + * The accepted spellings are exactly the ones the boot convergence reads + * (`SQLITE_BOOLEAN_TEXT_READINGS`): `true` / `false`, the numbers `1` / `0`, + * and the text `'1'` / `'0'`, `'true'` / `'false'` and `'1.0'` / `'0.0'`. Each + * is bound as `sqliteBooleanBinding`'s `'1'` / `'0'`, which a column the driver + * created stores as the INTEGER `1` / `0` and a TEXT-affinity column (a `text` + * field retyped to `boolean`) as the text `'1'` / `'0'`. Anything else answers + * `VALIDATION_ERROR` / 400 on every door and writes nothing. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { lowerFilterCondition } from '@objectstack/spec/data'; +import { SqlDriver } from './sql-driver.js'; + +const CREATED = 'bool_spellings_created'; +const RETYPED = 'bool_spellings_retyped'; + +function sqliteDriver(): SqlDriver { + return new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); +} + +const asText = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'text' }, live: { type: 'text' } } }); +const asBoolean = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'boolean' }, live: { type: 'toggle' } } }); + +/** Every spelling a write door accepts, and the boolean it is stored as. */ +const ACCEPTED: ReadonlyArray = [ + [true, true], [false, false], [1, true], [0, false], ['1', true], ['0', false], + ['true', true], ['false', false], ['1.0', true], ['0.0', false], +]; + +/** Values that spell no boolean: refused on every door. */ +const REFUSED: ReadonlyArray = ['yes', 'TRUE', ' true', '', 2, -1, Number.NaN, ['true'], { value: true }]; + +type Door = 'create' | 'update' | 'upsert' | 'bulkCreate' | 'bulkUpdate' | 'updateMany'; +const DOORS: readonly Door[] = ['create', 'update', 'upsert', 'bulkCreate', 'bulkUpdate', 'updateMany']; + +/** Write `value` to both boolean fields of row `id` through `door`; update doors first create the row as `seed`. */ +async function writeThrough(driver: SqlDriver, table: string, door: Door, id: string, value: unknown, seed = false): Promise { + const row = { id, label: door, flag: value, live: value }; + switch (door) { + case 'create': await driver.create(table, row); return; + case 'upsert': await driver.upsert(table, row); return; + case 'bulkCreate': await driver.bulkCreate(table, [row]); return; + default: break; + } + await driver.create(table, { id, label: door, flag: seed, live: seed }); + const patch = { flag: value, live: value }; + if (door === 'update') await driver.update(table, id, patch); + else if (door === 'bulkUpdate') await driver.bulkUpdate(table, [{ id, data: patch }]); + else await driver.updateMany(table, { where: { id } } as DriverQuery, patch); +} + +async function storedCell(driver: SqlDriver, table: string, id: string): Promise | null> { + const rows = await (driver as any).knex.raw(`select flag, typeof(flag) as t, live, typeof(live) as lt from ${table} where id = ?`, [id]); + return rows.length ? [[rows[0].flag, rows[0].t], [rows[0].live, rows[0].lt]] : null; +} + +const label = (v: unknown) => (typeof v === 'number' && Number.isNaN(v) ? 'NaN' : JSON.stringify(v)); + +for (const [table, form] of [[CREATED, 'INTEGER'], [RETYPED, 'TEXT']] as const) { + describe(`driver-sql — a boolean / toggle field on a ${form}-form column is stored as a boolean whatever spelling it is written in (sqlite)`, () => { + let driver: SqlDriver; + const stored = (b: boolean) => (form === 'INTEGER' ? [b ? 1 : 0, 'integer'] : [b ? '1' : '0', 'text']); + + beforeAll(async () => { + driver = sqliteDriver(); + if (form === 'TEXT') await driver.initObjects([asText(table)]); + await driver.initObjects([asBoolean(table)]); + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + it('the fixture: the column forms are the ones named', async () => { + const cols = await (driver as any).knex.raw(`select name, type from pragma_table_info('${table}') where name in ('flag', 'live') order by name`); + expect(cols.map((c: any) => c.type)).toEqual(form === 'INTEGER' ? ['boolean', 'boolean'] : ['TEXT', 'TEXT']); + }); + + for (const door of DOORS) { + it(`${door}: every accepted spelling is stored as its boolean`, async () => { + const got: Record = {}; + const want: Record = {}; + for (const [i, [value, b]] of ACCEPTED.entries()) { + const id = `${door}_ok_${i}`; + // An update door seeds the opposite value, so a write that changed nothing is seen. + await writeThrough(driver, table, door, id, value, !b); + got[label(value)] = await storedCell(driver, table, id); + want[label(value)] = [stored(b), stored(b)]; + } + expect(got).toEqual(want); + }); + + it(`${door}: a value that spells no boolean is refused with VALIDATION_ERROR / 400 and writes nothing`, async () => { + const verdicts: Record = {}; + const want: Record = {}; + for (const [i, value] of REFUSED.entries()) { + const id = `${door}_no_${i}`; + const outcome = await writeThrough(driver, table, door, id, value, true).then( + () => 'written', + (e: any) => ({ code: e?.code, status: e?.status }), + ); + const cell = await storedCell(driver, table, id); + verdicts[label(value)] = { outcome, cell }; + // An insert door leaves no row; an update door leaves the seeded `true` as it was. + const cellWant = ['create', 'upsert', 'bulkCreate'].includes(door) ? null : [stored(true), stored(true)]; + want[label(value)] = { outcome: { code: 'VALIDATION_ERROR', status: 400 }, cell: cellWant }; + } + expect(verdicts).toEqual(want); + }); + } + + it('null still writes NULL, and a write that names neither field leaves them as they were', async () => { + await driver.create(table, { id: 'nul', label: 'x', flag: null, live: null }); + expect(await storedCell(driver, table, 'nul')).toEqual([[null, 'null'], [null, 'null']]); + await driver.create(table, { id: 'untouched', label: 'x', flag: 'true', live: 'false' }); + await driver.update(table, 'untouched', { label: 'y' }); + expect(await storedCell(driver, table, 'untouched')).toEqual([stored(true), stored(false)]); + }); + + it('$ne: true / $nin: [true] / $not of = true never select a row written as the text true', async () => { + await driver.create(table, { id: 'neg_text_true', label: 'neg', flag: 'true', live: 'true' }); + await driver.create(table, { id: 'neg_text_false', label: 'neg', flag: 'false', live: 'false' }); + await driver.create(table, { id: 'neg_bool_true', label: 'neg', flag: true, live: true }); + // The filter as a seam hands it to the driver (the shared lowering). + const ids = async (where: Record) => { + const lowered = lowerFilterCondition({ label: 'neg', ...where }, { isDatetimeColumn: () => false }); + return ((await driver.find(table, { where: lowered } as DriverQuery)) as Array<{ id: string }>).map((r) => r.id).sort(); + }; + for (const field of ['flag', 'live']) { + expect(await ids({ [field]: { $ne: true } })).toEqual(['neg_text_false']); + expect(await ids({ [field]: { $nin: [true] } })).toEqual(['neg_text_false']); + expect(await ids({ $not: { [field]: true } })).toEqual(['neg_text_false']); + expect(await ids({ [field]: { $ne: false } })).toEqual(['neg_bool_true', 'neg_text_true']); + expect(await ids({ [field]: true })).toEqual(['neg_bool_true', 'neg_text_true']); + } + }); + }); +} diff --git a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts index 66b443f687f..ec0b7dbe923 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts @@ -177,6 +177,7 @@ import { activeConcurrentIndexDeferral, attachUniqueConstraintSql, clearConcurre import { isJsonColumnType, mediaColumnMoveDialect, mediaColumnMovePlan, type MediaColumnMovePlan, type MediaColumnMoveRefusal, type MediaColumnMoveScan } from './media-column-move.js'; import { StandardErrorCode } from '@objectstack/spec/api'; import { recoverUnencodedJsonText } from './unencoded-json-text.js'; +import { SQLITE_BOOLEAN_TEXT_SPELLINGS } from './sql-driver-sqlite-serialisation.js'; import { renderExistingTableAdoptionRefusal } from './existing-table-refusal.js'; import { renderDeclaredRenameRefusal } from './declared-rename.js'; import { aggregandColumnClass } from '@objectstack/core'; @@ -2058,8 +2059,22 @@ export async function backfillCanonicalTimes(this: Pick s.legacy)})`; + +/** + * The spellings of {@link SQLITE_BOOLEAN_TEXT_SPELLINGS} that `pick` keeps, as a + * SQL list of string literals (`'true', 'false', '1.0', '0.0'` for the legacy + * ones). The table is the write door's too (`sqliteBooleanWriteReading`), so + * the convergence and the write accept one set of spellings. Each spelling is + * a constant of that table, never a caller's value, and holds no quote. + */ +function sqlTextList(pick: (s: (typeof SQLITE_BOOLEAN_TEXT_SPELLINGS)[number]) => boolean): string { + return SQLITE_BOOLEAN_TEXT_SPELLINGS.filter(pick).map((s) => `'${s.text}'`).join(', '); +} /** * [#34973] How many ids of the converted rows the backfill's `info` line @@ -2126,7 +2141,7 @@ export async function backfillCanonicalBooleans(this: Pick !s.legacy)}) then 1 else 0 end), 0) as canonical ` + `from ?? where typeof(??) = 'text'`, [field, field, field, table, field], ); @@ -2139,7 +2154,7 @@ export async function backfillCanonicalBooleans(this: Pick s.legacy && s.value)}) then 1 else 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`, [table, field, field, field, field], ); // better-sqlite3 reports `changes`; a client whose raw path returns diff --git a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts index 70f2a4d38a7..6c45aa54ab9 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts @@ -28,6 +28,7 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ +import { StandardErrorCode } from '@objectstack/spec/api'; import { oracleDayBinding } from './sql-driver-oracle-dialect.js'; import { AUDIT_TIMESTAMP_COLUMNS, canonicalTimeOfDay, normalizeSqliteDatetimeOutput, presentAuditTimestampOutput, @@ -84,6 +85,94 @@ export function sqliteBooleanBinding(value: boolean): '1' | '0' { return value ? '1' : '0'; } +/** + * The text spellings a SQLite boolean cell can hold, and the boolean each one + * is. ONE table, read by the write door ({@link sqliteBooleanWriteReading}) and + * by the boot convergence (`SQLITE_LEGACY_BOOLEAN_TEXT` and the `UPDATE` of + * `backfillCanonicalBooleans`, `sql-driver-schema-sync.ts`), so the driver never + * accepts a spelling on write that the convergence would not recognise, nor + * converges one it would refuse to write. + * + * `'1'` / `'0'` are canonical: what {@link sqliteBooleanBinding} binds, which + * the NUMERIC affinity of a column the driver created folds into the INTEGER + * `1` / `0` and a TEXT-affinity column (a `text` field retyped to `boolean`) + * keeps as that text. The other four are `legacy`: `'true'` / `'false'`, the + * readings the console's inline grid sent, and `'1.0'` / `'0.0'`, the REAL a JS + * number was bound as on a TEXT-affinity column. Compared by `SameValueZero`, + * so `'TRUE'`, `' true'` and `'yes'` are not here. + */ +export const SQLITE_BOOLEAN_TEXT_SPELLINGS: ReadonlyArray<{ readonly text: string; readonly value: boolean; readonly legacy: boolean }> = Object.freeze([ + Object.freeze({ text: '1', value: true, legacy: false }), + Object.freeze({ text: '0', value: false, legacy: false }), + Object.freeze({ text: 'true', value: true, legacy: true }), + Object.freeze({ text: 'false', value: false, legacy: true }), + Object.freeze({ text: '1.0', value: true, legacy: true }), + Object.freeze({ text: '0.0', value: false, legacy: true }), +]); + +/** Every value a SQLite boolean write door accepts, and the boolean it is stored as. */ +const SQLITE_BOOLEAN_WRITE_READINGS: ReadonlyMap = new Map([ + [true, true], [false, false], [1, true], [0, false], + ...SQLITE_BOOLEAN_TEXT_SPELLINGS.map((s) => [s.text, s.value] as const), +]); + +/** + * The boolean a value written to a declared scalar `Field.boolean` / + * `Field.toggle` on SQLite is stored as, or `undefined` when it spells none. + * + * Accepted: `true` / `false`, the numbers `1` / `0`, and every text spelling of + * {@link SQLITE_BOOLEAN_TEXT_SPELLINGS}. The engine's door already writes the + * boolean its validator judged, but a write that reaches the driver another + * way (a caller of the driver itself, or a `beforeInsert` / `beforeUpdate` + * hook's assignment, which lands after the engine's rewrite) carried the + * spelling as sent, and SQLite kept `'true'` as TEXT beside the INTEGER `1`. + * Every comparison runs against the raw cell, and SQLite holds a TEXT cell + * unequal to every INTEGER, so such a row answered `= true` false and + * `$ne: true` true. Anything outside the table is refused by `formatInput` + * ({@link unwritableBooleanError}) rather than stored as text no boolean + * filter, sort or group reads as a boolean. + */ +export function sqliteBooleanWriteReading(value: unknown): boolean | undefined { + return SQLITE_BOOLEAN_WRITE_READINGS.get(value); +} + +/** The accepted text spellings, in pairs, for the refusal sentence: `'1' / '0', 'true' / 'false' and '1.0' / '0.0'`. */ +const ACCEPTED_BOOLEAN_TEXT_SENTENCE = (() => { + const pairs: string[] = []; + for (let i = 0; i < SQLITE_BOOLEAN_TEXT_SPELLINGS.length; i += 2) { + pairs.push(`'${SQLITE_BOOLEAN_TEXT_SPELLINGS[i].text}' / '${SQLITE_BOOLEAN_TEXT_SPELLINGS[i + 1].text}'`); + } + return `${pairs.slice(0, -1).join(', ')} and ${pairs[pairs.length - 1]}`; +})(); + +/** What a refused value is, without echoing it: a caller's value never reaches the error text or a log line. */ +function valueKind(value: unknown): string { + if (Array.isArray(value)) return 'an array'; + if (value instanceof Date) return 'a date'; + if (typeof value === 'object') return 'an object'; + if (typeof value === 'string') return 'a string'; + if (typeof value === 'number') return 'a number'; + return `a ${typeof value}`; +} + +/** + * The refusal of a value that spells no boolean, written to a declared scalar + * `Field.boolean` / `Field.toggle` on SQLite: `VALIDATION_ERROR` / 400, the + * family the write path refuses an unwritable value with (ADR-0112). Thrown + * before any statement is built, so the write stores nothing. + */ +function unwritableBooleanError(object: string, field: string, value: unknown): Error { + const err = new Error( + `The value written to the boolean field "${field}" on "${object}" is ${valueKind(value)} that spells no boolean, ` + + `so it was refused rather than stored. Write true or false; the numbers 1 / 0 and the text ` + + `${ACCEPTED_BOOLEAN_TEXT_SENTENCE} are stored as those booleans too. Any other value would stay in the ` + + `column as text, which no boolean filter, sort or group reads as true or false.`, + ) as Error & { code?: string; status?: number }; + err.code = StandardErrorCode.enum.VALIDATION_ERROR; + err.status = 400; + return err; +} + export interface SqliteSerialisationHost { readonly booleanFields: SqlDriver['booleanFields']; readonly columnFieldByObject: SqlDriver['columnFieldByObject']; @@ -329,14 +418,21 @@ export class SqliteSerialisationFacet { if (!this.isSqlite) return copy; // [#35341] A declared scalar boolean is bound as the text `'1'` / `'0'`. - // See {@link sqliteBooleanBinding}. + // See {@link sqliteBooleanBinding}. Whatever spelling it was written in: + // every accepted spelling is bound as the boolean it spells, and a value + // that spells none is refused before any statement is built. See + // {@link sqliteBooleanWriteReading}. `null` writes NULL, as before. const booleanFields = this.booleanFields[object]; if (booleanFields && booleanFields.length > 0 && copy && typeof copy === 'object') { for (const field of booleanFields) { + // Own-property: a field name may be `constructor` / `valueOf`. + if (!Object.prototype.hasOwnProperty.call(copy, field)) continue; const v = copy[field]; - if (typeof v !== 'boolean') continue; + if (v === undefined || v === null) continue; + const reading = sqliteBooleanWriteReading(v); + if (reading === undefined) throw unwritableBooleanError(object, field, v); if (!copied) { copy = { ...copy }; copied = true; } - copy[field] = sqliteBooleanBinding(v); + copy[field] = sqliteBooleanBinding(reading); } } diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index dd5910cf00d..dc1feb404f6 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -3858,6 +3858,11 @@ export class TursoDriver extends SqlDriver { // The column-map refusal runs once, before any row, as it did when the // batch was handed down whole. this.remoteTableFor(object, 'bulkCreate'); + // Every row's storage form is checked before the first row is written, + // so a row `formatInput` refuses (a boolean field written as a value that + // spells no boolean) refuses the batch with nothing written, as the local + // face's single INSERT does. Each `create` below forms its row again. + for (const row of data) this.toRemoteWriteForms(object, row); // The batch is written one row at a time through this class's own // `create`, so each row's record number is issued on the layer that holds // the schema and each row's #5495 collision re-seed is its own. diff --git a/packages/drivers/driver-turso/src/turso-local-remote-boolean-write-parity.test.ts b/packages/drivers/driver-turso/src/turso-local-remote-boolean-write-parity.test.ts new file mode 100644 index 00000000000..bbdd6d51f3d --- /dev/null +++ b/packages/drivers/driver-turso/src/turso-local-remote-boolean-write-parity.test.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Both faces of `TursoDriver` store a declared `Field.boolean` / `Field.toggle` + * as a boolean whatever spelling a write door is handed, and refuse a value + * that spells no boolean. + * + * The remote face never reaches `SqlDriver.create`: it puts the payload in its + * storage form with `toRemoteWriteForms`, which is `formatInput`, the function + * the local face's doors run. Neither face rewrote a string, so the text + * `'true'` / `'false'` a caller handed `create` / `update` / `updateMany` landed + * as TEXT. The remote face has no boot convergence for such a cell + * (`SqlDriver.initObjects` never runs there), and SQLite compares TEXT with an + * INTEGER as unequal, so the row satisfied `$ne: true` for good. A JS number + * fared no better on the remote face's `toggle` column, whose affinity is TEXT: + * `0` was bound as a REAL and stored as the text `'0.0'`, which reads as `true`. + * + * Both faces run over an embedded libSQL file: the local face by `file:` URL, + * the remote face through a real `@libsql/client` handed in as its client. Each + * stored cell is read back raw (`typeof`), so the assertion is about what is on + * disk, not what the row read presents. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { createClient, type Client } from '@libsql/client'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { lowerFilterCondition } from '@objectstack/spec/data'; +import { TursoDriver } from './turso-driver.js'; + +const OBJECT = { + name: 'bool_write_parity', + fields: { label: { type: 'string' }, flag: { type: 'boolean' }, live: { type: 'toggle' } }, +}; + +/** Accepted spellings and the boolean each one is stored as. */ +const ACCEPTED: ReadonlyArray = [ + [true, true], [false, false], [1, true], [0, false], ['1', true], ['0', false], + ['true', true], ['false', false], ['1.0', true], ['0.0', false], +]; +const REFUSED: ReadonlyArray = ['yes', 'TRUE', '', 2, ['true']]; + +type Door = 'create' | 'update' | 'upsert' | 'bulkCreate' | 'bulkUpdate' | 'updateMany'; +const DOORS: readonly Door[] = ['create', 'update', 'upsert', 'bulkCreate', 'bulkUpdate', 'updateMany']; +const OPTS = { bypassTenantAudit: true } as const; + +async function writeThrough(driver: TursoDriver, door: Door, id: string, value: unknown, seed: boolean): Promise { + const row = { id, label: door, flag: value, live: value }; + if (door === 'create') return void (await driver.create(OBJECT.name, row, OPTS)); + if (door === 'upsert') return void (await driver.upsert(OBJECT.name, row, undefined, OPTS)); + if (door === 'bulkCreate') return void (await driver.bulkCreate(OBJECT.name, [row], OPTS)); + await driver.create(OBJECT.name, { id, label: door, flag: seed, live: seed }, OPTS); + const patch = { flag: value, live: value }; + if (door === 'update') await driver.update(OBJECT.name, id, patch, OPTS); + else if (door === 'bulkUpdate') await driver.bulkUpdate(OBJECT.name, [{ id, data: patch }], OPTS); + else await driver.updateMany(OBJECT.name, { where: { id } } as DriverQuery, patch, OPTS); +} + +const label = (v: unknown) => JSON.stringify(v); + +for (const face of ['local', 'remote'] as const) { + describe(`TursoDriver ${face.toUpperCase()} — a boolean / toggle field is stored as a boolean whatever spelling it is written in`, () => { + let dir: string; + let driver: TursoDriver; + let raw: Client; + /** The cell form this face's columns store a boolean as: the remote `toggle` column has TEXT affinity. */ + const form = (field: 'flag' | 'live', b: boolean): [unknown, string] => + face === 'remote' && field === 'live' ? [b ? '1' : '0', 'text'] : [b ? 1 : 0, 'integer']; + + const cell = async (id: string): Promise | null> => { + const rs = await raw.execute({ + sql: `select flag, typeof(flag) as t, live, typeof(live) as lt from ${OBJECT.name} where id = ?`, + args: [id], + }); + const r = rs.rows[0] as any; + return r ? [[r.flag, r.t], [r.live, r.lt]] : null; + }; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), `bool-write-${face}-`)); + const file = join(dir, 'db.sqlite'); + if (face === 'local') { + driver = new TursoDriver({ url: `file:${file}` }); + await driver.initObjects([OBJECT]); + } else { + driver = new TursoDriver({ url: 'libsql://bool-write.turso.io', client: createClient({ url: `file:${file}` }) }); + await driver.connect(); + await driver.syncSchema(OBJECT.name, OBJECT); + } + expect(driver.transportMode).toBe(face); + raw = createClient({ url: `file:${file}` }); + }); + + afterAll(async () => { + raw.close(); + await driver.disconnect(); + rmSync(dir, { recursive: true, force: true }); + }); + + for (const door of DOORS) { + it(`${door}: every accepted spelling lands as its boolean`, async () => { + const got: Record = {}; + const want: Record = {}; + for (const [i, [value, b]] of ACCEPTED.entries()) { + const id = `${door}_ok_${i}`; + await writeThrough(driver, door, id, value, !b); + got[label(value)] = await cell(id); + want[label(value)] = [form('flag', b), form('live', b)]; + } + expect(got).toEqual(want); + }); + + it(`${door}: a value that spells no boolean is refused with VALIDATION_ERROR / 400 and writes nothing`, async () => { + const got: Record = {}; + const want: Record = {}; + const inserts = door === 'create' || door === 'upsert' || door === 'bulkCreate'; + for (const [i, value] of REFUSED.entries()) { + const id = `${door}_no_${i}`; + const outcome = await writeThrough(driver, door, id, value, true).then( + () => 'written', + (e: any) => ({ code: e?.code, status: e?.status }), + ); + got[label(value)] = { outcome, cell: await cell(id) }; + want[label(value)] = { + outcome: { code: 'VALIDATION_ERROR', status: 400 }, + cell: inserts ? null : [form('flag', true), form('live', true)], + }; + } + expect(got).toEqual(want); + }); + } + + it('bulkCreate: a refused row anywhere in the batch writes none of the batch', async () => { + const batch = [ + { id: 'batch_a', label: 'batch', flag: 'true', live: true }, + { id: 'batch_b', label: 'batch', flag: 'yes', live: true }, + { id: 'batch_c', label: 'batch', flag: false, live: false }, + ]; + await expect(driver.bulkCreate(OBJECT.name, batch, OPTS)).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect([await cell('batch_a'), await cell('batch_b'), await cell('batch_c')]).toEqual([null, null, null]); + }); + + it('a row written as the text true is never selected by $ne: true, $nin: [true] or $not of = true', async () => { + await driver.create(OBJECT.name, { id: 'neg_text_true', label: 'neg', flag: 'true', live: 'true' }, OPTS); + await driver.create(OBJECT.name, { id: 'neg_text_false', label: 'neg', flag: 'false', live: 'false' }, OPTS); + await driver.create(OBJECT.name, { id: 'neg_bool_true', label: 'neg', flag: true, live: true }, OPTS); + const ids = async (where: Record) => { + const lowered = lowerFilterCondition({ label: 'neg', ...where }, { isDatetimeColumn: () => false }); + return ((await driver.find(OBJECT.name, { where: lowered } as DriverQuery, OPTS)) as Array<{ id: string }>) + .map((r) => r.id) + .sort(); + }; + for (const field of ['flag', 'live']) { + expect(await ids({ [field]: { $ne: true } })).toEqual(['neg_text_false']); + expect(await ids({ [field]: { $nin: [true] } })).toEqual(['neg_text_false']); + expect(await ids({ $not: { [field]: true } })).toEqual(['neg_text_false']); + expect(await ids({ [field]: { $ne: false } })).toEqual(['neg_bool_true', 'neg_text_true']); + expect(await driver.count(OBJECT.name, { where: lowerFilterCondition({ label: 'neg', [field]: { $ne: true } }, { isDatetimeColumn: () => false }) } as DriverQuery, OPTS)).toBe(1); + } + }); + }); +} diff --git a/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts new file mode 100644 index 00000000000..979005842d2 --- /dev/null +++ b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A boolean field is stored as a boolean whatever spelling the caller sends, + * on both faces of `TursoDriver`, so a row-level `using` written in negative + * form answers each row by the boolean it was written as. + * + * Three writers hand the store the STRING `'true'`: + * + * - the engine's own door (`engine.insert`): it already writes the boolean its + * validator judged (`normalizeNumericStringValues`), the control; + * - the driver's door, called directly (a plugin or a migration that writes + * past the engine); + * - a `beforeInsert` hook that assigns the string: the engine's rewrite runs + * before the hooks, so the assignment reaches the driver as sent. + * + * The last two landed as TEXT. SQLite compares that TEXT with an INTEGER as + * unequal, so `restricted != true` and its negative siblings selected those + * rows for a member whose policy names them as the rows to withhold, on + * `find`, `count`, `findOne`, the REST list and get, and the REST delete. The + * driver's write door now binds every accepted spelling as the boolean it spells, + * so each row is answered as written. Every read below happens on the boot that + * wrote the rows: the local face's boot convergence would rewrite a TEXT cell + * on the next boot, and the remote face has none. + * + * Both faces run over an embedded libSQL file: the local face by `file:` URL, + * the remote face through a real `@libsql/client` handed in as its client. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect, afterAll, vi } from 'vitest'; +import { createClient, type Client } from '@libsql/client'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { ObjectQL } from '@objectstack/objectql'; +import { TursoDriver } from '@objectstack/driver-turso'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { RestServer } from '@objectstack/rest'; +// Paid at collection, not inside a case's clocked window: the stack reaches it by dynamic import. +import '@objectstack/metadata'; +import { installDefaultOrganization } from '../default-organization.testkit.js'; + +const OBJ = 'bool_spelling_row_scope'; +const SYS_CTX = { isSystem: true, userId: 'usr_system' }; +const MEMBER_CTX = { userId: 'usr_bool_spelling_member', positions: [], permissions: ['member_default'], posture: 'MEMBER' }; + +/** The rows the policy must withhold (each written as true), and the one it must serve. */ +const WITHHELD = ['driver_text_true', 'engine_text_true', 'hook_text_true'] as const; +const SERVED = ['engine_false']; + +/** Negative-form `using` shapes, over the boolean field and over the toggle field. */ +const SHAPES = ['restricted != true', '!(record.restricted in [true])', 'record.locked != true'] as const; + +type Face = 'local' | 'remote'; +const dirs: string[] = []; +afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); +}); + +function mockHttpServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function response() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, setHeader: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +async function boot(face: Face, file: string, using: string) { + const driver = face === 'local' + ? new TursoDriver({ url: `file:${file}` }) + : new TursoDriver({ url: 'libsql://bool-spelling-row-scope.turso.io', client: createClient({ url: `file:${file}` }) }); + const engine = new ObjectQL(); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.test.bool-spelling-row-scope', + name: 'bool spelling row scope', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ + name: OBJ, + label: 'Doc', + sharingModel: 'public_read_write', + fields: { + title: { name: 'title', type: 'text' }, + restricted: { name: 'restricted', type: 'boolean' }, + locked: { name: 'locked', type: 'toggle' }, + }, + }], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + const memberSet = PermissionSetSchema.parse({ + name: 'member_default', + label: 'Member', + objects: { [OBJ]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + rowLevelSecurity: [{ name: 'negative_form', object: OBJ, operation: 'all', using }], + }); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => (type === 'permission' ? (name === memberSet.name ? memberSet : null) : engine.getSchema(name) ?? null), + list: async () => [memberSet], + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + + const server = new RestServer(mockHttpServer() as any, new ObjectStackProtocolImplementation(engine as any) as any, { api: { requireAuth: false } } as any); + (server as any).resolveExecCtx = async () => ({ ...MEMBER_CTX }); + server.registerRoutes(); + const routes = server.getRoutes(); + const rest = async (method: string, path: string, id?: string) => { + const route = routes.find((r: any) => r.method === method && r.path === path); + if (!route) throw new Error(`no route ${method} ${path}`); + const res = response(); + await route.handler({ params: { object: OBJ, ...(id ? { id } : {}) }, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + return { engine, driver, rest }; +} + +/** Seed the four rows on the boot that reads them. */ +async function seed(engine: ObjectQL, driver: TursoDriver): Promise { + // A server-side hook that assigns the string, after the engine's own rewrite has run. + engine.registerHook('beforeInsert', async (ctx: any) => { + if (ctx.input?.data?.title === 'hook') { ctx.input.data.restricted = 'true'; ctx.input.data.locked = 'true'; } + }, { object: OBJ }); + await engine.insert(OBJ, { id: 'engine_false', title: 'engine', restricted: false, locked: false } as never, { context: SYS_CTX } as never); + await engine.insert(OBJ, { id: 'engine_text_true', title: 'engine', restricted: 'true', locked: 'true' } as never, { context: SYS_CTX } as never); + await engine.insert(OBJ, { id: 'hook_text_true', title: 'hook', restricted: false, locked: false } as never, { context: SYS_CTX } as never); + await driver.create(OBJ, { id: 'driver_text_true', title: 'driver', organization_id: 'org_default', restricted: 'true', locked: 'true' }); +} + +async function rawCells(file: string): Promise> { + const c: Client = createClient({ url: `file:${file}` }); + try { + const rs = await c.execute(`select id, typeof(restricted) as t, typeof(locked) as lt, title from ${OBJ} order by id`); + return Object.fromEntries(rs.rows.map((r: any) => [String(r.id), `${r.t}/${r.lt}`])); + } finally { + c.close(); + } +} + +for (const face of ['local', 'remote'] as const) { + describe(`TursoDriver ${face.toUpperCase()} — a negative-form row scope answers a boolean written as the string true by its boolean`, () => { + for (const using of SHAPES) { + it(`using: ${using}`, async () => { + const dir = mkdtempSync(join(tmpdir(), `bool-spelling-${face}-`)); + dirs.push(dir); + const file = join(dir, 'db.sqlite'); + const { engine, driver, rest } = await boot(face, file, using); + try { + await seed(engine, driver); + // What landed: a boolean on every row, never TEXT. The remote `toggle` column has TEXT affinity, + // so its canonical cell is the text '1' / '0' there. + const toggleForm = face === 'remote' ? 'text' : 'integer'; + expect(await rawCells(file)).toEqual(Object.fromEntries( + [...SERVED, ...WITHHELD].sort().map((id) => [id, `integer/${toggleForm}`]), + )); + + const found = (await engine.find(OBJ, { context: MEMBER_CTX } as never)) as Array<{ id: string }>; + const one: Record = {}; + const got: Record = {}; + for (const id of WITHHELD) { + one[id] = await engine.findOne(OBJ, { where: { id }, context: MEMBER_CTX } as never); + got[id] = (await rest('GET', '/api/v1/data/:object/:id', id)).status; + } + const listed = await rest('GET', '/api/v1/data/:object'); + const deleted: Record = {}; + for (const id of WITHHELD) deleted[id] = (await rest('DELETE', '/api/v1/data/:object/:id', id)).status; + + expect({ + find: found.map((r) => r.id).sort(), + count: await engine.count(OBJ, { context: MEMBER_CTX } as never), + findOne: one, + restList: ((listed.body?.records ?? []) as Array<{ id: string }>).map((r) => r.id).sort(), + restGet: got, + restDelete: deleted, + }).toEqual({ + find: SERVED, + count: SERVED.length, + findOne: Object.fromEntries(WITHHELD.map((id) => [id, null])), + restList: SERVED, + restGet: Object.fromEntries(WITHHELD.map((id) => [id, 404])), + restDelete: Object.fromEntries(WITHHELD.map((id) => [id, 404])), + }); + // The refused deletes removed nothing. + expect(Object.keys(await rawCells(file)).sort()).toEqual([...SERVED, ...WITHHELD].sort()); + } finally { + await engine.destroy(); + } + }); + } + }); +} From 280e66b7a46b5b28846eae3a6120c902b32eb587 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:01:36 +0000 Subject: [PATCH 2/3] chore: changeset and neutral pin wording Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .../boolean-write-spelling-canonical.md | 19 +++++++++++++++++++ ...boolean-written-spelling-row-scope.test.ts | 19 ++++++++++--------- 2 files changed, 29 insertions(+), 9 deletions(-) create mode 100644 .changeset/boolean-write-spelling-canonical.md diff --git a/.changeset/boolean-write-spelling-canonical.md b/.changeset/boolean-write-spelling-canonical.md new file mode 100644 index 00000000000..447fec1716e --- /dev/null +++ b/.changeset/boolean-write-spelling-canonical.md @@ -0,0 +1,19 @@ +--- +'@objectstack/driver-sql': patch +'@objectstack/driver-turso': patch +--- + +fix(driver-sql)!: a boolean field is stored as a boolean whatever spelling the caller sends + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a caller that writes through a SQLite-family driver directly (`create`, `update`, `upsert`, `bulkCreate`, `bulkUpdate`, `updateMany`) and sends a declared `boolean` / `toggle` field a value that spells no boolean, such as `'yes'`, `'TRUE'`, `''`, `2` or an array: it used to be stored as written and is now refused with `VALIDATION_ERROR` / 400 before anything is written. It ships `patch` because it is a non-protocol breaking change (AGENTS.md Post-Task Checklist step 3): no metadata author writes a driver call, so `Metadata-protocol` is `none`, and the engine's door already refuses those values. + +A declared scalar `Field.boolean` / `Field.toggle` is now stored as a boolean on SQLite whatever spelling the write sends. `true` / `false`, the numbers `1` / `0` and the text `'1'` / `'0'`, `'true'` / `'false'` and `'1.0'` / `'0.0'` are bound as the boolean they spell, so a column the driver created holds the INTEGER `1` / `0` and a `text` column retyped to `boolean` holds the text `'1'` / `'0'`. These are the spellings the local boot convergence already rewrites, read from the same table. Before, a string reached the column as text, on the local and the remote face of `TursoDriver` alike, so filters, sorts and groups did not read the row as the boolean it was written as. That includes a `beforeInsert` / `beforeUpdate` hook that assigns a string to such a field: the engine's own rewrite runs before the hooks, so the assignment now lands as a boolean too. On the remote face, a number written to a `toggle` field is stored as `'1'` / `'0'` instead of `'1.0'` / `'0.0'`. + +A remote `TursoDriver.bulkCreate` checks every row before it writes the first one, so a refused row refuses the batch with nothing written, as the local face's single INSERT already did. `null` still writes NULL. Rows stored before this change keep their stored form. + +To keep a direct write working, send `true` or `false` (or one of the spellings above) for a boolean or toggle field. diff --git a/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts index 979005842d2..04ed5cd31ae 100644 --- a/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts +++ b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts @@ -12,16 +12,17 @@ * - the driver's door, called directly (a plugin or a migration that writes * past the engine); * - a `beforeInsert` hook that assigns the string: the engine's rewrite runs - * before the hooks, so the assignment reaches the driver as sent. + * before the hooks, so the assignment reaches the driver as sent, and the + * driver's door is the one that stores it. * - * The last two landed as TEXT. SQLite compares that TEXT with an INTEGER as - * unequal, so `restricted != true` and its negative siblings selected those - * rows for a member whose policy names them as the rows to withhold, on - * `find`, `count`, `findOne`, the REST list and get, and the REST delete. The - * driver's write door now binds every accepted spelling as the boolean it spells, - * so each row is answered as written. Every read below happens on the boot that - * wrote the rows: the local face's boot convergence would rewrite a TEXT cell - * on the next boot, and the remote face has none. + * The driver's write door binds every accepted spelling as the boolean it + * spells, so all three land as a boolean, and a row-level `using` written in + * negative form (`restricted != true` and its siblings) answers each row by + * the boolean it was written as, on `find`, `count`, `findOne`, the REST list + * and get, and the REST delete. Every read below happens on the boot that + * wrote the rows: the local face's boot convergence rewrites a TEXT cell on + * the next boot, and the remote face has none, so a later boot would not tell + * the faces' write doors apart. * * Both faces run over an embedded libSQL file: the local face by `file:` URL, * the remote face through a real `@libsql/client` handed in as its client. From 821e6832c0912938ddc2d11cd419e914067e058e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 01:29:25 +0000 Subject: [PATCH 3/3] test(runtime): report the reads even when the stored-form check is red Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .../src/domains/boolean-written-spelling-row-scope.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts index 04ed5cd31ae..f2775a97b5b 100644 --- a/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts +++ b/packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts @@ -175,9 +175,9 @@ for (const face of ['local', 'remote'] as const) { try { await seed(engine, driver); // What landed: a boolean on every row, never TEXT. The remote `toggle` column has TEXT affinity, - // so its canonical cell is the text '1' / '0' there. + // so its canonical cell is the text '1' / '0' there. Soft, so a red here still reports the reads. const toggleForm = face === 'remote' ? 'text' : 'integer'; - expect(await rawCells(file)).toEqual(Object.fromEntries( + expect.soft(await rawCells(file)).toEqual(Object.fromEntries( [...SERVED, ...WITHHELD].sort().map((id) => [id, `integer/${toggleForm}`]), ));