|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 4 | +import { SqlDriver } from './sql-driver.js'; |
| 5 | +import { |
| 6 | + carriesNullSafeTenantKeyPart, |
| 7 | + diffManagedIndexes, |
| 8 | + hashShadowColumnFor, |
| 9 | + normalizeDeclaredIndex, |
| 10 | + uniqueIndexesFromFields, |
| 11 | + type ExpectedIndex, |
| 12 | + type PhysicalIndex, |
| 13 | +} from './schema-drift.js'; |
| 14 | +import { asPre18TenantColumn } from './pre-18-tenant-column.testkit.js'; |
| 15 | + |
| 16 | +/** |
| 17 | + * [18.x step 7b-1 + 7b-2] The organization key part of a unique index. |
| 18 | + * |
| 19 | + * 18.0 keyed every organization-scoped unique through ADR-0120 D3's |
| 20 | + * `COALESCE(organization_id, '__global__')`. Since ADR-0131 D1 the tenant |
| 21 | + * column is NOT NULL, so new DDL keys the plain column (7b-2), and the differ |
| 22 | + * reads the old form as the same constraint wherever the tenant column holds |
| 23 | + * no NULL: physically NOT NULL, or a certified database — a birth marker or an |
| 24 | + * organization-ownership ceremony marker of the current shape generation |
| 25 | + * (7b-1). Elsewhere the two forms are different constraints, and that |
| 26 | + * reading stays: the uncertified, nullable legs below are each case's control. |
| 27 | + */ |
| 28 | + |
| 29 | +const TABLE = 'eqv_account'; |
| 30 | +const ORG = 'organization_id'; |
| 31 | +const NAME = `uniq_${TABLE}_${ORG}_code`; |
| 32 | + |
| 33 | +/** What 18.0 built: the NULL-safe organization key part, attributed by introspection. */ |
| 34 | +const coalesced: PhysicalIndex = { |
| 35 | + name: NAME, |
| 36 | + columns: [ORG, 'code'], |
| 37 | + unique: true, |
| 38 | + expressions: [`COALESCE("${ORG}", '__global__')`], |
| 39 | + nullSafeColumns: [ORG], |
| 40 | +}; |
| 41 | +/** What HEAD builds: the plain composite. */ |
| 42 | +const plain: PhysicalIndex = { name: NAME, columns: [ORG, 'code'], unique: true }; |
| 43 | +const expectedPlain: ExpectedIndex = { name: NAME, columns: [ORG, 'code'], unique: true }; |
| 44 | +const expectedNullSafe: ExpectedIndex = { ...expectedPlain, nullSafeColumns: [ORG] }; |
| 45 | + |
| 46 | +const diff = (expected: ExpectedIndex, physical: PhysicalIndex, tenantKeyCertified?: boolean, tenantField: string | null = ORG) => |
| 47 | + diffManagedIndexes({ table: TABLE, expected: [expected], legacy: [], physical: [physical], tenantField, tenantKeyCertified }); |
| 48 | + |
| 49 | +describe('7b-2 — the generators key the plain organization column', () => { |
| 50 | + it('a field-level organization unique is the plain composite, tenant column first', () => { |
| 51 | + expect(uniqueIndexesFromFields(TABLE, { code: { type: 'text', unique: true } }, ORG)).toEqual([expectedPlain]); |
| 52 | + }); |
| 53 | + |
| 54 | + it("a declared `unique: 'organization'` prepends the plain tenant column", () => { |
| 55 | + expect(normalizeDeclaredIndex(TABLE, { fields: ['code'], unique: 'organization' }, ORG)).toEqual(expectedPlain); |
| 56 | + }); |
| 57 | + |
| 58 | + it('an input already normalized with a NULL-safe part is honoured verbatim (the read vocabulary stays)', () => { |
| 59 | + expect(normalizeDeclaredIndex(TABLE, { name: NAME, fields: [ORG, 'code'], unique: true, nullSafeColumns: [ORG] }, ORG)).toEqual( |
| 60 | + expectedNullSafe, |
| 61 | + ); |
| 62 | + }); |
| 63 | +}); |
| 64 | + |
| 65 | +describe('7b-1 — the differ: COALESCE(tenant) ≡ tenant where the tenant column holds no NULL', () => { |
| 66 | + it('an 18.0 COALESCE index against the plain expectation: no drift when certified', () => { |
| 67 | + expect(diff(expectedPlain, coalesced, true)).toEqual([]); |
| 68 | + }); |
| 69 | + |
| 70 | + it('control — the same pair, uncertified: a destructive recreate_index (the two are different constraints)', () => { |
| 71 | + const [entry, ...rest] = diff(expectedPlain, coalesced, false); |
| 72 | + expect(rest).toEqual([]); |
| 73 | + expect(entry).toMatchObject({ category: 'destructive', op: { type: 'recreate_index', indexName: NAME } }); |
| 74 | + }); |
| 75 | + |
| 76 | + it('the other direction: a plain physical index against a NULL-safe expectation, no drift when certified', () => { |
| 77 | + expect(diff(expectedNullSafe, plain, true)).toEqual([]); |
| 78 | + expect(diff(expectedNullSafe, plain, false).map((d) => d.op.type)).toEqual(['recreate_index']); |
| 79 | + }); |
| 80 | + |
| 81 | + it('the equivalence is the TENANT column\'s: with no tenant column named it does not apply', () => { |
| 82 | + expect(diff(expectedPlain, coalesced, true, null).map((d) => d.op.type)).not.toEqual([]); |
| 83 | + }); |
| 84 | + |
| 85 | + it('it changes the form of the key part only — a different column set stays drift, certified or not', () => { |
| 86 | + const other: ExpectedIndex = { name: NAME, columns: [ORG, 'code', 'region'], unique: true }; |
| 87 | + expect(diff(other, coalesced, true).map((d) => d.op.type)).toEqual(['recreate_index']); |
| 88 | + }); |
| 89 | + |
| 90 | + it('a MySQL hash shadow carrying the COALESCE key reads as the plain key when certified', () => { |
| 91 | + const carrier: PhysicalIndex = { |
| 92 | + name: NAME, |
| 93 | + columns: [hashShadowColumnFor(NAME)], |
| 94 | + unique: true, |
| 95 | + shadowKey: [ |
| 96 | + { column: ORG, nullSafe: true }, |
| 97 | + { column: 'code', nullSafe: false }, |
| 98 | + ], |
| 99 | + }; |
| 100 | + expect(diff(expectedPlain, carrier, true)).toEqual([]); |
| 101 | + expect(diff(expectedPlain, carrier, false).map((d) => d.op.type)).toEqual(['recreate_index']); |
| 102 | + }); |
| 103 | + |
| 104 | + it('carriesNullSafeTenantKeyPart answers for direct and shadow-carried keys, and only for the tenant column', () => { |
| 105 | + expect(carriesNullSafeTenantKeyPart([coalesced], ORG)).toBe(true); |
| 106 | + expect(carriesNullSafeTenantKeyPart([plain], ORG)).toBe(false); |
| 107 | + expect(carriesNullSafeTenantKeyPart([coalesced], null)).toBe(false); |
| 108 | + expect(carriesNullSafeTenantKeyPart([{ ...coalesced, nullSafeColumns: ['package_id'] }], ORG)).toBe(false); |
| 109 | + }); |
| 110 | +}); |
| 111 | + |
| 112 | +describe('the driver, on real SQLite', () => { |
| 113 | + let driver: SqlDriver; |
| 114 | + const object = { name: TABLE, fields: { code: { type: 'text', unique: true }, [ORG]: { type: 'text' } } }; |
| 115 | + |
| 116 | + beforeEach(async () => { |
| 117 | + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); |
| 118 | + await driver.initObjects([object]); |
| 119 | + }); |
| 120 | + |
| 121 | + afterEach(async () => { |
| 122 | + await driver.disconnect(); |
| 123 | + }); |
| 124 | + |
| 125 | + const knex = () => (driver as unknown as { knex: { raw(sql: string, b?: unknown[]): Promise<any> } }).knex; |
| 126 | + const indexSql = async (): Promise<string> => { |
| 127 | + const rows: any[] = await knex().raw(`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?`, [NAME]); |
| 128 | + return String(rows[0]?.sql ?? ''); |
| 129 | + }; |
| 130 | + /** The table as 18.0 left it: a nullable tenant column and the COALESCE index under the declared name. */ |
| 131 | + const as18Point0 = async (): Promise<void> => { |
| 132 | + await asPre18TenantColumn(driver, TABLE); |
| 133 | + await knex().raw(`DROP INDEX "${NAME}"`); |
| 134 | + await knex().raw(`CREATE UNIQUE INDEX "${NAME}" ON "${TABLE}" (COALESCE("${ORG}", '__global__'), "code")`); |
| 135 | + }; |
| 136 | + const indexOps = async () => (await driver.detectManagedDrift()).filter((d) => d.op.type.endsWith('_index')); |
| 137 | + |
| 138 | + it('a fresh table gets the plain composite — no COALESCE — and no index drift', async () => { |
| 139 | + const sql = await indexSql(); |
| 140 | + expect(sql).toMatch(/\(\s*[`"]?organization_id[`"]?\s*,\s*[`"]?code[`"]?\s*\)/); |
| 141 | + expect(sql).not.toMatch(/COALESCE/i); |
| 142 | + expect(await indexOps()).toEqual([]); |
| 143 | + }); |
| 144 | + |
| 145 | + it('an 18.0 table on a certified database: no drift, and the certification is asked', async () => { |
| 146 | + await as18Point0(); |
| 147 | + let asked = 0; |
| 148 | + driver.setTenantKeyCertifiedResolver(() => { |
| 149 | + asked++; |
| 150 | + return true; |
| 151 | + }); |
| 152 | + expect(await indexOps()).toEqual([]); |
| 153 | + expect(asked).toBeGreaterThan(0); |
| 154 | + expect(await indexSql()).toMatch(/COALESCE/); |
| 155 | + }); |
| 156 | + |
| 157 | + it('control — the same table with no certification: the destructive recreate_index the equivalence exists to remove', async () => { |
| 158 | + await as18Point0(); |
| 159 | + expect((await indexOps()).map((d) => [d.op.type, d.category])).toEqual([['recreate_index', 'destructive']]); |
| 160 | + }); |
| 161 | + |
| 162 | + it('a resolver that answers no, or throws, is "not certified"', async () => { |
| 163 | + await as18Point0(); |
| 164 | + driver.setTenantKeyCertifiedResolver(() => false); |
| 165 | + expect((await indexOps()).map((d) => d.op.type)).toEqual(['recreate_index']); |
| 166 | + driver.setTenantKeyCertifiedResolver(() => { |
| 167 | + throw new Error('ledger unreadable'); |
| 168 | + }); |
| 169 | + expect((await indexOps()).map((d) => d.op.type)).toEqual(['recreate_index']); |
| 170 | + }); |
| 171 | + |
| 172 | + it('a physically NOT NULL tenant column is its own witness: no drift without any certification', async () => { |
| 173 | + await knex().raw(`DROP INDEX "${NAME}"`); |
| 174 | + await knex().raw(`CREATE UNIQUE INDEX "${NAME}" ON "${TABLE}" (COALESCE("${ORG}", '__global__'), "code")`); |
| 175 | + expect(await indexOps()).toEqual([]); |
| 176 | + }); |
| 177 | + |
| 178 | + it('a table carrying no COALESCE tenant key part never asks the question', async () => { |
| 179 | + let asked = 0; |
| 180 | + driver.setTenantKeyCertifiedResolver(() => { |
| 181 | + asked++; |
| 182 | + return true; |
| 183 | + }); |
| 184 | + await asPre18TenantColumn(driver, TABLE); |
| 185 | + expect(await indexOps()).toEqual([]); |
| 186 | + expect(asked).toBe(0); |
| 187 | + }); |
| 188 | +}); |
0 commit comments