diff --git a/.changeset/34973-boolean-text-storage-convergence.md b/.changeset/34973-boolean-text-storage-convergence.md new file mode 100644 index 00000000000..029e16ac7bf --- /dev/null +++ b/.changeset/34973-boolean-text-storage-convergence.md @@ -0,0 +1,21 @@ +--- +'@objectstack/driver-sql': patch +'@objectstack/cli': patch +--- + +fix(driver-sql): boot converges legacy text `'true'` / `'false'` in a SQLite boolean column to `1` / `0`, so boolean filters, sorts and groups find those rows + +Clause-②: yes (widening: `@objectstack/driver-sql` exports `PendingSchemaWorkKind` from its index, and the CLI consumes it, so the union gains one published value, `normalize_boolean_storage`; boolean filters, sorts and groupBy on SQLite now answer legacy text rows as their boolean) +Metadata-protocol: none + +Before the engine stored the boolean a reading spells, a door that sent the text `'true'` / `'false'` (the console's inline grid) left that text in a SQLite `Field.boolean` or `Field.toggle` column. Since the previous release those rows read back as the right boolean, but every comparison ran against the raw text: `won = false` missed a stored `'false'`, `won = true` missed a stored `'true'`, `$in`, `$ne` and `$nin` answered wrongly, ORDER BY sorted the text after every integer, and an aggregate groupBy presented a text `'false'` as `true`. + +Schema sync now converges those cells at boot, the fourth storage convergence beside the datetime, time and JSON backfills (`backfillCanonicalBooleans`): + +- **SQLite only.** Postgres, MSSQL, MySQL and Oracle coerce or refuse the text, so no other dialect can hold such a row. +- **One guarded `UPDATE` per column**: `'true'` becomes `1` and `'false'` becomes `0`, and nothing else is written. A second boot converts 0 rows. +- **Other text is never rewritten.** A value such as `'yes'` or `'TRUE'` names no boolean the driver can read without guessing; it is counted and logged at `warn`, and boolean filters keep missing it until the value is corrected at the source. +- **The record** is an `info` line per table and field with the rows converted and up to five of their ids. There is no down step: a text row already reads as its integer, so an undo would only restore the form the filters miss. +- **Dry run.** Under `os migrate plan` the step is listed in place as `normalize_boolean_storage`, with its row count, and nothing is written; `os migrate apply` runs it after the confirmation. `OS_SKIP_SCHEMA_SYNC=1` skips it, as it skips every other schema-sync step. + +`os migrate plan`'s summary line now reads `N column(s) to converge in place` instead of `N temporal column(s) …`, because a boolean column is counted there too. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 2a72098eaa9..ee4a48b63c2 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1173,6 +1173,7 @@ performed. So `plan` really is a dry run, and everything `apply` is about to do In place (existing rows converged when you apply) ~ crm_contact [normalize_datetime_storage: signed_at — 1,240 row update(s)] + ~ crm_deal [normalize_boolean_storage: won — 312 row update(s)] Needs confirmation ~ crm_contact.email [relax_not_null] @@ -1189,10 +1190,16 @@ column needs when the database predates the canonical UTC storage (ADR-0053 addendum D-B1..D-B4). It carries a row count because that is the number deciding whether to run it now; on MySQL it reads `widen_datetime_columns` and is an `ALTER … MODIFY` table rebuild that holds a metadata lock for its -duration. - -Both are safe to apply — the convergence preserves every stored instant and is -idempotent — but only the second takes time proportional to your data. +duration. On SQLite it also lists `normalize_boolean_storage`: rows of a +`Field.boolean` or `Field.toggle` column that an older build stored as the text +`'true'` / `'false'` become `1` / `0`, so boolean filters, sorts and groups find +them. Any other text in such a column is left as stored and reported in the +log. + +All three are safe to apply — the datetime convergence preserves every stored +instant, the boolean step rewrites only the two canonical spellings, and each is +idempotent — but only the MySQL widen is a table rebuild whose duration grows with +your data. #### Runtime-owned indexes apply builds diff --git a/packages/cli/src/utils/schema-migrate.pending-render.test.ts b/packages/cli/src/utils/schema-migrate.pending-render.test.ts index cba4095d4c1..e8cc5549424 100644 --- a/packages/cli/src/utils/schema-migrate.pending-render.test.ts +++ b/packages/cli/src/utils/schema-migrate.pending-render.test.ts @@ -12,6 +12,16 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +// `schema-migrate.ts` reaches these through guarded dynamic imports +// (`schema-migration-plugins.ts`); loading them here pays the transform during +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; +import '@objectstack/service-datasource'; import { renderPendingSchemaWork, splitRefusedSchemaWork, @@ -44,6 +54,7 @@ const IN_PLACE: PendingSchemaWork[] = [ { table: 'legacy', kind: 'widen_datetime_columns', columns: ['at', 'created_at'], rows: 42 }, { table: 'shift', kind: 'normalize_time_storage', columns: ['starts_at'], rows: 7 }, { table: 'shift_my', kind: 'widen_time_columns', columns: ['starts_at'], rows: 9 }, + { table: 'deal', kind: 'normalize_boolean_storage', columns: ['won'], rows: 3 }, ]; describe('renderPendingSchemaWork (#3954)', () => { @@ -82,6 +93,9 @@ describe('renderPendingSchemaWork (#3954)', () => { expect(out()).toContain('7 row update(s)'); expect(out()).toContain('widen_time_columns: starts_at'); expect(out()).toContain('9 row table rebuild'); + // The boolean convergence (#34973) is a row update in place, like the + // temporal backfills. + expect(out()).toContain('deal [normalize_boolean_storage: won — 3 row update(s)]'); }); it('shows both sections when both kinds are pending', async () => { @@ -110,8 +124,10 @@ describe('summarizePendingSchemaWork (#3954)', () => { const summary = await summarizePendingSchemaWork([...ADDITIVE, ...IN_PLACE]); expect(summary).toContain('1 table(s) to create'); expect(summary).toContain('1 column(s) to add'); - expect(summary).toContain('5 temporal column(s) to converge in place'); - expect(summary).toContain('~1,234,625 rows'); + // [#34973] Not "temporal": a boolean column converges in place too. + expect(summary).toContain('6 column(s) to converge in place'); + expect(summary).not.toContain('temporal'); + expect(summary).toContain('~1,234,628 rows'); }); }); diff --git a/packages/cli/src/utils/schema-migrate.ts b/packages/cli/src/utils/schema-migrate.ts index de7da81e290..4a7a238ffc0 100644 --- a/packages/cli/src/utils/schema-migrate.ts +++ b/packages/cli/src/utils/schema-migrate.ts @@ -2016,7 +2016,9 @@ export async function summarizePendingSchemaWork(pending: PendingSchemaWork[]): if (inPlace.length > 0) { const cols = inPlace.reduce((n, p) => n + p.columns.length, 0); const rows = inPlace.reduce((n, p) => n + (p.rows ?? 0), 0); - parts.push(`${cols} temporal column(s) to converge in place (~${formatRows(rows)} rows)`); + // [#34973] "column(s)", not "temporal column(s)": the boolean storage + // convergence (`normalize_boolean_storage`) is counted here too. + parts.push(`${cols} column(s) to converge in place (~${formatRows(rows)} rows)`); } // [#30636] Named only when there are some, like the in-place count above. const rebuilds = pending.filter((p) => p.kind === 'rebuild_table').length; diff --git a/packages/drivers/driver-sql/src/schema-drift.ts b/packages/drivers/driver-sql/src/schema-drift.ts index 5580379a24b..83a517e19fd 100644 --- a/packages/drivers/driver-sql/src/schema-drift.ts +++ b/packages/drivers/driver-sql/src/schema-drift.ts @@ -361,8 +361,9 @@ export interface PendingSchemaWork { * How much data the step touches, when that is knowable up front and worth * knowing — absent for the additive kinds, which touch none. * - * For `normalize_datetime_storage` it is the number of row-writes (summed - * across `columns`, since each is its own `UPDATE`). For + * For `normalize_datetime_storage` and `normalize_boolean_storage` it is the + * number of row-writes (summed across `columns`, since each is its own + * `UPDATE`). For * `widen_datetime_columns` it is the table's row count, because MySQL's * `ALTER … MODIFY` is a full rebuild holding a metadata lock — which is the * number that decides "now" versus "in a maintenance window". @@ -398,6 +399,11 @@ export interface PendingSchemaWork { * section tells the operator the work is never data-losing, and that claim must * not silently come to cover a row rewrite. * + * [#34973] `normalize_boolean_storage` rewrites rows in place too: the SQLite + * boolean backfill, which turns legacy text `'true'` / `'false'` cells into + * `1` / `0`. It is in place by the rule below, and `os migrate plan` renders + * it as a row-update count beside the temporal ones. + * * [#30636] Two more describe the one existing-table shape the additive path * cannot adopt — keyed by `_id`, with no `id` column (`existing-table-refusal.ts`): * `rebuild_table` drops and recreates it while it is EMPTY (in place: it is @@ -418,6 +424,7 @@ export type PendingSchemaWorkKind = | 'add_columns' | 'normalize_datetime_storage' | 'normalize_time_storage' + | 'normalize_boolean_storage' | 'widen_datetime_columns' | 'widen_time_columns' | 'rebuild_table' diff --git a/packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts b/packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts index d1062535cbe..74312d0c1c6 100644 --- a/packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts @@ -16,12 +16,15 @@ * stored forms the driver writes itself read exactly as before. * * Out of this door: an equality filter compares the stored text, so - * `won = false` still misses a row stored as `'false'` until it is re-saved. + * `won = false` misses a row stored as `'false'`. [#34973] The boot's storage + * convergence (`backfillCanonicalBooleans`) rewrites those cells to `1` / `0`; + * its pins are the `[#34973]` describes at the end of this file. */ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; import type { DriverQuery } from '@objectstack/spec/contracts'; import { SqlDriver } from './sql-driver.js'; +import { isInPlaceSchemaWork } from './schema-drift.js'; const TABLE = 'bool_text_read_34916'; @@ -75,3 +78,308 @@ describe('[#34916] driver-sql — a boolean column holding text reads as the boo expect(row.flag).toBe(false); }); }); + +// ─── [#34973] The storage convergence: legacy text booleans become 1 / 0 ───── + +const CONV = 'bool_text_converge_34973'; +const CONV_OBJECT = { + name: CONV, + fields: { label: { type: 'string' }, flag: { type: 'boolean' }, live: { type: 'toggle' } }, +}; + +/** id · raw `flag` · raw `live`, written past the driver (the pre-#34916 forms). */ +const CONV_ROWS: ReadonlyArray = [ + ['int_one', 1, 1], + ['int_zero', 0, null], + ['nul', null, null], + ['text_false', 'false', 'false'], + ['text_true', 'true', null], +]; + +type Logged = { msg: string; meta?: any }; + +/** A SQLite database an older build wrote, with the driver's logger captured. */ +async function legacyBooleanDatabase(): Promise<{ driver: SqlDriver; info: Logged[]; warn: Logged[] }> { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + // First boot: the table is created here, so it is clean without a read. + await driver.initObjects([CONV_OBJECT]); + const knex = (driver as any).knex; + for (const [id, flag, live] of CONV_ROWS) await knex(CONV).insert({ id, label: id, flag, live }); + const info: Logged[] = []; + const warn: Logged[] = []; + // The default sink has no `info`; this instance gets one that records both. + (driver as any).logger = { + info: (msg: string, meta?: any) => { info.push({ msg, meta }); }, + warn: (msg: string, meta?: any) => { warn.push({ msg, meta }); }, + }; + return { driver, info, warn }; +} + +async function storedTypes(driver: SqlDriver, table: string, field: string): Promise> { + const rows = await (driver as any).knex.raw(`select id, typeof(${field}) as t from ${table} order by id`); + return Object.fromEntries(rows.map((r: any) => [r.id, r.t])); +} + +async function idsWhere(driver: SqlDriver, where: Record): Promise { + const rows = (await driver.find(CONV, { where } as DriverQuery)) as Array<{ id: string }>; + return rows.map((r) => r.id).sort(); +} + +const converged = (log: Logged[]) => log.filter((l) => l.msg.includes('canonicalised boolean storage')); + +describe('[#34973] driver-sql — boot converges legacy text booleans to 1 / 0 (sqlite)', () => { + let driver: SqlDriver; + let info: Logged[]; + let warn: Logged[]; + + beforeEach(async () => { + ({ driver, info, warn } = await legacyBooleanDatabase()); + }); + + afterEach(async () => { + await driver?.disconnect(); + }); + + it('before the step, = false misses the text false and = true misses the text true', async () => { + expect(await storedTypes(driver, CONV, 'flag')).toMatchObject({ text_false: 'text', text_true: 'text' }); + expect(await idsWhere(driver, { flag: false })).toEqual(['int_zero']); + expect(await idsWhere(driver, { flag: true })).toEqual(['int_one']); + }); + + it('after initObjects, = false finds the text false and = true the text true', async () => { + await driver.initObjects([CONV_OBJECT]); + expect(await storedTypes(driver, CONV, 'flag')).toEqual({ + int_one: 'integer', int_zero: 'integer', nul: 'null', text_false: 'integer', text_true: 'integer', + }); + expect(await idsWhere(driver, { flag: false })).toEqual(['int_zero', 'text_false']); + expect(await idsWhere(driver, { flag: true })).toEqual(['int_one', 'text_true']); + // A `toggle` column shares boolean storage and converges the same way. + expect(await idsWhere(driver, { live: false })).toEqual(['text_false']); + }); + + it('after the step, $in, $ne and $nin answer a former text row as its integer twin', async () => { + // Before: each operator compares the raw text, so it answers the text rows wrongly. + expect(await idsWhere(driver, { flag: { $in: [false] } })).toEqual(['int_zero']); + expect(await idsWhere(driver, { flag: { $ne: false } })).toContain('text_false'); + expect(await idsWhere(driver, { flag: { $nin: [true] } })).toContain('text_true'); + await driver.initObjects([CONV_OBJECT]); + expect(await idsWhere(driver, { flag: { $in: [true, false] } })).toEqual(['int_one', 'int_zero', 'text_false', 'text_true']); + expect(await idsWhere(driver, { flag: { $in: [false] } })).toEqual(['int_zero', 'text_false']); + const ne = await idsWhere(driver, { flag: { $ne: false } }); + expect(ne).toContain('text_true'); + expect(ne).not.toContain('text_false'); + expect(ne).not.toContain('int_zero'); + const nin = await idsWhere(driver, { flag: { $nin: [true] } }); + expect(nin).toContain('text_false'); + expect(nin).not.toContain('text_true'); + expect(nin).not.toContain('int_one'); + }); + + it('after the step, ORDER BY sorts a former text row with its boolean', async () => { + const order = async () => + ((await driver.find(CONV, { + orderBy: [{ field: 'flag', order: 'asc' }, { field: 'id', order: 'asc' }], + } as DriverQuery)) as Array<{ id: string }>).map((r) => r.id); + // Before: the text rows sort after every integer. + expect(await order()).toEqual(['nul', 'int_zero', 'int_one', 'text_false', 'text_true']); + await driver.initObjects([CONV_OBJECT]); + expect(await order()).toEqual(['nul', 'int_zero', 'text_false', 'int_one', 'text_true']); + }); + + it('after the step, an aggregate groupBy groups a former text false as false', async () => { + const groups = async () => { + const rows = (await driver.aggregate(CONV, { + groupBy: ['flag'], + aggregations: [{ function: 'count', field: 'id', alias: 'n' }], + } as DriverQuery)) as Array<{ flag: unknown; n: number }>; + return rows.map((r) => [r.flag, Number(r.n)]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))); + }; + // Before: four groups, and the text 'false' group presents as true. + expect(await groups()).toEqual([[false, 1], [null, 1], [true, 1], [true, 1], [true, 1]]); + await driver.initObjects([CONV_OBJECT]); + expect(await groups()).toEqual([[false, 2], [null, 1], [true, 2]]); + }); + + it('logs the rows converted per field with a sample of their ids, at info', async () => { + await driver.initObjects([CONV_OBJECT]); + const lines = converged(info).map((l) => l.meta); + expect(lines).toEqual([ + { table: CONV, field: 'flag', rowsConverted: 2, sampleIds: ['text_false', 'text_true'] }, + { table: CONV, field: 'live', rowsConverted: 1, sampleIds: ['text_false'] }, + ]); + expect(warn.filter((l) => l.msg.includes('boolean'))).toEqual([]); + }); + + it('is idempotent: a second boot converts 0 rows and logs nothing', async () => { + await driver.initObjects([CONV_OBJECT]); + // The first boot converted (flag and live), so the second has a converged column to leave alone. + expect(converged(info)).toHaveLength(2); + const after = await storedTypes(driver, CONV, 'flag'); + info.length = 0; + // Count every UPDATE the second boot sends against the table. + const knex = (driver as any).knex; + const updates: string[] = []; + const onQuery = (q: { sql: string }) => { + if (/^update/i.test(q.sql) && q.sql.includes(CONV)) updates.push(q.sql); + }; + knex.on('query', onQuery); + try { + await driver.initObjects([CONV_OBJECT]); + } finally { + knex.removeListener('query', onQuery); + } + expect(updates.filter((sql) => sql.includes("'true'"))).toEqual([]); + expect(converged(info)).toEqual([]); + expect(await storedTypes(driver, CONV, 'flag')).toEqual(after); + }); + + it('a skipSchemaSync boot (OS_SKIP_SCHEMA_SYNC=1) leaves the text rows untouched', async () => { + // What the objectql plugin runs for a skipSchemaSync boot instead of + // `initObjects`: the DDL-free registration door, which reaches no backfill. + driver.registerObjectMetadata([CONV_OBJECT]); + expect(await storedTypes(driver, CONV, 'flag')).toMatchObject({ text_false: 'text', text_true: 'text' }); + expect(converged(info)).toEqual([]); + }); +}); + +describe('[#34973] driver-sql — text that names no boolean is withheld and warned (sqlite)', () => { + const ODD = 'bool_text_odd_34973'; + const ODD_OBJECT = { name: ODD, fields: { flag: { type: 'boolean' } } }; + let driver: SqlDriver; + let warn: Logged[]; + + beforeEach(async () => { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + await driver.initObjects([ODD_OBJECT]); + // Past the validator, which would refuse 'yes' and 'TRUE': raw SQL only. + await (driver as any).knex(ODD).insert([ + { id: 'odd_upper', flag: 'TRUE' }, + { id: 'odd_yes', flag: 'yes' }, + { id: 'text_false', flag: 'false' }, + ]); + warn = []; + (driver as any).logger = { warn: (msg: string, meta?: any) => { warn.push({ msg, meta }); } }; + }); + + afterEach(async () => { + await driver?.disconnect(); + }); + + it('never rewrites the other text, converts the canonical text, and warns once with the count', async () => { + await driver.initObjects([ODD_OBJECT]); + const rows = await (driver as any).knex.raw(`select id, flag, typeof(flag) as t from ${ODD} order by id`); + expect(rows).toEqual([ + { id: 'odd_upper', flag: 'TRUE', t: 'text' }, + { id: 'odd_yes', flag: 'yes', t: 'text' }, + { id: 'text_false', flag: 0, t: 'integer' }, + ]); + const withheld = warn.filter((l) => l.msg.includes('unconverted')); + expect(withheld.map((l) => l.meta)).toEqual([{ table: ODD, field: 'flag', rowsWithheld: 2 }]); + }); + + it('the plan counts only the rows the step converts, never the withheld ones', async () => { + driver.setDeferredDdl(true); + await driver.initObjects([ODD_OBJECT]); + const pending = (await driver.previewDeferredSchemaWork()).filter((p) => p.kind === 'normalize_boolean_storage'); + expect(pending).toEqual([{ table: ODD, kind: 'normalize_boolean_storage', columns: ['flag'], rows: 1 }]); + }); +}); + +describe('[#34973] driver-sql — os migrate plan previews the boolean convergence (sqlite)', () => { + let driver: SqlDriver; + + beforeEach(async () => { + ({ driver } = await legacyBooleanDatabase()); + }); + + afterEach(async () => { + await driver?.disconnect(); + }); + + it('counts the rows as normalize_boolean_storage, in place, and writes nothing', async () => { + driver.setDeferredDdl(true); + await driver.initObjects([CONV_OBJECT]); + const pending = await driver.previewDeferredSchemaWork(); + expect(pending).toEqual([{ table: CONV, kind: 'normalize_boolean_storage', columns: ['flag', 'live'], rows: 3 }]); + expect(isInPlaceSchemaWork('normalize_boolean_storage')).toBe(true); + // The deferral's promise: plan measures, apply changes. + expect(await storedTypes(driver, CONV, 'flag')).toMatchObject({ text_false: 'text', text_true: 'text' }); + expect(await storedTypes(driver, CONV, 'live')).toMatchObject({ text_false: 'text' }); + }); + + it('apply (the flush) converges the rows the plan named, and a re-plan finds none', async () => { + driver.setDeferredDdl(true); + await driver.initObjects([CONV_OBJECT]); + await driver.flushDeferredSchemaDdl(); + expect(await idsWhere(driver, { flag: false })).toEqual(['int_zero', 'text_false']); + driver.setDeferredDdl(true); + await driver.initObjects([CONV_OBJECT]); + expect(await driver.previewDeferredSchemaWork()).toEqual([]); + }); +}); + +describe('[#34973] driver-sql — the convergence record on other column and client shapes (sqlite)', () => { + let driver: SqlDriver | undefined; + + afterEach(async () => { + await driver?.disconnect(); + driver = undefined; + }); + + it('a TEXT-affinity column: the canonical text 1 / 0 is not withheld, and the legacy text still converges', async () => { + const TXT = 'bool_text_affinity_34973'; + const TXT_OBJECT = { name: TXT, fields: { flag: { type: 'boolean' } } }; + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const knex = (driver as any).knex; + // A column whose type changed to boolean without a rebuild keeps TEXT + // affinity, so the driver's own 1 / 0 lands as the text '1' / '0'. + await knex.raw(`create table ${TXT} (id varchar(255) primary key, flag text)`); + await knex(TXT).insert([ + { id: 'canon_one', flag: '1' }, + { id: 'canon_zero', flag: '0' }, + { id: 'legacy_true', flag: 'true' }, + ]); + const warn: Logged[] = []; + const info: Logged[] = []; + (driver as any).logger = { + info: (msg: string, meta?: any) => { info.push({ msg, meta }); }, + warn: (msg: string, meta?: any) => { warn.push({ msg, meta }); }, + }; + await driver.initObjects([TXT_OBJECT]); + const rows = await knex.raw(`select id, flag from ${TXT} order by id`); + expect(rows).toEqual([ + { id: 'canon_one', flag: '1' }, + { id: 'canon_zero', flag: '0' }, + { id: 'legacy_true', flag: '1' }, + ]); + expect(converged(info).map((l) => l.meta)).toEqual([ + { table: TXT, field: 'flag', rowsConverted: 1, sampleIds: ['legacy_true'] }, + ]); + expect(warn.filter((l) => l.msg.includes('unconverted'))).toEqual([]); + }); + + it('a client whose raw UPDATE reports no changes still records the rows it converted', async () => { + let info: Logged[]; + ({ driver, info } = await legacyBooleanDatabase()); + const knex = (driver as any).knex; + // driver-sqlite-wasm and knex `sqlite3` answer a raw statement with rows, + // not `{ changes }`: the UPDATE runs, the count is not reported. knex's + // own `raw` is read-only, so the driver gets a facade that answers so. + const raw = async (sql: string, bindings?: unknown) => { + const res = await knex.raw(sql, bindings); + return /^update /i.test(sql) ? [] : res; + }; + (driver as any).knex = new Proxy(function facade(this: unknown, ...args: unknown[]) { return knex.apply(this, args); }, { + get: (_t, prop) => { + if (prop === 'raw') return raw; + const v = knex[prop]; + return typeof v === 'function' ? v.bind(knex) : v; + }, + }); + await driver.initObjects([CONV_OBJECT]); + expect(converged(info).map((l) => l.meta)).toEqual([ + { table: CONV, field: 'flag', rowsConverted: 2, sampleIds: ['text_false', 'text_true'] }, + { table: CONV, field: 'live', rowsConverted: 1, sampleIds: ['text_false'] }, + ]); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-rotation.ts b/packages/drivers/driver-sql/src/sql-driver-rotation.ts index 5d963ae6c36..73fd7d43831 100644 --- a/packages/drivers/driver-sql/src/sql-driver-rotation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-rotation.ts @@ -55,6 +55,7 @@ import { isInstantColumnType } from './date-on-instant-column.js'; export interface RotationHost { assertSchemaMutable: SqlDriver['assertSchemaMutable']; readonly autoNumberFields: SqlDriver['autoNumberFields']; + backfillCanonicalBooleans: SqlDriver['backfillCanonicalBooleans']; backfillCanonicalDatetimes: SqlDriver['backfillCanonicalDatetimes']; backfillCanonicalJsonEncoding: SqlDriver['backfillCanonicalJsonEncoding']; backfillCanonicalTimes: SqlDriver['backfillCanonicalTimes']; @@ -399,7 +400,7 @@ export class RotationFacet { } /** The body of `SqlDriver#initObjects`; the method's docblock there is its contract. */ - static async initObjects(this: Pick, objects: Array<{ name: string; fields?: Record; tenancy?: any; indexes?: any[]; lifecycle?: any }>): Promise { + static async initObjects(this: Pick, objects: Array<{ name: string; fields?: Record; tenancy?: any; indexes?: any[]; lifecycle?: any }>): Promise { // The ADR-0104 media arm, resolved BEFORE registration because // `registerObjectMetadata` below freezes `isJsonField`'s answer into // `jsonFields` for every media column it sees. Memoized, and every failure @@ -664,6 +665,9 @@ export class RotationFacet { // Commit 4045b954d: converge this table's `Field.json` columns on the injective // JSON-text storage form the rewritten `formatInput` now writes. await this.backfillCanonicalJsonEncoding(tableName, exists); + // #34973: converge this table's boolean columns: legacy text 'true' / + // 'false' cells on SQLite become 1 / 0, the form every write now takes. + await this.backfillCanonicalBooleans(tableName, exists); // #3942: the MySQL twin — widen legacy `TIMESTAMP` columns to `DATETIME(3)`. if (exists) await this.migrateMysqlDatetimeColumns(tableName, obj.fields ?? {}); // #3994: widen legacy MySQL `TIME` columns to `TIME(3)`. 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 bddf7eb22a5..537e5397bac 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts @@ -133,6 +133,13 @@ * `isRuntimeDefaultToken` from `@objectstack/spec/data`, which `sql-driver.ts` * no longer reads. * + * [#34973] Two bodies were born here rather than moved: + * `backfillCanonicalBooleans`, the fourth storage convergence (legacy text + * `'true'` / `'false'` in a SQLite boolean column to `1` / `0`), and + * `previewBooleanConvergence`, its deferred-DDL preview. Each carries its + * contract in its own docblock, and the class methods only point there, + * because `sql-driver.ts` sits under its facade line ceiling. + * * A MOVE, not a redesign. Each function below is the body of the `SqlDriver` * method of the same name as it stood, re-indented one level and otherwise * unedited: the same dialect statements, the same rebuild procedure, the same @@ -249,6 +256,7 @@ export interface SchemaSyncHost { readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject']; readonly physicalTableByObject: SqlDriver['physicalTableByObject']; planDeclaredRenames: SqlDriver['planDeclaredRenames']; + previewBooleanConvergence: SqlDriver['previewBooleanConvergence']; previewDatetimeConvergence: SqlDriver['previewDatetimeConvergence']; previewTimeConvergence: SqlDriver['previewTimeConvergence']; probeNullSafeUniqueDuplicates: SqlDriver['probeNullSafeUniqueDuplicates']; @@ -2036,6 +2044,132 @@ export async function backfillCanonicalTimes(this: Pick, table: string, tableExisted: boolean): Promise { + const fields = this.booleanFields[table]; + if (!this.isSqlite || !fields || fields.length === 0 || !tableExisted) return; + + for (const field of fields) { + try { + // One scan classifies every text cell: legacy (converted below), + // canonical text, or other text (withheld and warned about). Canonical + // text is the `'1'` / `'0'` a column with TEXT affinity (one whose type + // changed to boolean without a rebuild) stores for the driver's own + // `1` / `0`: it already reads as its boolean, so it is not withheld. + const counted: any = await this.knex.raw( + `select count(*) as text_rows, coalesce(sum(case when ${SQLITE_LEGACY_BOOLEAN_TEXT} then 1 else 0 end), 0) as legacy, ` + + `coalesce(sum(case when ?? in ('1', '0') then 1 else 0 end), 0) as canonical ` + + `from ?? where typeof(??) = 'text'`, + [field, field, field, table, field], + ); + const tally = Array.isArray(counted) ? counted[0] : counted; + const legacy = Number(tally?.legacy ?? 0); + const withheld = Number(tally?.text_rows ?? 0) - legacy - Number(tally?.canonical ?? 0); + if (legacy > 0) { + const sample: Array<{ id: unknown }> = await this.knex.raw( + `select id from ?? where ${SQLITE_LEGACY_BOOLEAN_TEXT} order by id limit ?`, + [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}`, + [table, field, field, field, field], + ); + // better-sqlite3 reports `changes`; a client whose raw path returns + // rows instead (driver-sqlite-wasm, knex `sqlite3`) does not, and the + // guarded UPDATE converts exactly the rows counted above. + const changes = (res as any)?.changes; + const converted = typeof changes === 'number' ? changes : legacy; + 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 ` + + `as the boolean they read as`, + { table, field, rowsConverted: converted, sampleIds: sample.map((r) => String(r.id)) }, + ); + } + } + 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 ` + + `read without guessing. Boolean filters do not match them until the values are ` + + `corrected or cleared at the source`, + { table, field, rowsWithheld: withheld }, + ); + } + } 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`, + { error: err instanceof Error ? err.message : String(err) }, + ); + } + } +} + /** The body of `SqlDriver#legacyMysqlTimestampColumns`; the method's docblock there is its contract. */ export async function legacyMysqlTimestampColumns(this: Pick, table: string, fields: Record): Promise> { if (!this.isMysql) return []; @@ -2368,7 +2502,7 @@ export function registerExternalObject(this: Pick): Promise { +export async function previewDeferredSchemaWork(this: Pick): Promise { const out: PendingSchemaWork[] = []; for (const [tableName, obj] of this.deferredSchemaObjects) { const declared = Object.entries(obj.fields ?? {}) @@ -2453,6 +2587,8 @@ export async function previewDeferredSchemaWork(this: Pick a.table.localeCompare(b.table) || a.kind.localeCompare(b.kind)); return out; @@ -2540,6 +2676,35 @@ export async function previewTimeConvergence(this: Pick, table: string, existingColumns: Set): Promise { + if (!this.isSqlite) return []; + try { + const declared = (this.booleanFields[table] ?? []).filter((c) => existingColumns.has(c)); + const columns: string[] = []; + let rows = 0; + for (const field of declared) { + const res: any = await this.knex.raw( + `select count(*) as n from ?? where ${SQLITE_LEGACY_BOOLEAN_TEXT}`, + [table, field, field], + ); + const n = Number((Array.isArray(res) ? res[0] : res)?.n ?? 0); + if (n > 0) { columns.push(field); rows += n; } + } + return columns.length === 0 ? [] : [{ table, kind: 'normalize_boolean_storage', columns, rows }]; + } catch { + return []; + } +} + /** The body of `SqlDriver#nowColumnDefault`; the method's docblock there is its contract. */ export function nowColumnDefault(this: Pick, type: string): Knex.Raw { if (!this.isSqlite) { diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 9c544c363df..85a046fc367 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -175,7 +175,7 @@ import { // `previewTimeConvergence`): the read-only plan of what the deferred schema sync would do. // [#25521 cut 19] And the declared column DEFAULT emission (`nowColumnDefault`, `applyDeclaredColumnDefault`): // what a field's `defaultValue` becomes in the DDL of a fresh or rebuilt column. -import { applyDeclaredColumnDefault, applyDriftOpInPlace, applyIndexDriftOp, applyMigrationEntries, applyMigrationEntriesKeepingDeferral, applyNullSafeUniquePreflight, applyPublishedColumnChanges, backfillCanonicalDatetimes, backfillCanonicalJsonEncoding, backfillCanonicalTimes, convergeJsonColumn, countNonTemporalTextRows, createNullSafeUniqueIndex, DEFERRED_DDL_LOCK_WAIT_TIMEOUT_SECONDS, detectManagedDrift, detectTableDrift, detectTableIndexDrift, ensureRotation, legacyMysqlTimeColumns, legacyMysqlTimestampColumns, nowColumnDefault, planMediaColumnMove, previewDatetimeConvergence, previewDeferredSchemaWork, previewTimeConvergence, rebuildSqliteTablePatched, reconcileAndWarnDrift, registerExternalObject, relaxDeclaredNotNull, restoreBareIndexAfterFailedTighten, rotationColumnList, rotationShardKey, runWideningAlters, syncDeclaredIndexes, warnBuiltinColumnCollisions } from './sql-driver-schema-sync.js'; +import { applyDeclaredColumnDefault, applyDriftOpInPlace, applyIndexDriftOp, applyMigrationEntries, applyMigrationEntriesKeepingDeferral, applyNullSafeUniquePreflight, applyPublishedColumnChanges, backfillCanonicalBooleans, backfillCanonicalDatetimes, backfillCanonicalJsonEncoding, backfillCanonicalTimes, convergeJsonColumn, countNonTemporalTextRows, createNullSafeUniqueIndex, DEFERRED_DDL_LOCK_WAIT_TIMEOUT_SECONDS, detectManagedDrift, detectTableDrift, detectTableIndexDrift, ensureRotation, legacyMysqlTimeColumns, legacyMysqlTimestampColumns, nowColumnDefault, planMediaColumnMove, previewBooleanConvergence, previewDatetimeConvergence, previewDeferredSchemaWork, previewTimeConvergence, rebuildSqliteTablePatched, reconcileAndWarnDrift, registerExternalObject, relaxDeclaredNotNull, restoreBareIndexAfterFailedTighten, rotationColumnList, rotationShardKey, runWideningAlters, syncDeclaredIndexes, warnBuiltinColumnCollisions } from './sql-driver-schema-sync.js'; import type { ConcurrentIndexDeferral } from './pg-concurrent-index.js'; // [#25521 cut 11] The autonumber sequence path (`getNextSequenceValue`, `fillAutoNumberFields`, // `issueAutonumbers`, `maxAutonumberCounter`, and the #5495 collision re-seed `collidingAutoNumberReservations` @@ -4962,6 +4962,26 @@ export class SqlDriver implements IDataDriver { return backfillCanonicalTimes.call(host, table, tableExisted); } + /** + * Converge one table's boolean columns on the integer storage form: legacy + * text `'true'` / `'false'` on SQLite becomes `1` / `0` (#34973). The + * contract is the docblock of `backfillCanonicalBooleans` in + * `sql-driver-schema-sync.ts`. + */ + protected backfillCanonicalBooleans(table: string, tableExisted: boolean): Promise { + const readBooleanFields = () => this.booleanFields; + const readIsSqlite = () => this.isSqlite; + const readKnex = () => this.knex; + const readLogger = () => this.logger; + const host: ThisParameterType = { + get booleanFields() { return readBooleanFields(); }, + get isSqlite() { return readIsSqlite(); }, + get knex() { return readKnex(); }, + get logger() { return readLogger(); }, + }; + return backfillCanonicalBooleans.call(host, table, tableExisted); + } + /** * The `Field.datetime` (and audit) columns of `table` that MySQL still stores * as a legacy `TIMESTAMP`, with the nullability each must keep. @@ -5307,6 +5327,7 @@ export class SqlDriver implements IDataDriver { get deferredSchemaObjects() { return readDeferredSchemaObjects(); }, get knex() { return readKnex(); }, planDeclaredRenames: (...a) => this.planDeclaredRenames(...a), + previewBooleanConvergence: (...a) => this.previewBooleanConvergence(...a), previewDatetimeConvergence: (...a) => this.previewDatetimeConvergence(...a), previewTimeConvergence: (...a) => this.previewTimeConvergence(...a), rotationShardKey: (...a) => this.rotationShardKey(...a), @@ -5389,6 +5410,24 @@ export class SqlDriver implements IDataDriver { return previewTimeConvergence.call(host, table, fields, existingColumns); } + /** + * The work {@link backfillCanonicalBooleans} would do for `table`, measured, + * not performed (#34973): `normalize_boolean_storage` in `os migrate plan`. + * The contract is the docblock of `previewBooleanConvergence` in + * `sql-driver-schema-sync.ts`. + */ + protected previewBooleanConvergence(table: string, existingColumns: Set): Promise { + const readBooleanFields = () => this.booleanFields; + const readIsSqlite = () => this.isSqlite; + const readKnex = () => this.knex; + const host: ThisParameterType = { + get booleanFields() { return readBooleanFields(); }, + get isSqlite() { return readIsSqlite(); }, + get knex() { return readKnex(); }, + }; + return previewBooleanConvergence.call(host, table, existingColumns); + } + /** * Run the deferred sync and disarm the deferral. Returns the work that was * outstanding (captured before the DDL ran, so the caller can report what it @@ -9763,6 +9802,7 @@ export class SqlDriver implements IDataDriver { rotationHost.install((driver) => ({ assertSchemaMutable: (...a) => driver.assertSchemaMutable(...a), get autoNumberFields() { return driver.autoNumberFields; }, + backfillCanonicalBooleans: (...a) => driver.backfillCanonicalBooleans(...a), backfillCanonicalDatetimes: (...a) => driver.backfillCanonicalDatetimes(...a), backfillCanonicalJsonEncoding: (...a) => driver.backfillCanonicalJsonEncoding(...a), backfillCanonicalTimes: (...a) => driver.backfillCanonicalTimes(...a),