diff --git a/.changeset/35862-mysql-text-to-varchar.md b/.changeset/35862-mysql-text-to-varchar.md new file mode 100644 index 00000000000..096f18512e5 --- /dev/null +++ b/.changeset/35862-mysql-text-to-varchar.md @@ -0,0 +1,19 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): on MySQL, `os migrate plan` / `apply` now converts a TEXT column to the `varchar(n)` its field declares, so an index over that column can be built + +Clause-②: no +Metadata-protocol: none + +Who sees it: a MySQL deployment with a text field that was created without a `maxLength`, later gained one, and is now part of an index. + +- **Before:** the column stayed `TEXT`, because the schema sync never changes an existing column's type. MySQL refuses to index a `TEXT` column, so the index was never created. No drift entry reported the column, and the only remedy was a hand-written `ALTER TABLE … MODIFY`. +- **Now:** `os migrate plan` reports a `narrow_varchar` entry for the column, at category `needs_confirm`. It first counts the rows whose value is longer than `n`: + - **No such rows:** the entry is a warning. `os migrate apply` converts the column to `varchar(n)` and keeps its NOT NULL, DEFAULT, character set, collation and comment. The next boot creates the index. + - **Some rows are too long:** the plan names a count and up to five row ids, and `os migrate apply` refuses the entry. The column stays `TEXT` until those values are shortened or the field declares a larger `maxLength`. +- The apply step checks the rows again just before it alters the column. It runs under strict SQL mode, so a value written after the plan cannot be truncated, and it waits a bounded time for the table's metadata lock. +- **An artifact-pinned boot** applies every entry that is not `destructive`, so it converts a clean column at boot and skips a dirty one with a warning. The entry is never `destructive`, so the boot is never refused for it. +- PostgreSQL and SQLite are unchanged: both can index a `text` column. +- The error logged when MySQL refuses such an index now names `os migrate plan` / `apply` instead of a hand-written `ALTER TABLE`. diff --git a/packages/drivers/driver-sql/src/mysql-text-to-varchar.ts b/packages/drivers/driver-sql/src/mysql-text-to-varchar.ts new file mode 100644 index 00000000000..a0f8cabed00 --- /dev/null +++ b/packages/drivers/driver-sql/src/mysql-text-to-varchar.ts @@ -0,0 +1,167 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The MySQL TEXT → `varchar(n)` conversion at the migration door (ruling A1′ + * on the keyed-TEXT index card). + * + * A column created as TEXT before its field declared a usable `maxLength` + * stays TEXT, because the additive sync never rewrites a column's type, and + * MySQL refuses every index that keys it (ER_BLOB_KEY_WITHOUT_LENGTH). + * `diffManagedTable` reports it as `narrow_varchar` over the TEXT column at + * category `needs_confirm` (never `destructive`: the artifact-pinned boot + * refuses `destructive` alone, and every database this describes is already + * serving). The two halves here decide the rest from the DATA: + * + * - {@link applyTextToVarcharPreflight}, the plan-side probe: clean rows keep + * the entry at `warning`; rows longer than n add an `applyLimit` naming them, + * which `os migrate apply` refuses however the entry is confirmed. + * - {@link convertMysqlTextColumnToVarchar}, the apply arm `applyDriftOpInPlace` + * routes a TEXT-source `narrow_varchar` to: it probes again, under strict SQL + * mode and a bounded metadata-lock wait, and restates the column's NOT NULL, + * DEFAULT, character set, collation and comment from the catalog. + * + * Module-local functions, not `SqlDriver` methods: the class's `.d.ts` carries + * its protected members, so a method would move a published entry point. + */ + +import type { Knex } from 'knex'; +import { isTextFamilyColumn, type ManagedDriftEntry } from './schema-drift.js'; + +type RunRaw = (sql: string, bindings: unknown[]) => Promise; + +/** The row array of a `knex.raw` answer: mysql2 answers `[rows, fields]`. */ +const rowsOf = (res: any): any[] => (Array.isArray(res?.[0]) ? res[0] : (res?.rows ?? res ?? [])); + +/** + * Rows of `table` whose `column` holds a value longer than `chars` + * characters, as the operator needs them named: the count, and the ids and + * lengths of the first five. MySQL only (`CHAR_LENGTH`); every caller is. + */ +async function probeOverLongTextRows( + run: RunRaw, + table: string, + column: string, + chars: number, +): Promise<{ count: number; sample: string }> { + const counted = rowsOf(await run('SELECT COUNT(*) AS n FROM ?? WHERE CHAR_LENGTH(??) > ?', [table, column, chars])); + const count = Number(counted?.[0]?.n ?? 0); + if (count === 0) return { count, sample: '' }; + const sampled = rowsOf( + await run('SELECT ?? AS id, CHAR_LENGTH(??) AS len FROM ?? WHERE CHAR_LENGTH(??) > ? ORDER BY ?? LIMIT 5', [ + 'id', + column, + table, + column, + chars, + 'id', + ]), + ); + const shown = sampled.map((r) => `id ${String(r.id)} (${Number(r.len)} chars)`).join('; '); + return { count, sample: count > sampled.length ? `${shown}; …and ${count - sampled.length} more` : shown }; +} + +/** + * The plan-side probe of every TEXT-source `narrow_varchar` entry in + * `entries`, rewritten in place. Clean data keeps the entry `needs_confirm`, + * at `warning`: the conversion loses nothing. Rows longer than n keep it + * `needs_confirm` and add an `applyLimit` naming them. A failed probe leaves + * the entry as the differ wrote it; the apply probes again before it alters + * anything. + */ +export async function applyTextToVarcharPreflight(knex: Knex, entries: ManagedDriftEntry[]): Promise { + for (const d of entries) { + const op = d.op; + if (op.type !== 'narrow_varchar' || op.from !== undefined || !isTextFamilyColumn(d.actual)) continue; + let found: { count: number; sample: string }; + try { + found = await probeOverLongTextRows((sql, b) => knex.raw(sql, b as any), op.table, op.column, op.to); + } catch { + continue; + } + if (found.count === 0) { + d.severity = 'warning'; + d.message = + `${op.table}.${op.column}: the column is ${String(d.actual).toUpperCase()} but metadata builds it as ` + + `varchar(${op.to}), and MySQL cannot key a TEXT column. No stored value is longer than ${op.to} ` + + `characters, so "os migrate apply" converts it without losing data, keeping its NOT NULL and DEFAULT.`; + continue; + } + d.applyLimit = `${found.count} row(s) hold a value longer than ${op.to} characters: ${found.sample}`; + d.message = + `${op.table}.${op.column}: the column is ${String(d.actual).toUpperCase()} but metadata builds it as ` + + `varchar(${op.to}), and MySQL cannot key a TEXT column. ${d.applyLimit}. The conversion is BLOCKED: ` + + `"os migrate apply" probes again and refuses, and the column stays ${String(d.actual).toUpperCase()}. ` + + `Shorten or remove those values, or declare a larger \`maxLength\`, then re-run "os migrate plan".`; + } +} + +/** + * The apply arm of `narrow_varchar` over a MySQL TEXT column. On ONE pinned + * connection: a bounded metadata-lock wait (`lockWaitSeconds`), strict SQL + * mode (so the ALTER refuses rather than truncates a value written after the + * probe), a re-probe that refuses on any value longer than `chars`, then + * `MODIFY` to `varchar(chars)` restating the column's NOT NULL, DEFAULT, + * character set, collation and comment from the catalog — MODIFY drops + * whatever it does not repeat. Answers `false` (skipped) on a refusal, with + * the rows named at warn. The session's prior `lock_wait_timeout` and + * `sql_mode` are restored. + */ +export async function convertMysqlTextColumnToVarchar( + host: { knex: Knex; logger: { warn(message: string, ...rest: any[]): void } }, + table: string, + column: string, + chars: number, + lockWaitSeconds: number, +): Promise { + return host.knex.transaction(async (trx) => { + const run = (sql: string, bindings: unknown[] = []) => trx.raw(sql, bindings as any); + const prior = rowsOf(await run('SELECT @@session.lock_wait_timeout AS lw, @@session.sql_mode AS sm'))[0] ?? {}; + await run('SET SESSION lock_wait_timeout = ?', [lockWaitSeconds]); + await run(`SET SESSION sql_mode = CONCAT_WS(',', NULLIF(@@session.sql_mode, ''), 'STRICT_ALL_TABLES')`); + try { + const found = await probeOverLongTextRows(run, table, column, chars); + if (found.count > 0) { + host.logger.warn( + `[schema-drift] did not convert ${table}.${column} to varchar(${chars}): ${found.count} row(s) hold a ` + + `value longer than ${chars} characters: ${found.sample}. The column stays TEXT.`, + ); + return false; + } + const cat = rowsOf( + await run( + `SELECT is_nullable AS nl, column_default AS dv, extra AS ex, character_set_name AS cs, + collation_name AS co, column_comment AS cm + FROM information_schema.columns + WHERE table_schema = database() AND table_name = ? AND column_name = ?`, + [table, column], + ), + )[0]; + if (!cat) return false; + const lit = (v: unknown) => trx.raw('?', [v as any]).toQuery(); + const parts = [`varchar(${chars})`]; + if (cat.cs) parts.push(`CHARACTER SET ${String(cat.cs)}`); + if (cat.co) parts.push(`COLLATE ${String(cat.co)}`); + parts.push(String(cat.nl).toUpperCase() === 'NO' ? 'NOT NULL' : 'NULL'); + if (cat.dv !== null && cat.dv !== undefined) { + // An expression default (MySQL 8.0.13+, the only form a TEXT column + // can carry) is reported as its expression, with the catalog's + // backslash escaping of quotes (measured on 8.0.46: + // `_utf8mb4\'anon\'`); restate it as that expression. A default + // this cannot restate makes the ALTER fail, and the failure is + // reported and skipped: the column is never left without it. + const expr = String(cat.dv).replace(/\\(['\\])/g, '$1'); + parts.push(/DEFAULT_GENERATED/i.test(String(cat.ex ?? '')) ? `DEFAULT (${expr})` : `DEFAULT ${lit(cat.dv)}`); + } + if (cat.cm) parts.push(`COMMENT ${lit(cat.cm)}`); + await run(`ALTER TABLE ?? MODIFY ?? ${parts.join(' ')}`, [table, column]); + return true; + } finally { + try { + await run('SET SESSION lock_wait_timeout = ?', [Number(prior.lw ?? lockWaitSeconds)]); + await run('SET SESSION sql_mode = ?', [String(prior.sm ?? '')]); + } catch { + // Best-effort: never mask the refusal being thrown past this block. + } + } + }); +} diff --git a/packages/drivers/driver-sql/src/schema-drift.ts b/packages/drivers/driver-sql/src/schema-drift.ts index fab3a56f702..7ce9bc0917d 100644 --- a/packages/drivers/driver-sql/src/schema-drift.ts +++ b/packages/drivers/driver-sql/src/schema-drift.ts @@ -1071,6 +1071,15 @@ function isCharacterColumn(type: string | undefined): boolean { return /char/i.test(String(type ?? '')); } +/** + * Is this physical column MySQL's TEXT family (`tinytext`, `text`, + * `mediumtext`, `longtext`), the column type MySQL refuses to key without a + * key length? Anchored, so `varchar` and `json` never match. + */ +export function isTextFamilyColumn(type: string | undefined): boolean { + return /^(tiny|medium|long)?text$/i.test(String(type ?? '').trim()); +} + /** * Is this physical column one that ACCEPTS a stringified JSON array without * complaint — i.e. `varchar`/`char`/`text` in any dialect's spelling (#11535)? @@ -1957,6 +1966,64 @@ export function diffManagedTable(args: { } } + // ── a field the emitter builds as varchar(n) over a MySQL TEXT column ── + // + // The upgrade shape: a column created as TEXT before its field declared a + // usable bound stays TEXT, because the additive sync never rewrites a + // column's type. MySQL then refuses every index that keys it + // (ER_BLOB_KEY_WITHOUT_LENGTH), and the varchar branch above never sees it: + // `isCharacterColumn` does not match `text`. + // + // MySQL only. Postgres keys a `text` column directly, so a TEXT column there + // is no divergence anything refuses; SQLite has no length to converge. + // + // The op is `narrow_varchar` because that is the conversion: the column + // goes from a wider type to `varchar(n)`. `from` stays absent, since the + // source column has no varchar length; the apply arm reads the catalog and + // recognises the TEXT source there. + // + // ## Category `needs_confirm`, decided by the data, never `destructive` + // + // Every database this describes is ALREADY SERVING, and + // `runArtifactBootMigrationGate` refuses a boot for `destructive` alone, so + // a `destructive` spelling would crash-loop a deployment whose rows all fit. + // The conversion loses nothing when no stored value is longer than n. + // Whether that is true is a question about the DATA, so the pure differ + // cannot answer it: the driver's plan-side probe + // (`applyTextToVarcharPreflight`) reads the rows, and when some are longer + // it adds an `applyLimit` naming them. The apply arm probes again before the + // ALTER and refuses on any such row, under strict SQL mode, so a value + // written between plan and apply still cannot be truncated. + if ( + dialect === 'mysql' && + !declaresJsonColumn && + declaredMaxLength !== undefined && + isTextFamilyColumn(col.type) && + varcharColumnChars !== undefined + ) { + const chars = varcharColumnChars(field, keyedColumns?.get(fieldName)); + if (chars !== null) { + out.push({ + kind: 'type_mismatch', + remoteName: table, + table, + column: fieldName, + expected: `varchar(${chars})`, + actual: String(col.type), + severity: 'error', + category: 'needs_confirm', + op: { type: 'narrow_varchar', table, column: fieldName, to: chars }, + message: + `${table}.${fieldName}: metadata caps at ${chars} chars, so ObjectStack builds this column as ` + + `varchar(${chars}), but the existing column is ${String(col.type).toUpperCase()}: it was created ` + + `before the bound was declared, and the additive sync never changes a column's type. MySQL ` + + `cannot key a TEXT column, so any index over it is refused. "os migrate plan" checks the stored ` + + `values and "os migrate apply" converts the column, keeping its NOT NULL and DEFAULT; it refuses ` + + `while any row holds a value longer than ${chars} characters.`, + }); + } + } + // ── an UNBOUNDED text-family field over a pre-existing varchar (#12121) ── // // The exact COMPLEMENT of the branch above: that one REQUIRES diff --git a/packages/drivers/driver-sql/src/sql-driver-12999-stale-text-remedy.test.ts b/packages/drivers/driver-sql/src/sql-driver-12999-stale-text-remedy.test.ts index 5bea023671d..f992960171b 100644 --- a/packages/drivers/driver-sql/src/sql-driver-12999-stale-text-remedy.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-12999-stale-text-remedy.test.ts @@ -145,15 +145,26 @@ describe('unkeyable TEXT column: the upgrade path names the real remedy (#12999) // The remedy, in full. Each clause is separately load-bearing: an operator // who converts the column without restating NOT NULL / DEFAULT on MySQL // ends up WORSE off than the no-op, having silently dropped the default. - expect(message).toMatch(/backup taken first/); - expect(message).toMatch(/restating the FULL column definition on MySQL/); - expect(message).toMatch(/MODIFY drops a NOT NULL or DEFAULT you do not repeat/); + // The remedy is the migration door, whose apply arm restates the whole + // column definition from the catalog, so the message names that door and + // what it keeps. + expect(message).toMatch(/run "os migrate plan", then "os migrate apply"/); + expect(message).toMatch(/keeping NOT NULL and DEFAULT/); + expect(message).toMatch(/refuses with the rows named/); expect(message).toContain('varchar(64)'); - expect(message).toMatch(/next boot create this index/); - - // ⛔ And it does NOT quietly become an instruction the driver will carry out - // itself: the rewrite needs an exclusive metadata lock, so it stays manual. - expect(message).toMatch(/does NOT rewrite the column for you/); + expect(message).toMatch(/next boot then creates this index/); + + // ⛔ And no manual path is left in it: the operator is not handed a + // hand-written MODIFY, the statement that drops a NOT NULL or DEFAULT it + // does not repeat. A manual path reintroduced here must bring back its + // backup-first and restate-everything guidance, and this pin says so. + expect(message).not.toMatch(/ALTER TABLE/i); + expect(message).not.toMatch(/\bMODIFY\b/i); + expect(message).not.toMatch(/by hand/i); + + // ⛔ The plain boot sync still does not rewrite the column itself: the + // rewrite needs an exclusive metadata lock, so it runs at the migration door. + expect(message).toMatch(/plain boot sync does not convert the column itself/); expect(message).toMatch(/exclusive metadata lock/); // ⛔ The CREATE-path advice must be GONE from this message — its presence is @@ -236,7 +247,7 @@ describe('unkeyable TEXT column: the upgrade path names the real remedy (#12999) // The stale half gets the conversion remedy… expect(message).toMatch(/"slug" \(declares `maxLength: 64`\)/); - expect(message).toMatch(/restating the FULL column definition on MySQL/); + expect(message).toMatch(/"os migrate apply": it converts the column\(s\) to varchar\(n\), keeping NOT NULL and DEFAULT/); // …and the genuinely unbounded half is still told to declare a bound, so a // composite key does not send the operator down one route for both columns. expect(message).toMatch(/Column\(s\) "note" in the same key declare no usable bound and DO need `maxLength`/); diff --git a/packages/drivers/driver-sql/src/sql-driver-35862-text-to-varchar.test.ts b/packages/drivers/driver-sql/src/sql-driver-35862-text-to-varchar.test.ts new file mode 100644 index 00000000000..c419506b4c0 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-35862-text-to-varchar.test.ts @@ -0,0 +1,253 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #35862 half A (ruling A1′) — a keyed TEXT column already stored on MySQL + * converges to its declared `varchar(n)` at the migration door. + * + * ## The shape + * + * A column created as TEXT before its field declared a usable `maxLength` + * stays TEXT: the additive sync never rewrites a column's type. MySQL then + * refuses every index that keys it (ER_BLOB_KEY_WITHOUT_LENGTH), and before + * this change no drift entry described it, because the varchar branch of + * `diffManagedTable` only reads `char` columns. + * + * ## The disposition this pins + * + * - The differ reports `narrow_varchar` over the TEXT column, MySQL only, at + * category `needs_confirm` — never `destructive`, which would refuse the + * artifact-pinned boot of a deployment that is already serving. + * - The plan-side probe reads the rows: clean data is a `warning`; rows longer + * than n add an `applyLimit` naming them. + * - The apply re-probes, then converts under strict SQL mode, restating NOT + * NULL and DEFAULT. On dirty data it refuses and the column stays TEXT. + * - Postgres and SQLite report nothing: neither refuses to key a TEXT column. + * + * ## The layers + * + * - Everywhere: the pure differ, per dialect. + * - Live MySQL: the real conversion, clean and dirty. Runs in the + * `Temporal Conformance (live PG + MySQL)` job. + * - Live PostgreSQL and SQLite: the controls. + * + * OS_TEST_MYSQL_URL=mysql://root:root@127.0.0.1:3306/conformance \ + * pnpm --filter @objectstack/driver-sql exec vitest run sql-driver-35862-text-to-varchar + */ + +import { describe, it, expect, afterEach, afterAll } from 'vitest'; +import { SqlDriver } from '../src/index.js'; +import { buildIndexName, diffManagedTable, indexedKeyColumns, type ManagedDriftEntry } from './schema-drift.js'; +import { DIALECT_CELLS, declareDialectCell, dialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; + +/** The emitter's own mirror, as `detectTableDrift` threads it. */ +const mirror = new SqlDriver(dialectCell('sqlite').config()); +const varcharColumnChars = (field: any, keyed?: { unique: boolean }): number | null => + (mirror as any).varcharColumnChars(field, keyed); + +const TABLE = 'os35862_text'; + +const fields = { user_id: { type: 'text', maxLength: 255 }, note: { type: 'text', maxLength: 255 } }; +const indexes = [{ fields: ['user_id', 'created_at'], unique: false }]; + +function diff(dialect: 'mysql' | 'postgres' | 'sqlite', type: string, maxLength?: number): ManagedDriftEntry[] { + return diffManagedTable({ + table: TABLE, + fields, + columns: [ + { name: 'id', type: 'varchar', nullable: false, maxLength: 255 }, + { name: 'user_id', type, nullable: true, maxLength }, + { name: 'note', type, nullable: true, maxLength }, + ], + dialect, + keyedColumns: indexedKeyColumns({ table: TABLE, fields, tenantField: null, declaredIndexes: indexes }), + varcharColumnChars, + }).filter((d) => d.column === 'user_id' || d.column === 'note'); +} + +describe('the differ reports a keyed TEXT column on MySQL (#35862)', () => { + afterAll(async () => { + await mirror.disconnect().catch(() => {}); + }); + + it('reports narrow_varchar over the KEYED TEXT column, at needs_confirm, with no varchar `from`', () => { + const entries = diff('mysql', 'text', 65535); + expect(entries).toHaveLength(1); + const [d] = entries; + expect(d!.column).toBe('user_id'); + expect(d!.category).toBe('needs_confirm'); + expect(d!.op).toEqual({ type: 'narrow_varchar', table: TABLE, column: 'user_id', to: 255 }); + expect(d!.expected).toBe('varchar(255)'); + expect(d!.actual).toBe('text'); + expect(d!.message).toContain('os migrate apply'); + }); + + it('reads every member of the TEXT family', () => { + for (const type of ['tinytext', 'mediumtext', 'longtext', 'TEXT']) { + expect(diff('mysql', type).map((d) => d.column)).toEqual(['user_id']); + } + }); + + it('CONTROL: the UNKEYED text field stays TEXT by design and is not reported', () => { + expect(diff('mysql', 'text', 65535).some((d) => d.column === 'note')).toBe(false); + }); + + it('CONTROL: Postgres and SQLite report nothing for a TEXT column', () => { + expect(diff('postgres', 'text')).toEqual([]); + expect(diff('sqlite', 'text')).toEqual([]); + }); + + it('CONTROL: a varchar column of the declared width reports nothing', () => { + expect(diff('mysql', 'varchar', 255)).toEqual([]); + }); +}); + +// ── Live: the conversion, on every dialect cell ───────────────────────────── + +const INDEX = buildIndexName(TABLE, ['user_id', 'created_at'], false); +const before = () => ({ name: TABLE, fields: { user_id: { type: 'text' }, note: { type: 'text' } } }); +const after = () => ({ name: TABLE, fields, indexes }); + +const userIdEntry = (drift: ManagedDriftEntry[]) => + drift.find((d) => d.table === TABLE && d.column === 'user_id' && d.op.type === 'narrow_varchar'); + +async function columnFacts(driver: SqlDriver, column: string) { + const knex = (driver as any).knex; + const rows: any[] = await knex + .select('COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT') + .from('information_schema.COLUMNS') + .where({ TABLE_SCHEMA: knex.client.database(), TABLE_NAME: TABLE, COLUMN_NAME: column }); + return { + type: String(rows[0]?.COLUMN_TYPE).toLowerCase(), + nullable: String(rows[0]?.IS_NULLABLE) === 'YES', + default: rows[0]?.COLUMN_DEFAULT ?? null, + }; +} + +function declareConversionSuite(cell: DialectCell): void { + describe(`TEXT → varchar(n) at the migration door — ${cell.label} (#35862)`, () => { + let driver: SqlDriver; + afterEach(async () => { + await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver?.disconnect().catch(() => {}); + }); + + /** The release before the bound, then the release that adds it and the index. */ + async function upgrade(seed: (d: SqlDriver) => Promise): Promise { + driver = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.initObjects([before()]); + if (cell.id === 'mysql') { + // NOT NULL with an expression DEFAULT: the two clauses MODIFY drops + // when it does not restate them. + await driver.execute(`alter table ${TABLE} modify user_id text not null default ('anon')`); + } + await seed(driver); + await driver.initObjects([after()]); + } + + it('clean data: planned at warning, applied, NOT NULL and DEFAULT kept, and the index builds', async () => { + await upgrade(async (d) => { + await d.execute(`insert into ${TABLE} (id, user_id, note) values ('r1', 'u1', 'a'), ('r2', 'u2', 'b')`); + }); + const drift = await driver.detectManagedDrift([after()]); + const entry = userIdEntry(drift); + if (cell.id !== 'mysql') { + // CONTROL: the column is keyable here, so there is nothing to converge. + expect(entry).toBeUndefined(); + return; + } + expect(entry).toBeDefined(); + expect(entry!.category).toBe('needs_confirm'); + expect(entry!.severity).toBe('warning'); + expect(entry!.applyLimit).toBeUndefined(); + // The artifact-pinned boot refuses `destructive` alone; nothing here is. + expect(drift.filter((d) => d.table === TABLE && d.category === 'destructive')).toEqual([]); + + // The column entry and the index entry only: the NOT NULL set up above + // also reports a `relax_not_null`, which is not this pin's subject. + const { applied } = await driver.applyMigrationEntries( + drift.filter((d) => d.table === TABLE && (d === entry || d.op.type === 'create_index')), + ); + expect(applied).toContain(entry); + const facts = await columnFacts(driver, 'user_id'); + expect(facts.type).toBe('varchar(255)'); + expect(facts.nullable).toBe(false); + expect(String(facts.default)).toContain('anon'); + // The index entry ran after the column entry, in the same apply. + expect((await (driver as any).getExistingIndexNames(TABLE)).has(INDEX)).toBe(true); + // And the stored rows are intact. + const rows: any[] = await (driver as any).knex(TABLE).select('id', 'user_id').orderBy('id'); + expect(rows.map((r) => r.user_id)).toEqual(['u1', 'u2']); + // Converged: a second plan reports nothing for the column. + expect(userIdEntry(await driver.detectManagedDrift([after()]))).toBeUndefined(); + }, 60_000); + + it('dirty data: planned with the rows named, refused at apply, and the column stays TEXT', async () => { + await upgrade(async (d) => { + await d.execute(`insert into ${TABLE} (id, user_id, note) values ('ok', 'u1', 'a'), ('long', '${'x'.repeat(300)}', 'b')`); + }); + const drift = await driver.detectManagedDrift([after()]); + const entry = userIdEntry(drift); + if (cell.id !== 'mysql') { + expect(entry).toBeUndefined(); + return; + } + expect(entry).toBeDefined(); + expect(entry!.category).toBe('needs_confirm'); + expect(entry!.applyLimit).toContain('1 row(s)'); + expect(entry!.applyLimit).toContain('id long (300 chars)'); + expect(entry!.message).toContain('BLOCKED'); + expect(drift.filter((d) => d.table === TABLE && d.category === 'destructive')).toEqual([]); + + const warned: string[] = []; + (driver as any).logger = { ...(driver as any).logger, warn: (msg: string) => warned.push(msg) }; + const { applied, skipped } = await driver.applyMigrationEntries([entry!]); + // Refused by the apply's own re-probe, naming the row, not by the server. + expect(warned.filter((m) => m.includes('did not convert') && m.includes('id long (300 chars)'))).toHaveLength(1); + expect(applied).toEqual([]); + expect(skipped).toContain(entry); + expect((await columnFacts(driver, 'user_id')).type).toBe('text'); + const rows: any[] = await (driver as any).knex(TABLE).select('user_id').where({ id: 'long' }); + expect(String(rows[0]?.user_id)).toHaveLength(300); + }, 60_000); + + // The artifact-pinned boot (`runArtifactBootMigrationGate`, in the CLI) + // refuses when any entry is `destructive`, and otherwise hands every other + // entry to `applyMigrationEntries` with `allowDestructive: false`. This is + // that policy, spelled over the driver, for both data shapes: the boot is + // never refused, a clean column converts, and a dirty one is skipped. + it('the artifact-pinned boot policy: ok for clean and dirty data alike', async () => { + for (const shape of ['clean', 'dirty'] as const) { + await upgrade(async (d) => { + const userId = shape === 'clean' ? 'u2' : 'x'.repeat(300); + await d.execute(`insert into ${TABLE} (id, user_id, note) values ('r1', 'u1', 'a'), ('r2', '${userId}', 'b')`); + }); + const drift = (await driver.detectManagedDrift([after()])).filter((d) => d.table === TABLE); + // `ok: false` is the gate's answer for a destructive entry and only that. + expect(drift.filter((d) => d.category === 'destructive'), shape).toEqual([]); + const entry = userIdEntry(drift); + const { applied, skipped } = await driver.applyMigrationEntries( + drift.filter((d) => d.category !== 'destructive'), + { allowDestructive: false }, + ); + const type = cell.id === 'mysql' ? (await columnFacts(driver, 'user_id')).type : null; + if (cell.id !== 'mysql') { + expect(entry, shape).toBeUndefined(); + } else if (shape === 'clean') { + expect(applied, shape).toContain(entry); + expect(type, shape).toBe('varchar(255)'); + expect((await (driver as any).getExistingIndexNames(TABLE)).has(INDEX), shape).toBe(true); + } else { + expect(skipped, shape).toContain(entry); + expect(type, shape).toBe('text'); + } + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.disconnect().catch(() => {}); + } + }, 120_000); + }); +} + +for (const cell of DIALECT_CELLS) { + declareDialectCell(cell, 'keyed TEXT to varchar convergence (#35862)', declareConversionSuite); +} diff --git a/packages/drivers/driver-sql/src/sql-driver-column-creation.ts b/packages/drivers/driver-sql/src/sql-driver-column-creation.ts index da129b0cf7c..bda4d033da9 100644 --- a/packages/drivers/driver-sql/src/sql-driver-column-creation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-column-creation.ts @@ -168,13 +168,15 @@ export class ColumnCreationFacet { .map(([c, n]) => `"${c}" (declares \`maxLength: ${n}\`)`) .join(', '); const [firstColumn, firstBound] = [...staleBounds][0]; - // Named in full, deliberately. The mirror case in `schema-drift.ts` (the - // unbounded field over a stale `varchar`) already had to derive this, and - // the two MySQL `MODIFY` hazards it names are recorded twice more in this - // file, on the datetime and time widenings: MODIFY does NOT repeat a - // `NOT NULL`, and it DROPS a `DEFAULT` it does not restate. An operator - // who follows an abbreviated version of this remedy ends up worse off than - // the no-op they started with — a column that lost its default. + // The remedy is the migration door, never a hand-written statement. The + // two MySQL `MODIFY` hazards are recorded twice more in this file, on the + // datetime and time widenings: MODIFY does NOT repeat a `NOT NULL`, and it + // DROPS a `DEFAULT` it does not restate. An operator handed a bare MODIFY + // ends up worse off than the no-op they started with — a column that lost + // its default — so the message names `os migrate apply`, whose apply arm + // (`mysql-text-to-varchar.ts`) restates the whole definition from the + // catalog, and carries no manual path. A manual path added back here + // brings its backup-first and restate-everything guidance with it. const others = offenders.length > staleBounds.size ? ` Column(s) ${offenders @@ -188,14 +190,13 @@ export class ColumnCreationFacet { `column in a key without a key length. Column(s) ${staleNamed} are stored as TEXT even though the ` + `field ALREADY declares a usable \`maxLength\` — the column was created before that bound was ` + `declared, and the additive sync never rewrites a column's type, so re-declaring \`maxLength\` ` + - `changes nothing here. REMEDY: convert the column(s) to varchar(n) by hand, with a backup ` + - `taken first, restating the FULL column definition on MySQL (MODIFY drops a NOT NULL or DEFAULT you ` + - `do not repeat) — e.g. ALTER TABLE \`${tableName}\` MODIFY \`${firstColumn}\` ` + - `varchar(${firstBound}) plus that column's existing NOT NULL / DEFAULT clauses, restated verbatim; ` + - `— and let the next boot create this index. ObjectStack does NOT rewrite the column for you: that ` + - `ALTER needs an exclusive metadata lock on the table, which makes it a destructive, hard-to-roll-back ` + - `action and a deliberate manual floor rather than a boot-time one.${others} The table exists but this ` + - `index does NOT, so any uniqueness it declared is currently unenforced. A prefix index is deliberately ` + + `changes nothing here. REMEDY: run "os migrate plan", then "os migrate apply": it converts the ` + + `column(s) to varchar(n), keeping NOT NULL and DEFAULT, after checking that no stored value is longer ` + + `than n, and refuses with the rows named when one is (e.g. \`${firstColumn}\` to ` + + `varchar(${firstBound})). The next boot then creates this index. The plain boot sync does not ` + + `convert the column itself: the ALTER takes an exclusive metadata lock on the table, so it runs at ` + + `the migration door (an artifact-pinned boot passes through that door).${others} The table exists ` + + `but this index does NOT, so any uniqueness it declared is currently unenforced. A prefix index is deliberately ` + `not substituted: on a UNIQUE index it constrains the prefix rather than the value, and rejects two ` + `different values that share one.` ); 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 3fbbf2dfc9e..991d86d4ae7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts @@ -172,8 +172,9 @@ import { isUniqueViolationError } from '@objectstack/types'; import type { Knex } from 'knex'; import { StorageNameMapping } from '@objectstack/spec/system'; -import { carriesNullSafeTenantKeyPart, ceremonyOwnedDropFinding, describeMissingIndexColumns, diffManagedIndexes, diffManagedTable, diffUnbuildableIndexes, driftKey, expectedIndexes, fieldHasColumn, GLOBAL_TENANT, indexedKeyColumns, isCeremonyOwnedColumnDrop, isIndexDriftOp, isManagedIndexName, legacyUniqueReplacements, normalizeDeclaredIndex, type DeclaredIndexInput, type DriftOp, type ManagedDriftEntry, type PendingSchemaWork, type PhysicalColumn } from './schema-drift.js'; +import { carriesNullSafeTenantKeyPart, ceremonyOwnedDropFinding, describeMissingIndexColumns, diffManagedIndexes, diffManagedTable, diffUnbuildableIndexes, driftKey, expectedIndexes, fieldHasColumn, GLOBAL_TENANT, indexedKeyColumns, isCeremonyOwnedColumnDrop, isIndexDriftOp, isManagedIndexName, isTextFamilyColumn, legacyUniqueReplacements, normalizeDeclaredIndex, type DeclaredIndexInput, type DriftOp, type ManagedDriftEntry, type PendingSchemaWork, type PhysicalColumn } from './schema-drift.js'; import { activeConcurrentIndexDeferral, attachUniqueConstraintSql, clearConcurrentIndexDeferral, concurrentIndexSql, type ConcurrentIndexSpec, dropInvalidIndexSql, invalidIndexNames, isPostgresLockTimeout, openConcurrentIndexDeferral, withAutocommitSession, withLockTimeout } from './pg-concurrent-index.js'; +import { applyTextToVarcharPreflight, convertMysqlTextColumnToVarchar } from './mysql-text-to-varchar.js'; import { isJsonColumnType, mediaColumnMoveDialect, mediaColumnMovePlan, type MediaColumnMovePlan, type MediaColumnMoveRefusal, type MediaColumnMoveScan } from './media-column-move.js'; import { StandardErrorCode } from '@objectstack/spec/api'; import { recoverUnencodedJsonText } from './unencoded-json-text.js'; @@ -557,6 +558,11 @@ export async function applyDriftOpInPlace(this: Pick (a.table === b.table ? (a.column ?? '').localeCompare(b.column ?? '') : a.table.localeCompare(b.table))); return out;