Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35341-sqlite-retyped-boolean-text-column.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<string, boolean> = {
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<void> {
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<Array<[string, unknown, string]>> {
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<Record<string, unknown>> {
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<string, unknown>): Promise<string[]> {
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<string, boolean>) =>
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<string, boolean> = { 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));
});
});
11 changes: 9 additions & 2 deletions packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -177,10 +177,17 @@ export class FilterHelpersFacet {
}

/** The body of `SqlDriver#coerceFilterValue`; the method's docblock there is its contract. */
static coerceFilterValue(this: Pick<FilterHelpersHost, 'coerceFilterValue' | 'isMssql' | 'isOracle' | 'oracleRawUuidFieldsByObject' | 'oracleUuidBinding' | 'storageDatetimeValue' | 'temporalFieldKind' | 'toDateOnly'>, table: string | null, field: string, value: any): any {
static coerceFilterValue(this: Pick<FilterHelpersHost, 'booleanFields' | 'coerceFilterValue' | 'isMssql' | 'isOracle' | 'isSqlite' | 'oracleRawUuidFieldsByObject' | 'oracleUuidBinding' | 'storageDatetimeValue' | 'temporalFieldKind' | 'toDateOnly'>, 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
Expand Down
25 changes: 15 additions & 10 deletions packages/drivers/driver-sql/src/sql-driver-schema-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2051,12 +2051,15 @@ export async function backfillCanonicalTimes(this: Pick<SchemaSyncHost, 'canonic
* all read this one predicate, so the plan cannot count rows the step will not
* convert.
*
* Only the two spellings `'true'` / `'false'` can be there: SQLite's NUMERIC
* Four spellings can be there. `'true'` / `'false'`: SQLite's NUMERIC
* affinity, which a `boolean` column takes, folds the text `'1'` / `'0'` into
* integers on write and keeps `'true'` / `'false'` as TEXT. `IN` compares with
* the BINARY collation, so `'TRUE'` or `'yes'` is not selected.
* integers on write and keeps `'true'` / `'false'` as TEXT. [#35341]
* `'1.0'` / `'0.0'`: on a column with TEXT affinity (a `text` field retyped to
* `boolean`), the driver's own writes stored the REAL its JS number bound as,
* as that text, until it bound `sqliteBooleanBinding`'s `'1'` / `'0'`. `IN`
* compares with the BINARY collation, so `'TRUE'` or `'yes'` is not selected.
*/
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in ('true', 'false')`;
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in ('true', 'false', '1.0', '0.0')`;

/**
* [#34973] How many ids of the converted rows the backfill's `info` line
Expand All @@ -2074,7 +2077,9 @@ const BOOLEAN_BACKFILL_SAMPLE_IDS = 5;
* ({@link SqlDriver.booleanFields}) on the integer form every write takes
* since the engine stores the boolean a reading spells (#34916). Rows written
* before that by a door that sent the text `'true'` / `'false'` (the console's
* inline grid) still hold that TEXT. The row read presents them as booleans,
* inline grid) still hold that TEXT. [#35341] So do the `'1.0'` / `'0.0'` the
* driver's own writes left on a TEXT-affinity column, which the row read
* presented as `true` both. The row read presents the others as booleans,
* but every comparison runs in SQL against the raw cell, so `= false` misses a
* text `'false'`, `$in`, `!=` and `$nin` answer wrongly, ORDER BY sorts the
* text after every integer, and an aggregate group key presents a text
Expand All @@ -2088,7 +2093,7 @@ const BOOLEAN_BACKFILL_SAMPLE_IDS = 5;
* it, so no other dialect can hold such a row.
*
* ONE `UPDATE` per column, atomic on SQLite, whose `WHERE` is
* {@link SQLITE_LEGACY_BOOLEAN_TEXT}: it selects only the two text spellings,
* {@link SQLITE_LEGACY_BOOLEAN_TEXT}: it selects only the four text spellings,
* so a converged column is a no-op and a second boot converts 0 rows. One
* counting scan over the column's text cells comes first, and the id sample and
* the `UPDATE` run only when it found legacy text, so a converged column costs
Expand Down Expand Up @@ -2134,7 +2139,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
[table, field, field, BOOLEAN_BACKFILL_SAMPLE_IDS],
);
const res = await this.knex.raw(
`update ?? set ?? = case ?? when 'true' then 1 when 'false' then 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`,
`update ?? set ?? = case when ?? in ('true', '1.0') 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
Expand All @@ -2145,7 +2150,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
if (converted) {
this.logger.info?.(
`[sql-driver] canonicalised boolean storage for ${table}.${field}: rows that held the ` +
`text 'true' / 'false' now hold 1 / 0, so boolean filters, sorts and groups answer them ` +
`text 'true' / 'false' (or '1.0' / '0.0') now hold 1 / 0, so boolean filters, sorts and groups answer them ` +
`as the boolean they read as`,
{ table, field, rowsConverted: converted, sampleIds: sample.map((r) => String(r.id)) },
);
Expand All @@ -2154,7 +2159,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
if (withheld > 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 },
Expand All @@ -2163,7 +2168,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
} catch (err) {
this.logger.warn(
`[sql-driver] could not canonicalise boolean storage for ${table}.${field}; rows holding ` +
`the text 'true' / 'false' stay missed by boolean filters until a later boot converts them`,
`the text 'true' / 'false' (or '1.0' / '0.0') stay missed by boolean filters until a later boot converts them`,
{ error: err instanceof Error ? err.message : String(err) },
);
}
Expand Down
Loading
Loading