Skip to content

Commit 88ae2f9

Browse files
fix(driver-sql): a plain index MySQL refuses to key no longer skips the object's remaining boot steps (#38225)
Part of #35862 — this lands the card's half (B), the bounded one it orders first. Half (A) stays open on the card: converging an old MySQL TEXT column to its declared varchar(n), then the inbox index itself, which this dispatch excluded (it belongs to the other half of #35530). Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:使用 MySQL 的部署里,某个对象声明的普通(非唯一)索引如果落在旧的长文本列上,MySQL 会拒建;以前这会让该对象每次启动都跳过后续的数据修复步骤并报"同步失败",现在只记一条错误日志、其余步骤照常跑完。PostgreSQL 与 SQLite 用户无感。 - 为什么做:这是收件箱铃铛提速(给消息表加按用户和时间的索引)的前置一半,先保证这类索引被拒时不再连带丢掉别的启动步骤。 - 出错会怎样:被拒的索引依旧不建、不做替代,日志照常报出并给出手工改列的办法;本改动可以直接撤回,撤回后回到原先"抛错并跳过后续步骤"的行为。 - 要你做什么:另一半(把旧文本列收敛成定长列,再上收件箱索引)走哪条路需要你定,见下方 Acceptance notes 第一条。 ## What changes - `syncDeclaredIndexes` (`packages/drivers/driver-sql/src/sql-driver-schema-sync.ts`): when MySQL refuses to key a PLAIN index (`ER_BLOB_KEY_WITHOUT_LENGTH` or `ER_TOO_LONG_KEY`, the codes `explainUnkeyableTextColumn` recognises), the refusal is still logged once at `error` through `logDurabilityFailure` with the same field-level remedy, and the loop now `continue`s instead of throwing. The index is still not created and still not substituted: no prefix index, no hash shadow (the existing scope limit for non-unique indexes). - What the throw used to cost, measured on live MySQL 8.0.46 before the fix: `initObjects` rejected for the object, so every index declared after the refused one was never attempted, and `retireIndexesNamedForOldKeys`, `reconcileAndWarnDrift`, the four canonical backfills and `migrateMysqlDatetimeColumns` / `migrateMysqlTimeColumns` never ran for that table, on every boot. - Unchanged on purpose: a UNIQUE index that the hash-shadow route could not carry still throws (the card's CONTROL). PostgreSQL and SQLite never raise these codes, so their path is byte-identical. - Why the fix sits in the producer and not in a catch in `initObjects` / `syncTableIndexes`: the throw is the defect; a catch further up would still lose every index after the refused one in the same loop, and would also swallow the UNIQUE case the card keeps. ## Tests - New `sql-driver-35862-refused-plain-index-boot-steps.test.ts`: - everywhere (SQLite): the MySQL refusal faked at `knex.schema.alterTable` with MySQL's own error shape, for both codes. Pins: one `error` line naming the object and the index; the refused index absent; the index declared after it built; every later boot step (8 named) called for the table; the drift report's warn line present. CONTROL: the same refusal on a UNIQUE index still rejects with `code: 'ER_BLOB_KEY_WITHOUT_LENGTH'` and the named refusal. - every dialect cell (SQLite, live PostgreSQL, live MySQL): the real upgrade, a TEXT `user_id` from the release before the bound, then the release that declares `maxLength: 255` and a plain `(user_id, created_at)` index plus a `seen_at` index. On MySQL: the column is still TEXT (the premise), the plain index is absent with no shadow column, one error line, the `seen_at` index built, and a legacy `TIMESTAMP` `seen_at` widened to `datetime(3)` (the last step `initObjects` runs). CONTROL on PostgreSQL and SQLite: the index is built directly, no error line. - live MySQL CONTROL: a UNIQUE index over a `maxLength: 1024` text column is still carried on a hash shadow (whole key part, `SUB_PART` null, `NON_UNIQUE` 0). - Rewritten, not deleted: three live MySQL pins asserted `initObjects` REJECTS for a non-unique unkeyable index (`sql-driver-11627-hash-shadow-key.test.ts` one, `sql-driver-keyed-text-mysql.test.ts` two). They pinned exactly the throw this change removes; they now read the same named refusal from the `error` channel and keep their negative half (no index keys the column, no shadow column). - In CI the live cells run in `Temporal Conformance (live PG + MySQL)`, step "Run driver-sql suite against both live servers" (it runs this whole package with `OS_TEST_MYSQL_URL` and `OS_TEST_POSTGRES_URL` set and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`). The SQLite layer also runs in `Test Core`. ## Acceptance notes - Fork left for the maintainer, half (A): the card's own Expected section asks for a keyed TEXT column to converge to its declared varchar(n) on MySQL, "either schema sync or an `os migrate` arm", refusing with the offending rows named when a stored value is longer than n. That choice is open, and neither alternative named in the dispatch fits: a hash shadow is ruled out for non-unique indexes by the existing scope limit (a digest serves no lookup), and a prefix index is a valid access path for a plain index but is not what the card asks for. No code for (A) is in this PR. - The refusal line `explainUnkeyableTextColumn` writes ends with "so any uniqueness it declared is currently unenforced" and a sentence about UNIQUE prefix indexes; on a plain index both are true but beside the point. Left as is: the line is shared with the UNIQUE path. - After the refusal the drift report warns that the index is missing and says to run "os migrate apply" to create it; on MySQL that apply meets the same refusal and reports the index as not applied (the create op checks presence). Existing wording, not changed here. - `SqlDriver#syncDeclaredIndexes`'s docblock in `sql-driver.ts` lists the dispositions; a bullet for this one would push the facade over its line ceiling (`check:facade-delegation-only`, 10071 lines, 0 left), so the disposition is documented at the body in `sql-driver-schema-sync.ts` instead. ## Verification Read first, by risk: 1. `packages/drivers/driver-sql/src/sql-driver-schema-sync.ts`, the new `if (!unique)` arm after `this.logDurabilityFailure(unkeyable, msg)`: the only behaviour change. 2. `packages/drivers/driver-sql/src/sql-driver-35862-refused-plain-index-boot-steps.test.ts`, the `refuseIndexes` fake: it decides the refusal from the index the `alterTable` callback declares, and passes everything else to the real knex. 3. `packages/drivers/driver-sql/src/sql-driver-keyed-text-mysql.test.ts`, the two rewritten pins. Two-minute check: `pnpm --filter @objectstack/driver-sql exec vitest run sql-driver-35862` prints `Tests 4 passed | 3 skipped (7)` with no server (the 3 skipped are the live PostgreSQL and MySQL cells); with `OS_TEST_MYSQL_URL` and `OS_TEST_POSTGRES_URL` set it prints `Tests 7 passed (7)`. Readings, all at head `f1c4549df3`, on local MySQL 8.0.46 (server zone +08:00) and PostgreSQL 16 (Asia/Shanghai), process `TZ=America/New_York`, `OS_EXPECT_LIVE_DIALECT_MATRIX=1`: <details><summary>The three touched files on live MySQL + PostgreSQL: 26/26</summary> `vitest run sql-driver-35862 sql-driver-11627-hash-shadow-key sql-driver-keyed-text-mysql`: `Test Files 3 passed (3)`, `Tests 26 passed (26)`. </details> <details><summary>Ablation: the fix removed, 6 red and every CONTROL green</summary> `scripts/ablation-replace.mjs` replaced the anchor `if (!unique) {` with `if (false) {` (anchor 1 to 0, blob 3fbbf2d to c0aaa9b00fb7) and ran the same three files: `Tests 6 failed | 20 passed (26)`. Red: both faked refusals, the live MySQL upgrade (it rejected with `ER_BLOB_KEY_WITHOUT_LENGTH` on `idx_os35862_inbox_user_id_created_at`, which is the card's premise, measured), and the three rewritten pins. Green: the UNIQUE CONTROL, the PostgreSQL and SQLite upgrade CONTROLs, the live hash-shadow CONTROL. Restored: blob equals HEAD (3fbbf2d), `git diff HEAD` empty. </details> <details><summary>Whole driver-sql suite: 7052 passed, 1 failed, both failing files environmental</summary> `pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2`: `Test Files 2 failed | 283 passed | 1 skipped (286)`, `Tests 1 failed | 7052 passed | 12 skipped (7065)`. The two files: `sql-driver-37095-pgvector-extension` (the local PostgreSQL has no pgvector extension; CI uses the pgvector image) and `sql-driver-11565-row-byte-budget` "reports InnoDB page-limit refusals" (fails identically with the fix ablated, so it is this local server, not this diff). `pnpm --filter @objectstack/driver-sql typecheck`: exit 0. </details> <details><summary>Derived gate families: 67 exit 0, 2 not measured</summary> `dispatch-gates.mjs --commands` (5 paths vs merge base 7605e0c) derived 69; all run; `--ran` reconciliation: 67 run, 2 NOT MEASURED. The two are `check:dual-build-cjs-loads` and `check:lean-entry-closure`, both exit 3 PREREQUISITE NOT MET (they read built output of the whole workspace, not built here); CI runs them. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSAaBEfQpU2yJexSJ8)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent f66cd5a commit 88ae2f9

