From b01a23c36fbc9a2a0770911854ee8370e8110cbb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:43:02 +0000 Subject: [PATCH 1/2] fix(driver-sql): read MySQL's functional row-scoped digest as the widening arm's partial guard Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cw787kMeaX7oyz7DDC --- .../drivers/driver-sql/src/schema-drift.ts | 148 ++++++++++++++-- .../src/sql-driver-column-creation.ts | 18 +- .../sql-driver-widened-connection-key.test.ts | 43 ++--- ...sql-driver-widened-declared-unique.test.ts | 164 ++++++++++++++++++ .../src/sql-driver-widened-grant-key.test.ts | 137 ++++++++++++++- 5 files changed, 458 insertions(+), 52 deletions(-) diff --git a/packages/drivers/driver-sql/src/schema-drift.ts b/packages/drivers/driver-sql/src/schema-drift.ts index 6b6324c5ba2..0c12ccac82e 100644 --- a/packages/drivers/driver-sql/src/schema-drift.ts +++ b/packages/drivers/driver-sql/src/schema-drift.ts @@ -696,6 +696,104 @@ export function parseHashShadowRowScope(generationExpression: string): string | return m ? m[1]!.replace(/``/g, '`') : null; } +/** + * The digest a #11627 hash shadow stores, as the driver writes it: + * `UNHEX(SHA2(, 256))`, where the key is the one part bare, or every part + * joined by a `0x1f` separator inside `CONCAT`, and a NULL-safe part is spelled + * `COALESCE(, '__global__')` (commit df1c75c4b). + * + * The one builder of that digest: `createHashShadowUniqueIndex` emits it, and + * {@link parseFunctionalRowScopedGuard} accepts a MySQL functional guard only + * when its digest is this one over the key parts it names. `metadata-protocol`'s + * package-less guards key "the driver's own hash-shadow digest" on the MySQL + * family, so a guard whose digest is anything else is not one of them. + */ +export function hashShadowDigestSql(columns: readonly string[], nullSafeColumns?: ReadonlySet): string { + const ref = (c: string) => `\`${c.replace(/`/g, '``')}\``; + const part = (c: string) => (nullSafeColumns?.has(c) ? `COALESCE(${ref(c)}, '${GLOBAL_TENANT}')` : ref(c)); + // ONE argument needs no separator, and CONCAT of one value would only add + // a chance to get the encoding wrong. + const key = columns.length === 1 ? part(columns[0]!) : `CONCAT(${columns.map(part).join(', 0x1f, ')})`; + return `UNHEX(SHA2(${key}, 256))`; +} + +/** + * An expression in the spelling MySQL stores it: every blank outside a quoted + * run dropped and everything outside a quoted run lower-cased; a back-quoted + * identifier or a string literal is kept byte for byte. Only for an expression + * of calls, identifiers and literals (a digest), where no blank separates two + * words. + */ +function mysqlStoredDigestSpelling(sql: string): string { + let out = ''; + let quote: string | null = null; + for (const ch of sql) { + if (quote !== null) { + out += ch; + if (ch === quote) quote = null; + continue; + } + if (ch === '`' || ch === "'") { + quote = ch; + out += ch; + continue; + } + if (/\s/.test(ch)) continue; + out += ch.toLowerCase(); + } + return out; +} + +/** + * `(case when ( is null) then end)`, as MySQL 8 stores a + * functional key part (`information_schema.STATISTICS.EXPRESSION`, measured on + * MySQL 8.0.46). See {@link parseFunctionalRowScopedGuard}. + */ +const FUNCTIONAL_ROW_SCOPE = + /^\s*\(\s*case\s+when\s+\(\s*`((?:[^`]|``)+)`\s+is\s+null\s*\)\s+then\s+([\s\S]*\S)\s+end\s*\)\s*$/i; + +/** A functional key part {@link parseFunctionalRowScopedGuard} reads as a partial unique. */ +export interface FunctionalRowScopedGuard { + /** The column whose NULL puts a row in the guard's scope. */ + rowScope: string; + /** The columns the digest hashes, in key order: the guard's key. */ + columns: string[]; +} + +/** + * The MySQL 8.0.13+ spelling of a package-less guard, read as the partial + * unique it is, or `null` for any other expression. + * + * `metadata-protocol`'s package-less guards (`*-packageless-index.ts`, ADR-0150 + * D4) build on MySQL a UNIQUE index over ONE functional key part, + * `(CASE WHEN IS NULL THEN END)`. UNIQUE is + * NULL-distinct, so every row whose `` is not NULL (a packaged row) + * hashes to NULL and is exempt: it is how MySQL says `UNIQUE () + * WHERE IS NULL`, the partial index the same guard is on SQLite and + * PostgreSQL. MariaDB, with no functional key part, spells it as a row-scoped + * hash shadow instead ({@link parseHashShadowRowScope}). + * + * Recognised strictly, never as "some expression over these columns": the + * whole stored expression must be the `case when ( is null) then … end` + * wrapper, the digest inside must be exactly what {@link hashShadowDigestSql} + * builds over the columns it names (plain parts only, the separator and the + * hash function included), and the scope column must not be one of them. So an + * operator's own functional index (`lower(name)`, another hash, another + * separator, an `IS NOT NULL` scope, a NULL-safe part) is never read as a guard. + */ +export function parseFunctionalRowScopedGuard(expression: string): FunctionalRowScopedGuard | null { + const m = FUNCTIONAL_ROW_SCOPE.exec(String(expression ?? '')); + if (!m) return null; + const rowScope = m[1]!.replace(/``/g, '`'); + const digest = m[2]!; + const parts = parseHashShadowKeyParts(digest); + if (parts.length === 0 || parts.some((p) => p.nullSafe)) return null; + const columns = parts.map((p) => p.column); + if (columns.includes(rowScope)) return null; + if (mysqlStoredDigestSpelling(digest) !== mysqlStoredDigestSpelling(hashShadowDigestSql(columns))) return null; + return { rowScope, columns }; +} + /** Minimal shape of an introspected physical column (see SqlDriver.introspectColumns). */ export interface PhysicalColumn { name: string; @@ -2611,14 +2709,15 @@ function widenedUniqueReplacements(args: { // A NULL in a gained column exempts the row from the wider key, so the // narrower index is the only thing keeping those rows to one per // `narrower`. It is offered for retirement only once a partial UNIQUE on - // exactly `narrower`, scoped by a WHERE, already stands beside it (the - // activation ledger's runtime-built package-less index). Until then it is - // KEPT: accounted for, so the orphan arm never offers to drop it either. - // A gained column the table does not have yet keeps it the same way: the - // wider index cannot exist before its column does. + // exactly `narrower`, scoped by a WHERE (or by MySQL's functional + // row-scoped digest), already stands beside it (the activation ledger's + // runtime-built package-less index). Until then it is KEPT: accounted + // for, so the orphan arm never offers to drop it either. A gained column + // the table does not have yet keeps it the same way: the wider index + // cannot exist before its column does. const kept = gained.some((c) => absent.has(c)) || - (nullable.length > 0 && !hasPartialUniqueGuard(args.physical ?? [], narrower)); + (nullable.length > 0 && !hasPartialUniqueGuard(args.physical ?? [], narrower, nullable)); out.push({ column: listed.find((c) => !narrower.includes(c))!, legacyColumns: narrower, @@ -2642,15 +2741,42 @@ function widenedUniqueReplacements(args: { * hash-shadow carrier — MariaDB's spelling of the partial guard, which stores * one digest column ({@link parseHashShadowRowScope}) — answers by the columns * it hashes, exactly as the SQLite/PostgreSQL partial index answers by its own. - */ -function hasPartialUniqueGuard(physical: ReadonlyArray, columns: readonly string[]): boolean { + * + * MySQL 8.0.13+'s spelling, a UNIQUE index over one functional key part + * ({@link parseFunctionalRowScopedGuard}), answers by the columns its digest + * hashes too, and only when its row scope is the gained column whose NULL + * exempts a row from the wider key: the one nullable gained column, `nullable`. + * With two nullable gained columns, a row NULL in the one the guard does not + * test escapes both keys, so no single-scope guard stands for the narrower key. + */ +function hasPartialUniqueGuard( + physical: ReadonlyArray, + columns: readonly string[], + nullable: readonly string[], +): boolean { return physical.some((p) => { - if (!p.unique || p.partial !== true || (p.expressions?.length ?? 0) > 0) return false; - const key = enforcedIndexKey(p).columns; - return key.length === columns.length && key.every((c, i) => c === columns[i]); + if (!p.unique) return false; + const functional = functionalRowScopedGuardOf(p); + if (functional !== null) { + return sameColumns(functional.columns, columns) && nullable.length === 1 && functional.rowScope === nullable[0]; + } + if (p.partial !== true || (p.expressions?.length ?? 0) > 0) return false; + return sameColumns(enforcedIndexKey(p).columns, columns); }); } +/** + * The guard a physical index is when its ONLY key part is MySQL's functional + * row-scoped digest ({@link parseFunctionalRowScopedGuard}), else `null`. An + * index with any column key part, a WHERE, a hash-shadow carrier or a second + * expression is not that guard. + */ +function functionalRowScopedGuardOf(p: PhysicalIndex): FunctionalRowScopedGuard | null { + if (p.primary === true || p.partial === true || p.columns.length > 0 || p.shadowKey !== undefined) return null; + const expressions = p.expressions ?? []; + return expressions.length === 1 ? parseFunctionalRowScopedGuard(expressions[0]!) : null; +} + /** The same column identities, in the same key order. */ function sameColumns(a: readonly string[], b: readonly string[]): boolean { return a.length === b.length && a.every((c, i) => c === b[i]); 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 cd5a3a9146d..0d3b982f300 100644 --- a/packages/drivers/driver-sql/src/sql-driver-column-creation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-column-creation.ts @@ -42,7 +42,7 @@ */ import { FILE_REFERENCE_TYPES, numericColumnFor } from '@objectstack/spec/data'; -import { GLOBAL_TENANT, canonicalIndexKey, hashShadowColumnFor, parseHashShadowKeyParts } from './schema-drift.js'; +import { GLOBAL_TENANT, canonicalIndexKey, hashShadowColumnFor, hashShadowDigestSql, parseHashShadowKeyParts } from './schema-drift.js'; import type { HashShadowKeyPart } from './schema-drift.js'; import type { Knex } from 'knex'; import { @@ -226,18 +226,12 @@ export class ColumnCreationFacet { if (!this.isMysql) return false; const shadow = SqlDriver.hashShadowColumnFor(indexName); const ref = (c: string) => `\`${c.replace(/`/g, '``')}\``; - // The DECLARED key part: NULL-safe parts in their COALESCE form (commit df1c75c4b), - // plain parts as the bare column. - const part = (c: string) => - nullSafeColumns?.has(c) ? `COALESCE(${ref(c)}, '${GLOBAL_TENANT}')` : ref(c); - // ONE argument needs no separator, and CONCAT of one value would only add - // a chance to get the encoding wrong. - const expr = - columns.length === 1 - ? part(columns[0]!) - : `CONCAT(${columns.map(part).join(', 0x1f, ')})`; + // The DECLARED key parts: NULL-safe parts in their COALESCE form (commit df1c75c4b), + // plain parts as the bare column. One builder (`hashShadowDigestSql`), so + // the digest the sync writes and the digest the differ recognises in a + // MySQL functional guard cannot drift apart. const addColumn = - `ADD COLUMN ${ref(shadow)} VARBINARY(32) GENERATED ALWAYS AS (UNHEX(SHA2(${expr}, 256))) STORED`; + `ADD COLUMN ${ref(shadow)} VARBINARY(32) GENERATED ALWAYS AS (${hashShadowDigestSql(columns, nullSafeColumns)}) STORED`; const addKey = `ADD UNIQUE KEY ${ref(indexName)} (${ref(shadow)})`; // Commit cd1348802: the shadow column OUTLIVES the index it carries. Dropping a // UNIQUE key by name does not drop the generated column keyed by it, so diff --git a/packages/drivers/driver-sql/src/sql-driver-widened-connection-key.test.ts b/packages/drivers/driver-sql/src/sql-driver-widened-connection-key.test.ts index ae13601330d..12871017658 100644 --- a/packages/drivers/driver-sql/src/sql-driver-widened-connection-key.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-widened-connection-key.test.ts @@ -24,12 +24,10 @@ * package's connection. * * The live cells (PostgreSQL, MySQL) run the same upgrade over a real server - * with the statement `metadata-protocol` runs there. On MySQL the guard is a - * functional key part, which `driver-sql`'s introspection reads as an - * expression rather than as a partial guard, so the widening arm KEEPS the old - * key: a declared limit, pinned so that teaching the driver to read it turns the - * pin red on purpose. It loosens nothing; the old key keeps refusing what it - * refused. + * with the statement `metadata-protocol` runs there, and answer alike: one SAFE + * replace. On MySQL the guard is a functional key part, the driver's hash-shadow + * digest under `CASE WHEN connector_package IS NULL`, which the widening arm + * reads as the partial unique it is (`parseFunctionalRowScopedGuard`). * * The table first shipped in 18.3.0, after plain organization keys (18.1.0), so * no released database carries its old key in ADR-0120 D3's NULL-safe form. @@ -179,10 +177,7 @@ for (const cell of [PG_CELL, MYSQL_CELL]) { }; const drift = async () => ((await live!.detectManagedDrift()) as any[]).filter((e) => e.table === CONNECTIONS); - it(c.id === 'pg' - ? 'with the guard: one SAFE replace, applied; re-plan empty; a second package admitted, a second package-less row refused' - : 'DECLARED LIMIT: the functional guard is not read as the partial guard, so the old key is KEPT and still refuses a second package', - async () => { + it('with the guard: one SAFE replace, applied; re-plan empty; a second package admitted, a second package-less row refused', async () => { live = new SqlDriver(c.config()); (live as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; await live.execute(`drop table if exists ${CONNECTIONS}`); @@ -192,24 +187,16 @@ for (const cell of [PG_CELL, MYSQL_CELL]) { await live.execute(c.id === 'pg' ? GUARD_SQL : MYSQL_GUARD_SQL); const plan = await drift(); - if (c.id === 'pg') { - expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); - expect(plan[0].op).toMatchObject({ dropIndexNames: [OLD_KEY_NAME] }); - const { applied, skipped } = await live.applyMigrationEntries(plan); - expect([applied.length, skipped]).toEqual([1, []]); - expect(await drift()).toEqual([]); - expect(await lands('p1', 'com.acme.crm')).toBe(true); - expect(await lands('p2', 'com.acme.hr')).toBe(true); - expect(await lands('p3', 'com.acme.crm')).toBe(false); - expect(await lands('n1', null)).toBe(true); - expect(await lands('n2', null)).toBe(false); - } else { - // Nothing offered — neither the replace nor an orphan drop of either index. - expect(plan.filter((e) => String(e.op.type).endsWith('_index'))).toEqual([]); - expect(await lands('p1', 'com.acme.crm')).toBe(true); - expect(await lands('p2', 'com.acme.hr')).toBe(false); - expect(await lands('n1', null)).toBe(false); - } + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(plan[0].op).toMatchObject({ dropIndexNames: [OLD_KEY_NAME] }); + const { applied, skipped } = await live.applyMigrationEntries(plan); + expect([applied.length, skipped]).toEqual([1, []]); + expect(await drift()).toEqual([]); + expect(await lands('p1', 'com.acme.crm')).toBe(true); + expect(await lands('p2', 'com.acme.hr')).toBe(true); + expect(await lands('p3', 'com.acme.crm')).toBe(false); + expect(await lands('n1', null)).toBe(true); + expect(await lands('n2', null)).toBe(false); }); }); }); diff --git a/packages/drivers/driver-sql/src/sql-driver-widened-declared-unique.test.ts b/packages/drivers/driver-sql/src/sql-driver-widened-declared-unique.test.ts index e3e844e9a13..175ff05d182 100644 --- a/packages/drivers/driver-sql/src/sql-driver-widened-declared-unique.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-widened-declared-unique.test.ts @@ -34,7 +34,9 @@ import { diffManagedIndexes, enforcedIndexKey, hashShadowColumnFor, + hashShadowDigestSql, legacyUniqueReplacements, + parseFunctionalRowScopedGuard, parseHashShadowKeyParts, parseHashShadowRowScope, type PhysicalIndex, @@ -302,6 +304,168 @@ describe('a row-scoped hash shadow (MariaDB package-less guard) — pure functio }); }); +// --------------------------------------------------------------------------- +// MySQL 8's spelling of the package-less guard: a functional key part +// --------------------------------------------------------------------------- + +/** + * MySQL 8.0.13+ builds the guard as a UNIQUE index over ONE functional key part, + * `(CASE WHEN package_id IS NULL THEN END)` + * (`buildActivationLedgerPackagelessIndexSql('mysql2')`). The expression below + * is the one MySQL 8.0.46 stores in `information_schema.STATISTICS.EXPRESSION` + * for that statement, measured; `introspectIndexes` records it verbatim as the + * index's one expression, with no column. + */ +const MYSQL_GUARD_EXPR = + '(case when (`package_id` is null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),256)) end)'; +const mysqlGuard = (expression = MYSQL_GUARD_EXPR): PhysicalIndex => ({ + name: GUARD_NAME, + columns: [], + unique: true, + expressions: [expression], +}); + +describe('a functional row-scoped digest (MySQL 8 package-less guard) — pure functions', () => { + it('reads as a partial unique on the digest\'s columns, scoped by the column its WHEN tests', () => { + expect(parseFunctionalRowScopedGuard(MYSQL_GUARD_EXPR)).toEqual({ rowScope: 'package_id', columns: ['metadata_type', 'name'] }); + }); + + it('the digest it accepts is the driver\'s own hash-shadow digest, spelled as MySQL stores it', () => { + const stored = MYSQL_GUARD_EXPR.slice('(case when (`package_id` is null) then '.length, -' end)'.length); + expect(hashShadowDigestSql(['metadata_type', 'name'])).toBe('UNHEX(SHA2(CONCAT(`metadata_type`, 0x1f, `name`), 256))'); + expect(hashShadowDigestSql(['metadata_type', 'name']).toLowerCase().replace(/\s/g, '')).toBe(stored); + }); + + it('counts as the widening arm\'s guard: the old two-part UNIQUE is one SAFE replace, and the guard draws no entry', () => { + const entries = diff([plain(OLD, ['metadata_type', 'name']), plain(NEW, ['metadata_type', 'package_id', 'name']), mysqlGuard()]); + expect(entries.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(entries[0].op).toMatchObject({ dropIndexNames: [OLD], createIndexName: NEW }); + }); + + // Strict: only the platform's own expression is the guard. Each of these is + // an operator's functional index, and the old key stays KEPT beside it. + const notTheGuard: Array<[string, string]> = [ + ['another function', 'lower(`name`)'], + ['the digest over other columns', '(case when (`package_id` is null) then unhex(sha2(concat(`name`,0x1f,`metadata_type`),256)) end)'], + ['the digest over one more column', '(case when (`package_id` is null) then unhex(sha2(concat(`id`,0x1f,`metadata_type`,0x1f,`name`),256)) end)'], + ['another hash width', '(case when (`package_id` is null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),512)) end)'], + ['another hash function', '(case when (`package_id` is null) then unhex(md5(concat(`metadata_type`,0x1f,`name`))) end)'], + ['another separator', '(case when (`package_id` is null) then unhex(sha2(concat(`metadata_type`,0x1e,`name`),256)) end)'], + ['no hex decoding', '(case when (`package_id` is null) then sha2(concat(`metadata_type`,0x1f,`name`),256) end)'], + ['the opposite scope', '(case when (`package_id` is not null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),256)) end)'], + ['an ELSE that hashes the packaged rows too', '(case when (`package_id` is null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),256)) else 0x00 end)'], + ['a NULL-safe key part', "(case when (`package_id` is null) then unhex(sha2(concat(coalesce(`metadata_type`,_utf8mb4'__global__'),0x1f,`name`),256)) end)"], + ['a scope that is a key column', '(case when (`name` is null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),256)) end)'], + ['a scope that is not the gained column', '(case when (`active` is null) then unhex(sha2(concat(`metadata_type`,0x1f,`name`),256)) end)'], + ]; + for (const [what, expression] of notTheGuard) { + it(`${what} is no guard: the old index stays KEPT`, () => { + const physical = [plain(OLD, ['metadata_type', 'name']), plain(NEW, ['metadata_type', 'package_id', 'name']), mysqlGuard(expression)]; + expect(diff(physical).some((e) => e.op.type === 'replace_unique_index')).toBe(false); + expect(legacyUniqueReplacements({ + table: LEDGER, fields: {}, tenantField: null, physicalColumns: ledgerColumns, declaredIndexes: ledgerIndexes, physical, + })).toEqual([expect.objectContaining({ legacyNames: [OLD], kept: true })]); + }); + } + + it('the expression as a second key part, beside a column, is no guard', () => { + const mixed: PhysicalIndex = { ...mysqlGuard(), columns: ['active'] }; + expect(diff([plain(OLD, ['metadata_type', 'name']), plain(NEW, ['metadata_type', 'package_id', 'name']), mixed]) + .some((e) => e.op.type === 'replace_unique_index')).toBe(false); + }); + + it('a non-unique index over the same expression is no guard', () => { + const nonUnique: PhysicalIndex = { ...mysqlGuard(), unique: false }; + expect(diff([plain(OLD, ['metadata_type', 'name']), plain(NEW, ['metadata_type', 'package_id', 'name']), nonUnique]) + .some((e) => e.op.type === 'replace_unique_index')).toBe(false); + }); + + it('with TWO nullable gained columns no single-scope guard stands for the narrower key: KEPT', () => { + // A row NULL in the gained column the guard does not test escapes both keys. + const twoGained = [{ fields: ['metadata_type', 'package_id', 'active', 'name'], unique: 'global' as const }]; + const physical = [plain(OLD, ['metadata_type', 'name']), mysqlGuard()]; + expect(legacyUniqueReplacements({ + table: LEDGER, fields: {}, tenantField: null, physicalColumns: ledgerColumns, declaredIndexes: twoGained, physical, + })).toEqual([expect.objectContaining({ legacyNames: [OLD], kept: true })]); + }); +}); + +declareDialectCell(MYSQL_CELL, 'activation ledger package-less guard on MySQL 8 (functional key part)', (cell) => { + describe('an upgraded MySQL 8 database: the old key retires safely beside the functional guard', () => { + let driver: SqlDriver | undefined; + afterEach(async () => { + await (driver as any)?.knex.raw(`DROP TABLE IF EXISTS ${LEDGER}`).catch(() => {}); + await driver?.disconnect(); + driver = undefined; + }); + + const ledger = (indexes: any[]) => [{ + name: LEDGER, + systemFields: { tenant: false }, + fields: { + metadata_type: { type: 'text', required: true, maxLength: 100 }, + name: { type: 'text', required: true, maxLength: 255 }, + package_id: { type: 'text', maxLength: 255 }, + active: { type: 'boolean' }, + }, + indexes, + }]; + + it('plan = one safe replace; apply; re-plan empty; two packages admitted, a second package-less row refused', async (ctx) => { + driver = new SqlDriver(cell.config()); + (driver as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const k = (driver as any).knex; + const [[version]] = await k.raw('SELECT VERSION() AS v'); + // MariaDB has no functional key part; its row-scoped shadow is measured above. + if (/mariadb/i.test(String(version?.v))) ctx.skip(); + await k.raw(`DROP TABLE IF EXISTS ${LEDGER}`); + + await driver.initObjects(ledger([{ fields: ['metadata_type', 'name'], unique: 'global' }]) as any); + await driver.initObjects(ledger(ledgerIndexes) as any); + // The statement `metadata-protocol` runs on MySQL + // (`buildActivationLedgerPackagelessIndexSql('mysql2')`), verbatim. + await k.raw( + `CREATE UNIQUE INDEX ${GUARD_NAME} ON ${LEDGER} ` + + '((CASE WHEN package_id IS NULL THEN unhex(sha2(concat(metadata_type, 0x1f, name), 256)) END))', + ); + // What the server stored is what the pure pins above read. + const [stored] = await k.raw( + 'SELECT EXPRESSION AS e FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ?', + [LEDGER, GUARD_NAME], + ); + expect(stored.map((r: any) => r.e)).toEqual([MYSQL_GUARD_EXPR]); + + const plan = (await driver.detectManagedDrift()).filter((e) => e.table === LEDGER); + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(plan[0].op).toMatchObject({ dropIndexNames: [OLD], createIndexName: NEW }); + + const { applied, skipped } = await driver.applyMigrationEntries(plan); + expect([applied.length, skipped]).toEqual([1, []]); + expect((await driver.detectManagedDrift()).filter((e) => e.table === LEDGER)).toEqual([]); + + const [stats] = await k.raw( + 'SELECT DISTINCT INDEX_NAME AS n FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + [LEDGER], + ); + expect(stats.map((r: any) => r.n).sort()).toEqual(['PRIMARY', NEW, GUARD_NAME].sort()); + + await driver.create(LEDGER, { id: 'a', metadata_type: 'flow', name: 'x', active: false }); + // A second row naming no package: refused by the guard. + await expect(driver.create(LEDGER, { id: 'b', metadata_type: 'flow', name: 'x', active: true })) + .rejects.toMatchObject({ code: 'ER_DUP_ENTRY', message: expect.stringContaining(GUARD_NAME) }); + await driver.create(LEDGER, { id: 'c', metadata_type: 'flow', name: 'x', package_id: 'com.acme.alpha', active: false }); + await driver.create(LEDGER, { id: 'd', metadata_type: 'flow', name: 'x', package_id: 'com.acme.beta', active: false }); + await expect( + driver.create(LEDGER, { id: 'e', metadata_type: 'flow', name: 'x', package_id: 'com.acme.alpha', active: true }), + ).rejects.toMatchObject({ code: 'ER_DUP_ENTRY', message: expect.stringContaining(NEW) }); + + // A second boot of this release leaves everything as it is. + await driver.initObjects(ledger(ledgerIndexes) as any); + expect((await driver.detectManagedDrift()).filter((e) => e.table === LEDGER)).toEqual([]); + }); + }); +}); + declareDialectCell(MYSQL_CELL, 'activation ledger package-less guard on MariaDB (row-scoped shadow)', (cell) => { describe('an upgraded MariaDB database: the old key retires safely, and the guard never shows', () => { let driver: SqlDriver | undefined; diff --git a/packages/drivers/driver-sql/src/sql-driver-widened-grant-key.test.ts b/packages/drivers/driver-sql/src/sql-driver-widened-grant-key.test.ts index 92e50d6e849..1bfad4e239c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-widened-grant-key.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-widened-grant-key.test.ts @@ -31,12 +31,18 @@ * on the upgrade dogfoods' 18.0 and 18.0.0 fixtures first (#32164); * - the narrower key carried by a #11627 hash shadow (MySQL, MariaDB), plain * or NULL-safe, certified or not, guard or none: KEPT, nothing offered, - * never an orphan `drop_index` (pure functions; no live MySQL here). + * never an orphan `drop_index` (pure functions); + * - the guard as MySQL 8 builds it, a functional key part over the driver's + * hash-shadow digest scoped by `permission_set_package IS NULL`, stands for + * the partial index: one SAFE replace of a plain narrower key (pure + * functions, and the live MySQL cell with the statement `metadata-protocol` + * runs there). */ import { describe, it, expect, afterEach, vi } from 'vitest'; import { SqlDriver } from './index.js'; import { asPre18TenantColumn } from './pre-18-tenant-column.testkit.js'; +import { MYSQL_CELL, declareDialectCell } from './live-dialect-matrix.testkit.js'; import { buildIndexName, diffManagedIndexes, @@ -389,3 +395,132 @@ describe('the narrower key carried by a hash shadow (MySQL, MariaDB) — pure fu expect(diff([plainNarrow, wide, guard], true).map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); }); }); + +// ── MySQL 8's spelling of the guard: a functional key part ──────────────────── + +/** + * What MySQL 8.0.46 stores (`information_schema.STATISTICS.EXPRESSION`) for the + * guard `buildUserPermissionSetPackagelessIndexSql('mysql2')` builds, measured + * (the live cell below asserts it again). + */ +const MYSQL_GUARD_EXPR = + '(case when (`permission_set_package` is null) then ' + + 'unhex(sha2(concat(`user_id`,0x1f,`permission_set`,0x1f,`organization_id`),256)) end)'; +/** `buildUserPermissionSetPackagelessIndexSql('mysql2')` in metadata-protocol, verbatim. */ +const MYSQL_GUARD_SQL = + `CREATE UNIQUE INDEX ${GUARD_NAME} ON ${GRANTS} ` + + '((CASE WHEN permission_set_package IS NULL THEN unhex(sha2(concat(user_id, 0x1f, permission_set, 0x1f, organization_id), 256)) END))'; + +describe('the guard as a MySQL 8 functional key part — pure functions', () => { + const NARROW = ['user_id', 'permission_set', 'organization_id']; + const WIDE = ['user_id', 'permission_set', 'permission_set_package', 'organization_id']; + const LEGACY = buildIndexName(GRANTS, NARROW, true); + const WIDE_NAME = buildIndexName(GRANTS, WIDE, true); + const columns = new Set(['id', ...WIDE]); + const fields = grants(NEW_INDEXES)[0].fields; + const wide: PhysicalIndex = { name: WIDE_NAME, columns: WIDE, unique: true }; + const functional = (expression = MYSQL_GUARD_EXPR): PhysicalIndex => ({ name: GUARD_NAME, columns: [], unique: true, expressions: [expression] }); + const diff = (physical: PhysicalIndex[]) => + diffManagedIndexes({ + table: GRANTS, + expected: [{ name: WIDE_NAME, columns: WIDE, unique: true }], + legacy: legacyUniqueReplacements({ + table: GRANTS, fields, tenantField: 'organization_id', physicalColumns: columns, declaredIndexes: NEW_INDEXES, physical, + }), + physical, + tenantField: 'organization_id', + tenantKeyCertified: true, + }); + + it('beside a plain narrower key: one SAFE replace, and the guard draws no entry', () => { + const plainNarrow: PhysicalIndex = { name: LEGACY, columns: NARROW, unique: true }; + const entries = diff([plainNarrow, wide, functional()]); + expect(entries.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(entries[0].op).toMatchObject({ dropIndexNames: [LEGACY], createIndexName: WIDE_NAME }); + }); + + it('CONTROL: the same digest over the key columns in another order is no guard — KEPT, nothing offered', () => { + const plainNarrow: PhysicalIndex = { name: LEGACY, columns: NARROW, unique: true }; + const reordered = MYSQL_GUARD_EXPR.replace('`user_id`,0x1f,`permission_set`', '`permission_set`,0x1f,`user_id`'); + expect(reordered).not.toBe(MYSQL_GUARD_EXPR); + expect(diff([plainNarrow, wide, functional(reordered)])).toEqual([]); + }); + + it('a narrower key carried by a hash shadow stays KEPT beside it, as beside the partial guard', () => { + const carrier: PhysicalIndex = { + name: LEGACY, + columns: [hashShadowColumnFor(LEGACY)], + unique: true, + shadowKey: NARROW.map((column) => ({ column, nullSafe: false })), + }; + expect(diff([carrier, wide, functional()])).toEqual([]); + }); +}); + +declareDialectCell(MYSQL_CELL, 'grant key widened by its package column on MySQL 8 (#32164)', (cell) => { + describe('the grant key widened by its package column on an upgraded MySQL 8 database', () => { + let live: SqlDriver | undefined; + afterEach(async () => { + await live?.execute(`drop table if exists ${GRANTS}`).catch(() => {}); + await live?.disconnect().catch(() => {}); + live = undefined; + }); + + // Keyed text as the platform object declares it, so the old key is a plain + // key over varchar columns (a TEXT key part would be shadow-carried, which + // the arm keeps whatever the guard: pinned above). + const keyedGrants = (indexes: unknown[]) => [{ + name: GRANTS, + fields: { + user_id: { type: 'text', required: true, maxLength: 255 }, + permission_set: { type: 'text', required: true, maxLength: 100 }, + permission_set_package: { type: 'text', maxLength: 255 }, + organization_id: { type: 'text', maxLength: 255 }, + }, + indexes, + }]; + const drift = async () => ((await live!.detectManagedDrift()) as any[]).filter((e) => e.table === GRANTS); + const lands = async (id: string, pkg: string | null): Promise => { + try { + await (live as any).knex(GRANTS).insert({ id, user_id: 'u1', permission_set: 'sales_rep', permission_set_package: pkg, organization_id: 'org_1' }); + return true; + } catch { + return false; + } + }; + + it('with the functional guard: one SAFE replace, applied; re-plan empty; two packages admitted, a second package-less grant refused', async (ctx) => { + live = new SqlDriver(cell.config()); + (live as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const k = (live as any).knex; + const [[version]] = await k.raw('SELECT VERSION() AS v'); + // MariaDB has no functional key part (its guard is a row-scoped shadow). + if (/mariadb/i.test(String(version?.v))) ctx.skip(); + await live.execute(`drop table if exists ${GRANTS}`); + await live.initObjects(keyedGrants(OLD_INDEXES) as any); + await live.initObjects(keyedGrants(NEW_INDEXES) as any); + const legacy = buildIndexName(GRANTS, ['user_id', 'permission_set', 'organization_id'], true); + // Without the guard the old key is KEPT: nothing offered. + expect((await drift()).filter((e) => String(e.op.type).endsWith('_index'))).toEqual([]); + + await live.execute(MYSQL_GUARD_SQL); + const [stored] = await k.raw( + 'SELECT EXPRESSION AS e FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ?', + [GRANTS, GUARD_NAME], + ); + expect(stored.map((r: any) => r.e)).toEqual([MYSQL_GUARD_EXPR]); + + const plan = await drift(); + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(plan[0].op).toMatchObject({ dropIndexNames: [legacy] }); + const { applied, skipped } = await live.applyMigrationEntries(plan); + expect([applied.length, skipped]).toEqual([1, []]); + expect(await drift()).toEqual([]); + expect(await lands('n1', null)).toBe(true); + expect(await lands('n2', null)).toBe(false); + expect(await lands('p1', 'com.acme.crm')).toBe(true); + expect(await lands('p2', 'com.acme.hr')).toBe(true); + expect(await lands('p3', 'com.acme.crm')).toBe(false); + }); + }); +}); From b3e78bb48a13eb96e92b1df6964e0841ca34caac Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:53:19 +0000 Subject: [PATCH 2/2] docs(driver-sql): retire the MySQL functional-guard limit from the docs, the pending note and the guard's docblock; add the changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cw787kMeaX7oyz7DDC --- .changeset/31699-connection-key-package.md | 2 +- ...river-sql-mysql-functional-packageless-guard.md | 14 ++++++++++++++ content/docs/deployment/cli.mdx | 9 ++++----- .../connector-connection-packageless-index.ts | 9 +++++---- 4 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 .changeset/driver-sql-mysql-functional-packageless-guard.md diff --git a/.changeset/31699-connection-key-package.md b/.changeset/31699-connection-key-package.md index ec4c203e7c2..56b8d4dae75 100644 --- a/.changeset/31699-connection-key-package.md +++ b/.changeset/31699-connection-key-package.md @@ -33,7 +33,7 @@ Part of #31699 (ADR-0150 child B, PR 3a: the storage half). The maintainer's rul **Declared limits.** -- MySQL 8, upgraded databases: `driver-sql` reads the guard's functional key part as an expression, not as a partial guard, so the widening arm keeps the old key there. The old key keeps refusing what it refused, so an organization cannot connect a second package's instance of one name on such a database until `driver-sql` recognises the form. A database created fresh on MySQL 8 has the wide key and the guard and no old key. The permission-set grant's guard (#32164) shares this limit. MySQL before 8.0.13 and MariaDB before 10.3 build no form, keep the old key (or build it under the driver's generated name where it is missing) and say so at `error` each boot. +- MySQL 8, upgraded databases: `driver-sql` reads the guard's functional key part as the partial unique it is, so the old key retires there as it does on PostgreSQL, as one safe `replace_unique_index` on the next sync that runs safe drift. A database created fresh on MySQL 8 has the wide key and the guard and no old key. MySQL before 8.0.13 and MariaDB before 10.3 build no form, keep the old key (or build it under the driver's generated name where it is missing) and say so at `error` each boot. - `driver-memory` builds no guard (no raw-SQL seam), as for the grant: a pin measures that its unique check treats a NULL package as distinct, so two package-less connections of one instance are admitted there. - The MySQL, MariaDB and real-mongod pins run in suites that run on `main` only, so they first run after this lands. diff --git a/.changeset/driver-sql-mysql-functional-packageless-guard.md b/.changeset/driver-sql-mysql-functional-packageless-guard.md new file mode 100644 index 00000000000..224c3786758 --- /dev/null +++ b/.changeset/driver-sql-mysql-functional-packageless-guard.md @@ -0,0 +1,14 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): on an upgraded MySQL 8 database the widening arm reads the package-less guard's functional key part as the partial unique it is, so the old, narrower unique key retires as it does on PostgreSQL + +Clause-②: no +Metadata-protocol: none + +`metadata-protocol` builds each package-less guard on MySQL 8.0.13+ as a UNIQUE index over one functional key part, `(CASE WHEN IS NULL THEN END)`. `os migrate plan` and the dev `autoMigrate: 'safe'` sync read that key part as an unknown expression, never as the guard the widening arm waits for, so on a database upgraded from a release that had the narrower key they kept that key and offered nothing. + +- FROM kept TO retired, on an upgraded MySQL 8 database, once the guard stands: `sys_user_permission_set`'s `(user_id, permission_set, organization_id)`, `sys_connector_connection`'s `(organization_id, connector_name)` and `sys_metadata_activation`'s `(metadata_type, name)` are each one `replace_unique_index`, categorized `safe`, created before it is dropped, applied by the next sync that runs safe drift or by `os migrate apply` with no `--allow-destructive`. Who sees it: a user can hold two packages' permission sets of one name in one organization, and an organization can connect two packages' connector instances of one name, where the old key refused the second. A second row naming no package is still refused, by the guard. Measured on MySQL 8.0.46 for all three tables. +- The guard is recognised strictly: the whole expression must be that `CASE WHEN IS NULL THEN … END` over exactly the driver's own digest (`UNHEX(SHA2(CONCAT( joined by 0x1f), 256))`, plain columns) of the narrower key's columns in key order, scoped by the one nullable column the wider key gained. Any other functional index (another function, hash, separator or scope, a NULL-safe part, an `ELSE`) is not a guard, and the narrower key stays kept beside it. +- Unchanged: MariaDB (its guard is a row-scoped generated column, already read as a guard), SQLite and PostgreSQL; a narrower key carried by a #11627 hash shadow is still kept whatever the guard; MySQL before 8.0.13 builds no guard and keeps the old key. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index a1cbb3b6c42..11935bad67e 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1214,11 +1214,10 @@ Once a guard stands, the next safe sync (or `os migrate apply`) retires the key it stands beside — the grant's `(user_id, permission_set, organization_id)`, the connection's `(organization_id, connector_name)` — as one `replace_unique_index` categorized safe, created before it is dropped. Until then that key stays and -keeps refusing a second package's grant or connection of one name. On an -upgraded MySQL database both old keys stay, because `driver-sql` does not read a -guard's functional key part as a guard there, so a second package's grant or -connection of one name stays refused on MySQL. A database created fresh on -MySQL never has the old keys. +keeps refusing a second package's grant or connection of one name. On MySQL 8 +the guard is a functional key part, and `driver-sql` reads it as the guard it is, +so an upgraded MySQL database retires both old keys the same way. A database +created fresh on MySQL never has the old keys. Under `--json` the section is the `schemaSyncIndexes` array, whose entries carry `table`, `index`, `keyParts`, `rowScope` and a `status` of `build`, `blocked` or diff --git a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts index 75e480f17f6..d48f25d0f8b 100644 --- a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts +++ b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts @@ -50,10 +50,11 @@ * - SQLite and PostgreSQL: a partial unique index, * `(organization_id, connector_name) WHERE connector_package IS NULL`. * - MySQL (8.0.13+): a functional key part over the driver's hash-shadow digest, - * NULL for a packaged connection, which UNIQUE then exempts. ⚠ `driver-sql` - * reads that key part as an expression, not as a partial guard, so on MySQL - * the widening arm keeps the old key (a declared limit; the grant guard - * shares it). The old key keeps refusing what it refused, nothing more. + * NULL for a packaged connection, which UNIQUE then exempts. `driver-sql` + * reads that key part as a partial unique on the two columns + * (`parseFunctionalRowScopedGuard`), but only while the digest is exactly the + * one its own hash shadow writes, so this statement and that builder move + * together. * - MariaDB: a UNIQUE key over an INVISIBLE generated column carrying that * digest, `uniq_sys_connector_connection_packageless__hash` (MariaDB 10.3+), * which `driver-sql` reads as a partial unique on the two columns.