Skip to content

Commit c0484c8

Browse files
fix(driver-sql): a boolean retyped from text stores 1 / 0 on SQLite, so a saved false no longer reads as true (#35511)
repo:objectstack#5 · os-bill · session_01Utp6Ca1jJvsA1dHsPwMiQb Fixes #35341 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在 SQLite 上,把字段类型从「文本」改成「是/否」之后,存「否」的记录现在读出来就是「否」,列表、去重、分组和「= 否」筛选结果一致;以前存成怪写法的老记录会在下次启动时自动纠正。 - 为什么做:这类字段过去每次保存「否」都被存成「0.0」,读出来却显示「是」,筛选和显示互相矛盾,用户看到的是/否值是错的。 - 出错会怎样:只影响 SQLite 上改过类型的是/否字段;新建的是/否字段存储形式不变。若启动时纠正失败,只会记一条警告并在下次启动重试,不会阻止启动。 - 要你做什么:无,席位落地。 ## 席位核对 - Where to look first: `sql-driver-sqlite-serialisation.ts` (the new `sqliteBooleanBinding` and its use at the end of `formatInput`), then the comparand branch at the top of `coerceFilterValue` in `sql-driver-filter-helpers.ts`, then the widened `SQLITE_LEGACY_BOOLEAN_TEXT` and the `UPDATE` in `backfillCanonicalBooleans` (`sql-driver-schema-sync.ts`). - Two-minute check: `pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 src/sql-driver-35341-retyped-boolean-text-column.test.ts` answers 11/11 green; the CONTROL describe (a boolean column the driver created) shows the integer `1` / `0` storage unchanged. - Route: B (the card's Ask), no read-side backstop. Reason: binding the write and the comparand as the text `'1'` / `'0'` and extending the boot convergence to `'1.0'` / `'0.0'` makes `find()`, `distinct()` and `= false` agree on new and existing rows, so `presentStoredBoolean` needs no widening (AGENTS.md Prime Directive 12) and the stored form converges on one spelling, the direction of PR #35076. ## What changes On SQLite, a `text` field retyped to `boolean` keeps its TEXT column. knex's better-sqlite3 client binds a JS boolean as `Number(b)`, better-sqlite3 binds a JS number as a REAL, and TEXT affinity keeps the REAL as the text `'0.0'` / `'1.0'`, which `presentStoredBoolean` read as `true` both. - **Write.** `formatInput` (SQLite only) binds a declared scalar boolean (`booleanFields`) that holds a JS boolean as the text `'1'` / `'0'` (`sqliteBooleanBinding`). NUMERIC affinity (a column the driver created) folds it into the INTEGER `1` / `0`, unchanged from before; TEXT affinity keeps `'1'` / `'0'`, the spelling the boot convergence writes and the presenter reads. Every write door runs through `formatInput`: create, update, upsert, bulkCreate, bulkUpdate, updateMany. - **Comparand.** `coerceFilterValue` binds a boolean comparand on the same fields the same way, so `= false` / `= true` / `$in` / `$ne` select the rows the row read presents as that boolean. - **Existing rows.** `SQLITE_LEGACY_BOOLEAN_TEXT` (the backfill's count, sample, `UPDATE` and the `os migrate plan` preview all read it) now also selects `'1.0'` / `'0.0'`, and the `UPDATE` maps them to `1` / `0`. They were counted as withheld and warned about before. - A BigInt would bind an INTEGER too; it is not used because knex's query-text formatter throws on one (measured: `str.replace is not a function`). ## Tests <details><summary>New pin: sql-driver-35341-retyped-boolean-text-column.test.ts, 11/11 green</summary> Three describes: the retyped TEXT column written through all six write doors (storage is the text `1` / `0`; `find()`, `distinct()`, `= false`, `= true`, `$ne`, `$in` agree); a retyped column holding `'0.0'` / `'1.0'` / `'0'` across a boot (the plan counts 2 rows as `normalize_boolean_storage`, the boot rewrites them, withholds nothing, and the reads and filter agree); CONTROL, a boolean column the driver created (INTEGER `1` / `0`, answers unchanged). ``` Test Files 1 passed (1) Tests 11 passed (11) ``` </details> <details><summary>Ablation, one arm per mechanism (scripts/ablation-replace.mjs; the test imports src, no dist on the path)</summary> - Arm 1, write bind removed (`copy[field] = v;`): anchor 1 to 0, blob 70f2a4d to aadb818335c5; 5 failed / 6 passed (storage, find, distinct, filters red; CONTROL green). Restored: blob == HEAD, `git diff HEAD` empty. - Arm 2, comparand branch removed (`return value;`): blob 21ac54f to 528a57d1a45e; 3 failed / 8 passed (`= false` / `= true`, `$ne` / `$in`, the existing-rows filter red). Restored. - Arm 3, convergence predicate back to `('true', 'false')`: blob 66b443f to 3886962a9261; 3 failed / 8 passed (plan count, boot rewrite, existing-rows agreement red). Restored. </details> <details><summary>driver-sql package suite and typecheck</summary> - `pnpm --filter @objectstack/driver-sql test` (lock VERDICT command-exit 0, tree 5d191fa; the later head af25ec3 adds only the changeset): Test Files 265 passed, 13 skipped (278); Tests 4408 passed, 257 skipped (4665). - `pnpm --filter @objectstack/driver-sql typecheck`: exit 0 (tsconfig includes `src/**/*`, so the new test is compiled). </details> ## Acceptance notes - The data door was measured, before and after (todo example on a better-sqlite3 file database, a field booted as `text` then retyped to `boolean`; the example edit was a scratch edit, reverted, not in this diff). See Verification. - driver-sqlite-wasm and driver-turso inherit `isSqlite` and so take the same bind. sql.js already bound an integer-valued number as INTEGER, so a TEXT column there stored `'0'` before this change and stores `'0'` after; this was reasoned from sql.js's binder, not measured here. - A number `0` / `1` (not a JS boolean) handed straight to the driver is not rebound; the engine's boolean arm hands the driver JS booleans. ## Verification <details><summary>A0, the REST data door, origin/main 6f36818 vs this branch</summary> Before (origin/main): after the retype boot, `pragma_table_info` reads `probe_flag` TEXT. `POST /api/v1/data/todo_task` with `probe_flag: false` answers 201 with `"probe_flag":true`; the cell is the text `'0.0'` (and `'1.0'` for true). The list reads both rows as `true`; the `probe_flag = false` filter returns the false row, presented as `true`. After (driver-sql rebuilt at af25ec3, same database file): the boot rewrote the two rows to `'0'` / `'1'`. `POST` with `false` answers `"probe_flag":false` and stores `'0'`. The list reads `[door_false,false],[door_true,true],[post_false,false],[post_true,true]`; the `= false` filter returns exactly `door_false` and `post_false`, both `false`. </details> <details><summary>A1 to A3, measured on origin/main 6f36818 at the driver</summary> - A1: knex 3.3.0 `client-better-sqlite3` `_formatBindings` maps a boolean to `Number(b)`; better-sqlite3 13.0.3 binds it as REAL. On the retyped TEXT column, create, update, bulkCreate and updateMany all stored `'0.0'` / `'1.0'`; on an INTEGER-form column, `0` / `1`. - A2: `backfillCanonicalBooleans` writes the integer `1` / `0`, which a TEXT column stores as the text `'1'` / `'0'`. `'0.0'` / `'1.0'` were not in its population: a reboot logged `left 7 row(s) of ... unconverted` and changed nothing. - A3: `presentStoredBoolean` reads `'false'` / `'0'` as false, `'true'` / `'1'` as true, anything else as `Boolean(value)`, so `'0.0'` reads `true`. The `= false` comparand bound as REAL compared as `'0.0'` on the TEXT column: it matched the `'0.0'` rows and missed the `'0'` row the convergence left. </details> <details><summary>Local gates (derived with dispatch-gates.mjs --commands, run on head af25ec3)</summary> 68 families derived for the 5 changed paths; 66 exit 0, 2 NOT MEASURED (exit 3, PREREQUISITE NOT MET): `pnpm check:dual-build-cjs-loads` (reads every package's dist; no whole-repo build here) and `pnpm check:type-check-debt` (its re-measure build never got a turn on the shared verify lock). Both run in CI's `Lint & Repo Gates`. `dispatch-gates.mjs --ran` with the exit codes recorded: `✓ 68 derived famil(ies) accounted for — 66 run, 2 NOT-MEASURED`. `overlap-check.mjs --branch=HEAD`: `VERDICT clean exit 0`. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 94fb8db commit c0484c8

5 files changed

Lines changed: 271 additions & 13 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): on SQLite, a boolean field retyped from text stores `1` / `0`, so a saved `false` no longer reads as `true`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
- **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.
13+
- **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.
14+
- **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.
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#35341] On SQLite, a `text` field retyped to `boolean` keeps its TEXT
5+
* column, and the driver's own boolean writes landed there as the text
6+
* `'1.0'` / `'0.0'`: knex binds a JS boolean as `Number(b)`, better-sqlite3
7+
* binds a JS number as a REAL, and TEXT affinity keeps the REAL as text. The
8+
* row read presented both as `true` (`presentStoredBoolean('0.0')` is
9+
* `Boolean('0.0')`), so a stored `false` read as `true` through `find()` and
10+
* `distinct()`, while the `= false` comparand, bound the same way, matched
11+
* `'0.0'` and missed the `'0'` rows the boot convergence writes on that column.
12+
*
13+
* The write and the comparand now bind `sqliteBooleanBinding`'s `'1'` / `'0'`,
14+
* which a TEXT-affinity column keeps as that text and the NUMERIC affinity of a
15+
* column the driver created folds into the INTEGER `1` / `0`; the boot
16+
* convergence rewrites the `'1.0'` / `'0.0'` rows already stored. Three
17+
* describes: the retyped column's new writes, its existing rows across a
18+
* boot, and the CONTROL — an INTEGER-form boolean column the driver created,
19+
* whose stored form and answers do not change.
20+
*/
21+
22+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
23+
import type { DriverQuery } from '@objectstack/spec/contracts';
24+
import { SqlDriver } from './sql-driver.js';
25+
26+
const RETYPED = 'bool_retyped_35341';
27+
const EXISTING = 'bool_retyped_existing_35341';
28+
const CONTROL = 'bool_integer_35341';
29+
30+
interface Logged { msg: string; meta?: any }
31+
32+
function sqliteDriver(): SqlDriver {
33+
return new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any);
34+
}
35+
36+
const asText = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'text' } } });
37+
const asBoolean = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'boolean' } } });
38+
39+
/** The rows every write door leaves, by id: which boolean each one was last written as. */
40+
const WRITTEN: Record<string, boolean> = {
41+
bulk_false: false, bulk_true: true, bulkupd_false: false, create_false: false, create_true: true,
42+
many_false: false, update_false: false, upsert_false: false,
43+
};
44+
45+
/** Write `WRITTEN` through every door: create, update, upsert, bulkCreate, bulkUpdate, updateMany. */
46+
async function writeThroughEveryDoor(driver: SqlDriver, table: string): Promise<void> {
47+
await driver.create(table, { id: 'create_false', label: 'x', flag: false });
48+
await driver.create(table, { id: 'create_true', label: 'x', flag: true });
49+
await driver.create(table, { id: 'update_false', label: 'x', flag: true });
50+
await driver.update(table, 'update_false', { flag: false });
51+
await driver.upsert(table, { id: 'upsert_false', label: 'x', flag: false });
52+
await driver.bulkCreate(table, [{ id: 'bulk_false', label: 'x', flag: false }, { id: 'bulk_true', label: 'x', flag: true }]);
53+
await driver.create(table, { id: 'bulkupd_false', label: 'x', flag: true });
54+
await driver.bulkUpdate(table, [{ id: 'bulkupd_false', data: { flag: false } }]);
55+
await driver.create(table, { id: 'many_false', label: 'x', flag: true });
56+
await driver.updateMany(table, { where: { id: 'many_false' } } as DriverQuery, { flag: false });
57+
}
58+
59+
async function stored(driver: SqlDriver, table: string): Promise<Array<[string, unknown, string]>> {
60+
const rows = await (driver as any).knex.raw(`select id, flag, typeof(flag) as t from ${table} order by id`);
61+
return rows.map((r: any) => [r.id, r.flag, r.t]);
62+
}
63+
64+
async function presented(driver: SqlDriver, table: string): Promise<Record<string, unknown>> {
65+
const rows = (await driver.find(table, {} as DriverQuery)) as Array<{ id: string; flag: unknown }>;
66+
return Object.fromEntries(rows.map((r) => [r.id, r.flag]));
67+
}
68+
69+
async function idsWhere(driver: SqlDriver, table: string, where: Record<string, unknown>): Promise<string[]> {
70+
const rows = (await driver.find(table, { where } as DriverQuery)) as Array<{ id: string }>;
71+
return rows.map((r) => r.id).sort();
72+
}
73+
74+
const idsWritten = (value: boolean, rows: Record<string, boolean>) =>
75+
Object.keys(rows).filter((id) => rows[id] === value).sort();
76+
77+
describe('[#35341] driver-sql — a boolean retyped from text: every write door stores 1 / 0 the reads and filters agree on (sqlite)', () => {
78+
let driver: SqlDriver;
79+
80+
beforeAll(async () => {
81+
driver = sqliteDriver();
82+
await driver.initObjects([asText(RETYPED)]);
83+
await driver.initObjects([asBoolean(RETYPED)]);
84+
await writeThroughEveryDoor(driver, RETYPED);
85+
});
86+
87+
afterAll(async () => {
88+
await driver.disconnect();
89+
});
90+
91+
it('the fixture: the retyped column is still TEXT', async () => {
92+
const cols = await (driver as any).knex.raw(`select type from pragma_table_info('${RETYPED}') where name = 'flag'`);
93+
expect(cols).toEqual([{ type: 'TEXT' }]);
94+
});
95+
96+
it('every write door stores the text 1 / 0, never 1.0 / 0.0', async () => {
97+
expect(await stored(driver, RETYPED)).toEqual(
98+
Object.keys(WRITTEN).sort().map((id) => [id, WRITTEN[id] ? '1' : '0', 'text']),
99+
);
100+
});
101+
102+
it('find() presents each row as the boolean it was written as', async () => {
103+
expect(await presented(driver, RETYPED)).toEqual(WRITTEN);
104+
});
105+
106+
it('distinct() answers false and true', async () => {
107+
expect([...(await driver.distinct(RETYPED, 'flag'))].sort()).toEqual([false, true]);
108+
});
109+
110+
it('= false and = true select exactly the rows find() presents as false and true', async () => {
111+
expect(await idsWhere(driver, RETYPED, { flag: false })).toEqual(idsWritten(false, WRITTEN));
112+
expect(await idsWhere(driver, RETYPED, { flag: true })).toEqual(idsWritten(true, WRITTEN));
113+
});
114+
115+
it('$ne and $in agree too', async () => {
116+
expect(await idsWhere(driver, RETYPED, { flag: { $ne: true } })).toEqual(idsWritten(false, WRITTEN));
117+
expect(await idsWhere(driver, RETYPED, { flag: { $in: [false] } })).toEqual(idsWritten(false, WRITTEN));
118+
});
119+
});
120+
121+
describe('[#35341] driver-sql — a boot converges the 1.0 / 0.0 an older build stored on a retyped column (sqlite)', () => {
122+
let driver: SqlDriver;
123+
let pendingBeforeBoot: unknown;
124+
const info: Logged[] = [];
125+
const warn: Logged[] = [];
126+
const OLD: Record<string, boolean> = { old_false: false, old_true: true, old_zero: false };
127+
128+
beforeAll(async () => {
129+
driver = sqliteDriver();
130+
await driver.initObjects([asText(EXISTING)]);
131+
const knex = (driver as any).knex;
132+
// What the driver's own writes stored on this column before the fix, and
133+
// the '0' an earlier convergence of a text 'false' left.
134+
await knex(EXISTING).insert([
135+
{ id: 'old_false', label: 'x', flag: '0.0' },
136+
{ id: 'old_true', label: 'x', flag: '1.0' },
137+
{ id: 'old_zero', label: 'x', flag: '0' },
138+
]);
139+
(driver as any).logger = {
140+
info: (msg: string, meta?: any) => { info.push({ msg, meta }); },
141+
warn: (msg: string, meta?: any) => { warn.push({ msg, meta }); },
142+
};
143+
driver.setDeferredDdl(true);
144+
await driver.initObjects([asBoolean(EXISTING)]);
145+
pendingBeforeBoot = (await driver.previewDeferredSchemaWork()).filter((p) => p.kind === 'normalize_boolean_storage');
146+
driver.setDeferredDdl(false);
147+
await driver.initObjects([asBoolean(EXISTING)]);
148+
});
149+
150+
afterAll(async () => {
151+
await driver.disconnect();
152+
});
153+
154+
it('os migrate plan counts the 1.0 / 0.0 rows as normalize_boolean_storage', () => {
155+
expect(pendingBeforeBoot).toEqual([{ table: EXISTING, kind: 'normalize_boolean_storage', columns: ['flag'], rows: 2 }]);
156+
});
157+
158+
it('the boot rewrites them to the text 1 / 0, withholds nothing, and says so', async () => {
159+
expect(await stored(driver, EXISTING)).toEqual([
160+
['old_false', '0', 'text'], ['old_true', '1', 'text'], ['old_zero', '0', 'text'],
161+
]);
162+
expect(warn.filter((l) => l.msg.includes('unconverted'))).toEqual([]);
163+
const converted = info.filter((l) => l.msg.includes('canonicalised boolean storage'));
164+
expect(converted.map((l) => [l.meta.field, l.meta.rowsConverted])).toEqual([['flag', 2]]);
165+
});
166+
167+
it('find(), distinct() and = false then agree on every row', async () => {
168+
expect(await presented(driver, EXISTING)).toEqual(OLD);
169+
expect([...(await driver.distinct(EXISTING, 'flag'))].sort()).toEqual([false, true]);
170+
expect(await idsWhere(driver, EXISTING, { flag: false })).toEqual(idsWritten(false, OLD));
171+
});
172+
});
173+
174+
describe('[#35341] driver-sql — CONTROL: a boolean column the driver created stores and answers as before (sqlite)', () => {
175+
let driver: SqlDriver;
176+
177+
beforeAll(async () => {
178+
driver = sqliteDriver();
179+
await driver.initObjects([asBoolean(CONTROL)]);
180+
await writeThroughEveryDoor(driver, CONTROL);
181+
});
182+
183+
afterAll(async () => {
184+
await driver.disconnect();
185+
});
186+
187+
it('every write door stores the INTEGER 1 / 0', async () => {
188+
expect(await stored(driver, CONTROL)).toEqual(
189+
Object.keys(WRITTEN).sort().map((id) => [id, WRITTEN[id] ? 1 : 0, 'integer']),
190+
);
191+
});
192+
193+
it('find(), distinct() and = false / = true agree', async () => {
194+
expect(await presented(driver, CONTROL)).toEqual(WRITTEN);
195+
expect([...(await driver.distinct(CONTROL, 'flag'))].sort()).toEqual([false, true]);
196+
expect(await idsWhere(driver, CONTROL, { flag: false })).toEqual(idsWritten(false, WRITTEN));
197+
expect(await idsWhere(driver, CONTROL, { flag: true })).toEqual(idsWritten(true, WRITTEN));
198+
});
199+
});

