Skip to content

Commit cee4b16

Browse files
fix(metadata-protocol): land the NULL-safe sys_setting / sys_notification_preference identity on PostgreSQL, and never report a no-op as created (#26782)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XUEEEpJPSpQ64pHamCtDAD3)_ Fixes #26630 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:PostgreSQL 上 `sys_setting` 与 `sys_notification_preference` 的空值安全行身份(`COALESCE(user_id, '')`)现在真正落库;落不了时启动日志如实报出,不再假报成功。 - **为什么改**:18.2.0 在 PG 上声明的唯一键是约束而非索引,迁移的 `DROP INDEX` 被拒(2BP01),随后 `CREATE … IF NOT EXISTS` 空转却报 `created`,同一组织同一设置键可存两行,读设置时没有确定的胜者。 - **风险与回滚**:只动启动迁移在 PG 上的删除与判定;SQLite/MySQL 的建删语句与结果不变。有重复数据时照旧不删不并、保留旧键,只多报计数。回滚即回退本 PR。 - **先看**:`packages/metadata-protocol/src/migrations/partial-index-probe.ts`(`probeThenReplaceIndexPostgres` 与 `freePostgresIndexName`)、`identity-index.live-postgres.test.ts`、`sys-setting-identity-index.ts` 冲突分支。 - **两分钟验证**:`OS_TEST_POSTGRES_URL=postgres://… pnpm --filter @objectstack/metadata-protocol exec vitest run identity-index.live-postgres`,预期 7 个测试全过;在 `origin/main` 上同一命令 5 个红。 - **需要你做的**:无,席位落地。 ## What changes `probeThenReplaceIndex` (the shared seam both identity migrations use) gets a PostgreSQL arm, selected when the caller passes the table and the seam's knex client: 1. **The drop frees what actually holds the name.** On PostgreSQL the declared unique is a UNIQUE CONSTRAINT (`SqlDriver.syncDeclaredIndexes` → knex `table.unique()` → `ALTER TABLE … ADD CONSTRAINT … UNIQUE`). The replace step now runs `ALTER TABLE t DROP CONSTRAINT IF EXISTS name` then `DROP INDEX IF EXISTS name`, which is the spelling the driver's own `dropIndexIfExists` already uses (dialect-chosen, constraint first). No `CASCADE`. 2. **`created` means the definition is in place.** The probe's definition is read with `pg_get_indexdef(to_regclass(…))` before the probe is dropped; after the real create, the real name's definition is read the same way and must be equal (compared from ` ON ` onward). Anything else is `status: 'failed'`, `failedAt: 'verify'`, with the drop's refusal in `detail`, so each caller prints its existing ADR-0120 D4 `could not rebuild …` line naming what is not enforced, and the boot keeps running. 3. **Existing duplicates are reported with a count.** The `conflict` lines of both migrations now carry `(N duplicated key(s), held by M row(s))`, counted by wrapping each migration's own duplicate probe in `SELECT COUNT(*), SUM(duplicate_rows) FROM (…)`. Counts only, no row values. No row is deleted or merged; the previous key stays (unchanged behaviour). Both callers (`sys-setting-identity-index.ts`, `notification-preference-identity-index.ts`) pass `table` and `client`; `overlay-index.ts` passes neither and keeps the dialect-blind order. `read-probe.ts` exports its existing `catalogFamilyOf` so the two modules share one reading of which client is PostgreSQL. `driver-sql` is not touched. SQLite stays byte-for-byte on the probe, the drop, the create and the outcome: a unit test pins the identical statement stream for `sqlite3`, `better-sqlite3`, `mysql2`, an unnamed client, and a `pg` caller that names no table. The one addition on every dialect is the count query, run only after a `conflict` outcome. ## Tests - `identity-index.live-postgres.test.ts` (new, live PostgreSQL, same harness and isolation as `seed-tenancy-backfill.live-postgres.test.ts`; fixture constraints are the exact knex-compiled statements). Both tables: the constraint is replaced by the COALESCE index and the duplicate insert is refused (23505); a second run is quiet and identical; with duplicates present the result is `conflict`, the constraint stays, no row is deleted, and the line carries the count and no value; a name the drop cannot free (a foreign key depends on the constraint, so 2BP01 without `CASCADE`) is `failed`, never `created`. - `partial-index-probe.test.ts`: the PostgreSQL arm's exact statement order and no `CASCADE`; the verify failure naming the refusal; a probe whose definition cannot be read fails at `probe` before the real name is touched; the legacy order for every other client; `countDuplicateKeys` / `describeDuplicateKeys`. - `sys-setting-identity-index.test.ts`, `notification-preference-identity-index.test.ts` (SQLite): the conflict line carries the count. ## Acceptance notes - **CI lane.** The new live file is selected by name by the existing `Run the metadata-protocol migration statements against live MySQL and PostgreSQL` step (`vitest run live-mysql live-postgres`). That step lives in the `Temporal Conformance (live PG + MySQL)` job, whose `if:` excludes `pull_request` and `merge_group`, so its first CI run is `main`'s push battery after the merge. No new job or gate was added; the local live runs below are the pre-merge evidence. - The verify read-back runs only on PostgreSQL; MySQL never reaches the replace step (its dialect refuses the probe, `unsupported`). ## Verification Local PostgreSQL 16.15. Base = `origin/main` `5cc31c788`. <details><summary>Red on base: os dev boot on an empty PostgreSQL</summary> Boot log (`objectstack dev --seed-admin --no-watch -d postgres://…/os26630_red`, app-showcase, base build): ```text [sql-driver] DATABASE_ERROR — the backend refused a raw statement (2BP01). … cannot drop index uniq_sys_setting_organization_id_namespace_key_scope_user_id because constraint uniq_sys_setting_organization_id_namespace_key_scope_user_id on table sys_setting requires it [sql-driver] DATABASE_ERROR — the backend refused a raw statement (2BP01). … cannot drop index uniq_sys_notification_preference_a22d7d27 because constraint uniq_sys_notification_preference_a22d7d27 on table sys_notification_preference requires it ✓ Server is ready ``` `pg_indexes` / `pg_constraint` after the boot: ```text uniq_sys_setting_… ON public.sys_setting USING btree (organization_id, namespace, key, scope, user_id) uniq_sys_notification_preference_a22d7d27 ON public.sys_notification_preference USING btree (organization_id, user_id, topic, channel) pg_constraint: both names present, contype u ``` Copy of the tenant-scope `localization/timezone` row under a new id, in a transaction: `INSERT 0 1`, count 2, rolled back. The new live suite on the base source: 5 failed, 2 passed (7). </details> <details><summary>Green: same boot after the fix</summary> Three boots, no `2BP01` and no `[metadata-protocol]` line on any: (1) over the red database above (the upgrade path), (2) on an empty database, (3) a second boot over (2). Both databases afterwards: ```text uniq_sys_setting_… ON public.sys_setting USING btree (organization_id, namespace, key, scope, COALESCE(user_id, ''::character varying)) uniq_sys_notification_preference_a22d7d27 ON public.sys_notification_preference USING btree (organization_id, COALESCE(user_id, ''::character varying), topic, channel) constraints holding either name: 0 duplicate tenant-row insert: ERROR: duplicate key value violates unique constraint "uniq_sys_setting_organization_id_namespace_key_scope_user_id" ``` Conflict boot (constraint restored and one duplicate tenant row inserted, then booted on the fix): one `ERROR [metadata-protocol] cannot tighten 'uniq_sys_setting_…' on "sys_setting" — existing rows violate (organization_id, namespace, key, scope, COALESCE(user_id, '')) (1 duplicated key, held by 2 rows). The previous index is left in place …`, `Server is ready`, the duplicate row still present, the constraint still present, and neither the organization id nor the key value appears anywhere in the log. The new live suite on the fix: 7 passed (7). </details> <details><summary>Package suite, typecheck, lint, gates</summary> All at head `1d5f19a2b`; every `packages/*/vitest.repo-tests.json` project's `test:repo` also passes. - `pnpm --filter @objectstack/metadata-protocol test` with `OS_TEST_POSTGRES_URL` set (under the verify lock): `VERDICT command-exit 0`, Test Files 271 passed / 2 skipped (the two live-MySQL files, no MySQL here), Tests 21599 passed / 12 skipped. - `pnpm --filter @objectstack/metadata-protocol typecheck`: `VERDICT command-exit 0` (its `tsc` program lists the migration test files, 16 of them). - `eslint --no-inline-config packages/metadata-protocol/src/migrations/`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands` on this diff: 58 commands, each run with its exit code captured before any pipe. 57 exited 0 on the first pass. `check-plugin-teardown-shape.mjs --self-test` exited 3 on the shallow clone (its pinned fixture commit was missing); after `git fetch origin 621a487…` it exited 0 (48 cases). `--ran` reconciliation: `58 derived, 58 run, 0 NOT-MEASURED, 0 UNRUN`. - Not measured locally, by design: the CI type-check lanes and the path-scheduled CI jobs the derivation lists outside its total; the `Temporal Conformance` job (it does not run on PRs, see Acceptance notes). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5kZqq2RmtHXdiXnRqX --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kZqq2RmtHXdiXnRqX)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c8583f8 commit cee4b16

11 files changed

Lines changed: 834 additions & 13 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): on PostgreSQL, the NULL-safe row identity of `sys_setting` and `sys_notification_preference` now lands, and a tightening that did not land is reported instead of answered `created`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On PostgreSQL the declared unique both tables start with is a UNIQUE CONSTRAINT (the driver builds it with knex `table.unique()`), not a bare index. The boot migration that replaces it with the NULL-safe key ran `DROP INDEX` on the constraint's index, which PostgreSQL refuses (2BP01, printed on every boot), and then `CREATE UNIQUE INDEX IF NOT EXISTS` under the name the constraint still held, which succeeds as a no-op. Both migrations reported `created` while the plain, NULL-distinct key stayed: two tenant-scope or global-scope settings rows for one (organization, namespace, key) could coexist.
11+
12+
- **The drop.** On PostgreSQL the replace step now frees the name the way the driver's own `dropIndexIfExists` does: `ALTER TABLE … DROP CONSTRAINT IF EXISTS`, then `DROP INDEX IF EXISTS`. No `CASCADE`.
13+
- **The verdict.** On PostgreSQL `created` is answered only after the definition under the real name reads back (`pg_get_indexdef`) equal to the one the probe built. When it does not (something depends on the old constraint and the drop is refused), the boot prints the existing `[metadata-protocol] could not rebuild …` line naming what is not enforced, with the refusal, and keeps running.
14+
- **Existing duplicates.** When rows already break the NULL-safe key, nothing is deleted or merged and the old key stays, as before. The `cannot tighten …` line now also says how many keys are duplicated and how many rows hold them, on every dialect. It prints no row values.
15+
- SQLite and MySQL run the same probe, drop and create statements as before, with the same outcomes. The only new statement there is the count, and it runs only on a conflict.
Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #26630 — the NULL-safe row identity of `sys_setting` and
5+
* `sys_notification_preference`, LANDED on a live PostgreSQL.
6+
*
7+
* ## The defect this pins
8+
*
9+
* On PostgreSQL the declared unique both tables start with is a UNIQUE
10+
* CONSTRAINT, not a bare index: `SqlDriver.syncDeclaredIndexes` builds it with
11+
* knex's `table.unique()`, which compiles there to `ALTER TABLE … ADD
12+
* CONSTRAINT … UNIQUE`. The probe-first replacement then ran `DROP INDEX IF
13+
* EXISTS` on the constraint's index — refused, 2BP01 — and `CREATE UNIQUE INDEX
14+
* IF NOT EXISTS` under the name the constraint still held, which succeeds as a
15+
* no-op. Both migrations reported `created` and the plain, NULL-distinct key
16+
* stayed. Measured on published 18.2.0 against PostgreSQL 16: two tenant-scope
17+
* rows for one (organization, namespace, key) were accepted.
18+
*
19+
* SQLite never had the defect (knex emits a bare `CREATE UNIQUE INDEX` there),
20+
* which is why the SQLite suites stayed green with it fully present. Only a
21+
* server can answer what PostgreSQL does with the drop, so a server answers.
22+
*
23+
* ## The fixture is the driver's statement, compiled by knex
24+
*
25+
* `metadata-protocol` must not depend on a driver, so the declared constraint is
26+
* the exact text knex's PostgreSQL client compiles `table.unique(columns, {
27+
* indexName })` to — read off knex 3 for both tables:
28+
*
29+
* ```text
30+
* alter table "sys_setting" add constraint "uniq_sys_setting_organization_id_namespace_key_scope_user_id"
31+
* unique ("organization_id", "namespace", "key", "scope", "user_id")
32+
* ```
33+
*
34+
* ## Non-vacuity
35+
*
36+
* 1. the suite asserts it is talking to a real PostgreSQL, in its own schema;
37+
* 2. every fixture first asserts the declared name IS held by a constraint
38+
* (`pg_constraint`), the precondition the defect needs — without it a green
39+
* run would only show that a bare index can be dropped.
40+
*
41+
* ## Provisioning and isolation
42+
*
43+
* The sibling `seed-tenancy-backfill.live-postgres.test.ts`'s rules, unchanged:
44+
* `OS_TEST_POSTGRES_URL` or a named SKIP, `OS_EXPECT_LIVE_DIALECT_MATRIX=1`
45+
* turns a missing URL into a failure, and everything runs in this file's own
46+
* schema from `currentLiveMysqlDatabase()` (its header says why the MySQL-named
47+
* resolver). CI runs this file in the existing metadata-protocol live step,
48+
* whose `live-postgres` filter selects it by name.
49+
*/
50+
51+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
52+
import pg from 'pg';
53+
54+
import {
55+
ensureSysSettingIdentityIndex,
56+
SYS_SETTING_IDENTITY_INDEX_NAME,
57+
SYS_SETTING_IDENTITY_PROBE_INDEX_NAME,
58+
SYS_SETTING_TABLE,
59+
} from './sys-setting-identity-index.js';
60+
import {
61+
ensureNotificationPreferenceIdentityIndex,
62+
NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME,
63+
NOTIFICATION_PREFERENCE_TABLE,
64+
} from './notification-preference-identity-index.js';
65+
import { currentLiveMysqlDatabase } from './live-mysql-database.testkit.js';
66+
import type { IndexExec } from './partial-index-probe.js';
67+
68+
const PG_URL = process.env.OS_TEST_POSTGRES_URL;
69+
const EXPECT_LIVE = process.env.OS_EXPECT_LIVE_DIALECT_MATRIX === '1';
70+
const SCHEMA = currentLiveMysqlDatabase();
71+
72+
/** A value no report may print: settings rows can hold secrets. */
73+
const SECRET = 'os26630-secret-value';
74+
75+
if (!PG_URL && EXPECT_LIVE) {
76+
describe('#26630 live PostgreSQL', () => {
77+
it('OS_TEST_POSTGRES_URL must be set — this runner declared it provisioned a server', () => {
78+
throw new Error(
79+
'OS_EXPECT_LIVE_DIALECT_MATRIX=1 without OS_TEST_POSTGRES_URL: the live PostgreSQL cell for ' +
80+
'the identity-index migrations would have been skipped, and PostgreSQL is the one dialect ' +
81+
'on which they reported success for a no-op.',
82+
);
83+
});
84+
});
85+
}
86+
87+
describe.skipIf(!PG_URL)('#26630 identity indexes on a LIVE PostgreSQL', () => {
88+
let client: pg.Client;
89+
const exec: IndexExec = (sql: string) => client.query(sql);
90+
91+
const quietLogger = () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() });
92+
93+
const indexDef = async (name: string): Promise<string | undefined> => {
94+
const { rows } = await client.query<{ indexdef: string | null }>(
95+
`SELECT pg_get_indexdef(to_regclass('"${name}"')) AS indexdef`,
96+
);
97+
return rows[0]?.indexdef ?? undefined;
98+
};
99+
100+
const constraintHolds = async (table: string, name: string): Promise<boolean> => {
101+
const { rows } = await client.query(
102+
'SELECT 1 FROM pg_constraint WHERE conname = $1 AND conrelid = to_regclass($2)',
103+
[name, `"${table}"`],
104+
);
105+
return rows.length > 0;
106+
};
107+
108+
/** A tenant-scope settings row — `user_id` is NULL, as `SettingsService.set` writes it. */
109+
const insertSetting = (id: string) =>
110+
client.query(
111+
'INSERT INTO sys_setting (id, organization_id, namespace, key, scope, user_id, value) ' +
112+
"VALUES ($1, 'org_live', 'branding', 'workspace_name', 'tenant', NULL, $2)",
113+
[id, SECRET],
114+
);
115+
116+
const seedSysSetting = async (): Promise<void> => {
117+
await client.query('DROP TABLE IF EXISTS os26630_setting_ref');
118+
await client.query('DROP TABLE IF EXISTS sys_setting');
119+
await client.query(
120+
'CREATE TABLE sys_setting (id VARCHAR(64) PRIMARY KEY, organization_id VARCHAR(64) NOT NULL, ' +
121+
'namespace VARCHAR(255), key VARCHAR(255), scope VARCHAR(32), user_id VARCHAR(64), value TEXT)',
122+
);
123+
// The driver's statement, as knex compiles it (header).
124+
await client.query(
125+
`alter table "sys_setting" add constraint "${SYS_SETTING_IDENTITY_INDEX_NAME}" ` +
126+
'unique ("organization_id", "namespace", "key", "scope", "user_id")',
127+
);
128+
expect(await constraintHolds(SYS_SETTING_TABLE, SYS_SETTING_IDENTITY_INDEX_NAME)).toBe(true);
129+
};
130+
131+
beforeAll(async () => {
132+
client = new pg.Client({ connectionString: PG_URL });
133+
await client.connect();
134+
await client.query(`CREATE SCHEMA IF NOT EXISTS "${SCHEMA}"`);
135+
await client.query(`SET search_path TO "${SCHEMA}"`);
136+
});
137+
138+
afterAll(async () => {
139+
if (!client) return;
140+
await client.query('SET search_path TO "$user", public');
141+
await client.query(`DROP SCHEMA IF EXISTS "${SCHEMA}" CASCADE`);
142+
await client.end();
143+
});
144+
145+
it("is pointed at a real PostgreSQL, in this file's own schema — without this the run proves nothing", async () => {
146+
const { rows } = await client.query<{ version: string; search_path: string }>(
147+
"SELECT version() AS version, current_setting('search_path') AS search_path",
148+
);
149+
// eslint-disable-next-line no-console
150+
console.log(`[#26630] live ${String(rows[0]!.version).split(',')[0]} search_path=${rows[0]!.search_path}`);
151+
expect(rows[0]!.version).toContain('PostgreSQL');
152+
expect(rows[0]!.search_path).toContain(SCHEMA);
153+
});
154+
155+
describe('sys_setting', () => {
156+
beforeEach(seedSysSetting);
157+
158+
it('replaces the declared CONSTRAINT with the NULL-safe index, quietly, and it refuses the duplicate', async () => {
159+
const logger = quietLogger();
160+
const result = await ensureSysSettingIdentityIndex(exec, logger, { client: 'pg' });
161+
162+
expect(result).toEqual({ status: 'created' });
163+
expect(logger.error).not.toHaveBeenCalled();
164+
expect(logger.warn).not.toHaveBeenCalled();
165+
// The constraint is gone and the name now holds the NULL-safe key.
166+
expect(await constraintHolds(SYS_SETTING_TABLE, SYS_SETTING_IDENTITY_INDEX_NAME)).toBe(false);
167+
expect(await indexDef(SYS_SETTING_IDENTITY_INDEX_NAME)).toMatch(
168+
/^CREATE UNIQUE INDEX \S+ ON \S+ USING btree \(organization_id, namespace, key, scope, COALESCE\(user_id, ''::character varying\)\)$/,
169+
);
170+
expect(await indexDef(SYS_SETTING_IDENTITY_PROBE_INDEX_NAME)).toBeUndefined();
171+
172+
// The behaviour the key exists for: the second tenant-scope row for
173+
// one (organization, namespace, key) is refused, SQLSTATE 23505.
174+
await insertSetting('s1');
175+
await expect(insertSetting('s2')).rejects.toMatchObject({ code: '23505' });
176+
});
177+
178+
it('a second boot over the same database is quiet and idempotent', async () => {
179+
await ensureSysSettingIdentityIndex(exec, quietLogger(), { client: 'pg' });
180+
const first = await indexDef(SYS_SETTING_IDENTITY_INDEX_NAME);
181+
182+
const logger = quietLogger();
183+
expect(await ensureSysSettingIdentityIndex(exec, logger, { client: 'pg' })).toEqual({
184+
status: 'created',
185+
});
186+
expect(logger.error).not.toHaveBeenCalled();
187+
expect(logger.warn).not.toHaveBeenCalled();
188+
expect(await indexDef(SYS_SETTING_IDENTITY_INDEX_NAME)).toBe(first);
189+
});
190+
191+
it('duplicates already present: refuses, keeps the constraint, deletes nothing, and reports a count without values', async () => {
192+
await insertSetting('d1');
193+
await insertSetting('d2');
194+
const logger = quietLogger();
195+
196+
const result = await ensureSysSettingIdentityIndex(exec, logger, { client: 'pg' });
197+
198+
expect(result.status).toBe('conflict');
199+
expect(await constraintHolds(SYS_SETTING_TABLE, SYS_SETTING_IDENTITY_INDEX_NAME)).toBe(true);
200+
expect(await indexDef(SYS_SETTING_IDENTITY_PROBE_INDEX_NAME)).toBeUndefined();
201+
const { rows } = await client.query('SELECT id FROM sys_setting ORDER BY id');
202+
expect(rows.map((r) => r.id)).toEqual(['d1', 'd2']);
203+
204+
expect(logger.error).toHaveBeenCalledTimes(1);
205+
const [message, error] = logger.error.mock.calls[0]!;
206+
expect(message).toContain(`"${SYS_SETTING_TABLE}"`);
207+
expect(message).toContain('organization_id, namespace, key, scope');
208+
expect(message).toContain('(1 duplicated key, held by 2 rows)');
209+
expect(`${message}\n${(error as Error).message}`).not.toContain(SECRET);
210+
});
211+
212+
it('a name the drop cannot free is reported as NOT enforced — never as created', async () => {
213+
// Something depends on the declared constraint, so PostgreSQL refuses
214+
// to drop it (2BP01) and, without CASCADE, must keep refusing. The
215+
// `IF NOT EXISTS` create then succeeds as a no-op: the exact shape
216+
// that used to be answered `created`.
217+
await client.query(
218+
'CREATE TABLE os26630_setting_ref (organization_id VARCHAR(64), namespace VARCHAR(255), ' +
219+
'key VARCHAR(255), scope VARCHAR(32), user_id VARCHAR(64), ' +
220+
'FOREIGN KEY (organization_id, namespace, key, scope, user_id) ' +
221+
'REFERENCES sys_setting (organization_id, namespace, key, scope, user_id))',
222+
);
223+
const logger = quietLogger();
224+
225+
const result = await ensureSysSettingIdentityIndex(exec, logger, { client: 'pg' });
226+
227+
expect(result.status).toBe('failed');
228+
expect(result.detail).toContain('cannot drop');
229+
expect(await constraintHolds(SYS_SETTING_TABLE, SYS_SETTING_IDENTITY_INDEX_NAME)).toBe(true);
230+
expect(logger.error).toHaveBeenCalledTimes(1);
231+
const [message] = logger.error.mock.calls[0]!;
232+
expect(message).toContain(SYS_SETTING_IDENTITY_INDEX_NAME);
233+
expect(message).toContain('duplicate tenant-scope and global-scope settings rows can still be created');
234+
});
235+
});
236+
237+
describe('sys_notification_preference', () => {
238+
beforeEach(async () => {
239+
await client.query('DROP TABLE IF EXISTS sys_notification_preference');
240+
await client.query(
241+
'CREATE TABLE sys_notification_preference (id VARCHAR(64) PRIMARY KEY, ' +
242+
'organization_id VARCHAR(64) NOT NULL, user_id VARCHAR(64), topic VARCHAR(255), ' +
243+
'channel VARCHAR(64))',
244+
);
245+
await client.query(
246+
`alter table "sys_notification_preference" add constraint ` +
247+
`"${NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME}" ` +
248+
'unique ("organization_id", "user_id", "topic", "channel")',
249+
);
250+
expect(
251+
await constraintHolds(NOTIFICATION_PREFERENCE_TABLE, NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME),
252+
).toBe(true);
253+
});
254+
255+
const insertPreference = (id: string) =>
256+
client.query(
257+
'INSERT INTO sys_notification_preference (id, organization_id, user_id, topic, channel) ' +
258+
"VALUES ($1, 'org_live', NULL, 'record.assigned', 'email')",
259+
[id],
260+
);
261+
262+
it('replaces the declared CONSTRAINT with the NULL-safe index, and it refuses the duplicate', async () => {
263+
const logger = quietLogger();
264+
expect(await ensureNotificationPreferenceIdentityIndex(exec, logger, { client: 'pg' })).toEqual({
265+
status: 'created',
266+
});
267+
expect(logger.error).not.toHaveBeenCalled();
268+
expect(
269+
await constraintHolds(NOTIFICATION_PREFERENCE_TABLE, NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME),
270+
).toBe(false);
271+
expect(await indexDef(NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME)).toContain('COALESCE(user_id');
272+
273+
await insertPreference('p1');
274+
await expect(insertPreference('p2')).rejects.toMatchObject({ code: '23505' });
275+
});
276+
277+
it('duplicates already present: refuses, keeps the constraint, and reports a count', async () => {
278+
await insertPreference('p1');
279+
await insertPreference('p2');
280+
await insertPreference('p3');
281+
const logger = quietLogger();
282+
283+
expect((await ensureNotificationPreferenceIdentityIndex(exec, logger, { client: 'pg' })).status).toBe(
284+
'conflict',
285+
);
286+
expect(
287+
await constraintHolds(NOTIFICATION_PREFERENCE_TABLE, NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME),
288+
).toBe(true);
289+
const { rows } = await client.query('SELECT COUNT(*)::int AS n FROM sys_notification_preference');
290+
expect(rows[0].n).toBe(3);
291+
const [message] = logger.error.mock.calls[0]!;
292+
expect(message).toContain('(1 duplicated key, held by 3 rows)');
293+
});
294+
});
295+
});

