Skip to content

Commit 1342d1d

Browse files
committed
test(cli): the generators emit the plain organization composite; the dev self-heal fence is staged with the legacy global unique
Claude-Session: https://claude.ai/code/session_01NnXVu3vF2TKFLMi5Me4CUd Co-authored-by: Claude <noreply@anthropic.com>
1 parent 31c75dd commit 1342d1d

2 files changed

Lines changed: 180 additions & 78 deletions

File tree

‎packages/cli/src/commands/generate-declared-unique-index.pin.test.ts‎

Lines changed: 126 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,31 @@
3434
* constraint. The COLUMN — the #16091 result this change must not spend — read
3535
* `character varying(100)` on all three both before and after.
3636
*
37-
* ## What this pin does NOT claim, stated so nobody reads it as closed
37+
* ## The organization composite — emitted since ADR-0131 D1
38+
*
39+
* Until ADR-0131 D1 the ORGANIZATION-SCOPED form was the ADR-0120 D3
40+
* expression `(COALESCE(<tenant>, '__global__'), <field>)`, which neither format
41+
* could spell, so it was deliberately unemitted and named in a NOT EMITTED
42+
* line. The driver now keys the PLAIN tenant column — a fresh table's tenant
43+
* column is NOT NULL, so the ADR-0120 D3 NULL-organization bucket the COALESCE
44+
* existed for is gone from new DDL — and the bare `(organization_id, field)` IS
45+
* the platform's constraint. So both formats emit it, and this file pins that
46+
* the generated table carries the SAME composite the driver creates and refuses
47+
* the same in-organization duplicate (block A), and that no NOT EMITTED line is
48+
* printed for it any more (block B).
3849
*
39-
* Two declaration shapes are deliberately unemitted, and this file asserts that
40-
* they are unemitted *and named*, never that they are handled:
50+
* ## What this pin does NOT claim, stated so nobody reads it as closed
4151
*
42-
* 1. The ADR-0120 D3 ORGANIZATION-SCOPED form — `(COALESCE(<tenant>,
43-
* '__global__'), <field>)`. Emitting the bare composite instead would be
44-
* worse than emitting nothing: under SQL's NULL-distinct UNIQUE a bare
45-
* `(organization_id, field)` constrains NOTHING on rows with no
46-
* organization, which on a single-tenant stack is every row (#5030) — a
47-
* constraint advertised and not delivered, which is the failure Prime
48-
* Directive #10 names.
49-
* 2. OBJECT-LEVEL `indexes[]`. `normalizeDeclaredIndex` is a second
50-
* normalizer that reads the same `unique: true` token DIFFERENTLY (verbatim
51-
* as global, a maintainer ruling), so it is a second transcription with a
52-
* second pin, not a loop added to this one.
52+
* One declaration shape is deliberately unemitted, and this file asserts that it
53+
* is unemitted *and named*, never that it is handled: OBJECT-LEVEL `indexes[]`.
54+
* `normalizeDeclaredIndex` is a second normalizer that reads the same
55+
* `unique: true` token DIFFERENTLY (verbatim as global, a maintainer ruling), so
56+
* it is a second transcription with a second pin, not a loop added to this one.
5357
*
54-
* ⭐ Measured for the record, because "can the TypeScript format express an
55-
* expression key part through knex at all" was the open question that kept the
56-
* scoped form off this change (knex 3.3.0, live PostgreSQL 16.13):
58+
* ⭐ Measured for the record — HISTORICAL since ADR-0131 D1 retired the
59+
* expression key part, kept because it is why the scoped form was once
60+
* unemitted, and stays true for any future expression key part (knex 3.3.0,
61+
* live PostgreSQL 16.13):
5762
*
5863
* ```
5964
* table.unique([knex.raw("COALESCE(...)"), 'f'], {indexName})
@@ -72,8 +77,9 @@
7277
* knex handle and `db.raw` is exactly the seam `SqlDriver.createNullSafeUniqueIndex`
7378
* already uses for this — but knex's SCHEMA BUILDER cannot express it in either
7479
* format, so the scoped form costs a raw statement rather than another
75-
* `table.unique(...)` line. That is a fact for whoever takes the scoped half,
76-
* recorded here rather than acted on.
80+
* `table.unique(...)` line. ADR-0131 D1 made that moot for the organization
81+
* composite (its key parts are plain columns now); it is recorded for whoever
82+
* next meets an expression key part.
7783
*
7884
* ## Why this pin reads the driver instead of asserting the names
7985
*
@@ -82,7 +88,7 @@
8288
* transcribed `uniq_probe_keyed_unique` would re-create the defect one layer up
8389
* and stay green the day the driver's naming moves. Every name and every key-part
8490
* ordering here is recomputed from `driver-sql`'s own exported
85-
* `uniqueIndexesFromFields` / `buildIndexName` / `GLOBAL_TENANT`.
91+
* `uniqueIndexesFromFields` / `buildIndexName`.
8692
*
8793
* ⭐ And the leaves are not the authority. Above the differential sits THE REAL
8894
* CHAIN: all three producers driven into ONE in-memory better-sqlite3 database,
@@ -109,7 +115,7 @@
109115
* measuring the parser.
110116
*/
111117

112-
import { SqlDriver, GLOBAL_TENANT, buildIndexName, uniqueIndexesFromFields } from '@objectstack/driver-sql';
118+
import { SqlDriver, buildIndexName, uniqueIndexesFromFields } from '@objectstack/driver-sql';
113119
import { afterAll, describe, expect, it } from 'vitest';
114120

115121
import { generateMigrationSql, generateMigrationTs } from './generate.js';
@@ -210,8 +216,12 @@ function loadEmittedTs(ts: string): { up: (db: any) => Promise<void>; down: (db:
210216
interface Probe {
211217
label: string;
212218
object: Record<string, any>;
213-
/** What the object's declarations mean for the emitters, asserted below. */
214-
expect: 'emitted' | 'scoped-not-emitted' | 'no-column' | 'none';
219+
/**
220+
* What the object's declarations mean for the emitters, asserted below.
221+
* `scoped` is the organization composite — emitted like `emitted`, with the
222+
* plain tenant column as its FIRST key part (ADR-0131 D1).
223+
*/
224+
expect: 'emitted' | 'scoped' | 'no-column' | 'none';
215225
}
216226

217227
const ORG = { type: 'text', maxLength: 64 } as const;
@@ -229,14 +239,14 @@ const CORPUS: Probe[] = [
229239
expect: 'emitted',
230240
},
231241
{
232-
label: '`unique: true` beside an organization column — the ADR-0120 D3 scoped composite',
242+
label: '`unique: true` beside an organization column — the plain organization composite (ADR-0131 D1)',
233243
object: { name: 'p_scoped_true', fields: { organization_id: ORG, f: { ...KEYED, unique: true } } },
234-
expect: 'scoped-not-emitted',
244+
expect: 'scoped',
235245
},
236246
{
237247
label: "explicit `unique: 'organization'` — the same scoped composite",
238248
object: { name: 'p_scoped_word', fields: { organization_id: ORG, f: { ...KEYED, unique: 'organization' } } },
239-
expect: 'scoped-not-emitted',
249+
expect: 'scoped',
240250
},
241251
{
242252
label: 'unique ON the organization column itself — "one row per tenant" stays single-column',
@@ -259,7 +269,7 @@ const CORPUS: Probe[] = [
259269
tenancy: { tenantField: 'org' },
260270
fields: { org: ORG, f: { ...KEYED, unique: true } },
261271
},
262-
expect: 'scoped-not-emitted',
272+
expect: 'scoped',
263273
},
264274
{
265275
label: 'a name past the 60-character identifier budget — hash-suffixed',
@@ -349,8 +359,9 @@ describe('#16317 — the index each generator emits is the index the driver CREA
349359

350360
// ⭐ THE AUTHORITY. Whatever the driver's own table carries, the ts
351361
// format's table carries too — by NAME, because both go through knex's
352-
// named-index spelling — except for the two declared exclusions.
353-
const emittable = probe.expect === 'emitted';
362+
// named-index spelling — except for the declared exclusions. Since
363+
// ADR-0131 D1 the organization composite is one of the emitted shapes.
364+
const emittable = probe.expect === 'emitted' || probe.expect === 'scoped';
354365
if (emittable) {
355366
expect(uniqueShapes(built.tsgen)).toEqual(uniqueShapes(built.driver));
356367
expect(uniqueShapes(built.sqlgen)).toEqual(uniqueShapes(built.driver));
@@ -362,22 +373,28 @@ describe('#16317 — the index each generator emits is the index the driver CREA
362373
for (const want of wanted) expect(built.sqlText).toContain(`CONSTRAINT "${want.name}" UNIQUE (`);
363374
}
364375

365-
if (probe.expect === 'scoped-not-emitted') {
366-
// The driver DOES build it — the expression key part is why we do not.
376+
if (probe.expect === 'scoped') {
377+
// ADR-0131 D1: the driver keys the PLAIN tenant column, so the
378+
// composite it creates is a two-column list with the tenant FIRST and
379+
// no expression key part — the shape both formats can spell, and do.
380+
const tenant = newOracle().tenantFieldFor(probe.object);
381+
expect(tenant).not.toBeNull();
367382
expect(wanted.length).toBeGreaterThan(0);
368383
for (const want of wanted) {
369-
expect(want.nullSafeColumns ?? []).not.toHaveLength(0);
370-
// ⛔ Absence must be loud: named in the generated file, both formats.
371-
expect(built.sqlText).toContain(`NOT EMITTED: UNIQUE index "${want.name}"`);
372-
expect(built.tsText).toContain(`NOT EMITTED: UNIQUE index '${want.name}'`);
373-
expect(built.sqlText).toContain(`COALESCE("${want.nullSafeColumns![0]}", '${GLOBAL_TENANT}')`);
374-
// ...and NOT emitted as the bare composite, which would advertise a
375-
// constraint the table does not carry (#5030).
376-
expect(built.sqlText).not.toContain(`CONSTRAINT "${want.name}" UNIQUE (`);
377-
expect(built.tsText).not.toContain(`indexName: '${want.name}'`);
384+
expect(want.nullSafeColumns ?? []).toHaveLength(0);
385+
expect(want.columns).toHaveLength(2);
386+
expect(want.columns[0]).toBe(tenant);
378387
}
379-
expect(uniqueShapes(built.tsgen)).toHaveLength(0);
380-
expect(uniqueShapes(built.sqlgen)).toHaveLength(0);
388+
// The catalog agrees: every producer's table carries the composite as
389+
// two PLAIN key parts (SQLite reports `null` for an expression part).
390+
for (const rows of [built.driver, built.sqlgen, built.tsgen]) {
391+
expect(uniqueShapes(rows)).toEqual(wanted.map((w) => w.columns.join(',')).sort());
392+
}
393+
// ...and nothing is announced as missing, because nothing is.
394+
expect(built.sqlText).not.toContain('NOT EMITTED');
395+
expect(built.tsText).not.toContain('NOT EMITTED');
396+
expect(built.sqlText).not.toContain('COALESCE');
397+
expect(built.tsText).not.toContain('COALESCE');
381398
}
382399

383400
if (probe.expect === 'no-column') {
@@ -425,6 +442,44 @@ describe('#16317 — the index each generator emits is the index the driver CREA
425442
expect(verdicts).toEqual({ driver: 'refused', sqlgen: 'refused', tsgen: 'refused' });
426443
});
427444

445+
/**
446+
* ⭐ The same consequence for the ORGANIZATION composite (ADR-0131 D1): a
447+
* duplicate inside ONE organization is refused by the driver's table and by
448+
* BOTH generated ones, and the same value in a SECOND organization is accepted
449+
* by all three — uniqueness is per organization, not platform-wide. Rows
450+
* carry an explicit organization: a fresh driver table's tenant column is
451+
* NOT NULL, so a NULL-organization row is not a case the driver's table has.
452+
*/
453+
it('a duplicate inside one organization is refused by BOTH generated tables and the driver; another organization is not', async () => {
454+
const object = { name: 'p_enforce_org', fields: { organization_id: ORG, f: { ...KEYED, unique: true } } };
455+
const built = await threeTables(object);
456+
const insert = (db: any, id: string, org: string) =>
457+
db.raw(`INSERT INTO "p_enforce_org" ("id", "organization_id", "f") VALUES (?, ?, 'dup')`, [id, org]);
458+
const verdicts: Record<string, { sameOrg: string; otherOrg: string }> = {};
459+
for (const [who, db] of Object.entries(built.dbs)) {
460+
await insert(db, 'a', 'org_1');
461+
let sameOrg: string;
462+
try {
463+
await insert(db, 'b', 'org_1');
464+
sameOrg = 'accepted';
465+
} catch (err) {
466+
// A UNIQUE refusal specifically — not any error the insert could raise.
467+
expect(String((err as Error).message)).toMatch(/UNIQUE constraint failed/);
468+
sameOrg = 'refused';
469+
}
470+
let otherOrg: string;
471+
try {
472+
await insert(db, 'c', 'org_2');
473+
otherOrg = 'accepted';
474+
} catch {
475+
otherOrg = 'refused';
476+
}
477+
verdicts[who] = { sameOrg, otherOrg };
478+
}
479+
const perOrg = { sameOrg: 'refused', otherOrg: 'accepted' };
480+
expect(verdicts).toEqual({ driver: perOrg, sqlgen: perOrg, tsgen: perOrg });
481+
});
482+
428483
/**
429484
* NON-VACUITY for the whole block. A corpus that built no unique index at all
430485
* would satisfy every `toEqual` above by agreeing on emptiness.
@@ -436,7 +491,7 @@ describe('#16317 — the index each generator emits is the index the driver CREA
436491
for (const probe of CORPUS) {
437492
const wanted = driverIndexes(oracle, probe.object);
438493
if (probe.expect === 'emitted') counts.emitted += wanted.length;
439-
if (probe.expect === 'scoped-not-emitted') counts.scoped += wanted.length;
494+
if (probe.expect === 'scoped') counts.scoped += wanted.length;
440495
if (probe.expect === 'no-column') counts.noColumn += wanted.length;
441496
if (probe.expect === 'none') counts.none += wanted.length;
442497
for (const w of wanted) if (/_[0-9a-f]{8}$/.test(w.name)) counts.hashed += 1;
@@ -477,11 +532,29 @@ describe('#16317 — the transcriptions in generate.ts are the driver\'s own', (
477532
expect(hashed).toBeGreaterThanOrEqual(3);
478533
});
479534

480-
/** The `__global__` sentinel the unemitted-index note names. */
481-
it('the sentinel the NOT EMITTED note prints is the driver\'s GLOBAL_TENANT', () => {
535+
/**
536+
* The `__global__` sentinel retired with the ADR-0120 D3 expression key part
537+
* (ADR-0131 D1), and with it the NOT EMITTED note that printed it. What is
538+
* left to pin is that the generators stopped announcing the organization
539+
* composite as missing — a stale note would tell the operator to hand-write
540+
* an index the file already creates — and that no COALESCE spelling of it
541+
* survives in either format, comment or code.
542+
*/
543+
it('no NOT EMITTED line is printed for an organization composite, in either format', () => {
482544
const object = { name: 'g_probe', fields: { organization_id: ORG, f: { ...KEYED, unique: true } } };
483-
expect(generateMigrationSql(configFor(object))).toContain(`'${GLOBAL_TENANT}'`);
484-
expect(generateMigrationTs(configFor(object))).toContain(`'${GLOBAL_TENANT}'`);
545+
const [want] = driverIndexes(oracle, object);
546+
expect(want.columns).toEqual(['organization_id', 'f']);
547+
const sql = generateMigrationSql(configFor(object));
548+
const ts = generateMigrationTs(configFor(object));
549+
expect(sql).not.toContain('NOT EMITTED');
550+
expect(ts).not.toContain('NOT EMITTED');
551+
expect(sql).not.toContain('COALESCE');
552+
expect(ts).not.toContain('COALESCE');
553+
expect(sql).not.toContain('__global__');
554+
expect(ts).not.toContain('__global__');
555+
// Non-vacuity: the index is in the file — as itself, not as a note.
556+
expect(sql).toContain(`CONSTRAINT "${want.name}" UNIQUE ("organization_id", "f")`);
557+
expect(ts).toContain(`table.unique(['organization_id', 'f'], { indexName: '${want.name}' });`);
485558
});
486559

487560
/**
@@ -495,16 +568,19 @@ describe('#16317 — the transcriptions in generate.ts are the driver\'s own', (
495568
const ts = generateMigrationTs(configFor(probe.object));
496569
for (const want of driverIndexes(oracle, probe.object)) {
497570
checked += 1;
498-
const scoped = (want.nullSafeColumns ?? []).length > 0;
499-
const emitted = probe.expect === 'emitted';
571+
// ADR-0131 D1: every key part is a plain column, the organization
572+
// composite's included, so every emitted index is a column list.
573+
expect(want.nullSafeColumns ?? []).toHaveLength(0);
574+
const emitted = probe.expect === 'emitted' || probe.expect === 'scoped';
500575
const cols = want.columns.map((c) => `"${c}"`).join(', ');
501576
if (emitted) {
502-
expect(scoped).toBe(false);
503577
expect(sql).toContain(`CONSTRAINT "${want.name}" UNIQUE (${cols})`);
504578
expect(ts).toContain(
505579
`table.unique([${want.columns.map((c) => `'${c}'`).join(', ')}], { indexName: '${want.name}' });`,
506580
);
507581
} else {
582+
// Only the no-column exclusion is left to announce.
583+
expect(probe.expect).toBe('no-column');
508584
expect(sql).toContain(`NOT EMITTED: UNIQUE index "${want.name}" on (${want.columns.join(', ')})`);
509585
expect(ts).toContain(`NOT EMITTED: UNIQUE index '${want.name}' on (${want.columns.join(', ')})`);
510586
}

0 commit comments

Comments
 (0)