Skip to content
Draft
19 changes: 19 additions & 0 deletions .changeset/35862-mysql-text-to-varchar.md
Original file line number Diff line number Diff line change
@@ -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`.
167 changes: 167 additions & 0 deletions packages/drivers/driver-sql/src/mysql-text-to-varchar.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>;

/** 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<void> {
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<boolean> {
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.
}
}
});
}
67 changes: 67 additions & 0 deletions packages/drivers/driver-sql/src/schema-drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)?
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`/);
Expand Down
Loading
Loading