5 files changed

Lines changed: 437 additions & 16 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): a plain index MySQL refuses to key is logged and the sync goes on, so the object's remaining boot steps run
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
MySQL refuses a TEXT column in a key without a key length (`ER_BLOB_KEY_WITHOUT_LENGTH`) and a key part wider than 3072 bytes (`ER_TOO_LONG_KEY`). A UNIQUE index past that refusal is carried on a hash shadow; a plain (non-unique) index has no such route. Schema sync logged the refusal and then threw it, and no caller between it and the per-object boot loop caught the throw. So on every boot, for that object, every index declared after the refused one was never attempted, and the old-key index retirement, the drift reconcile and report, the canonical datetime/time/json/boolean backfills and the MySQL `TIMESTAMP`/`TIME` widenings were all skipped, while the boot counted a schema-sync failure.
11+
12+
The shape that reaches it is an upgrade: a column created as TEXT before its field declared a `maxLength` stays TEXT, so a release that adds the bound and a plain index over that column hits the refusal.
13+
14+
FROM: the refusal is logged at `error` and thrown, and the object's remaining steps are skipped. TO: the refusal is logged at `error` once, on the durability channel, with the same field-level remedy, and the sync goes on. The index is still not created and still not substituted (no prefix index, no shadow column); the drift report still lists it as missing. A UNIQUE index that the hash-shadow route could not carry still throws, as before. PostgreSQL and SQLite never refuse these keys and are unchanged.
15+
16+
To build the refused index, convert the column to `varchar(n)` by hand (the remedy the log line names) and let the next boot create it.