‎packages/metadata-protocol/src/migrations/notification-preference-identity-index.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,12 +163,16 @@ describe('sys_notification_preference: one admin-global default per key', () =>
163163

164164
it('reports once at ERROR, naming the index, the consequence, and the query that lists the rows', async () => {
165165
const logger = { error: vi.fn(), warn: vi.fn(), info: vi.fn() };
166-
await ensureNotificationPreferenceIdentityIndex(exec, logger);
166+
// [#26630] A seam that answers a SELECT, so the count has rows to read.
167+
const answering: IndexExec = async (sql: string) =>
168+
/^\s*SELECT/i.test(sql) ? db.prepare(sql).all() : db.exec(sql);
169+
await ensureNotificationPreferenceIdentityIndex(answering, logger);
167170
expect(logger.error).toHaveBeenCalledTimes(1);
168171
expect(logger.warn).not.toHaveBeenCalled();
169172
const [message] = logger.error.mock.calls[0]!;
170173
expect(message).toContain(NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME);
171174
expect(message).toContain('The previous index is left in place');
175+
expect(message).toContain('(1 duplicated key, held by 2 rows)');
172176
expect(message).toContain('no row is discarded automatically');
173177
expect(message).toContain(buildNotificationPreferenceDuplicateProbeSql());
174178
expect(message).toContain('os migrate duplicates');

0 commit comments

Comments
 (0)