Skip to content

Commit 1d01986

Browse files
committed
wip(driver-sql, driver-turso, driver-memory, objectql, cli, metadata-protocol): plain organization key part in new DDL; the differ reads COALESCE as plain on a certified table
Claude-Session: https://claude.ai/code/session_01NnXVu3vF2TKFLMi5Me4CUd Co-authored-by: Claude <noreply@anthropic.com>
1 parent 420499a commit 1d01986

7 files changed

Lines changed: 322 additions & 143 deletions

File tree

‎packages/cli/src/commands/generate.ts‎

Lines changed: 19 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3226,17 +3226,6 @@ function indexKeyColumns(obj: Record<string, any>): ReadonlySet<string> {
32263226
* is what keeps the transcription honest — it recomputes every name from the
32273227
* driver's own exported `uniqueIndexesFromFields` and compares.
32283228
*/
3229-
/**
3230-
* `driver-sql`'s `GLOBAL_TENANT` — the sentinel the ADR-0120 D3 NULL-safe
3231-
* organization key part folds a NULL organization onto.
3232-
*
3233-
* Transcribed for the same #5726 reason as the rest of this block, and it
3234-
* reaches only a COMMENT in the generated file: this format emits no expression
3235-
* key part, so the sentinel is here to NAME the index that was not emitted, not
3236-
* to build one. The pin compares it against the driver's own export.
3237-
*/
3238-
const GLOBAL_TENANT_KEY = '__global__';
3239-
32403229
const INDEX_NAME_MAX = 60;
32413230
/** Chars kept from `<prefix>_<table>` before the `_<hash8>` suffix of a truncated name. */
32423231
const INDEX_NAME_HEAD = INDEX_NAME_MAX - 9;
@@ -3253,15 +3242,13 @@ function buildIndexName(table: string, columns: string[], unique: boolean): stri
32533242
interface MirroredUniqueIndex {
32543243
/** {@link buildIndexName}'s answer — the identifier the driver would use. */
32553244
name: string;
3256-
/** The key parts, in the driver's order (tenant column first when scoped). */
3257-
columns: string[];
32583245
/**
3259-
* The tenant column whose key part materializes as the ADR-0120 D3 NULL-safe
3260-
* expression `COALESCE(<column>, '__global__')` rather than as a bare column,
3261-
* or `null` for a plain single-column unique. An expression key part is what
3262-
* neither format emits — see {@link uniqueIndexesForObject}.
3246+
* The key parts, in the driver's order (tenant column first when scoped).
3247+
* Every part is a plain column: since ADR-0131 D1 the driver keys the
3248+
* NOT NULL tenant column itself, so an organization composite is a column
3249+
* list both formats can emit.
32633250
*/
3264-
nullSafeColumn: string | null;
3251+
columns: string[];
32653252
}
32663253

32673254
/**
@@ -3276,10 +3263,10 @@ interface MirroredUniqueIndex {
32763263
* {@link isUniqueScopeDeclared}, {@link isOrganizationScopedUnique} and
32773264
* {@link tenantFieldOf} — so they cannot disagree about which fields are keyed.
32783265
*
3279-
* Scoping rule, transcribed from the driver (ADR-0120 D1/D3):
3266+
* Scoping rule, transcribed from the driver (ADR-0120 D1, ADR-0131 D1):
32803267
* - `unique: 'global'` → single-column `(field)`, platform-wide.
32813268
* - `unique: true` / `'organization'` on a tenant-scoped table → composite
3282-
* `(COALESCE(tenantField, '__global__'), field)`, tenant column FIRST.
3269+
* `(tenantField, field)`, tenant column FIRST.
32833270
* - `unique: true` / `'organization'` with no tenant column → `(field)`.
32843271
* - a unique declaration ON the tenant column itself stays single-column —
32853272
* `(organization_id, organization_id)` is not a constraint.
@@ -3301,11 +3288,7 @@ function uniqueIndexesForObject(obj: Record<string, any>): MirroredUniqueIndex[]
33013288
const scoped =
33023289
isOrganizationScopedUnique(field.unique) && tenantField != null && tenantField !== name;
33033290
const columns = scoped ? [tenantField as string, name] : [name];
3304-
out.push({
3305-
name: buildIndexName(table, columns, true),
3306-
columns,
3307-
nullSafeColumn: scoped ? (tenantField as string) : null,
3308-
});
3291+
out.push({ name: buildIndexName(table, columns, true), columns });
33093292
}
33103293
return out;
33113294
}
@@ -3314,24 +3297,19 @@ function uniqueIndexesForObject(obj: Record<string, any>): MirroredUniqueIndex[]
33143297
* The subset of {@link uniqueIndexesForObject} a format may actually emit, and
33153298
* a line for every one it may not.
33163299
*
3317-
* Two exclusions, and BOTH are the driver's own behaviour rather than a
3318-
* convenience here:
3300+
* One exclusion, and it is the driver's own behaviour rather than a
3301+
* convenience here: a key part with no column. `syncDeclaredIndexes` skips a
3302+
* declared index whose columns are not in `physicalColumns` and warns; the
3303+
* generator's equivalent of "not materialized" is a field this file emits no
3304+
* column for — a VIRTUAL `formula` (commit 08706f0e0). Emitting the index
3305+
* anyway produces DDL that refuses to run at all.
33193306
*
3320-
* 1. A key part with no column. `syncDeclaredIndexes` skips a declared index
3321-
* whose columns are not in `physicalColumns` and warns; the generator's
3322-
* equivalent of "not materialized" is a field this file emits no column
3323-
* for — a VIRTUAL `formula` (commit 08706f0e0). Emitting the index anyway produces
3324-
* DDL that refuses to run at all.
3325-
* 2. An EXPRESSION key part. `COALESCE(<tenant>, '__global__')` is what the
3326-
* driver builds through raw DDL precisely because knex's schema builder
3327-
* cannot express it, and it is NOT interchangeable with the bare composite:
3328-
* under SQL's NULL-distinct UNIQUE a bare `(organization_id, field)`
3329-
* enforces NOTHING on rows without an organization, which on a
3330-
* single-tenant stack is every row (#5030). So emitting the bare composite
3331-
* here would ADVERTISE a constraint the table does not carry — worse than
3332-
* emitting nothing, and the failure mode Prime Directive #10 names.
3307+
* The organization composite is emitted: since ADR-0131 D1 the driver keys the
3308+
* plain tenant column, so the bare `(organization_id, field)` IS the platform's
3309+
* constraint, no longer the ADR-0120 D3 `COALESCE` expression neither format
3310+
* could spell.
33333311
*
3334-
* ⛔ Neither exclusion is silent. A skipped index is named in the generated file
3312+
* ⛔ The exclusion is not silent. A skipped index is named in the generated file
33353313
* itself, with what it would have keyed, because the operator reading that file
33363314
* is the only person who can act on it — "Absence must be loud".
33373315
*/
@@ -3347,15 +3325,6 @@ function partitionUniqueIndexes(
33473325
skipped.push({ index, why: `no column is generated for ${missing.join(', ')}` });
33483326
continue;
33493327
}
3350-
if (index.nullSafeColumn !== null) {
3351-
skipped.push({
3352-
index,
3353-
why:
3354-
`its organization key part is COALESCE("${index.nullSafeColumn}", '${GLOBAL_TENANT_KEY}'), ` +
3355-
'an expression key part this format does not emit; the platform creates it at boot',
3356-
});
3357-
continue;
3358-
}
33593328
emit.push(index);
33603329
}
33613330
return { emit, skipped };

