Skip to content

Commit 702b0cf

Browse files
fix(driver-sql)!: a boolean field is stored as a boolean whatever spelling the caller sends (#35718)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D1WDVL9JpCQhTUF97fpymtZ)_ Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — the published skills teach no write of a boolean field through a driver; the engine's door and authored metadata are unchanged. ## 维护者速读 - 用户无感:经界面和接口写入的布尔与开关字段照旧;插件、钩子或脚本直接写这类字段时,真假的各种写法从此一律存成真正的布尔值。 - 替写插件、钩子和迁移脚本的开发者解决:同一个布尔字段不再因写法不同而存成两种形态,筛选、排序、分组读到的真假始终一致。 - 绕过引擎直接写库、又传了认不出真假的值(比如“yes”)的代码,会收到校验错误而不是悄悄存进去;本改动可整体撤回。 - 无。 ## What changes A boolean field is stored as a boolean whatever spelling the caller sends. - **The SQLite write door (`formatInput`, `packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts`).** For a declared scalar `Field.boolean` / `Field.toggle`, it used to bind only a JS boolean and pass every other value through as sent, so a string reached the column as text. It now reads the value through one table, `SQLITE_BOOLEAN_TEXT_SPELLINGS`: - accepted, and bound as the boolean they spell: `true` / `false`, the numbers `1` / `0`, and the text `'1'` / `'0'`, `'true'` / `'false'` and `'1.0'` / `'0.0'`; - refused before any statement is built, with `VALIDATION_ERROR` / 400 (ADR-0112): every other value, for example `'yes'`, `'TRUE'`, `' true'`, `''`, `2`, `NaN`, an array or an object. The error message names the field and the object and describes the value's type without echoing it; - `null` still writes NULL, and an absent key is left alone. Every SQLite-family write door forms its row here: `SqlDriver` on SQLite, both faces of `TursoDriver` (the remote face forms its rows through the same `formatInput`), and `SqliteWasmDriver`. That covers `create`, `update`, `upsert`, `bulkCreate`, `bulkUpdate` and `updateMany`. - **One rule for write and boot convergence (`sql-driver-schema-sync.ts`).** The local boot convergence (`SQLITE_LEGACY_BOOLEAN_TEXT` and the `UPDATE` in `backfillCanonicalBooleans`) now builds its spelling lists from the same table. The SQL it emits is byte-identical to before. The write door and the convergence cannot drift apart: neither accepts a spelling the other does not. - **Remote `TursoDriver.bulkCreate`** checks every row's storage form before it writes the first row. A refused row refuses the whole batch with nothing written, as the local face's single INSERT already did. - **The engine's door.** It already writes the boolean its validator judged, and these tests pin that. A `beforeInsert` / `beforeUpdate` hook that assigns a string runs after that rewrite, so the string reached the driver as sent. It now lands as a boolean through the driver's door. - **Not changed:** Postgres and MySQL; the engine's validation; any schema or export shape. Rows already stored keep their stored form, and nothing is rewritten at boot that was not rewritten before. ## Tests - `packages/drivers/driver-sql/src/sql-driver-boolean-write-spellings.test.ts` (30 cases): every accepted spelling through all six doors lands canonical, on a column the driver created (INTEGER) and on a `text` column retyped to `boolean` (the text `'1'` / `'0'`). Every refused value comes back as `{ code: 'VALIDATION_ERROR', status: 400 }` with nothing written. Negative and positive filters (`$ne`, `$nin`, `$not`, `=`) answer each row by the boolean it was written as. - `packages/drivers/driver-turso/src/turso-local-remote-boolean-write-parity.test.ts` (28 cases): the same doors on both `TursoDriver` faces over an embedded libSQL file, raw `typeof` read back through a separate client, plus a remote `bulkCreate` batch with one refused row that writes nothing. - `packages/runtime/src/domains/boolean-written-spelling-row-scope.test.ts` (6 cases): the engine, a permission set and REST, on both faces. Three writers send the string `'true'`: the engine's door, the driver's door, and a `beforeInsert` hook. A row-level rule written in negative form (`restricted != true`, `!(record.restricted in [true])`, `record.locked != true`) answers each of those rows by the boolean it was written as, on `find`, `count`, `findOne`, and the REST list, get and delete. **Ablation of the new arm** (head `821e6832c09`). The mutant puts the arm back as it stood at the base: only a JS boolean is bound, and every other value passes through as sent. Each leg was rebuilt and proven to reach `dist/` (`ablation-dist-preflight`: the marker present in 2 built files, then absent from all 6). | leg | driver-sql pin | driver-turso pin | runtime pin | |---|---|---|---| | mutant | 28 failed, 2 passed (30) | 28 failed (28) | 6 failed (6) | | restored (`git diff HEAD` empty, whole tree clean) | 30 passed (full suite below) | 28 passed (28) | 6 passed (6) | Under the mutant, the runtime pin stores `driver_text_true` and `hook_text_true` as `text` on both faces, while `engine_text_true` stays `integer`: the engine's door already writes a boolean on its own. <details><summary>Suites and typechecks at 821e683 (all under the shared verify lock; VERDICT command-exit 0)</summary> ```text pnpm --filter @objectstack/driver-sql typecheck EXIT=0 pnpm --filter @objectstack/driver-turso typecheck EXIT=0 pnpm --filter @objectstack/runtime typecheck EXIT=0 driver-sql vitest run --maxWorkers=2 Test Files 266 passed | 13 skipped (279) Tests 4438 passed | 257 skipped (4695) driver-turso vitest run --maxWorkers=2 Test Files 102 passed | 1 skipped (103) Tests 2593 passed | 36 skipped (2629) driver-sqlite-wasm vitest run Test Files 41 passed (41) Tests 768 passed (768) runtime vitest run --project local src/domains/boolean-written-spelling-row-scope.test.ts Tests 6 passed (6) ``` The full runtime suite and the downstream consumers' suites are left to CI (`Test Core`). This PR changes no runtime source; it adds one test file there. </details> ## Acceptance notes - On the remote face of `TursoDriver`, a `toggle` column is created with TEXT affinity, while the local face gives it boolean (NUMERIC) affinity. Now that writes are canonical, the remote cell is the text `'1'` / `'0'`, and every boolean filter reads it correctly. Noted, not filed. - The engine's validator accepts fewer text spellings than the driver's door: it does not accept `'1.0'` / `'0.0'`. The engine stays the stricter of the two doors. Noted, not filed. - No stored row is rewritten. A cell stored before this change keeps its stored form, on either face. - The runtime pin file takes about 11 s, almost all of it import time (10.9 s of 11.5 s); its six cases take 0.43 s. ## Verification **Read first, by risk:** 1. `packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts`, the `formatInput` boolean arm: the one place a value a direct caller could write before is now refused. 2. `packages/drivers/driver-turso/src/turso-driver.ts`, remote `bulkCreate`: the per-row check before the first write. 3. `packages/drivers/driver-sql/src/sql-driver-schema-sync.ts`: the convergence SQL is now built from the shared table; it should read byte-identical. **Two-minute verification:** with `@objectstack/driver-sql` built, run `pnpm --filter @objectstack/driver-turso exec vitest run --maxWorkers=2 src/turso-local-remote-boolean-write-parity.test.ts`. Expect `Tests 28 passed (28)`. **Dogfood battery, once, on the final head** (`821e6832c09`, the title carries `!`): the `@objectstack/dogfood^...` closure was built, then `pnpm --filter @objectstack/dogfood test` ran under the verify lock. VERDICT command-exit 0: `Test Files 482 passed | 3 skipped (485)`, `Tests 4093 passed | 68 skipped (4161)`. No line of the run's log carries the new refusal's text. <details><summary>Local gate families at 821e683: 70 derived, 69 run green, 1 not measured</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 70 families from this diff. `--ran` reconciliation: `70 derived famil(ies) accounted for — 69 run, 1 NOT-MEASURED`. `check:dual-build-cjs-loads` exits 3 (PREREQUISITE NOT MET) because it reads the built output of every package, and this checkout built only the dogfood closure. CI's `Build Core` job runs it. ```text exit 0 node scripts/check-adr-0087-registration.mjs --base origin/main exit 0 node scripts/check-adr-0087-registration.mjs --self-test exit 0 node scripts/check-changeset-no-major.mjs --base origin/main exit 0 node scripts/check-closing-keyword-parity.mjs exit 0 node scripts/check-closing-keyword-parity.mjs --self-test exit 0 node scripts/check-comment-mask-adoption.mjs exit 0 node scripts/check-comment-mask-adoption.mjs --self-test exit 0 node scripts/check-comment-mask-corpus.mjs exit 0 node scripts/check-empty-changeset.mjs --base origin/main exit 0 node scripts/check-empty-changeset.mjs --self-test exit 0 node scripts/check-issue-citations.mjs exit 0 node scripts/check-plugin-teardown-shape.mjs exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test exit 0 node scripts/ci/snapshot-next.mjs --self-test exit 0 node scripts/docs-audit/check-affected-docs.mjs exit 0 node scripts/docs-audit/check-drift-comment.mjs exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test exit 0 node scripts/release-pending-publish.mjs --self-test exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys exit 0 pnpm check:adr-anchors exit 0 pnpm check:adr-symbol-anchors exit 0 pnpm check:changeset-gate-self-tests exit 0 pnpm check:ci-filter-parity exit 0 pnpm check:cli-command-ids exit 0 pnpm check:closed-ceremony-text exit 0 pnpm check:cross-package-test-inputs exit 0 pnpm check:doc-authoring exit 0 pnpm check:durability-log-level exit 0 pnpm check:engine-double-contract exit 0 pnpm check:error-status-conformance exit 0 pnpm check:gitlink-declared exit 0 pnpm check:issue-citations exit 0 pnpm check:keyed-text-bounds exit 0 pnpm check:logger-receiver-detach exit 0 pnpm check:nul-bytes exit 0 pnpm check:object-def-param-keys exit 0 pnpm check:objectql-double-limit exit 0 pnpm check:optional-error-sink exit 0 pnpm check:org-identifier exit 0 pnpm check:page-declaration-shape exit 0 pnpm check:platform-object-tenancy-census exit 0 pnpm check:query-options-erasure exit 0 pnpm check:refd-timer-probe exit 0 pnpm check:registry-log-declared exit 0 pnpm check:rest-log-spy-declared exit 0 pnpm check:route-envelope exit 0 pnpm check:settings-bind-window exit 0 pnpm check:slot-lookup exit 0 pnpm check:system-context-census exit 0 pnpm check:tenant-chokepoint exit 0 pnpm check:test-source-alias exit 0 pnpm check:tier-file-adoption exit 0 pnpm check:undeclared-dep-imports exit 0 pnpm check:vouch-for-reference-callers exit 0 pnpm check:watch-hint-literal exit 0 pnpm check:where-matcher exit 0 node scripts/check-dts-emitted.mjs --self-test exit 0 pnpm check:driver-conformance exit 0 pnpm check:driver-memory-census exit 0 pnpm check:dts-closure exit 3 pnpm check:dual-build-cjs-loads exit 0 pnpm check:lean-entry-closure exit 0 pnpm check:published-files exit 0 pnpm check:sourcemap-no-sources-content exit 0 pnpm check:type-check-coverage exit 0 pnpm check:type-check-debt (re-run under the verify lock: 0 ledger entries re-measured, 0 raw tsc errors) ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c321914 commit 702b0cf

7 files changed

Lines changed: 678 additions & 6 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
'@objectstack/driver-turso': patch
4+
---
5+
6+
fix(driver-sql)!: a boolean field is stored as a boolean whatever spelling the caller sends
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. What moves is the write door of the SQLite-family drivers (SqlDriver on SQLite, both faces of TursoDriver, SqliteWasmDriver) for a direct caller: a value on a declared boolean or toggle field that spells no boolean is refused instead of stored, and the spellings it accepts are stored as the boolean they spell. The engine's own door already refuses those values with invalid_boolean, so no authored metadata, seed or stored row is rewritten and nothing needs a tombstone. -->
12+
13+
**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.
14+
15+
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'`.
16+
17+
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.
18+
19+
To keep a direct write working, send `true` or `false` (or one of the spellings above) for a boolean or toggle field.
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A declared scalar `Field.boolean` / `Field.toggle` is stored as a boolean on
5+
* SQLite whatever spelling the caller hands a write door, and a value that
6+
* spells no boolean is refused instead of stored.
7+
*
8+
* The engine writes the boolean its validator judged, but a caller that writes
9+
* through the driver itself (a plugin, a migration, a `beforeInsert` hook's
10+
* assignment, which lands after the engine's rewrite) reached `formatInput`
11+
* with the text `'true'` / `'false'`, and SQLite kept that TEXT beside rows
12+
* holding the INTEGER `1` / `0`. Every filter, sort and group then ran against
13+
* the raw cell: `'true' <> 1` holds in SQLite, so a row written as `'true'`
14+
* satisfied `$ne: true`. Any other text (`'yes'`) was stored as itself and read
15+
* back as `Boolean('yes')`.
16+
*
17+
* The accepted spellings are exactly the ones the boot convergence reads
18+
* (`SQLITE_BOOLEAN_TEXT_READINGS`): `true` / `false`, the numbers `1` / `0`,
19+
* and the text `'1'` / `'0'`, `'true'` / `'false'` and `'1.0'` / `'0.0'`. Each
20+
* is bound as `sqliteBooleanBinding`'s `'1'` / `'0'`, which a column the driver
21+
* created stores as the INTEGER `1` / `0` and a TEXT-affinity column (a `text`
22+
* field retyped to `boolean`) as the text `'1'` / `'0'`. Anything else answers
23+
* `VALIDATION_ERROR` / 400 on every door and writes nothing.
24+
*/
25+
26+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
27+
import type { DriverQuery } from '@objectstack/spec/contracts';
28+
import { lowerFilterCondition } from '@objectstack/spec/data';
29+
import { SqlDriver } from './sql-driver.js';
30+
31+
const CREATED = 'bool_spellings_created';
32+
const RETYPED = 'bool_spellings_retyped';
33+
34+
function sqliteDriver(): SqlDriver {
35+
return new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any);
36+
}
37+
38+
const asText = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'text' }, live: { type: 'text' } } });
39+
const asBoolean = (name: string) => ({ name, fields: { label: { type: 'string' }, flag: { type: 'boolean' }, live: { type: 'toggle' } } });
40+
41+
/** Every spelling a write door accepts, and the boolean it is stored as. */
42+
const ACCEPTED: ReadonlyArray<readonly [unknown, boolean]> = [
43+
[true, true], [false, false], [1, true], [0, false], ['1', true], ['0', false],
44+
['true', true], ['false', false], ['1.0', true], ['0.0', false],
45+
];
46+
47+
/** Values that spell no boolean: refused on every door. */
48+
const REFUSED: ReadonlyArray<unknown> = ['yes', 'TRUE', ' true', '', 2, -1, Number.NaN, ['true'], { value: true }];
49+
50+
type Door = 'create' | 'update' | 'upsert' | 'bulkCreate' | 'bulkUpdate' | 'updateMany';
51+
const DOORS: readonly Door[] = ['create', 'update', 'upsert', 'bulkCreate', 'bulkUpdate', 'updateMany'];
52+
53+
/** Write `value` to both boolean fields of row `id` through `door`; update doors first create the row as `seed`. */
54+
async function writeThrough(driver: SqlDriver, table: string, door: Door, id: string, value: unknown, seed = false): Promise<void> {
55+
const row = { id, label: door, flag: value, live: value };
56+
switch (door) {
57+
case 'create': await driver.create(table, row); return;
58+
case 'upsert': await driver.upsert(table, row); return;
59+
case 'bulkCreate': await driver.bulkCreate(table, [row]); return;
60+
default: break;
61+
}
62+
await driver.create(table, { id, label: door, flag: seed, live: seed });
63+
const patch = { flag: value, live: value };
64+
if (door === 'update') await driver.update(table, id, patch);
65+
else if (door === 'bulkUpdate') await driver.bulkUpdate(table, [{ id, data: patch }]);
66+
else await driver.updateMany(table, { where: { id } } as DriverQuery, patch);
67+
}
68+
69+
async function storedCell(driver: SqlDriver, table: string, id: string): Promise<Array<[unknown, string]> | null> {
70+
const rows = await (driver as any).knex.raw(`select flag, typeof(flag) as t, live, typeof(live) as lt from ${table} where id = ?`, [id]);
71+
return rows.length ? [[rows[0].flag, rows[0].t], [rows[0].live, rows[0].lt]] : null;
72+
}
73+
74+
const label = (v: unknown) => (typeof v === 'number' && Number.isNaN(v) ? 'NaN' : JSON.stringify(v));
75+
76+
for (const [table, form] of [[CREATED, 'INTEGER'], [RETYPED, 'TEXT']] as const) {
77+
describe(`driver-sql — a boolean / toggle field on a ${form}-form column is stored as a boolean whatever spelling it is written in (sqlite)`, () => {
78+
let driver: SqlDriver;
79+
const stored = (b: boolean) => (form === 'INTEGER' ? [b ? 1 : 0, 'integer'] : [b ? '1' : '0', 'text']);
80+
81+
beforeAll(async () => {
82+
driver = sqliteDriver();
83+
if (form === 'TEXT') await driver.initObjects([asText(table)]);
84+
await driver.initObjects([asBoolean(table)]);
85+
});
86+
87+
afterAll(async () => {
88+
await driver.disconnect();
89+
});
90+
91+
it('the fixture: the column forms are the ones named', async () => {
92+
const cols = await (driver as any).knex.raw(`select name, type from pragma_table_info('${table}') where name in ('flag', 'live') order by name`);
93+
expect(cols.map((c: any) => c.type)).toEqual(form === 'INTEGER' ? ['boolean', 'boolean'] : ['TEXT', 'TEXT']);
94+
});
95+
96+
for (const door of DOORS) {
97+
it(`${door}: every accepted spelling is stored as its boolean`, async () => {
98+
const got: Record<string, unknown> = {};
99+
const want: Record<string, unknown> = {};
100+
for (const [i, [value, b]] of ACCEPTED.entries()) {
101+
const id = `${door}_ok_${i}`;
102+
// An update door seeds the opposite value, so a write that changed nothing is seen.
103+
await writeThrough(driver, table, door, id, value, !b);
104+
got[label(value)] = await storedCell(driver, table, id);
105+
want[label(value)] = [stored(b), stored(b)];
106+
}
107+
expect(got).toEqual(want);
108+
});
109+
110+
it(`${door}: a value that spells no boolean is refused with VALIDATION_ERROR / 400 and writes nothing`, async () => {
111+
const verdicts: Record<string, unknown> = {};
112+
const want: Record<string, unknown> = {};
113+
for (const [i, value] of REFUSED.entries()) {
114+
const id = `${door}_no_${i}`;
115+
const outcome = await writeThrough(driver, table, door, id, value, true).then(
116+
() => 'written',
117+
(e: any) => ({ code: e?.code, status: e?.status }),
118+
);
119+
const cell = await storedCell(driver, table, id);
120+
verdicts[label(value)] = { outcome, cell };
121+
// An insert door leaves no row; an update door leaves the seeded `true` as it was.
122+
const cellWant = ['create', 'upsert', 'bulkCreate'].includes(door) ? null : [stored(true), stored(true)];
123+
want[label(value)] = { outcome: { code: 'VALIDATION_ERROR', status: 400 }, cell: cellWant };
124+
}
125+
expect(verdicts).toEqual(want);
126+
});
127+
}
128+
129+
it('null still writes NULL, and a write that names neither field leaves them as they were', async () => {
130+
await driver.create(table, { id: 'nul', label: 'x', flag: null, live: null });
131+
expect(await storedCell(driver, table, 'nul')).toEqual([[null, 'null'], [null, 'null']]);
132+
await driver.create(table, { id: 'untouched', label: 'x', flag: 'true', live: 'false' });
133+
await driver.update(table, 'untouched', { label: 'y' });
134+
expect(await storedCell(driver, table, 'untouched')).toEqual([stored(true), stored(false)]);
135+
});
136+
137+
it('$ne: true / $nin: [true] / $not of = true never select a row written as the text true', async () => {
138+
await driver.create(table, { id: 'neg_text_true', label: 'neg', flag: 'true', live: 'true' });
139+
await driver.create(table, { id: 'neg_text_false', label: 'neg', flag: 'false', live: 'false' });
140+
await driver.create(table, { id: 'neg_bool_true', label: 'neg', flag: true, live: true });
141+
// The filter as a seam hands it to the driver (the shared lowering).
142+
const ids = async (where: Record<string, unknown>) => {
143+
const lowered = lowerFilterCondition({ label: 'neg', ...where }, { isDatetimeColumn: () => false });
144+
return ((await driver.find(table, { where: lowered } as DriverQuery)) as Array<{ id: string }>).map((r) => r.id).sort();
145+
};
146+
for (const field of ['flag', 'live']) {
147+
expect(await ids({ [field]: { $ne: true } })).toEqual(['neg_text_false']);
148+
expect(await ids({ [field]: { $nin: [true] } })).toEqual(['neg_text_false']);
149+
expect(await ids({ $not: { [field]: true } })).toEqual(['neg_text_false']);
150+
expect(await ids({ [field]: { $ne: false } })).toEqual(['neg_bool_true', 'neg_text_true']);
151+
expect(await ids({ [field]: true })).toEqual(['neg_bool_true', 'neg_text_true']);
152+
}
153+
});
154+
});
155+
}

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

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ import { activeConcurrentIndexDeferral, attachUniqueConstraintSql, clearConcurre
177177
import { isJsonColumnType, mediaColumnMoveDialect, mediaColumnMovePlan, type MediaColumnMovePlan, type MediaColumnMoveRefusal, type MediaColumnMoveScan } from './media-column-move.js';
178178
import { StandardErrorCode } from '@objectstack/spec/api';
179179
import { recoverUnencodedJsonText } from './unencoded-json-text.js';
180+
import { SQLITE_BOOLEAN_TEXT_SPELLINGS } from './sql-driver-sqlite-serialisation.js';
180181
import { renderExistingTableAdoptionRefusal } from './existing-table-refusal.js';
181182
import { renderDeclaredRenameRefusal } from './declared-rename.js';
182183
import { aggregandColumnClass } from '@objectstack/core';
@@ -2058,8 +2059,22 @@ export async function backfillCanonicalTimes(this: Pick<SchemaSyncHost, 'canonic
20582059
* `boolean`), the driver's own writes stored the REAL its JS number bound as,
20592060
* as that text, until it bound `sqliteBooleanBinding`'s `'1'` / `'0'`. `IN`
20602061
* compares with the BINARY collation, so `'TRUE'` or `'yes'` is not selected.
2062+
* The four are the `legacy` rows of `SQLITE_BOOLEAN_TEXT_SPELLINGS`, the table
2063+
* the write door binds from, so no write stores one of them any more and
2064+
* neither door nor convergence can take a spelling the other does not.
20612065
*/
2062-
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in ('true', 'false', '1.0', '0.0')`;
2066+
const SQLITE_LEGACY_BOOLEAN_TEXT = `typeof(??) = 'text' and ?? in (${sqlTextList((s) => s.legacy)})`;
2067+
2068+
/**
2069+
* The spellings of {@link SQLITE_BOOLEAN_TEXT_SPELLINGS} that `pick` keeps, as a
2070+
* SQL list of string literals (`'true', 'false', '1.0', '0.0'` for the legacy
2071+
* ones). The table is the write door's too (`sqliteBooleanWriteReading`), so
2072+
* the convergence and the write accept one set of spellings. Each spelling is
2073+
* a constant of that table, never a caller's value, and holds no quote.
2074+
*/
2075+
function sqlTextList(pick: (s: (typeof SQLITE_BOOLEAN_TEXT_SPELLINGS)[number]) => boolean): string {
2076+
return SQLITE_BOOLEAN_TEXT_SPELLINGS.filter(pick).map((s) => `'${s.text}'`).join(', ');
2077+
}
20632078

20642079
/**
20652080
* [#34973] How many ids of the converted rows the backfill's `info` line
@@ -2126,7 +2141,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21262141
// `1` / `0`: it already reads as its boolean, so it is not withheld.
21272142
const counted: any = await this.knex.raw(
21282143
`select count(*) as text_rows, coalesce(sum(case when ${SQLITE_LEGACY_BOOLEAN_TEXT} then 1 else 0 end), 0) as legacy, ` +
2129-
`coalesce(sum(case when ?? in ('1', '0') then 1 else 0 end), 0) as canonical ` +
2144+
`coalesce(sum(case when ?? in (${sqlTextList((s) => !s.legacy)}) then 1 else 0 end), 0) as canonical ` +
21302145
`from ?? where typeof(??) = 'text'`,
21312146
[field, field, field, table, field],
21322147
);
@@ -2139,7 +2154,7 @@ export async function backfillCanonicalBooleans(this: Pick<SchemaSyncHost, 'bool
21392154
[table, field, field, BOOLEAN_BACKFILL_SAMPLE_IDS],
21402155
);
21412156
const res = await this.knex.raw(
2142-
`update ?? set ?? = case when ?? in ('true', '1.0') then 1 else 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`,
2157+
`update ?? set ?? = case when ?? in (${sqlTextList((s) => s.legacy && s.value)}) then 1 else 0 end where ${SQLITE_LEGACY_BOOLEAN_TEXT}`,
21432158
[table, field, field, field, field],
21442159
);
21452160
// better-sqlite3 reports `changes`; a client whose raw path returns

0 commit comments

Comments
 (0)