‎packages/drivers/driver-sql/src/sql-driver-11627-hash-shadow-key.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -296,17 +296,25 @@ declareDialectCell(MYSQL_CELL, 'hash-shadow key (#11627)', (cell) => {
296296
* creating one would trade a loud refusal for a table that syncs, costs
297297
* writes on every row, and accelerates nothing. This asserts the refusal is
298298
* still a refusal — the scope limit is a decision, not an omission.
299+
*
300+
* #35862: the refusal is reported at `error` and no longer thrown, so the
301+
* object's remaining boot steps run. What this pins is unchanged: no
302+
* index, and no shadow column grown for it.
299303
*/
300304
it('leaves a non-unique unkeyable index refused rather than shadowing it', async () => {
301305
driver = new SqlDriver(cell.config());
306+
const errors: string[] = [];
307+
(driver as any).logger = { debug() {}, info() {}, warn() {}, error: (msg: string) => errors.push(msg) };
302308
const nonUnique = {
303309
name: 'os11627_nonuniq',
304310
fields: { v: { type: 'text', maxLength: 1024 } },
305311
indexes: [{ fields: ['v'], unique: false, name: 'idx_os11627_nonuniq_v' }],
306312
};
307-
await expect(driver.initObjects([nonUnique])).rejects.toThrow(
308-
/hash-shadow|cannot create index|BLOB\/TEXT/i,
309-
);
313+
await driver.initObjects([nonUnique]);
314+
expect(errors.filter((m) => /cannot create index 'idx_os11627_nonuniq_v'/.test(m))).toHaveLength(1);
315+
const { cols, idx } = await catalog('os11627_nonuniq');
316+
expect(idx.filter((i: any) => i.INDEX_NAME === 'idx_os11627_nonuniq_v')).toEqual([]);
317+
expect(cols.filter((c: any) => isHashShadowColumn(c.COLUMN_NAME))).toEqual([]);
310318
}, 60_000);
311319
});
312320
});
Lines changed: 351 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,351 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #35862 — a PLAIN index MySQL refuses to key no longer throws away the
5+
* object's remaining boot steps.
6+
*
7+
* ## The defect this pins
8+
*
9+
* MySQL refuses a TEXT column in a key without a key length
10+
* (`ER_BLOB_KEY_WITHOUT_LENGTH`), and refuses a key part wider than 3072 bytes
11+
* (`ER_TOO_LONG_KEY`). The hash-shadow route (#11627) carries a UNIQUE index
12+
* past that refusal; a PLAIN index has no such route, by decision (a digest
13+
* serves no lookup). Before this change `syncDeclaredIndexes` logged the
14+
* refusal and then THREW it. Nothing between it and the objectql per-object
15+
* loop caught the throw, so on every boot:
16+
*
17+
* - every index declared after the refused one was never attempted;
18+
* - `initObjects` left the object before the old-key index retirement, the
19+
* drift reconcile and report, the canonical datetime/time/json/boolean
20+
* backfills and the MySQL datetime/time widenings.
21+
*
22+
* The shape that reaches it is an UPGRADE: a column created as TEXT before its
23+
* field declared a `maxLength` stays TEXT (the additive sync never rewrites a
24+
* column's type), so a release that adds the bound and a plain index over it
25+
* (the `sys_inbox_message (user_id, created_at)` case) hits the refusal.
26+
*
27+
* ## The disposition this pins
28+
*
29+
* The refused plain index is still refused: not created, not substituted by a
30+
* prefix or a shadow, and reported once at `error` on the durability channel
31+
* with the field-level remedy. The sync goes on.
32+
*
33+
* ## The layers
34+
*
35+
* - Everywhere (SQLite): the server refusal is FAKED at the one DDL seam,
36+
* `knex.schema.alterTable`, with MySQL's own error shape, so the
37+
* continuation is proven on every runner, Test Core included.
38+
* - Live MySQL: the real refusal, on the real upgrade. Runs in the
39+
* `Temporal Conformance (live PG + MySQL)` job, whose driver-sql leg runs
40+
* this whole package with `OS_TEST_MYSQL_URL` set.
41+
* - Live PostgreSQL and SQLite: the controls. They never refuse, so the same
42+
* upgrade builds the index directly, exactly as before.
43+
*
44+
* OS_TEST_MYSQL_URL=mysql://root:root@127.0.0.1:3306/conformance \
45+
* pnpm --filter @objectstack/driver-sql exec vitest run sql-driver-35862
46+
*/
47+
48+
import { describe, it, expect, afterEach, vi } from 'vitest';
49+
import { SqlDriver } from '../src/index.js';
50+
import { buildIndexName, isHashShadowColumn } from './schema-drift.js';
51+
import { DIALECT_CELLS, MYSQL_CELL, dialectCell, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js';
52+
53+
interface LogLine {
54+
level: 'debug' | 'info' | 'warn' | 'error';
55+
msg: string;
56+
meta?: unknown;
57+
}
58+
59+
/** The logger double: every channel, with the structured meta kept. */
60+
function attachLogSpy(driver: SqlDriver): LogLine[] {
61+
const logs: LogLine[] = [];
62+
(driver as any).logger = {
63+
debug: (msg: string, meta?: unknown) => logs.push({ level: 'debug', msg, meta }),
64+
info: (msg: string, meta?: unknown) => logs.push({ level: 'info', msg, meta }),
65+
warn: (msg: string, meta?: unknown) => logs.push({ level: 'warn', msg, meta }),
66+
error: (msg: string, meta?: unknown) => logs.push({ level: 'error', msg, meta }),
67+
};
68+
return logs;
69+
}
70+
71+
const existingIndexNames = (driver: SqlDriver, table: string): Promise<Set<string>> =>
72+
(driver as any).getExistingIndexNames(table);
73+
74+
/** MySQL 8.0's own refusal objects, as mysql2 hands them to knex. */
75+
const REFUSALS = {
76+
ER_BLOB_KEY_WITHOUT_LENGTH: {
77+
code: 'ER_BLOB_KEY_WITHOUT_LENGTH',
78+
errno: 1170,
79+
message: "BLOB/TEXT column 'user_id' used in key specification without a key length",
80+
},
81+
ER_TOO_LONG_KEY: {
82+
code: 'ER_TOO_LONG_KEY',
83+
errno: 1071,
84+
message: 'Specified key was too long; max key length is 3072 bytes',
85+
},
86+
} as const;
87+
88+
/**
89+
* Make the DDL seam refuse the named indexes with `refusal`, and pass every
90+
* other statement to the real knex. The refusal is decided by the index the
91+
* `alterTable` callback declares, read with a recording stand-in for the table
92+
* builder, so the real builder only ever sees statements that go through.
93+
*/
94+
function refuseIndexes(driver: SqlDriver, refused: ReadonlySet<string>, refusal: { code: string; errno: number; message: string }): void {
95+
const real = (driver as any).knex;
96+
const schemaFor = () => {
97+
const schema = real.schema;
98+
return new Proxy(schema, {
99+
get(target, prop) {
100+
if (prop === 'alterTable') {
101+
return (table: string, build: (t: unknown) => void) => {
102+
const named: string[] = [];
103+
const recorder: any = new Proxy(
104+
{},
105+
{
106+
get: (_t, method) => (...args: any[]) => {
107+
if (method === 'index' && typeof args[1] === 'string') named.push(args[1]);
108+
if (method === 'unique' && typeof args[1]?.indexName === 'string') named.push(args[1].indexName);
109+
return recorder;
110+
},
111+
},
112+
);
113+
build(recorder);
114+
if (named.some((n) => refused.has(n))) {
115+
return Promise.reject(Object.assign(new Error(refusal.message), { code: refusal.code, errno: refusal.errno }));
116+
}
117+
return target.alterTable(table, build);
118+
};
119+
}
120+
const value = Reflect.get(target, prop, target);
121+
return typeof value === 'function' ? value.bind(target) : value;
122+
},
123+
});
124+
};
125+
(driver as any).knex = new Proxy(real, {
126+
get(target, prop) {
127+
if (prop === 'schema') return schemaFor();
128+
return Reflect.get(target, prop, target);
129+
},
130+
});
131+
}
132+
133+
/** The steps `initObjects` runs for an existing table after its indexes. */
134+
const LATER_STEPS = [
135+
'retireIndexesNamedForOldKeys',
136+
'reconcileAndWarnDrift',
137+
'backfillCanonicalDatetimes',
138+
'backfillCanonicalTimes',
139+
'backfillCanonicalJsonEncoding',
140+
'backfillCanonicalBooleans',
141+
'migrateMysqlDatetimeColumns',
142+
'migrateMysqlTimeColumns',
143+
] as const;
144+
145+
const spyLaterSteps = (driver: SqlDriver) =>
146+
Object.fromEntries(LATER_STEPS.map((step) => [step, vi.spyOn(driver as any, step)])) as Record<
147+
(typeof LATER_STEPS)[number],
148+
ReturnType<typeof vi.spyOn>
149+
>;
150+
151+
// ── Everywhere: the refusal faked at the DDL seam ───────────────────────────
152+
153+
describe('a refused PLAIN index does not skip the object’s remaining boot steps (#35862)', () => {
154+
const T = 'os35862_fake';
155+
const REFUSED = buildIndexName(T, ['user_id', 'created_at'], false);
156+
const AFTER = buildIndexName(T, ['status'], false);
157+
158+
/** The release before the bound: `user_id` is created TEXT, no index. */
159+
const before = () => ({
160+
name: T,
161+
fields: { user_id: { type: 'text' }, status: { type: 'text', maxLength: 32 }, seen_at: { type: 'datetime' } },
162+
});
163+
/** The release that adds the bound and the plain index over it, then one more index. */
164+
const after = (unique: boolean) => ({
165+
name: T,
166+
fields: {
167+
user_id: { type: 'text', maxLength: 255 },
168+
status: { type: 'text', maxLength: 32 },
169+
seen_at: { type: 'datetime' },
170+
},
171+
indexes: [
172+
{ fields: ['user_id', 'created_at'], unique },
173+
{ fields: ['status'], unique: false },
174+
],
175+
});
176+
177+
let driver: SqlDriver;
178+
afterEach(async () => {
179+
vi.restoreAllMocks();
180+
await driver?.disconnect().catch(() => {});
181+
});
182+
183+
it.each(Object.keys(REFUSALS) as Array<keyof typeof REFUSALS>)(
184+
'%s on a plain index: logged at error, the next index is built, and every later step runs',
185+
async (code) => {
186+
driver = new SqlDriver(dialectCell('sqlite').config());
187+
await driver.initObjects([before()]);
188+
189+
const logs = attachLogSpy(driver);
190+
refuseIndexes(driver, new Set([REFUSED]), REFUSALS[code]);
191+
const steps = spyLaterSteps(driver);
192+
193+
await expect(driver.initObjects([after(false)])).resolves.toBeUndefined();
194+
195+
// Reported once at error, naming the object and the index it refused…
196+
const lines = logs.filter((l) => l.msg.includes(`'${REFUSED}'`));
197+
const errors = lines.filter((l) => l.level === 'error');
198+
expect(errors).toHaveLength(1);
199+
expect(errors[0]!.msg).toContain(`"${T}"`);
200+
expect(errors[0]!.msg).toContain('cannot create index');
201+
// …and once more by the drift report, which only runs after the indexes.
202+
expect(lines.filter((l) => l.level === 'warn' && l.msg.startsWith('[schema-drift]'))).toHaveLength(1);
203+
204+
// Still refused: nothing was built under that name.
205+
const indexes = await existingIndexNames(driver, T);
206+
expect(indexes.has(REFUSED)).toBe(false);
207+
// The loop went on: the index declared after the refused one exists.
208+
expect(indexes.has(AFTER)).toBe(true);
209+
210+
// And `initObjects` went on: every later step ran for this table.
211+
for (const step of LATER_STEPS) {
212+
expect(steps[step].mock.calls.some((c: unknown[]) => c[0] === T), `${step} ran for ${T}`).toBe(true);
213+
}
214+
},
215+
);
216+
217+
/**
218+
* CONTROL: a UNIQUE index refused the same way keeps today's disposition.
219+
* On SQLite the hash-shadow route is not offered (it is MySQL's), so the
220+
* refusal is thrown carrying the field-level fix and the server's code.
221+
*/
222+
it('CONTROL: the same refusal on a UNIQUE index still throws the named refusal', async () => {
223+
driver = new SqlDriver(dialectCell('sqlite').config());
224+
await driver.initObjects([before()]);
225+
attachLogSpy(driver);
226+
const refusedUnique = buildIndexName(T, ['user_id', 'created_at'], true);
227+
refuseIndexes(driver, new Set([refusedUnique]), REFUSALS.ER_BLOB_KEY_WITHOUT_LENGTH);
228+
229+
const rejected: any = await driver.initObjects([after(true)]).then(
230+
() => undefined,
231+
(e: unknown) => e,
232+
);
233+
expect(rejected).toBeInstanceOf(Error);
234+
expect(rejected.code).toBe('ER_BLOB_KEY_WITHOUT_LENGTH');
235+
expect(String(rejected.message)).toContain(`cannot create index '${refusedUnique}'`);
236+
});
237+
});
238+
239+
// ── Live: the real upgrade, on every dialect cell ───────────────────────────
240+
241+
const LIVE_TABLE = 'os35862_inbox';
242+
const LIVE_REFUSED = buildIndexName(LIVE_TABLE, ['user_id', 'created_at'], false);
243+
const LIVE_AFTER = buildIndexName(LIVE_TABLE, ['seen_at'], false);
244+
245+
const liveBefore = () => ({
246+
name: LIVE_TABLE,
247+
fields: { user_id: { type: 'text' }, seen_at: { type: 'datetime' } },
248+
});
249+
const liveAfter = () => ({
250+
name: LIVE_TABLE,
251+
fields: { user_id: { type: 'text', maxLength: 255 }, seen_at: { type: 'datetime' } },
252+
indexes: [
253+
{ fields: ['user_id', 'created_at'], unique: false },
254+
{ fields: ['seen_at'], unique: false },
255+
],
256+
});
257+
258+
/** CONTROL object: a UNIQUE index over a keyed TEXT column, the #11627 shape. */
259+
const SHADOW_TABLE = 'os35862_shadow';
260+
const SHADOW_INDEX = buildIndexName(SHADOW_TABLE, ['token'], true);
261+
const shadowObject = () => ({
262+
name: SHADOW_TABLE,
263+
fields: { token: { type: 'text', maxLength: 1024 } },
264+
indexes: [{ fields: ['token'], unique: true }],
265+
});
266+
267+
function declareUpgradeSuite(cell: DialectCell): void {
268+
describe(`the inbox-shaped upgrade — ${cell.label} (#35862)`, () => {
269+
let driver: SqlDriver;
270+
afterEach(async () => {
271+
for (const t of [LIVE_TABLE, SHADOW_TABLE]) {
272+
await driver?.execute(`drop table if exists ${t}`).catch(() => {});
273+
}
274+
await driver?.disconnect().catch(() => {});
275+
});
276+
277+
it('boots the release that adds the bound and a plain index over the old TEXT column', async () => {
278+
driver = new SqlDriver(cell.config());
279+
await driver.execute(`drop table if exists ${LIVE_TABLE}`).catch(() => {});
280+
await driver.initObjects([liveBefore()]);
281+
if (cell.id === 'mysql') {
282+
// A table from before #3942: the datetime field on a legacy TIMESTAMP.
283+
// Its widening is the LAST step `initObjects` runs for the table, so
284+
// finding it widened proves the steps after the refusal ran.
285+
await driver.execute(`alter table ${LIVE_TABLE} modify column seen_at timestamp null`);
286+
}
287+
const logs = attachLogSpy(driver);
288+
289+
await driver.initObjects([liveAfter()]);
290+
291+
const indexes = await existingIndexNames(driver, LIVE_TABLE);
292+
// The index declared after the plain one is built on every dialect.
293+
expect(indexes.has(LIVE_AFTER)).toBe(true);
294+
295+
if (cell.id === 'mysql') {
296+
// The premise, measured: the column is still TEXT after the upgrade.
297+
const knex = (driver as any).knex;
298+
const cols: any[] = await knex
299+
.select('COLUMN_NAME', 'COLUMN_TYPE')
300+
.from('information_schema.COLUMNS')
301+
.where({ TABLE_SCHEMA: knex.client.database(), TABLE_NAME: LIVE_TABLE });
302+
const typeOf = (c: string) => String(cols.find((r) => r.COLUMN_NAME === c)?.COLUMN_TYPE).toLowerCase();
303+
expect(typeOf('user_id')).toBe('text');
304+
// The refused plain index: still refused, and never substituted.
305+
expect(indexes.has(LIVE_REFUSED)).toBe(false);
306+
expect(cols.filter((r) => isHashShadowColumn(r.COLUMN_NAME))).toEqual([]);
307+
// Reported once at error by the sync, then by the drift report.
308+
const lines = logs.filter((l) => l.msg.includes(`'${LIVE_REFUSED}'`));
309+
expect(lines.filter((l) => l.level === 'error')).toHaveLength(1);
310+
expect(lines.filter((l) => l.level === 'warn' && l.msg.startsWith('[schema-drift]'))).toHaveLength(1);
311+
// The last boot step ran: the legacy TIMESTAMP was widened.
312+
expect(typeOf('seen_at')).toBe('datetime(3)');
313+
} else {
314+
// CONTROL: PostgreSQL and SQLite never refuse; the index is built directly.
315+
expect(indexes.has(LIVE_REFUSED)).toBe(true);
316+
expect(logs.filter((l) => l.level === 'error')).toEqual([]);
317+
}
318+
}, 60_000);
319+
});
320+
}
321+
322+
for (const cell of DIALECT_CELLS) {
323+
declareDialectCell(cell, 'refused plain index boot steps (#35862)', declareUpgradeSuite);
324+
}
325+
326+
// ── Live MySQL CONTROL: a UNIQUE index over keyed TEXT keeps its shadow ─────
327+
328+
declareDialectCell(MYSQL_CELL, 'refused plain index boot steps (#35862)', (cell) => {
329+
describe('UNIQUE over a keyed TEXT column on live MySQL keeps the hash shadow (#35862 control)', () => {
330+
let driver: SqlDriver;
331+
afterEach(async () => {
332+
await driver?.execute(`drop table if exists ${SHADOW_TABLE}`).catch(() => {});
333+
await driver?.disconnect().catch(() => {});
334+
});
335+
336+
it('carries the UNIQUE index on a shadow column, not refused and not a prefix', async () => {
337+
driver = new SqlDriver(cell.config());
338+
await driver.execute(`drop table if exists ${SHADOW_TABLE}`).catch(() => {});
339+
await driver.initObjects([shadowObject()]);
340+
const knex = (driver as any).knex;
341+
const idx: any[] = await knex
342+
.select('INDEX_NAME', 'COLUMN_NAME', 'SUB_PART', 'NON_UNIQUE')
343+
.from('information_schema.STATISTICS')
344+
.where({ TABLE_SCHEMA: knex.client.database(), TABLE_NAME: SHADOW_TABLE, INDEX_NAME: SHADOW_INDEX });
345+
expect(idx).toHaveLength(1);
346+
expect(isHashShadowColumn(String(idx[0].COLUMN_NAME))).toBe(true);
347+
expect(idx[0].SUB_PART ?? null).toBeNull();
348+
expect(Number(idx[0].NON_UNIQUE)).toBe(0);
349+
}, 60_000);
350+
});
351+
});

0 commit comments

Comments
 (0)