Skip to content

Commit e4c6ffe

Browse files
committed
test(driver-sql): re-pin the organization unique suites to the plain key part (ADR-0131 D1)
Claude-Session: https://claude.ai/code/session_01NnXVu3vF2TKFLMi5Me4CUd Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0ad6c5b commit e4c6ffe

9 files changed

Lines changed: 362 additions & 278 deletions

‎packages/drivers/driver-sql/src/adr0120-three-posture-conformance.test.ts‎

Lines changed: 37 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ const FIXTURE_APP = [
6969
{
7070
// S1 — per-organization unique field. Two organizations may each hold
7171
// `a@b.com`; a duplicate WITHIN one may not. S8's mixed population rides
72-
// along: NULL-organization rows form one platform bucket (D3).
72+
// along: NULL-organization rows (pre-18 databases only) are exempt from
73+
// the plain organization key part (ADR-0131 D1).
7374
name: 'crm_contact',
7475
fields: {
7576
organization_id: { type: 'string' },
@@ -152,22 +153,23 @@ const FIXTURE_APP = [
152153

153154
/**
154155
* The expected unique key parts, per table — the SAME map for every posture.
155-
* `COALESCE(col)` is the literal-agnostic reading of the NULL-safe organization
156-
* key part, matching the identity the drift differ compares on.
156+
* The organization key part is the PLAIN column (ADR-0131 D1): a legacy
157+
* NULL-safe part would read here as `COALESCE(col)` (literal elided, the
158+
* differ's identity) and fail the map, so no posture can bring one back.
157159
*/
158160
const EXPECTED_UNIQUE_KEY_PARTS: Record<string, Record<string, string[]>> = {
159-
crm_contact: { uniq_crm_contact_organization_id_email: ['COALESCE(organization_id)', 'email'] },
161+
crm_contact: { uniq_crm_contact_organization_id_email: ['organization_id', 'email'] },
160162
crm_device: { uniq_crm_device_serial: ['serial'] },
161163
// Note the index NAME: the deterministic name is derived from the RESOLVED
162164
// columns, so a declared `'organization'` index carries the organization
163165
// column in its name even though the author never listed it. That is the
164166
// differ's identity too, which is why declaring and detecting cannot drift.
165167
crm_case: {
166-
uniq_crm_case_organization_id_department_code: ['COALESCE(organization_id)', 'department', 'code'],
168+
uniq_crm_case_organization_id_department_code: ['organization_id', 'department', 'code'],
167169
},
168170
crm_delivery: { uniq_crm_delivery_source_dedup_key: ['source', 'dedup_key'] },
169171
crm_team: { uniq_crm_team_name_organization_id: ['name', 'organization_id'] },
170-
crm_product: { uniq_crm_product_organization_id_code: ['COALESCE(organization_id)', 'code'] },
172+
crm_product: { uniq_crm_product_organization_id_code: ['organization_id', 'code'] },
171173
crm_registry: { uniq_crm_registry_slug: ['slug'] },
172174
};
173175

@@ -279,21 +281,29 @@ describe('ADR-0120 — one app package, three tenancy postures (S13/S14 acceptan
279281
.rejects.toThrow(REJECTED);
280282
});
281283

282-
it('S7/S8 — the NULL-organization bucket is a real bucket, in every posture', async () => {
283-
// THE #5030 headline, and the reason `'organization'` could ship at all:
284-
// before D3 this pair inserted twice on a single-organization stack
285-
// (SQL UNIQUE is NULL-distinct), so every field-level unique was a
286-
// silent no-op there. It must now be enforced under `single` exactly as
287-
// under `isolated` — the posture is not what makes a constraint real.
288-
// The NULL bucket exists only on a database built before 18.x (ADR-0131
289-
// D1 makes a fresh tenant column NOT NULL).
284+
it('S7/S8 — NULL organization: refused on a fresh table, exempt on a pre-18 one, in every posture', async () => {
285+
// THE #5030 headline: before ADR-0120 D3 a NULL-organization pair
286+
// inserted twice on a single-organization stack (SQL UNIQUE is
287+
// NULL-distinct), so every field-level unique was a silent no-op there.
288+
// ADR-0131 D1 closes that at the COLUMN, not the index: a fresh tenant
289+
// column is NOT NULL, so the row cannot be written at all — under
290+
// `single` exactly as under `isolated`; the posture is not what makes a
291+
// constraint real.
292+
await expect(driver.create('crm_contact', { email: 'platform@b.com' }))
293+
.rejects.toThrow(/NOT NULL constraint failed|null value in column/);
294+
// A database built before 18.x keeps its nullable column; there the
295+
// plain key part is NULL-distinct, so NULL-organization rows are exempt
296+
// (the D3 platform bucket is retired, not rebuilt)…
290297
await asPre18TenantColumn(driver, 'crm_contact');
291298
await driver.create('crm_contact', { email: 'platform@b.com' });
292299
await expect(driver.create('crm_contact', { email: 'platform@b.com' }))
293-
.rejects.toThrow(REJECTED);
294-
// …while an organization-owned row with the same value still fits (S8).
300+
.resolves.toBeTruthy();
301+
// …while an organization-owned row with the same value still fits (S8),
302+
// once — the organization stays constrained.
295303
await expect(driver.create('crm_contact', { organization_id: 'org_a', email: 'platform@b.com' }))
296304
.resolves.toBeTruthy();
305+
await expect(driver.create('crm_contact', { organization_id: 'org_a', email: 'platform@b.com' }))
306+
.rejects.toThrow(REJECTED);
297307
});
298308

299309
it('S2 — a platform-wide unique field crosses organizations, in every posture', async () => {
@@ -308,12 +318,15 @@ describe('ADR-0120 — one app package, three tenancy postures (S13/S14 acceptan
308318
.resolves.toBeTruthy();
309319
await expect(driver.create('crm_case', { organization_id: 'org_a', department: 'ops', code: 'C1' }))
310320
.rejects.toThrow(REJECTED);
311-
// …and the NULL bucket is constrained too (D3 reaches declared indexes).
312-
// The NULL bucket exists only on a database built before 18.x (ADR-0131
313-
// D1 makes a fresh tenant column NOT NULL).
321+
// …and NULL-organization rows, which exist only on a database built
322+
// before 18.x, are exempt from the declared composite exactly as from
323+
// the field-level one: its organization key part is plain (ADR-0131 D1).
314324
await asPre18TenantColumn(driver, 'crm_case');
315325
await driver.create('crm_case', { department: 'ops', code: 'C9' });
316326
await expect(driver.create('crm_case', { department: 'ops', code: 'C9' }))
327+
.resolves.toBeTruthy();
328+
// The relaxation left the composite in force for organizations.
329+
await expect(driver.create('crm_case', { organization_id: 'org_a', department: 'ops', code: 'C1' }))
317330
.rejects.toThrow(REJECTED);
318331
});
319332

@@ -340,10 +353,11 @@ describe('ADR-0120 — one app package, three tenancy postures (S13/S14 acceptan
340353
.rejects.toThrow(REJECTED);
341354
await expect(driver.create('crm_team', { organization_id: 'org_b', name: 'Core' }))
342355
.resolves.toBeTruthy();
343-
// The un-closed NULL hole, pinned as the honest status quo (D5c nudges
344-
// toward the respelling that closes it; nothing forces it).
345-
// The NULL bucket exists only on a database built before 18.x (ADR-0131
346-
// D1 makes a fresh tenant column NOT NULL).
356+
// NULL-organization rows are exempt, pinned as the honest status quo.
357+
// Since ADR-0131 D1 the respelling D5c nudges toward is plain too, so
358+
// this is no longer a hole one spelling has and the other closes: such
359+
// rows exist only on a database built before 18.x (a fresh tenant
360+
// column is NOT NULL).
347361
await asPre18TenantColumn(driver, 'crm_team');
348362
await driver.create('crm_team', { name: 'Platform' });
349363
await expect(driver.create('crm_team', { name: 'Platform' })).resolves.toBeTruthy();

‎packages/drivers/driver-sql/src/sql-driver-14902-plain-unique-duplicate-preflight.test.ts‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,14 @@ import { SqlDriver } from '../src/index.js';
3838
*
3939
* ## What this suite pins
4040
*
41-
* Parity, in both halves, plus path A as the CONTROL. A change that quietly
42-
* moved path A while making path B loud would otherwise read as success, so the
43-
* last block asserts path A's message and classification are still their own —
44-
* the `#5030` framing, which is precisely what the plain path must NOT claim
45-
* (nothing ever admitted these rows; the constraint is simply newly declared
46-
* over data that does not satisfy it).
41+
* Parity, in both halves, plus the tenanted composite as the CONTROL. Path A
42+
* as measured no longer exists: since ADR-0131 D1 the organization key part is
43+
* PLAIN (no COALESCE), so a tenanted `unique: true` is path B's shape with the
44+
* organization column in front. The last block pins that it reaches path B's
45+
* disposition — loud, `destructive`, the conflicting groups named — and that
46+
* it does NOT carry path A's retired `#5030` framing: no NULL-safe story, no
47+
* `'__global__'` bucket, and NULL-organization rows (which never conflict under
48+
* a plain UNIQUE) are not reported as duplicates.
4749
*
4850
* ⛔ Nothing here pins the DATABASE's raw error text: the `catch` shape is
4951
* dialect-independent, that text is not. Assertions are on our own messages and
@@ -272,8 +274,8 @@ describe('#14902 plain unique index over duplicate rows', () => {
272274
});
273275
});
274276

275-
describe('CONTROL — path A is untouched', () => {
276-
it('still logs its own NULL-safe #5030 message and still reports destructive with the key groups', async () => {
277+
describe('CONTROL — the tenanted composite, plain since ADR-0131 D1', () => {
278+
it('reaches the plain disposition with the organization key part, and never reports NULL-organization rows', async () => {
277279
await seed(true, [
278280
{ id: 'r1', organization_id: null, quote_number: 'QUO-00009' },
279281
{ id: 'r2', organization_id: null, quote_number: 'QUO-00009' },
@@ -282,7 +284,7 @@ describe('#14902 plain unique index over duplicate rows', () => {
282284
]);
283285

284286
// `unique: true` on a tenanted object == `unique: 'organization'` — the
285-
// #13894 default, and the shape this card must not have disturbed.
287+
// #13894 default. Its key is `(organization_id, quote_number)`, plain.
286288
await expect(
287289
driver.initObjects([
288290
{
@@ -297,20 +299,28 @@ describe('#14902 plain unique index over duplicate rows', () => {
297299

298300
const durability = logs.filter((l) => l.level === 'error');
299301
expect(durability).toHaveLength(1);
300-
expect(durability[0].msg).toContain('NULL-safe unique index');
301-
expect(durability[0].msg).toContain('NULL-distinct');
302-
expect(durability[0].msg).toContain('ADR-0120 D4');
303-
expect(durability[0].msg).toContain("'organization_id, quote_number'");
302+
const msg = durability[0].msg;
303+
expect(msg).toContain("'uniq_crm_quote_organization_id_quote_number'");
304+
expect(msg).toContain("'organization_id, quote_number'");
305+
expect(msg).toMatch(/Conflicting group\(s\)/);
306+
expect(msg).toContain('(organization_id="org_x", quote_number="QUO-00010") × 2 rows');
307+
expect(msg).toMatch(/NOT enforced/);
308+
expect(msg).toContain('os migrate plan');
309+
// The two NULL-organization rows never conflict under a plain UNIQUE
310+
// (NULL-distinct), so the pre-flight does not report them — and the
311+
// retired ADR-0120 D3/D4 framing is gone with the COALESCE key.
312+
expect(msg).not.toContain('QUO-00009');
313+
expect(msg).not.toContain('NULL-safe');
314+
expect(msg).not.toContain('__global__');
304315

305316
const entry = (await driver.detectManagedDrift()).find((d) => d.op.type === 'create_index')!;
306317
expect(entry.category).toBe('destructive');
307318
expect(entry.severity).toBe('error');
308-
expect(entry.message).toContain('NULL-distinct');
309-
expect(entry.message).toContain('__global__');
310-
// Both key groups, with counts — the NULL-organization bucket and a real
311-
// organization, which is what makes the COALESCE key self-describing.
312-
expect(entry.message).toContain('(organization_id="__global__", quote_number="QUO-00009")');
319+
expect(entry.message).toMatch(/BLOCKED/);
313320
expect(entry.message).toContain('(organization_id="org_x", quote_number="QUO-00010")');
321+
expect(entry.message).not.toContain('QUO-00009');
322+
expect(entry.message).not.toContain('__global__');
323+
expect(entry.message).not.toContain('NULL-safe');
314324
});
315325
});
316326
});

‎packages/drivers/driver-sql/src/sql-driver-autonumber-resync.test.ts‎

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,13 @@
4040
*
4141
* - the filing's own message is a **composite** —
4242
* `UNIQUE constraint failed: crm_case.organization_id, crm_case.case_number`
43-
* — and `uniqueViolationColumn` refuses composites by contract;
44-
* - what this repo builds **today** is narrower still: ADR-0120 D3 makes the
45-
* tenanted unique index `(COALESCE(organization_id,'__global__'), field)`,
46-
* an *expression* index, on which SQLite reports
47-
* `UNIQUE constraint failed: index 'uniq_…'` and names no column at all.
43+
* — and `uniqueViolationColumn` refuses composites by contract. Since
44+
* ADR-0131 D1 that is again exactly what this repo builds **today**: the
45+
* tenanted unique index is the plain `(organization_id, field)`;
46+
* - a database still carrying the ADR-0120 D3 index is narrower still: its
47+
* `(COALESCE(organization_id,'__global__'), field)` is an *expression*
48+
* index, on which SQLite reports `UNIQUE constraint failed: index 'uniq_…'`
49+
* and names no column at all.
4850
*
4951
* So the "column not determinable" limb is not an edge case on this path — it
5052
* is the only limb that ever runs for a tenanted autonumber. The discriminator
@@ -210,13 +212,16 @@ describe('[#5495] autonumber sequence re-seed on a provable collision', () => {
210212
it('pins WHY the column-name predicate cannot carry this decision', async () => {
211213
await driver.initObjects([CRM_CASE]);
212214

213-
// 1. What this repo builds today: an expression composite, on which SQLite
214-
// reports the INDEX and no column.
215+
// 1. What this repo builds today (ADR-0131 D1): the PLAIN tenant composite,
216+
// on which SQLite reports both columns — a composite, which
217+
// `uniqueViolationColumn` refuses by contract. This is the filing's own
218+
// message, byte for byte.
215219
const indexes: any[] = await knex().raw(
216220
`select name, sql from sqlite_master where type='index' and tbl_name='crm_case'`,
217221
);
218222
const declared = indexes.find((r) => r.name === 'uniq_crm_case_organization_id_case_number');
219-
expect(declared?.sql).toContain(`COALESCE(\`organization_id\`, '__global__')`);
223+
expect(declared?.sql).toContain('(`organization_id`, `case_number`)');
224+
expect(declared?.sql).not.toContain('COALESCE');
220225

221226
await knex()('crm_case').insert({ id: 'd1', organization_id: 'orgA', case_number: 'CASE-00001', title: 'a' });
222227
const caught = await knex()('crm_case')
@@ -226,14 +231,28 @@ describe('[#5495] autonumber sequence re-seed on a provable collision', () => {
226231
(e: unknown) => e,
227232
);
228233
expect(isUniqueViolationError(caught)).toBe(true);
229-
expect((caught as Error).message).toMatch(/UNIQUE constraint failed: index '/);
234+
expect((caught as Error).message).toContain(
235+
'UNIQUE constraint failed: crm_case.organization_id, crm_case.case_number',
236+
);
230237
expect(uniqueViolationColumn(caught)).toBeUndefined();
231238

232-
// 2. And the message the filing itself reported — the plain composite that
233-
// predates ADR-0120 D3 — is refused for the other reason.
234-
expect(
235-
uniqueViolationColumn('UNIQUE constraint failed: crm_case.organization_id, crm_case.case_number'),
236-
).toBeUndefined();
239+
// 2. And a database still carrying the ADR-0120 D3 expression composite —
240+
// built before ADR-0131 D1, honoured as it stands — is refused for the
241+
// other reason: SQLite reports the INDEX and no column.
242+
await knex().raw('create table legacy_case (id text primary key, organization_id text, case_number text)');
243+
await knex().raw(
244+
`create unique index uniq_legacy_case_organization_id_case_number on legacy_case (COALESCE(organization_id, '__global__'), case_number)`,
245+
);
246+
await knex()('legacy_case').insert({ id: 'l1', organization_id: 'orgA', case_number: 'CASE-00001' });
247+
const caughtLegacy = await knex()('legacy_case')
248+
.insert({ id: 'l2', organization_id: 'orgA', case_number: 'CASE-00001' })
249+
.then(
250+
() => undefined,
251+
(e: unknown) => e,
252+
);
253+
expect(isUniqueViolationError(caughtLegacy)).toBe(true);
254+
expect((caughtLegacy as Error).message).toMatch(/UNIQUE constraint failed: index '/);
255+
expect(uniqueViolationColumn(caughtLegacy)).toBeUndefined();
237256
});
238257

239258
/**

0 commit comments

Comments
 (0)