Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(events): recordId and UPDATE pairing use the whole row key (#1866)

Sid0a3a7b49f827
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index 2b24cb9277..b257739af9 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -53,7 +53,7 @@ behaviour arrived, not where to read the current definition. Details:
`handlerType` CHECK now allows all six: `WEBHOOK, WORKFLOW, SYNC, SEARCH, AUDIT, EMBEDDING` (widened across `20260204080000` → `20260212152709` → `20260326120000`).
### PL/pgSQL functions (in `_event_system_impl` + later)
-- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads `event-system/functions/dispatch_event_batch.sql` and fails when the two lists diverge.
+- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). `recordId` comes from the same key: `id` when the primary key has one, otherwise every primary-key column joined by `:` (`workCenterProcess`, `jobOperationDependency`); a table with no primary key keeps its single legacy column, because the audit log files `itemPlanning` under its `itemId`. `supabase/tests/event-record-id.test.sql` checks this and the UPDATE pairing for every evented table. `get_primary_key_columns()` read a unique index's columns from position 1 of a 0-based `indkey` until that test found it: `itemPlanning` paired on `locationId` alone and a bulk UPDATE queued rows × rows events. Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads `event-system/functions/dispatch_event_batch.sql` and fails when the two lists diverge.
- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).
- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).
- Both dispatchers are SECURITY DEFINER (`20260925121735`), so interceptors run as the owner on every write. Write a new interceptor as **SECURITY INVOKER**: it still runs as the owner from the dispatcher, but a direct `/rpc/<interceptor>` call with a forged payload runs under the caller's RLS. A SECURITY DEFINER interceptor is callable by anyone with the anon key as the owner — `public-definer-function-authorizes-caller` fails on it.
diff --git a/packages/database/src/event-dispatch.test.ts b/packages/database/src/event-dispatch.test.ts
index 54022eb411..10b5ecfe5b 100644
--- a/packages/database/src/event-dispatch.test.ts
+++ b/packages/database/src/event-dispatch.test.ts
@@ -38,3 +38,29 @@ describe.each(files)("%s", (file) => {
expect(columns.sort()).toEqual([...auditConfig.skipFields].sort());
});
});
+
+describe("dispatch_event_batch recordId", () => {
+ const read = (name: string) =>
+ readFileSync(
+ fileURLToPath(
+ new URL(`event-system/functions/${name}.sql`, import.meta.url)
+ ),
+ "utf8"
+ );
+
+ // Behaviour is proven against a database, for every evented table, by
+ // supabase/tests/event-record-id.test.sql. These keep the two edits that
+ // test depends on from being reverted where no database runs.
+ it("is built from the whole primary key, not one column of it", () => {
+ const sql = read("dispatch_event_batch");
+ expect(sql).toContain("pk_columns := public.get_primary_key_columns(");
+ expect(sql.match(/''recordId'', %s,/g)).toHaveLength(3);
+ expect(sql).toContain("IF 'id' = ANY(pk_columns)");
+ });
+
+ it("reads a unique index's key columns from position 0", () => {
+ const sql = read("get_primary_key_columns");
+ expect(sql).toContain("[0:i.indnkeyatts - 1]");
+ expect(sql).not.toContain("[1:i.indnkeyatts]");
+ });
+});
diff --git a/packages/database/src/event-system/functions/dispatch_event_batch.sql b/packages/database/src/event-system/functions/dispatch_event_batch.sql
index 60293a23db..ce43111718 100644
--- a/packages/database/src/event-system/functions/dispatch_event_batch.sql
+++ b/packages/database/src/event-system/functions/dispatch_event_batch.sql
@@ -11,8 +11,9 @@ DECLARE
has_subs BOOLEAN;
current_actor_id TEXT;
current_workflow_run_id TEXT;
- pk_column TEXT;
+ pk_columns TEXT[];
pk_join TEXT;
+ record_id_expr TEXT;
query_text TEXT;
did_enqueue BOOLEAN := FALSE;
ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
@@ -44,13 +45,31 @@ BEGIN
-- Looked up only once a subscription exists: almost no company subscribes
-- to most tables, and this catalog read ran on every write statement.
- pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+ pk_columns := public.get_primary_key_columns(TG_TABLE_NAME);
-- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
-- on tables with composite identity.
SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
INTO pk_join
- FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;
+ FROM unnest(pk_columns) AS col;
+
+ -- recordId names one row. "id" does that wherever it is part of the key
+ -- ((id, companyId) tables); a primary key without one is every column joined
+ -- by ':', since a single column of it is shared by many rows. A table with no
+ -- primary key keeps the one column it always sent: the audit log files
+ -- itemPlanning (unique on itemId + locationId) under its itemId.
+ -- %1$s is the row alias.
+ IF 'id' = ANY(pk_columns) THEN
+ record_id_expr := '%1$s."id"::TEXT';
+ ELSIF EXISTS (
+ SELECT 1 FROM pg_index WHERE indrelid = TG_RELID AND indisprimary
+ ) THEN
+ SELECT 'concat_ws('':'', ' || string_agg(format('%%1$s.%I::TEXT', col), ', ') || ')'
+ INTO record_id_expr
+ FROM unnest(pk_columns) AS col;
+ ELSE
+ record_id_expr := format('%%1$s.%I::TEXT', public.get_primary_key_column(TG_TABLE_NAME));
+ END IF;
FOR sub IN
SELECT * FROM "eventSystemSubscription"
@@ -76,7 +95,7 @@ BEGIN
''event'', jsonb_build_object(
''table'', $7,
''operation'', $8,
- ''recordId'', t.%I::TEXT,
+ ''recordId'', %s,
''new'', row_to_json(t)::jsonb,
''old'', null,
''timestamp'', clock_timestamp()
@@ -86,7 +105,7 @@ BEGIN
FROM batched_new t
WHERE t."companyId" = $5
AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
- ', pk_column);
+ ', format(record_id_expr, 't'));
EXECUTE query_text INTO msg_batch
USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
@@ -107,7 +126,7 @@ BEGIN
''event'', jsonb_build_object(
''table'', $7,
''operation'', $8,
- ''recordId'', t.%I::TEXT,
+ ''recordId'', %s,
''new'', null,
''old'', row_to_json(t)::jsonb,
''timestamp'', clock_timestamp()
@@ -117,7 +136,7 @@ BEGIN
FROM batched_old t
WHERE t."companyId" = $5
AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
- ', pk_column);
+ ', format(record_id_expr, 't'));
EXECUTE query_text INTO msg_batch
USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
@@ -138,7 +157,7 @@ BEGIN
''event'', jsonb_build_object(
''table'', $7,
''operation'', $8,
- ''recordId'', n.%I::TEXT,
+ ''recordId'', %s,
''new'', row_to_json(n)::jsonb,
''old'', row_to_json(o)::jsonb,
''timestamp'', clock_timestamp()
@@ -150,7 +169,7 @@ BEGIN
WHERE n."companyId" = $5
AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
- ', pk_column, pk_join);
+ ', format(record_id_expr, 'n'), pk_join);
EXECUTE query_text INTO msg_batch
USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
diff --git a/packages/database/src/event-system/functions/get_primary_key_columns.sql b/packages/database/src/event-system/functions/get_primary_key_columns.sql
index 7615d1c4d2..91c37c0d2b 100644
--- a/packages/database/src/event-system/functions/get_primary_key_columns.sql
+++ b/packages/database/src/event-system/functions/get_primary_key_columns.sql
@@ -16,12 +16,13 @@ BEGIN
-- No PK: key columns of the smallest valid, non-partial, non-expression
-- unique index. Partial/expression indexes don't guarantee row identity for
-- every row, and INCLUDE columns (positions past indnkeyatts) aren't part of
- -- the uniqueness constraint — the slice keeps key columns only.
+ -- the uniqueness constraint — the slice keeps key columns only. indkey is an
+ -- int2vector, so its first element is at 0: [1:n] dropped the first column.
IF pk_columns IS NULL THEN
SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
FROM pg_index i
JOIN pg_attribute a ON a.attrelid = i.indrelid
- AND a.attnum = ANY ((i.indkey::int2[])[1:i.indnkeyatts])
+ AND a.attnum = ANY ((i.indkey::int2[])[0:i.indnkeyatts - 1])
WHERE i.indexrelid = (
SELECT i2.indexrelid
FROM pg_index i2
diff --git a/packages/database/supabase/migrations/20261008124647_event-record-id-full-key.sql b/packages/database/supabase/migrations/20261008124647_event-record-id-full-key.sql
new file mode 100644
index 0000000000..24206cdd1c
--- /dev/null
+++ b/packages/database/supabase/migrations/20261008124647_event-record-id-full-key.sql
@@ -0,0 +1,250 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ current_workflow_run_id TEXT;
+ pk_columns TEXT[];
+ pk_join TEXT;
+ record_id_expr TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+BEGIN
+ current_actor_id := auth.uid()::TEXT;
+ current_workflow_run_id :=
+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ -- Looked up only once a subscription exists: almost no company subscribes
+ -- to most tables, and this catalog read ran on every write statement.
+ pk_columns := public.get_primary_key_columns(TG_TABLE_NAME);
+
+ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
+ -- on tables with composite identity.
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(pk_columns) AS col;
+
+ -- recordId names one row. "id" does that wherever it is part of the key
+ -- ((id, companyId) tables); a primary key without one is every column joined
+ -- by ':', since a single column of it is shared by many rows. A table with no
+ -- primary key keeps the one column it always sent: the audit log files
+ -- itemPlanning (unique on itemId + locationId) under its itemId.
+ -- %1$s is the row alias.
+ IF 'id' = ANY(pk_columns) THEN
+ record_id_expr := '%1$s."id"::TEXT';
+ ELSIF EXISTS (
+ SELECT 1 FROM pg_index WHERE indrelid = TG_RELID AND indisprimary
+ ) THEN
+ SELECT 'concat_ws('':'', ' || string_agg(format('%%1$s.%I::TEXT', col), ', ') || ')'
+ INTO record_id_expr
+ FROM unnest(pk_columns) AS col;
+ ELSE
+ record_id_expr := format('%%1$s.%I::TEXT', public.get_primary_key_column(TG_TABLE_NAME));
+ END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
+ ', format(record_id_expr, 'n'), pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id,
+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
+ ignored_columns;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
+ -- bulk import posts a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_primary_key_columns(p_table_name text)
+ RETURNS text[]
+ LANGUAGE plpgsql
+ STABLE
+AS $function$
+DECLARE
+ pk_columns TEXT[];
+BEGIN
+ -- All columns of the primary key
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary;
+
+ -- No PK: key columns of the smallest valid, non-partial, non-expression
+ -- unique index. Partial/expression indexes don't guarantee row identity for
+ -- every row, and INCLUDE columns (positions past indnkeyatts) aren't part of
+ -- the uniqueness constraint — the slice keeps key columns only. indkey is an
+ -- int2vector, so its first element is at 0: [1:n] dropped the first column.
+ IF pk_columns IS NULL THEN
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
+ AND a.attnum = ANY ((i.indkey::int2[])[0:i.indnkeyatts - 1])
+ WHERE i.indexrelid = (
+ SELECT i2.indexrelid
+ FROM pg_index i2
+ WHERE i2.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i2.indisunique
+ AND i2.indisvalid
+ AND i2.indpred IS NULL
+ AND i2.indexprs IS NULL
+ ORDER BY i2.indnkeyatts ASC
+ LIMIT 1
+ );
+ END IF;
+
+ -- Last resort: the legacy single-column resolver
+ IF pk_columns IS NULL OR array_length(pk_columns, 1) IS NULL THEN
+ pk_columns := ARRAY[public.get_primary_key_column(p_table_name)];
+ END IF;
+
+ RETURN pk_columns;
+END;
+$function$;
diff --git a/packages/database/supabase/tests/event-record-id.test.sql b/packages/database/supabase/tests/event-record-id.test.sql
new file mode 100644
index 0000000000..34ed50e353
--- /dev/null
+++ b/packages/database/supabase/tests/event-record-id.test.sql
@@ -0,0 +1,214 @@
+-- An event's recordId, and the pairing of an UPDATE's old and new rows, for
+-- EVERY table that queues events, on INSERT, UPDATE and DELETE.
+--
+-- primary key has "id" -> recordId is the id ((id, companyId) tables)
+-- primary key without "id" -> every key column joined by ':'
+-- no primary key -> the one column it always sent (the audit log
+-- files itemPlanning under its itemId)
+--
+-- Each table is exercised through a temp table of the same name, which shadows
+-- it: same columns, defaults, primary key and unique indexes, but no foreign
+-- keys, so no fixtures are needed and no real row is touched. The real
+-- dispatch_event_batch() runs on it and queues to the real pgmq queue.
+--
+-- Run from the repository root against an existing local database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/event-record-id.test.sql
+-- Everything is confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '120s';
+SET LOCAL client_min_messages = warning;
+
+DO $proof$
+DECLARE
+ company text;
+ -- Evented tables with no primary key, and the column their recordId is.
+ keyless constant jsonb := '{"itemCost":"itemId","itemPlanning":"itemId","itemUnitSalePrice":"itemId"}';
+ row_count constant int := 4;
+ tbl text;
+ real oid;
+ pk text[];
+ key_cols text[];
+ expected_cols text[];
+ col record;
+ cols text;
+ vals text;
+ value text;
+ op text;
+ events int;
+ wrong int;
+ distinct_ids int;
+ tables_checked int := 0;
+ composite_checked int := 0;
+BEGIN
+ SELECT "id" INTO company FROM "company" ORDER BY "id" LIMIT 1;
+ ASSERT company IS NOT NULL, 'the local database has a company';
+
+ CREATE TEMP TABLE queued_before ON COMMIT DROP AS
+ SELECT msg_id FROM pgmq.q_event_system;
+
+ FOR tbl, real IN
+ SELECT c.relname::text, c.oid
+ FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid
+ WHERE t.tgname LIKE 'trg_event_async_ins_%'
+ AND c.relnamespace = 'public'::regnamespace
+ ORDER BY 1
+ LOOP
+ SELECT array_agg(a.attname::text ORDER BY a.attnum) INTO pk
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey)
+ WHERE i.indrelid = real AND i.indisprimary;
+
+ IF pk IS NULL THEN
+ ASSERT keyless ? tbl,
+ format('%s queues events but has no primary key: decide its recordId and add it to this test', tbl);
+ expected_cols := ARRAY[keyless->>tbl];
+ ELSIF 'id' = ANY (pk) THEN
+ expected_cols := ARRAY['id'];
+ ELSE
+ expected_cols := pk;
+ END IF;
+
+ EXECUTE format(
+ 'CREATE TEMP TABLE %1$I (LIKE public.%1$I INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING IDENTITY INCLUDING INDEXES) ON COMMIT DROP',
+ tbl);
+ real := format('pg_temp.%I', tbl)::regclass;
+
+ -- The columns that identify a row, read from the catalog here rather than
+ -- from the function under test: the primary key, else the key columns of
+ -- the smallest plain unique index, else the keyless table's one column.
+ key_cols := pk;
+ IF key_cols IS NULL THEN
+ SELECT array_agg(a.attname::text ORDER BY a.attnum) INTO key_cols
+ FROM pg_index i
+ CROSS JOIN LATERAL unnest(i.indkey::int2[]) WITH ORDINALITY AS k(attnum, pos)
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
+ WHERE k.pos <= i.indnkeyatts
+ AND i.indexrelid = (
+ SELECT i2.indexrelid FROM pg_index i2
+ WHERE i2.indrelid = real AND i2.indisunique AND i2.indisvalid
+ AND i2.indpred IS NULL AND i2.indexprs IS NULL
+ ORDER BY i2.indnkeyatts LIMIT 1);
+ END IF;
+ key_cols := COALESCE(key_cols, expected_cols);
+ ASSERT public.get_primary_key_columns(tbl) = key_cols,
+ format('%s: get_primary_key_columns returned %s, the row identity is %s',
+ tbl, public.get_primary_key_columns(tbl), key_cols);
+
+ -- Unique indexes other than the key would only reject the generated rows
+ IF pk IS NOT NULL THEN
+ FOR value IN
+ SELECT CASE WHEN c.conname IS NULL
+ THEN format('DROP INDEX %s', i.indexrelid::regclass)
+ ELSE format('ALTER TABLE pg_temp.%I DROP CONSTRAINT %I', tbl, c.conname) END
+ FROM pg_index i
+ LEFT JOIN pg_constraint c ON c.conindid = i.indexrelid AND c.conrelid = i.indrelid
+ WHERE i.indrelid = real AND NOT i.indisprimary
+ LOOP
+ EXECUTE value;
+ END LOOP;
+ END IF;
+
+ EXECUTE format(
+ 'CREATE TRIGGER probe_ins AFTER INSERT ON pg_temp.%1$I REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT EXECUTE FUNCTION public.dispatch_event_batch();
+ CREATE TRIGGER probe_upd AFTER UPDATE ON pg_temp.%1$I REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION public.dispatch_event_batch();
+ CREATE TRIGGER probe_del AFTER DELETE ON pg_temp.%1$I REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT EXECUTE FUNCTION public.dispatch_event_batch();',
+ tbl);
+
+ INSERT INTO "eventSystemSubscription"
+ ("name", "companyId", "table", "operations", "handlerType", "config", "filter", "active")
+ VALUES ('record-id-probe', company, tbl, ARRAY['INSERT', 'UPDATE', 'DELETE'],
+ 'WEBHOOK', '{"url":"http://record-id-probe.invalid"}', '{}', TRUE);
+
+ -- Four rows in one statement. Across a composite key they are
+ -- (k1,s) (k2,s) (k3,o3) (k1,o4): two share the first column and two share
+ -- the rest, so pairing on any single column of the key multiplies events.
+ cols := NULL; vals := NULL;
+ FOR col IN
+ SELECT a.attname::text AS name, t.typname::text AS typ, t.typtype::text AS typtype,
+ t.typcategory::text AS cat, a.atttypid AS typid,
+ a.attname = ANY (key_cols) AS is_key,
+ array_position(key_cols, a.attname::text) AS key_pos,
+ (a.attnotnull AND NOT a.atthasdef AND a.attidentity = '') AS required
+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid
+ WHERE a.attrelid = real AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = ''
+ ORDER BY a.attnum
+ LOOP
+ IF col.name = 'companyId' THEN
+ value := quote_literal(company);
+ ELSIF col.is_key AND col.cat = 'S' THEN
+ IF (SELECT count(*) FROM unnest(key_cols) k WHERE k <> 'companyId') = 1 THEN
+ value := $v$'k' || n$v$;
+ ELSIF col.key_pos = (SELECT min(array_position(key_cols, k)) FROM unnest(key_cols) k WHERE k <> 'companyId') THEN
+ value := $v$CASE n WHEN 4 THEN 'k1' ELSE 'k' || n END$v$;
+ ELSE
+ value := $v$CASE WHEN n <= 2 THEN 's' ELSE 'o' || n END$v$;
+ END IF;
+ ELSIF col.is_key AND col.cat = 'N' THEN
+ value := 'n';
+ ELSIF NOT col.required THEN
+ CONTINUE;
+ ELSIF col.cat = 'S' THEN value := $v$'p' || n$v$;
+ ELSIF col.cat = 'N' THEN value := 'n';
+ ELSIF col.cat = 'B' THEN value := 'false';
+ ELSIF col.cat = 'D' THEN value := 'now()';
+ ELSIF col.cat = 'A' THEN value := $v$'{}'$v$;
+ ELSIF col.typ IN ('json', 'jsonb') THEN value := $v$'{}'$v$;
+ ELSIF col.typ = 'uuid' THEN value := 'gen_random_uuid()';
+ ELSIF col.typtype = 'e' THEN
+ value := quote_literal((SELECT enumlabel FROM pg_enum WHERE enumtypid = col.typid ORDER BY enumsortorder LIMIT 1));
+ ELSE
+ RAISE EXCEPTION '%.%: no generated value for type %', tbl, col.name, col.typ;
+ END IF;
+ cols := concat_ws(', ', cols, quote_ident(col.name));
+ vals := concat_ws(', ', vals, format('(%s)::%s', value, col.typid::regtype));
+ END LOOP;
+
+ EXECUTE format('INSERT INTO pg_temp.%I (%s) SELECT %s FROM generate_series(1, %s) n',
+ tbl, cols, vals, row_count);
+ EXECUTE format('UPDATE pg_temp.%I SET "companyId" = "companyId"', tbl);
+ EXECUTE format('DELETE FROM pg_temp.%I', tbl);
+
+ FOREACH op IN ARRAY ARRAY['INSERT', 'UPDATE', 'DELETE'] LOOP
+ SELECT count(*),
+ count(DISTINCT e.record_id),
+ count(*) FILTER (WHERE e.record_id IS DISTINCT FROM (
+ SELECT string_agg(e.record->>k.col, ':' ORDER BY k.ord)
+ FROM unnest(expected_cols) WITH ORDINALITY AS k(col, ord)))
+ INTO events, distinct_ids, wrong
+ FROM (
+ SELECT message->'event'->>'recordId' AS record_id,
+ CASE WHEN op = 'DELETE' THEN message->'event'->'old'
+ ELSE message->'event'->'new' END AS record
+ FROM pgmq.q_event_system
+ WHERE msg_id NOT IN (SELECT msg_id FROM queued_before)
+ AND message->'event'->>'table' = tbl
+ AND message->'handlerConfig'->>'url' = 'http://record-id-probe.invalid'
+ AND message->'event'->>'operation' = op
+ ) e;
+
+ ASSERT events = row_count,
+ format('%s %s: %s rows queued %s events', tbl, op, row_count, events);
+ ASSERT wrong = 0,
+ format('%s %s: %s of %s events carry a recordId that is not %s', tbl, op, wrong, events, expected_cols);
+ -- A key names one row, so its recordIds are distinct. A keyless table's
+ -- single column is shared (two itemPlanning rows of one item).
+ ASSERT pk IS NULL OR distinct_ids = row_count,
+ format('%s %s: %s events share %s recordIds', tbl, op, events, distinct_ids);
+ END LOOP;
+
+ tables_checked := tables_checked + 1;
+ IF array_length(key_cols, 1) > 1 THEN composite_checked := composite_checked + 1; END IF;
+ END LOOP;
+
+ ASSERT tables_checked > 50, format('only %s evented tables found', tables_checked);
+ SET LOCAL client_min_messages = notice;
+ RAISE NOTICE 'ok: % evented tables x INSERT/UPDATE/DELETE, % with a multi-column key',
+ tables_checked, composite_checked;
+END;
+$proof$;
+
+ROLLBACK;