‎packages/drivers/driver-memory/src/memory-unique-constraint.ts‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
* | declaration | tenant column | driver-sql index | here |
4040
* |:---|:---|:---|:---|
4141
* | `unique: 'global'` | any | `(field)` | scope `null` |
42-
* | `unique: true` / `'organization'` | present, ≠ field | `(COALESCE(tenant,'__global__'), field)` | scope = tenant column |
42+
* | `unique: true` / `'organization'` | present, ≠ field | `(tenant, field)` | scope = tenant column |
4343
* | `unique: true` / `'organization'` | absent | `(field)` | scope `null` |
4444
* | `unique: true` / `'organization'` | IS the field | `(field)` | scope `null` |
4545
* | absent / `false` | any | no index | not a constraint |
@@ -61,8 +61,8 @@
6161
* | `fields` empty / absent / no non-empty strings | any | `null` — unusable | no constraint |
6262
* | `unique` absent / `false` | any | a PLAIN index | not a constraint |
6363
* | `unique: true` / `'global'` | any | the listed columns VERBATIM | `columns` = listed, no NULL-safe part |
64-
* | `unique: 'organization'`, tenant column NOT listed | present | `(COALESCE(tenant,'__global__'), …listed)` | `columns` = `[tenant, …listed]`, `nullSafeColumns` = `[tenant]` |
65-
* | `unique: 'organization'`, tenant column ALREADY listed | present | listed verbatim, the tenant's own key part goes NULL-safe | `columns` = listed (order kept), `nullSafeColumns` = `[tenant]` |
64+
* | `unique: 'organization'`, tenant column NOT listed | present | `(tenant, …listed)` | `columns` = `[tenant, …listed]`, `scopeColumns` = `[tenant]` |
65+
* | `unique: 'organization'`, tenant column ALREADY listed | present | listed verbatim | `columns` = listed (order kept), `scopeColumns` = `[tenant]` |
6666
* | `unique: 'organization'` | absent | degrades to the listed columns alone | `columns` = listed, no NULL-safe part |
6767
*
6868
* ⚠️ **bare `true` inverts between the two surfaces.** On a declared index it
@@ -105,9 +105,16 @@
105105
* NULL key part exempts the row (below), so such an index constrains
106106
* nothing. The field surface has the same exposure and the same answer.
107107
*
108-
* ### Why the NULL-organization fold needs no `'__global__'` token here
108+
* ### The organization key part is plain since ADR-0131 D1
109109
*
110-
* ADR-0120 D3 materializes the organization key part as
110+
* The tenant column is NOT NULL (ADR-0131 D1), so `driver-sql` keys the plain
111+
* column and a row whose organization is NULL is exempt under its
112+
* NULL-distinct UNIQUE, like a NULL in any other key part. This module answers
113+
* the same: the organization key part is an ordinary one. The fold the next
114+
* paragraphs describe is what ADR-0120 D3 did before, kept for the record of
115+
* why `nullSafeColumns` exists on the constraint shape.
116+
*
117+
* ADR-0120 D3 materialized the organization key part as
111118
* `COALESCE(organization_id, '__global__')` because SQL `UNIQUE` is
112119
* NULL-DISTINCT: a raw `(organization_id, field)` composite enforces NOTHING on
113120
* rows whose organization is NULL, which on a single-organization stack is
@@ -148,9 +155,9 @@
148155
*
149156
* So there is exactly ONE rule, and {@link uniqueKeyOf} is the one place it
150157
* lives: **a NULL in any key part EXEMPTS the row, except in a NULL-SAFE part,
151-
* where it folds onto the shared `null` bucket.** The organization key part is
152-
* the only NULL-safe one, on either surface, because on the SQL side it is the
153-
* only one materialized as an expression that can never be NULL.
158+
* where it folds onto the shared `null` bucket.** Since ADR-0131 D1 no
159+
* organization key part is NULL-safe; the one NULL-safe part left is the
160+
* constant platform scope of a field-level constraint with no tenant column.
154161
*
155162
* ## Which column conflicted: this driver answers `undefined`, always
156163
*
@@ -244,10 +251,15 @@ export interface MemoryDeclaredIndexConstraint {
244251
readonly columns: readonly string[];
245252
/**
246253
* The subset of {@link columns} whose NULL FOLDS onto one shared bucket
247-
* instead of exempting the row (ADR-0120 D3). In practice the organization
248-
* key part, and only on the `'organization'` spelling.
254+
* instead of exempting the row (ADR-0120 D3). Empty from every declaration
255+
* since ADR-0131 D1, which keys the plain organization column.
249256
*/
250257
readonly nullSafeColumns: readonly string[];
258+
/**
259+
* The organization key part the `'organization'` spelling prepended or
260+
* named — what the refusal states as the scope. Absent otherwise.
261+
*/
262+
readonly scopeColumns?: readonly string[];
251263
}
252264