‎packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAs
4545
import type { JsonColumnFieldClass } from '@objectstack/core';
4646
import { StorageNameMapping } from '@objectstack/spec/system';
4747
import { emitBalancedGroup } from './sql-driver-balanced-group.js';
48-
import { presentStoredBoolean } from './sql-driver-sqlite-serialisation.js';
48+
import { presentStoredBoolean, sqliteBooleanBinding } from './sql-driver-sqlite-serialisation.js';
4949
import type { Knex } from 'knex';
5050
import {
5151
AUDIT_TIMESTAMP_COLUMNS, CROSS_FIELD_COMPARISON_OPERATORS, SQLITE_TIME_EXPR_REFS, TEXT_OPERATORS,
@@ -177,10 +177,17 @@ export class FilterHelpersFacet {
177177
}
178178

179179
/** The body of `SqlDriver#coerceFilterValue`; the method's docblock there is its contract. */
180-
static coerceFilterValue(this: Pick<FilterHelpersHost, 'coerceFilterValue' | 'isMssql' | 'isOracle' | 'oracleRawUuidFieldsByObject' | 'oracleUuidBinding' | 'storageDatetimeValue' | 'temporalFieldKind' | 'toDateOnly'>, table: string | null, field: string, value: any): any {
180+
static coerceFilterValue(this: Pick<FilterHelpersHost, 'booleanFields' | 'coerceFilterValue' | 'isMssql' | 'isOracle' | 'isSqlite' | 'oracleRawUuidFieldsByObject' | 'oracleUuidBinding' | 'storageDatetimeValue' | 'temporalFieldKind' | 'toDateOnly'>, table: string | null, field: string, value: any): any {
181181
if (value == null || !table) return value;
182182
if (Array.isArray(value)) return value.map((v) => this.coerceFilterValue(table, field, v));
183183

184+
// [#35341] A boolean comparand against a declared scalar boolean column is
185+
// bound the way `formatInput` binds the write (`sqliteBooleanBinding`), so
186+
// `= false` selects the rows the row read presents as `false`.
187+
if (this.isSqlite && typeof value === 'boolean' && this.booleanFields[table]?.includes(field) === true) {
188+
return sqliteBooleanBinding(value);
189+
}
190+
184191
// [#31390] Oracle: a comparand against a `RAW(16)` uuid column (as the
185192
// catalog reports it — `SqlDriver#primeOracleRawUuidColumns`) binds as
186193
// `HEXTORAW(?)`. A comparison comparand that is not uuid text was refused

‎packages/drivers/driver-sql/src/sql-driver-schema-sync.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2051,12 +2051,15 @@ export async function backfillCanonicalTimes(this: Pick<SchemaSyncHost, 'canonic
20512051
* all read this one predicate, so the plan cannot count rows the step will not
20522052
* convert.
20532053
*
2054-
* Only the two spellings `'true'` / `'false'` can be there: SQLite's NUMERIC
2054+
* Four spellings can be there. `'true'` / `'false'`: SQLite's NUMERIC
20552055
* affinity, which a `boolean` column takes, folds the text `'1'` / `'0'` into
2056-
* integers on write and keeps `'true'` / `'false'` as TEXT. `IN` compares with
2057-
* the BINARY collation, so `'TRUE'` or `'yes'` is not selected.
2056+
* integers on write and keeps `'true'` / `'false'` as TEXT. [#35341]
2057+
* `'1.0'` / `'0.0'`: on a column with TEXT affinity (a `text` field retyped to
2058+
* `boolean`), the driver's own writes stored the REAL its JS number bound as,
2059+
* as that text, until it bound `sqliteBooleanBinding`'s `'1'` / `'0'`. `IN`
2060+
* compares with the BINARY collation, so `'TRUE'` or `'yes'` is not selected.
20582061
*/
2059-
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in ('true', 'false')`;
2062+
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in ('true', 'false', '1.0', '0.0')`;
20602063

20612064
/**
20622065
* [#34973] How many ids of the converted rows the backfill's `info` line
@@ -2074,7 +2077,9 @@ const BOOLEAN_BACKFILL_SAMPLE_IDS = 5;
20742077
* ({@link SqlDriver.booleanFields}) on the integer form every write takes
20752078
* since the engine stores the boolean a reading spells (#34916). Rows written
20762079
* before that by a door that sent the text `'true'` / `'false'` (the console's
2077-
* inline grid) still hold that TEXT. The row read presents them as booleans,
2080+
* inline grid) still hold that TEXT. [#35341] So do the `'1.0'` / `'0.0'` the
2081+
* driver's own writes left on a TEXT-affinity column, which the row read
2082+
* presented as `true` both. The row read presents the others as booleans,
20782083
* but every comparison runs in SQL against the raw cell, so `= false` misses a
20792084
* text `'false'`, `$in`, `!=` and `$nin` answer wrongly, ORDER BY sorts the
20802085
* text after every integer, and an aggregate group key presents a text
@@ -2088,7 +2093,7 @@ const BOOLEAN_BACKFILL_SAMPLE_IDS = 5;
20882093
* it, so no other dialect can hold such a row.
20892094
*
20902095
* ONE `UPDATE` per column, atomic on SQLite, whose `WHERE` is
2091-
* {@link SQLITE_LEGACY_BOOLEAN_TEXT}: it selects only the two text spellings,
2096+
* {@link SQLITE_LEGACY_BOOLEAN_TEXT}: it selects only the four text spellings,
20922097
* so a converged column is a no-op and a second boot converts 0 rows. One
20932098
* counting scan over the column's text cells comes first, and the id sample and
20942099
* the `UPDATE` run only when it found legacy text, so a converged column costs
@@ -2134,7 +2139,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21342139
[table, field, field, BOOLEAN_BACKFILL_SAMPLE_IDS],
21352140
);
21362141
const res = await this.knex.raw(
2137-
`update ?? set ?? = case ?? when 'true' then 1 when 'false' then 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`,
2142+
`update ?? set ?? = case when ?? in ('true', '1.0') then 1 else 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`,
21382143
[table, field, field, field, field],
21392144
);
21402145
// better-sqlite3 reports `changes`; a client whose raw path returns
@@ -2145,7 +2150,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21452150
if (converted) {
21462151
this.logger.info?.(
21472152
`[sql-driver] canonicalised boolean storage for ${table}.${field}: rows that held the ` +
2148-
`text 'true' / 'false' now hold 1 / 0, so boolean filters, sorts and groups answer them ` +
2153+
`text 'true' / 'false' (or '1.0' / '0.0') now hold 1 / 0, so boolean filters, sorts and groups answer them ` +
21492154
`as the boolean they read as`,
21502155
{ table, field, rowsConverted: converted, sampleIds: sample.map((r) => String(r.id)) },
21512156
);
@@ -2154,7 +2159,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21542159
if (withheld > 0) {
21552160
this.logger.warn(
21562161
`[sql-driver] left ${withheld} row(s) of ${table}.${field} unconverted: their stored ` +
2157-
`value is text other than 'true' or 'false', which names no boolean the driver can ` +
2162+
`value is text other than 'true', 'false', '1.0' or '0.0', which names no boolean the driver can ` +
21582163
`read without guessing. Boolean filters do not match them until the values are ` +
21592164
`corrected or cleared at the source`,
21602165
{ table, field, rowsWithheld: withheld },
@@ -2163,7 +2168,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21632168
} catch (err) {
21642169
this.logger.warn(
21652170
`[sql-driver] could not canonicalise boolean storage for ${table}.${field}; rows holding ` +
2166-
`the text 'true' / 'false' stay missed by boolean filters until a later boot converts them`,
2171+
`the text 'true' / 'false' (or '1.0' / '0.0') stay missed by boolean filters until a later boot converts them`,
21672172
{ error: err instanceof Error ? err.message : String(err) },
21682173
);
21692174
}

0 commit comments

Comments
 (0)