From 5d191faf28224790fef40ea129defa4ab52305be Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:30:44 +0000 Subject: [PATCH 1/2] fix(driver-sql): a boolean retyped from text stores 1 / 0 on SQLite, and the boot converges 1.0 / 0.0 A text field retyped to boolean keeps its TEXT column on SQLite. knex binds a JS boolean as a number, better-sqlite3 binds a number as REAL, and TEXT affinity kept it as the text '1.0' / '0.0', which the row read presented as true both. The write and the filter comparand of a declared scalar boolean now bind the text '1' / '0' (NUMERIC affinity folds it to the integer 1 / 0; TEXT keeps the spelling the boot convergence writes), and the convergence rewrites existing '1.0' / '0.0' rows. Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-Authored-By: Claude --- ...-35341-retyped-boolean-text-column.test.ts | 199 ++++++++++++++++++ .../src/sql-driver-filter-helpers.ts | 11 +- .../driver-sql/src/sql-driver-schema-sync.ts | 25 ++- .../src/sql-driver-sqlite-serialisation.ts | 35 ++- 4 files changed, 257 insertions(+), 13 deletions(-) create mode 100644 packages/drivers/driver-sql/src/sql-driver-35341-retyped-boolean-text-column.test.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-35341-retyped-boolean-text-column.test.ts b/packages/drivers/driver-sql/src/sql-driver-35341-retyped-boolean-text-column.test.ts new file mode 100644 index 00000000000..0f614697c08 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-35341-retyped-boolean-text-column.test.ts @@ -0,0 +1,199 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35341] On SQLite, a `text` field retyped to `boolean` keeps its TEXT + * column, and the driver's own boolean writes landed there as the text + * `'1.0'` / `'0.0'`: knex binds a JS boolean as `Number(b)`, better-sqlite3 + * binds a JS number as a REAL, and TEXT affinity keeps the REAL as text. The + * row read presented both as `true` (`presentStoredBoolean('0.0')` is + * `Boolean('0.0')`), so a stored `false` read as `true` through `find()` and + * `distinct()`, while the `= false` comparand, bound the same way, matched + * `'0.0'` and missed the `'0'` rows the boot convergence writes on that column. + * + * The write and the comparand now bind `sqliteBooleanBinding`'s `'1'` / `'0'`, + * which a TEXT-affinity column keeps as that text and the NUMERIC affinity of a + * column the driver created folds into the INTEGER `1` / `0`; the boot + * convergence rewrites the `'1.0'` / `'0.0'` rows already stored. Three + * describes: the retyped column's new writes, its existing rows across a + * boot, and the CONTROL — an INTEGER-form boolean column the driver created, + * whose stored form and answers do not change. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { SqlDriver } from './sql-driver.js'; + +const RETYPED = 'bool_retyped_35341'; +const EXISTING = 'bool_retyped_existing_35341'; +const CONTROL = 'bool_integer_35341'; + +interface Logged { msg: string; meta?: any } + +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' } } }); +const asBoolean = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'boolean' } } }); + +/** The rows every write door leaves, by id: which boolean each one was last written as. */ +const WRITTEN: Record = { + bulk_false: false, bulk_true: true, bulkupd_false: false, create_false: false, create_true: true, + many_false: false, update_false: false, upsert_false: false, +}; + +/** Write `WRITTEN` through every door: create, update, upsert, bulkCreate, bulkUpdate, updateMany. */ +async function writeThroughEveryDoor(driver: SqlDriver, table: string): Promise { + await driver.create(table, { id: 'create_false', label: 'x', flag: false }); + await driver.create(table, { id: 'create_true', label: 'x', flag: true }); + await driver.create(table, { id: 'update_false', label: 'x', flag: true }); + await driver.update(table, 'update_false', { flag: false }); + await driver.upsert(table, { id: 'upsert_false', label: 'x', flag: false }); + await driver.bulkCreate(table, [{ id: 'bulk_false', label: 'x', flag: false }, { id: 'bulk_true', label: 'x', flag: true }]); + await driver.create(table, { id: 'bulkupd_false', label: 'x', flag: true }); + await driver.bulkUpdate(table, [{ id: 'bulkupd_false', data: { flag: false } }]); + await driver.create(table, { id: 'many_false', label: 'x', flag: true }); + await driver.updateMany(table, { where: { id: 'many_false' } } as DriverQuery, { flag: false }); +} + +async function stored(driver: SqlDriver, table: string): Promise> { + const rows = await (driver as any).knex.raw(`select id, flag, typeof(flag) as t from ${table} order by id`); + return rows.map((r: any) => [r.id, r.flag, r.t]); +} + +async function presented(driver: SqlDriver, table: string): Promise> { + const rows = (await driver.find(table, {} as DriverQuery)) as Array<{ id: string; flag: unknown }>; + return Object.fromEntries(rows.map((r) => [r.id, r.flag])); +} + +async function idsWhere(driver: SqlDriver, table: string, where: Record): Promise { + const rows = (await driver.find(table, { where } as DriverQuery)) as Array<{ id: string }>; + return rows.map((r) => r.id).sort(); +} + +const idsWritten = (value: boolean, rows: Record) => + Object.keys(rows).filter((id) => rows[id] === value).sort(); + +describe('[#35341] driver-sql — a boolean retyped from text: every write door stores 1 / 0 the reads and filters agree on (sqlite)', () => { + let driver: SqlDriver; + + beforeAll(async () => { + driver = sqliteDriver(); + await driver.initObjects([asText(RETYPED)]); + await driver.initObjects([asBoolean(RETYPED)]); + await writeThroughEveryDoor(driver, RETYPED); + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + it('the fixture: the retyped column is still TEXT', async () => { + const cols = await (driver as any).knex.raw(`select type from pragma_table_info('${RETYPED}') where name = 'flag'`); + expect(cols).toEqual([{ type: 'TEXT' }]); + }); + + it('every write door stores the text 1 / 0, never 1.0 / 0.0', async () => { + expect(await stored(driver, RETYPED)).toEqual( + Object.keys(WRITTEN).sort().map((id) => [id, WRITTEN[id] ? '1' : '0', 'text']), + ); + }); + + it('find() presents each row as the boolean it was written as', async () => { + expect(await presented(driver, RETYPED)).toEqual(WRITTEN); + }); + + it('distinct() answers false and true', async () => { + expect([...(await driver.distinct(RETYPED, 'flag'))].sort()).toEqual([false, true]); + }); + + it('= false and = true select exactly the rows find() presents as false and true', async () => { + expect(await idsWhere(driver, RETYPED, { flag: false })).toEqual(idsWritten(false, WRITTEN)); + expect(await idsWhere(driver, RETYPED, { flag: true })).toEqual(idsWritten(true, WRITTEN)); + }); + + it('$ne and $in agree too', async () => { + expect(await idsWhere(driver, RETYPED, { flag: { $ne: true } })).toEqual(idsWritten(false, WRITTEN)); + expect(await idsWhere(driver, RETYPED, { flag: { $in: [false] } })).toEqual(idsWritten(false, WRITTEN)); + }); +}); + +describe('[#35341] driver-sql — a boot converges the 1.0 / 0.0 an older build stored on a retyped column (sqlite)', () => { + let driver: SqlDriver; + let pendingBeforeBoot: unknown; + const info: Logged[] = []; + const warn: Logged[] = []; + const OLD: Record = { old_false: false, old_true: true, old_zero: false }; + + beforeAll(async () => { + driver = sqliteDriver(); + await driver.initObjects([asText(EXISTING)]); + const knex = (driver as any).knex; + // What the driver's own writes stored on this column before the fix, and + // the '0' an earlier convergence of a text 'false' left. + await knex(EXISTING).insert([ + { id: 'old_false', label: 'x', flag: '0.0' }, + { id: 'old_true', label: 'x', flag: '1.0' }, + { id: 'old_zero', label: 'x', flag: '0' }, + ]); + (driver as any).logger = { + info: (msg: string, meta?: any) => { info.push({ msg, meta }); }, + warn: (msg: string, meta?: any) => { warn.push({ msg, meta }); }, + }; + driver.setDeferredDdl(true); + await driver.initObjects([asBoolean(EXISTING)]); + pendingBeforeBoot = (await driver.previewDeferredSchemaWork()).filter((p) => p.kind === 'normalize_boolean_storage'); + driver.setDeferredDdl(false); + await driver.initObjects([asBoolean(EXISTING)]); + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + it('os migrate plan counts the 1.0 / 0.0 rows as normalize_boolean_storage', () => { + expect(pendingBeforeBoot).toEqual([{ table: EXISTING, kind: 'normalize_boolean_storage', columns: ['flag'], rows: 2 }]); + }); + + it('the boot rewrites them to the text 1 / 0, withholds nothing, and says so', async () => { + expect(await stored(driver, EXISTING)).toEqual([ + ['old_false', '0', 'text'], ['old_true', '1', 'text'], ['old_zero', '0', 'text'], + ]); + expect(warn.filter((l) => l.msg.includes('unconverted'))).toEqual([]); + const converted = info.filter((l) => l.msg.includes('canonicalised boolean storage')); + expect(converted.map((l) => [l.meta.field, l.meta.rowsConverted])).toEqual([['flag', 2]]); + }); + + it('find(), distinct() and = false then agree on every row', async () => { + expect(await presented(driver, EXISTING)).toEqual(OLD); + expect([...(await driver.distinct(EXISTING, 'flag'))].sort()).toEqual([false, true]); + expect(await idsWhere(driver, EXISTING, { flag: false })).toEqual(idsWritten(false, OLD)); + }); +}); + +describe('[#35341] driver-sql — CONTROL: a boolean column the driver created stores and answers as before (sqlite)', () => { + let driver: SqlDriver; + + beforeAll(async () => { + driver = sqliteDriver(); + await driver.initObjects([asBoolean(CONTROL)]); + await writeThroughEveryDoor(driver, CONTROL); + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + it('every write door stores the INTEGER 1 / 0', async () => { + expect(await stored(driver, CONTROL)).toEqual( + Object.keys(WRITTEN).sort().map((id) => [id, WRITTEN[id] ? 1 : 0, 'integer']), + ); + }); + + it('find(), distinct() and = false / = true agree', async () => { + expect(await presented(driver, CONTROL)).toEqual(WRITTEN); + expect([...(await driver.distinct(CONTROL, 'flag'))].sort()).toEqual([false, true]); + expect(await idsWhere(driver, CONTROL, { flag: false })).toEqual(idsWritten(false, WRITTEN)); + expect(await idsWhere(driver, CONTROL, { flag: true })).toEqual(idsWritten(true, WRITTEN)); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 6ec738601be..21ac54f81c7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -45,7 +45,7 @@ import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAs import type { JsonColumnFieldClass } from '@objectstack/core'; import { StorageNameMapping } from '@objectstack/spec/system'; import { emitBalancedGroup } from './sql-driver-balanced-group.js'; -import { presentStoredBoolean } from './sql-driver-sqlite-serialisation.js'; +import { presentStoredBoolean, sqliteBooleanBinding } from './sql-driver-sqlite-serialisation.js'; import type { Knex } from 'knex'; import { AUDIT_TIMESTAMP_COLUMNS, CROSS_FIELD_COMPARISON_OPERATORS, SQLITE_TIME_EXPR_REFS, TEXT_OPERATORS, @@ -177,10 +177,17 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#coerceFilterValue`; the method's docblock there is its contract. */ - static coerceFilterValue(this: Pick, table: string | null, field: string, value: any): any { + static coerceFilterValue(this: Pick, table: string | null, field: string, value: any): any { if (value == null || !table) return value; if (Array.isArray(value)) return value.map((v) => this.coerceFilterValue(table, field, v)); + // [#35341] A boolean comparand against a declared scalar boolean column is + // bound the way `formatInput` binds the write (`sqliteBooleanBinding`), so + // `= false` selects the rows the row read presents as `false`. + if (this.isSqlite && typeof value === 'boolean' && this.booleanFields[table]?.includes(field) === true) { + return sqliteBooleanBinding(value); + } + // [#31390] Oracle: a comparand against a `RAW(16)` uuid column (as the // catalog reports it — `SqlDriver#primeOracleRawUuidColumns`) binds as // `HEXTORAW(?)`. A comparison comparand that is not uuid text was refused 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 537e5397bac..66b443f687f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts @@ -2051,12 +2051,15 @@ export async function backfillCanonicalTimes(this: Pick String(r.id)) }, ); @@ -2154,7 +2159,7 @@ export async function backfillCanonicalBooleans(this: Pick 0) { this.logger.warn( `[sql-driver] left ${withheld} row(s) of ${table}.${field} unconverted: their stored ` + - `value is text other than 'true' or 'false', which names no boolean the driver can ` + + `value is text other than 'true', 'false', '1.0' or '0.0', which names no boolean the driver can ` + `read without guessing. Boolean filters do not match them until the values are ` + `corrected or cleared at the source`, { table, field, rowsWithheld: withheld }, @@ -2163,7 +2168,7 @@ export async function backfillCanonicalBooleans(this: Pick, object: string, data: any): any { + static formatInput(this: Pick, object: string, data: any): any { let copy: any = data; let copied = false; @@ -307,6 +328,18 @@ export class SqliteSerialisationFacet { if (!this.isSqlite) return copy; + // [#35341] A declared scalar boolean is bound as the text `'1'` / `'0'`. + // See {@link sqliteBooleanBinding}. + const booleanFields = this.booleanFields[object]; + if (booleanFields && booleanFields.length > 0 && copy && typeof copy === 'object') { + for (const field of booleanFields) { + const v = copy[field]; + if (typeof v !== 'boolean') continue; + if (!copied) { copy = { ...copy }; copied = true; } + copy[field] = sqliteBooleanBinding(v); + } + } + // Safety net: better-sqlite3 can only bind numbers/strings/bigints/buffers/ // null. Any value still an array or plain object here (a field type not // classified as JSON, a `Field.multiple` we didn't catch, or an ad-hoc From af25ec33ef9b5f4adac57664ab038caf738f398b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:49:15 +0000 Subject: [PATCH 2/2] chore(changeset): driver-sql patch for the retyped boolean column on SQLite Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-Authored-By: Claude --- .../35341-sqlite-retyped-boolean-text-column.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/35341-sqlite-retyped-boolean-text-column.md diff --git a/.changeset/35341-sqlite-retyped-boolean-text-column.md b/.changeset/35341-sqlite-retyped-boolean-text-column.md new file mode 100644 index 00000000000..da7094ec65a --- /dev/null +++ b/.changeset/35341-sqlite-retyped-boolean-text-column.md @@ -0,0 +1,14 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): on SQLite, a boolean field retyped from text stores `1` / `0`, so a saved `false` no longer reads as `true` + +Clause-②: no +Metadata-protocol: none + +On SQLite, a field whose type changed from `text` to `boolean` keeps its TEXT column. Every write of that field (create, update, upsert, bulk create, bulk update, update-many) stored `false` as the text `'0.0'` and `true` as `'1.0'`, because the JS number a boolean was bound as reached SQLite as a REAL. Reads then answered `true` for both, `distinct()` and group keys counted every row as `true`, and an `= false` filter disagreed with what the rows showed. + +- **Writes.** A declared scalar `boolean` / `toggle` value is now bound as the text `'1'` / `'0'`. A column the driver created still stores the integer `1` / `0`, so its stored form does not change; a retyped TEXT column stores `'1'` / `'0'`, which reads back as the boolean that was written. +- **Filters.** A boolean comparand on such a field is bound the same way, so `= false`, `= true` and `in [false]` select exactly the rows that read as that boolean. +- **Existing rows.** The boot's boolean storage convergence now also rewrites the `'1.0'` / `'0.0'` that earlier writes left, the same as it rewrites `'true'` / `'false'`; `os migrate plan` counts them under `normalize_boolean_storage`. Nothing to run by hand: the next start converges them.