253265
/**
@@ -459,11 +471,11 @@ export function uniqueConstraintsFromDeclaredIndexes(
459471
if (!isUniqueDeclared(idx?.unique)) continue;
460472

461473
if (isOrganizationUnique(idx?.unique) && tenantField) {
462-
// A listed column that IS the tenant column is not prepended again — its
463-
// own key part becomes the NULL-safe one instead (the hand-written S6
464-
// spelling, opted in), and the author's column order is kept.
474+
// A listed column that IS the tenant column is not prepended again (the
475+
// hand-written S6 spelling), and the author's column order is kept. The
476+
// organization key part is plain (ADR-0131 D1).
465477
const columns = listed.includes(tenantField) ? listed : [tenantField, ...listed];
466-
out.push({ columns, nullSafeColumns: [tenantField] });
478+
out.push({ columns, nullSafeColumns: [], scopeColumns: [tenantField] });
467479
continue;
468480
}
469481
// `'global'`, bare `true`, or `'organization'` on an object with no tenant
@@ -491,8 +503,8 @@ export function uniqueKeyOf(
491503
const parts: unknown[] = [];
492504
for (const part of keyPartsOf(constraint)) {
493505
// A NULL-SAFE part folds: `null` IS its bucket, and the row stays
494-
// constrained. That is the ADR-0120 D3 organization key part, and the only
495-
// kind of part that behaves this way on either surface.
506+
// constrained: the constant platform scope of a field-level constraint.
507+
// The organization key part is plain (ADR-0131 D1).
496508
if (part.nullSafe) {
497509
parts.push(part.column === null ? null : (record[part.column] ?? null));
498510
continue;
@@ -530,7 +542,9 @@ function keyPartsOf(constraint: MemoryUniqueEnforcement): readonly UniqueKeyPart
530542
}));
531543
}
532544
return [
533-
{ column: constraint.scopeField, nullSafe: true },
545+
// The constant platform scope (`null`) folds; an organization column is a
546+
// plain key part (ADR-0131 D1), so a row with no organization is exempt.
547+
{ column: constraint.scopeField, nullSafe: constraint.scopeField === null },
534548
{ column: constraint.field, nullSafe: false },
535549
];
536550
}
@@ -574,10 +588,10 @@ export function declaredIndexViolationError(
574588
constraint: MemoryDeclaredIndexConstraint,
575589
record: Record<string, unknown>,
576590
): Error & { code: string; status: number } {
577-
const scope = constraint.nullSafeColumns;
591+
const scope = constraint.scopeColumns ?? constraint.nullSafeColumns;
578592
const keyed = constraint.columns.filter((c) => !scope.includes(c));
579-
// A key whose ONLY part is the NULL-safe organization ("one row per
580-
// organization") has nothing left to list, so it reports its own column.
593+
// A key whose ONLY part is the organization ("one row per organization")
594+
// has nothing left to list, so it reports its own column.
581595
const reported = keyed.length > 0 ? keyed : constraint.columns;
582596
const scoped =
583597
keyed.length > 0 && scope.length > 0

0 commit comments

Comments
 (0)