Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/31699-connection-key-package.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/metadata-protocol': patch
'@objectstack/service-automation': patch
Expand Down Expand Up @@ -33,7 +33,7 @@

**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.

Expand Down
14 changes: 14 additions & 0 deletions .changeset/driver-sql-mysql-functional-packageless-guard.md
Original file line number Diff line number Diff line change
@@ -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 <package column> IS NULL THEN <the driver's hash-shadow digest of the key columns> 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 <column> IS NULL THEN … END` over exactly the driver's own digest (`UNHEX(SHA2(CONCAT(<key columns> 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.
9 changes: 4 additions & 5 deletions content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
148 changes: 137 additions & 11 deletions packages/drivers/driver-sql/src/schema-drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(<key>, 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(<col>, '__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>): 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 (<col> is null) then <digest> 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 <scope> IS NULL THEN <digest of the key columns> END)`. UNIQUE is
* NULL-distinct, so every row whose `<scope>` is not NULL (a packaged row)
* hashes to NULL and is exempt: it is how MySQL says `UNIQUE (<key columns>)
* WHERE <scope> 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 (<col> 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;
Expand Down Expand Up @@ -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,
Expand All @@ -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<PhysicalIndex>, 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<PhysicalIndex>,
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]);
Expand Down
18 changes: 6 additions & 12 deletions packages/drivers/driver-sql/src/sql-driver-column-creation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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}`);
Expand All @@ -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);
});
});
});
Expand Down
Loading
Loading