@pgxsinkit/server 0.1.32 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/bin/pgxsinkit-generate.mjs +25 -0
- package/dist/cli/generate.d.ts +14 -2
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/electric-proxy.d.ts +30 -2
- package/dist/electric-proxy.d.ts.map +1 -1
- package/dist/index.d.ts +56 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3936 -937
- package/dist/index.js.map +40 -25
- package/dist/migrations/utilities.d.ts +13 -0
- package/dist/migrations/utilities.d.ts.map +1 -0
- package/dist/mutations/plpgsql-apply.d.ts +36 -0
- package/dist/mutations/plpgsql-apply.d.ts.map +1 -0
- package/dist/mutations/route.d.ts +64 -0
- package/dist/mutations/route.d.ts.map +1 -0
- package/dist/mutations/types.d.ts +4 -0
- package/dist/mutations/types.d.ts.map +1 -0
- package/dist/operations-log/ddl.d.ts +6 -0
- package/dist/operations-log/ddl.d.ts.map +1 -1
- package/dist/operations-log/schema.d.ts +2 -32
- package/dist/operations-log/schema.d.ts.map +1 -1
- package/dist/operations-log/types.d.ts +1 -5
- package/dist/operations-log/types.d.ts.map +1 -1
- package/dist/operations-log/writer.d.ts.map +1 -1
- package/dist/router.d.ts +22 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/sql-state.d.ts +23 -0
- package/dist/sql-state.d.ts.map +1 -0
- package/package.json +11 -6
- package/skills/deploying/SKILL.md +162 -0
- package/src/cli/generate.ts +292 -21
- package/src/electric-proxy.ts +280 -45
- package/src/index.ts +146 -59
- package/src/migrations/utilities.ts +25 -0
- package/src/mutations/plpgsql-apply.ts +658 -0
- package/src/mutations/route.ts +1176 -0
- package/src/mutations/{bulk/types.ts → types.ts} +0 -2
- package/src/operations-log/ddl.ts +13 -3
- package/src/operations-log/schema.ts +9 -6
- package/src/operations-log/types.ts +1 -7
- package/src/operations-log/writer.ts +0 -2
- package/src/router.ts +109 -0
- package/src/sql-state.ts +59 -0
- package/dist/mutations/bulk/plpgsql-strategy.d.ts +0 -17
- package/dist/mutations/bulk/plpgsql-strategy.d.ts.map +0 -1
- package/dist/mutations/bulk/route.d.ts +0 -7
- package/dist/mutations/bulk/route.d.ts.map +0 -1
- package/dist/mutations/bulk/types.d.ts +0 -5
- package/dist/mutations/bulk/types.d.ts.map +0 -1
- package/src/mutations/bulk/plpgsql-strategy.ts +0 -370
- package/src/mutations/bulk/route.ts +0 -580
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
import { getTableName, sql } from "drizzle-orm";
|
|
2
|
+
import { getTableConfig, type AnyPgTable, type PgAsyncDatabase, type PgQueryResultHKT } from "drizzle-orm/pg-core";
|
|
3
|
+
import { getColumns } from "drizzle-orm/utils";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
CLOCK_US_CALL_SQL_TEXT,
|
|
7
|
+
escapeSqlLiteral as toSqlLiteral,
|
|
8
|
+
getProjectedColumns,
|
|
9
|
+
hashString,
|
|
10
|
+
quoteIdentifier as quoteIdent,
|
|
11
|
+
resolveServerVersionColumnName,
|
|
12
|
+
type BatchMutationRequest,
|
|
13
|
+
type RegistryRelations,
|
|
14
|
+
type SyncTableEntry,
|
|
15
|
+
type SyncTableRegistry,
|
|
16
|
+
} from "@pgxsinkit/contracts";
|
|
17
|
+
|
|
18
|
+
import type { TransactionClient } from "./types";
|
|
19
|
+
|
|
20
|
+
function qualifyIdent(schemaName: string | undefined, name: string): string {
|
|
21
|
+
if (!schemaName) {
|
|
22
|
+
return quoteIdent(name);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function toSqlTextOrNull(value: string): string {
|
|
29
|
+
return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface ResolvedManagedField {
|
|
33
|
+
propertyKey: string;
|
|
34
|
+
columnName: string;
|
|
35
|
+
strategy: "nowMicroseconds" | "authClaim";
|
|
36
|
+
claimPath?: string[];
|
|
37
|
+
cast?: string;
|
|
38
|
+
columnSqlType: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The single claim-stamping strategy (ADR-0026): `authClaim` reads the verified request claim at its JSON
|
|
42
|
+
// path — `auth.uid()` is just `{ claimPath: ["sub"], cast: "uuid" }`, so there is one mechanism. The path
|
|
43
|
+
// segments are validated plain identifiers at registry build, so the `'{a,b}'` text-array literal is
|
|
44
|
+
// injection-safe; `current_setting('request.jwt.claims', …)` is set by this function before the apply DML
|
|
45
|
+
// (it is what RLS reads), NULLIF guards an unset GUC (an absent claim stamps NULL, never errors), and the
|
|
46
|
+
// cast defaults to the target column's own SQL type so a `uuid` column needs no explicit cast.
|
|
47
|
+
function buildManagedFieldExpression(field: ResolvedManagedField): string {
|
|
48
|
+
if (field.strategy === "authClaim") {
|
|
49
|
+
const path = (field.claimPath ?? []).join(",");
|
|
50
|
+
const castType = field.cast ?? field.columnSqlType;
|
|
51
|
+
return `(NULLIF(current_setting('request.jwt.claims', true), '')::jsonb #>> '{${path}}')::${castType}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Call the canonical microsecond-clock DB function, never inline the expression. The rendered
|
|
55
|
+
// artifact therefore DEPENDS on the utilities function (public.pgxsinkit_clock_us()): the utilities
|
|
56
|
+
// migration (renderPgxsinkitUtilitiesMigration) must precede this artifact in any consumer's chain.
|
|
57
|
+
// The ADR-0030 fingerprint recomputes from this rendered text, so a change to the call form is
|
|
58
|
+
// coordinated through the normal regenerate-and-commit flow.
|
|
59
|
+
return CLOCK_US_CALL_SQL_TEXT;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function getManagedFieldsForOperation(entry: SyncTableEntry, operation: "create" | "update"): ResolvedManagedField[] {
|
|
63
|
+
const columns = getColumns(entry.table as AnyPgTable);
|
|
64
|
+
const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
|
|
65
|
+
|
|
66
|
+
return (entry.governance?.managedFields ?? []).flatMap((field) => {
|
|
67
|
+
if (!field.applyOn.includes(operation)) {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const columnName = columnNameMap.get(field.column);
|
|
72
|
+
if (!columnName) {
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const column =
|
|
77
|
+
(columns as Record<string, { getSQLType: () => string } | undefined>)[field.column] ??
|
|
78
|
+
Object.values(columns).find((candidate) => candidate.name === field.column);
|
|
79
|
+
|
|
80
|
+
return [
|
|
81
|
+
{
|
|
82
|
+
propertyKey: field.column,
|
|
83
|
+
columnName,
|
|
84
|
+
strategy: field.strategy,
|
|
85
|
+
...(field.claimPath ? { claimPath: field.claimPath } : {}),
|
|
86
|
+
...(field.cast ? { cast: field.cast } : {}),
|
|
87
|
+
columnSqlType: column?.getSQLType() ?? "text",
|
|
88
|
+
},
|
|
89
|
+
];
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function buildTableBranch(entry: SyncTableEntry): string {
|
|
94
|
+
const tableName = getTableName(entry.table as AnyPgTable);
|
|
95
|
+
const { schema } = getTableConfig(entry.table as AnyPgTable);
|
|
96
|
+
const qualifiedTableName = qualifyIdent(schema, tableName);
|
|
97
|
+
const columns = getColumns(entry.table as AnyPgTable);
|
|
98
|
+
const projectedColumns = getProjectedColumns(entry);
|
|
99
|
+
// The canonical Entity identity is the full server primary-key tuple, by column name with
|
|
100
|
+
// typed values (ADR-0012): the applier matches update/delete over EVERY pk column. Keying on
|
|
101
|
+
// only the first column (the old `columns[0]`) matched too many rows on a composite-PK table.
|
|
102
|
+
const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
|
|
103
|
+
const columnObject = Object.values(columns).find((column) => column.name === columnName);
|
|
104
|
+
if (!columnObject) {
|
|
105
|
+
// Hard error, not a silent `text` fallback: an unmatched PK column means the primaryKey spec
|
|
106
|
+
// has drifted from the table (e.g. a rename) — a generated applier keyed on a mistyped tuple
|
|
107
|
+
// would mis-match rows at apply time.
|
|
108
|
+
throw new Error(
|
|
109
|
+
`plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` +
|
|
110
|
+
`the entry's primaryKey spec has drifted from its Drizzle table`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return { name: columnName, type: columnObject.getSQLType() };
|
|
114
|
+
});
|
|
115
|
+
const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));
|
|
116
|
+
|
|
117
|
+
const createManagedFields = getManagedFieldsForOperation(entry, "create");
|
|
118
|
+
const updateManagedFields = getManagedFieldsForOperation(entry, "update");
|
|
119
|
+
const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));
|
|
120
|
+
const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));
|
|
121
|
+
|
|
122
|
+
const allColumnPairs = projectedColumns
|
|
123
|
+
.map(({ column }) => column)
|
|
124
|
+
.filter((column) => !createManagedFieldNames.has(column.name))
|
|
125
|
+
.map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)
|
|
126
|
+
.join(",\n ");
|
|
127
|
+
|
|
128
|
+
const nonPrimaryKeyColumnPairs = projectedColumns
|
|
129
|
+
.map(({ column }) => column)
|
|
130
|
+
.filter((column) => !primaryKeyColumnNames.has(column.name) && !updateManagedFieldNames.has(column.name))
|
|
131
|
+
.map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)
|
|
132
|
+
.join(",\n ");
|
|
133
|
+
|
|
134
|
+
const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
|
|
135
|
+
const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(", ");
|
|
136
|
+
// ADR-0010: the Server version (the nowMicroseconds-on-update managed field) must be strictly
|
|
137
|
+
// monotonic per row, so its on-update stamp is floored at the previous value + 1 — it can never
|
|
138
|
+
// repeat or step backwards under wall-clock (NTP) skew, which would let a stale echo clear an
|
|
139
|
+
// optimistic write early. The bare column on the RHS of an UPDATE SET is the pre-update value.
|
|
140
|
+
const serverVersionColumn = resolveServerVersionColumnName(entry);
|
|
141
|
+
const updateManagedAssignmentsSql = updateManagedFields
|
|
142
|
+
.map((field) => {
|
|
143
|
+
const expression =
|
|
144
|
+
field.strategy === "nowMicroseconds" && field.columnName === serverVersionColumn
|
|
145
|
+
? `GREATEST(${buildManagedFieldExpression(field)}, ${quoteIdent(field.columnName)} + 1)`
|
|
146
|
+
: buildManagedFieldExpression(field);
|
|
147
|
+
return `${quoteIdent(field.columnName)} = ${expression}`;
|
|
148
|
+
})
|
|
149
|
+
.join(", ");
|
|
150
|
+
|
|
151
|
+
// Set-based apply (ADR-0014 Phase 4): one statement per (table, kind, payload column-set) group,
|
|
152
|
+
// over the group's rows materialised by jsonb_to_recordset. The PK match spans the full tuple
|
|
153
|
+
// (ADR-0012): DELETE matches the recordset's typed PK columns directly; UPDATE matches each row's
|
|
154
|
+
// entity key carried as `x.k` jsonb. Safe from the same-PK `UPDATE … FROM` join hazard because the
|
|
155
|
+
// Per-entity flush serialization invariant leaves at most one mutation per entity in a batch.
|
|
156
|
+
const pkRecordDef = primaryKeyColumns.map((pk) => `${quoteIdent(pk.name)} ${pk.type}`).join(", ");
|
|
157
|
+
const pkDeleteJoin = primaryKeyColumns
|
|
158
|
+
.map((pk) => `t.${quoteIdent(pk.name)} = x.${quoteIdent(pk.name)}`)
|
|
159
|
+
.join(" AND ");
|
|
160
|
+
const pkUpdateJoin = primaryKeyColumns
|
|
161
|
+
.map((pk) => `t.${quoteIdent(pk.name)} = (x.k->>'${toSqlLiteral(pk.name)}')::${pk.type}`)
|
|
162
|
+
.join(" AND ");
|
|
163
|
+
|
|
164
|
+
// Templates the runtime format() fills with the per-group column list. Single quotes are doubled
|
|
165
|
+
// because these are embedded as PL/pgSQL string literals.
|
|
166
|
+
const insertTemplate =
|
|
167
|
+
`INSERT INTO ${qualifiedTableName} (%s) SELECT %s FROM jsonb_to_recordset($1) AS x(p jsonb)`.replace(/'/g, "''");
|
|
168
|
+
const updateTemplate =
|
|
169
|
+
`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb) WHERE ${pkUpdateJoin}`.replace(
|
|
170
|
+
/'/g,
|
|
171
|
+
"''",
|
|
172
|
+
);
|
|
173
|
+
const deleteSql =
|
|
174
|
+
`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(
|
|
175
|
+
/'/g,
|
|
176
|
+
"''",
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
// The create/update column fragments come from the group signature (∩ writable columns) plus the
|
|
180
|
+
// static managed fields. An empty intersection ⇒ NULL fragment ⇒ a managed-only statement (the
|
|
181
|
+
// Server version still bumps on a PK-only update, exactly as the per-mutation path did).
|
|
182
|
+
const createColumnSelect = allColumnPairs.length
|
|
183
|
+
? `SELECT
|
|
184
|
+
string_agg(quote_ident(col_name), ', ' ORDER BY col_name),
|
|
185
|
+
string_agg(format('(x.p->>%L)::%s', col_name, col_type), ', ' ORDER BY col_name)
|
|
186
|
+
INTO v_cols, v_vals
|
|
187
|
+
FROM (VALUES
|
|
188
|
+
${allColumnPairs}
|
|
189
|
+
) AS col_types(col_name, col_type)
|
|
190
|
+
WHERE col_name = ANY(string_to_array(v_sig, ','));`
|
|
191
|
+
: `v_cols := NULL; v_vals := NULL;`;
|
|
192
|
+
|
|
193
|
+
const updateSetSelect = nonPrimaryKeyColumnPairs.length
|
|
194
|
+
? `SELECT string_agg(format('%I = (x.p->>%L)::%s', col_name, col_name, col_type), ', ' ORDER BY col_name)
|
|
195
|
+
INTO v_set
|
|
196
|
+
FROM (VALUES
|
|
197
|
+
${nonPrimaryKeyColumnPairs}
|
|
198
|
+
) AS col_types(col_name, col_type)
|
|
199
|
+
WHERE col_name = ANY(string_to_array(v_sig, ','));`
|
|
200
|
+
: `v_set := NULL;`;
|
|
201
|
+
|
|
202
|
+
const createBranch = `
|
|
203
|
+
${createColumnSelect}
|
|
204
|
+
|
|
205
|
+
dml_sql := format(
|
|
206
|
+
'${insertTemplate}',
|
|
207
|
+
concat_ws(', ', nullif(v_cols, ''), ${toSqlTextOrNull(createManagedColumnsSql)}),
|
|
208
|
+
concat_ws(', ', nullif(v_vals, ''), ${toSqlTextOrNull(createManagedValuesSql)})
|
|
209
|
+
);
|
|
210
|
+
EXECUTE dml_sql USING (
|
|
211
|
+
SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb))), '[]'::jsonb)
|
|
212
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
213
|
+
);
|
|
214
|
+
`.trim();
|
|
215
|
+
|
|
216
|
+
// ADR-0015: a `reject-if-stale` table compares each targeted row's current Server version to the
|
|
217
|
+
// mutation's Base server version (`x.b`). `current > base` ⇒ stale (an external write interleaved):
|
|
218
|
+
// the row is NOT applied, and the conflict (mutation id + the row's current Server version) is
|
|
219
|
+
// collected for the handler to turn into a `conflicted` ack. `last-write-wins` keeps today's apply
|
|
220
|
+
// (now a named choice). The policy is known here at DDL-generation time, so each table emits the SQL
|
|
221
|
+
// its policy needs; a create has no base (its conflict is a PK collision), so it is unchanged.
|
|
222
|
+
// #6: an UPDATE whose target row is MISSING (deleted by another writer after authoring) is also a
|
|
223
|
+
// conflict ('target row no longer exists', `currentServerVersion` NULL) — otherwise the edit would
|
|
224
|
+
// silently no-op and ack as success. A DELETE of a missing row stays idempotent success (the user
|
|
225
|
+
// wanted it gone), so the delete branch keeps its inner join and does not report missing targets.
|
|
226
|
+
const serverVersionRef = serverVersionColumn ? quoteIdent(serverVersionColumn) : null;
|
|
227
|
+
const rejectIfStale = entry.conflictPolicy === "reject-if-stale" && serverVersionRef != null;
|
|
228
|
+
// For the missing-target conflict (ADR-0015 #6): a LEFT JOIN whose right side is absent leaves the
|
|
229
|
+
// first PK column NULL. The Server version is NOT NULL on any existing writable row, so a NULL
|
|
230
|
+
// `currentServerVersion` in a returned conflict means exactly "the target row no longer exists".
|
|
231
|
+
const firstPkRef = quoteIdent(primaryKeyColumns[0]!.name);
|
|
232
|
+
|
|
233
|
+
// The conflict-collect SELECT and the staleness guard need the base + mutation id alongside each
|
|
234
|
+
// row, so reject-if-stale carries them in the recordset (`b bigint, m text`). The mutation id is
|
|
235
|
+
// `text` (not `uuid`): a derived child envelope's id is a composite non-UUID string, and a `m uuid`
|
|
236
|
+
// recordset column would raise 22P02 the moment such a write is stale.
|
|
237
|
+
const conflictObjectSql = (alias: string) =>
|
|
238
|
+
`jsonb_build_object('mutationId', ${alias}.m, 'tableName', '${toSqlLiteral(tableName)}', 'currentServerVersion', t.${serverVersionRef})`;
|
|
239
|
+
|
|
240
|
+
const updateBranch = rejectIfStale
|
|
241
|
+
? `
|
|
242
|
+
${updateSetSelect}
|
|
243
|
+
|
|
244
|
+
EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql("x")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) LEFT JOIN ${qualifiedTableName} AS t ON ${pkUpdateJoin} WHERE t.${firstPkRef} IS NULL OR (x.b IS NOT NULL AND t.${serverVersionRef} > x.b)`.replace(/'/g, "''")}'
|
|
245
|
+
INTO v_group_conflicts
|
|
246
|
+
USING (
|
|
247
|
+
SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)
|
|
248
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
249
|
+
);
|
|
250
|
+
v_conflicts := v_conflicts || v_group_conflicts;
|
|
251
|
+
|
|
252
|
+
dml_sql := format(
|
|
253
|
+
'${`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) WHERE ${pkUpdateJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, "''")}',
|
|
254
|
+
concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})
|
|
255
|
+
);
|
|
256
|
+
EXECUTE dml_sql USING (
|
|
257
|
+
SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)
|
|
258
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
259
|
+
);
|
|
260
|
+
`.trim()
|
|
261
|
+
: `
|
|
262
|
+
${updateSetSelect}
|
|
263
|
+
|
|
264
|
+
dml_sql := format(
|
|
265
|
+
'${updateTemplate}',
|
|
266
|
+
concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})
|
|
267
|
+
);
|
|
268
|
+
EXECUTE dml_sql USING (
|
|
269
|
+
SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb))), '[]'::jsonb)
|
|
270
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
271
|
+
);
|
|
272
|
+
`.trim();
|
|
273
|
+
|
|
274
|
+
const deleteBranch = rejectIfStale
|
|
275
|
+
? `
|
|
276
|
+
EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql("x")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) JOIN ${qualifiedTableName} AS t ON ${pkDeleteJoin} WHERE x.b IS NOT NULL AND t.${serverVersionRef} > x.b`.replace(/'/g, "''")}'
|
|
277
|
+
INTO v_group_conflicts
|
|
278
|
+
USING (
|
|
279
|
+
SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)
|
|
280
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
281
|
+
);
|
|
282
|
+
v_conflicts := v_conflicts || v_group_conflicts;
|
|
283
|
+
|
|
284
|
+
EXECUTE '${`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) WHERE ${pkDeleteJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, "''")}' USING (
|
|
285
|
+
SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)
|
|
286
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
287
|
+
);
|
|
288
|
+
`.trim()
|
|
289
|
+
: `
|
|
290
|
+
EXECUTE '${deleteSql}' USING (
|
|
291
|
+
SELECT COALESCE(jsonb_agg(elem->'entityKey'), '[]'::jsonb)
|
|
292
|
+
FROM jsonb_array_elements(v_rows) AS elem
|
|
293
|
+
);
|
|
294
|
+
`.trim();
|
|
295
|
+
|
|
296
|
+
return `
|
|
297
|
+
ELSIF v_table = '${toSqlLiteral(tableName)}' THEN
|
|
298
|
+
IF v_kind = 'create' THEN
|
|
299
|
+
${createBranch}
|
|
300
|
+
ELSIF v_kind = 'update' THEN
|
|
301
|
+
${updateBranch}
|
|
302
|
+
ELSIF v_kind = 'delete' THEN
|
|
303
|
+
${deleteBranch}
|
|
304
|
+
ELSE
|
|
305
|
+
RAISE EXCEPTION 'Unsupported mutation kind "%" for table "%"', v_kind, v_table;
|
|
306
|
+
END IF;
|
|
307
|
+
`.trim();
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const APPLY_FUNCTION_NAME = "pgxsinkit_apply_mutations";
|
|
311
|
+
// ADR-0030: the trailing `text` is `p_expected_fingerprint` — the running server passes the fingerprint
|
|
312
|
+
// it expects for its registry + codegen, and the function verifies itself against its stamped comment
|
|
313
|
+
// before touching any table. The previous (pre-ADR-0030) signature dropped the trailing `text`.
|
|
314
|
+
const APPLY_FUNCTION_ARG_TYPES = "jsonb, text, boolean, boolean, jsonb, text";
|
|
315
|
+
const APPLY_FUNCTION_ARG_TYPES_LEGACY = "jsonb, text, boolean, boolean, jsonb";
|
|
316
|
+
// ADR-0018: version-prefixed so the stored format can evolve; the reader parses the prefix and
|
|
317
|
+
// treats an unknown prefix as "can't compare" (warn) rather than a mismatch (error).
|
|
318
|
+
const APPLY_FINGERPRINT_PREFIX = "pgxsinkit:fp1:";
|
|
319
|
+
|
|
320
|
+
function buildApplyFunctionBody(
|
|
321
|
+
registry: SyncTableRegistry,
|
|
322
|
+
options: {
|
|
323
|
+
functionSchema?: string;
|
|
324
|
+
} = {},
|
|
325
|
+
): string {
|
|
326
|
+
const tableBranches = Object.values(registry)
|
|
327
|
+
// A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's
|
|
328
|
+
// branch already handles that physical table. Emitting a branch for the projection too would
|
|
329
|
+
// DUPLICATE the owner's table branch (same table name). Read projections are readonly and never
|
|
330
|
+
// reach the write path, so exclude them from the apply function entirely.
|
|
331
|
+
.filter((entry) => !(entry as SyncTableEntry).readProjection)
|
|
332
|
+
.map((entry) => buildTableBranch(entry as SyncTableEntry))
|
|
333
|
+
.join("\n");
|
|
334
|
+
const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
|
|
335
|
+
|
|
336
|
+
return `
|
|
337
|
+
-- ADR-0015: the function now RETURNS the per-mutation conflicts (a reject-if-stale stale write). A
|
|
338
|
+
-- return-type change cannot be a bare CREATE OR REPLACE, so drop the prior (void-returning) signature
|
|
339
|
+
-- first. Idempotent: re-running installs the same definition.
|
|
340
|
+
--
|
|
341
|
+
-- TWO-TIER MUTATION-ID INVARIANT. \`mutation_id\` is TEXT here (RETURNS TABLE + operations_log), not
|
|
342
|
+
-- uuid, so this apply function can serve a DIRECT server-side caller that derives child envelopes with
|
|
343
|
+
-- composite non-UUID ids (\`\${parentId}:<tag>:<n>\`). That is the ONLY non-UUID path. pgxsinkit's public
|
|
344
|
+
-- surface — the HTTP route's request/ack schemas and the client's \`mutation_id UUID\` journal — stays
|
|
345
|
+
-- UUID-only (see packages/contracts/src/mutation.ts): the route validates every request id as a UUID and
|
|
346
|
+
-- builds every ack from that request id, never from the TEXT conflict rows this returns. A non-UUID id
|
|
347
|
+
-- therefore never crosses into the UUID-typed surface.
|
|
348
|
+
--
|
|
349
|
+
-- ADR-0030: the signature gained a trailing p_expected_fingerprint text, so the prior (pre-ADR-0030,
|
|
350
|
+
-- 5-arg) function is a DIFFERENT overload — drop it too, else a CREATE of the 6-arg form would leave a
|
|
351
|
+
-- stale 5-arg beside it. The runtime only ever calls the 6-arg form; dropping the legacy one keeps an
|
|
352
|
+
-- in-place upgrade clean.
|
|
353
|
+
DROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES_LEGACY});
|
|
354
|
+
DROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES});
|
|
355
|
+
|
|
356
|
+
CREATE OR REPLACE FUNCTION ${functionName}(
|
|
357
|
+
p_batch jsonb,
|
|
358
|
+
p_request_path text,
|
|
359
|
+
p_log_enabled boolean,
|
|
360
|
+
p_rls_enabled boolean,
|
|
361
|
+
p_user_claims jsonb,
|
|
362
|
+
p_expected_fingerprint text
|
|
363
|
+
) RETURNS TABLE(mutation_id text, table_name text, current_server_version bigint) LANGUAGE plpgsql AS $$
|
|
364
|
+
DECLARE
|
|
365
|
+
dml_sql text;
|
|
366
|
+
v_table text;
|
|
367
|
+
v_kind text;
|
|
368
|
+
v_sig text;
|
|
369
|
+
v_rows jsonb;
|
|
370
|
+
v_cols text;
|
|
371
|
+
v_vals text;
|
|
372
|
+
v_set text;
|
|
373
|
+
-- ADR-0015: stale-write conflicts collected across the batch (mutationId + the row's current
|
|
374
|
+
-- Server version), returned to the handler which turns them into 'conflicted' acks.
|
|
375
|
+
v_conflicts jsonb := '[]'::jsonb;
|
|
376
|
+
v_group_conflicts jsonb;
|
|
377
|
+
-- ADR-0030: the fingerprint this installed function was stamped with (its own ADR-0018 comment),
|
|
378
|
+
-- read back once for the self-verification gate below.
|
|
379
|
+
_installed_fingerprint text;
|
|
380
|
+
_claims jsonb;
|
|
381
|
+
_target_role text;
|
|
382
|
+
_previous_role text;
|
|
383
|
+
_previous_claims text;
|
|
384
|
+
_previous_claim_sub text;
|
|
385
|
+
BEGIN
|
|
386
|
+
-- ADR-0030: the apply function verifies ITSELF against its ADR-0018 fingerprint comment before it
|
|
387
|
+
-- touches any table. p_expected_fingerprint is what the running server expects for its registry +
|
|
388
|
+
-- codegen; obj_description(...) is the fingerprint this installed function was stamped with, atomically,
|
|
389
|
+
-- by the same migration. A mismatch — INCLUDING an absent comment (a hand-installed / pre-fingerprint
|
|
390
|
+
-- function ⇒ NULL, refused per ADR-0030) — means the installed function is stale relative to the caller,
|
|
391
|
+
-- so raise SQLSTATE 'PXS01' and apply nothing. The check IS the call (no read-then-call TOCTOU) and
|
|
392
|
+
-- costs no extra round trip (the argument rides the existing invocation; the comparison is one text
|
|
393
|
+
-- equality). The signature literal is embedded, never the fingerprint hash itself — baking the hash
|
|
394
|
+
-- into the body would be circular with the hash-of-body the fingerprint is.
|
|
395
|
+
_installed_fingerprint := obj_description('${functionName}(${APPLY_FUNCTION_ARG_TYPES})'::regprocedure, 'pg_proc');
|
|
396
|
+
IF p_expected_fingerprint IS DISTINCT FROM _installed_fingerprint THEN
|
|
397
|
+
RAISE EXCEPTION 'pgxsinkit_apply_mutations is stale: the installed apply-function fingerprint (%) does not match the fingerprint this server expects (%). Regenerate the sync-function migration (pgxsinkit-generate) and apply it before serving writes.', COALESCE(_installed_fingerprint, '(none)'), p_expected_fingerprint
|
|
398
|
+
USING ERRCODE = 'PXS01';
|
|
399
|
+
END IF;
|
|
400
|
+
|
|
401
|
+
IF p_rls_enabled THEN
|
|
402
|
+
-- Capture the caller's role/claims before switching into the RLS actor context, so the
|
|
403
|
+
-- batch does not leak that context into the rest of the caller's transaction. The HTTP
|
|
404
|
+
-- route RESET ROLEs after calling this function, but in-transaction callers cannot —
|
|
405
|
+
-- restoring here leaves every caller exactly as it was found.
|
|
406
|
+
_previous_role := current_setting('role', true);
|
|
407
|
+
_previous_claims := current_setting('request.jwt.claims', true);
|
|
408
|
+
_previous_claim_sub := current_setting('request.jwt.claim.sub', true);
|
|
409
|
+
_claims := COALESCE(p_user_claims, '{}'::jsonb);
|
|
410
|
+
_target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');
|
|
411
|
+
BEGIN
|
|
412
|
+
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = _target_role) THEN
|
|
413
|
+
PERFORM set_config('role', _target_role, true);
|
|
414
|
+
ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN
|
|
415
|
+
PERFORM set_config('role', 'authenticated', true);
|
|
416
|
+
END IF;
|
|
417
|
+
EXCEPTION WHEN insufficient_privilege THEN NULL;
|
|
418
|
+
END;
|
|
419
|
+
PERFORM set_config('request.jwt.claims', _claims::text, true);
|
|
420
|
+
IF _claims ? 'sub' THEN
|
|
421
|
+
PERFORM set_config('request.jwt.claim.sub', _claims ->> 'sub', true);
|
|
422
|
+
END IF;
|
|
423
|
+
END IF;
|
|
424
|
+
|
|
425
|
+
IF jsonb_typeof(p_batch) <> 'object' THEN
|
|
426
|
+
RAISE EXCEPTION 'Batch payload must be a JSON object';
|
|
427
|
+
END IF;
|
|
428
|
+
|
|
429
|
+
IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN
|
|
430
|
+
RAISE EXCEPTION 'Batch payload mutations must be a JSON array';
|
|
431
|
+
END IF;
|
|
432
|
+
|
|
433
|
+
-- Group the batch by (table, kind, payload column-set) and apply each group with one statement
|
|
434
|
+
-- (ADR-0014 Phase 4). Groups run in ascending min(mutationSeq) so submission order is preserved
|
|
435
|
+
-- across tables (FK-safe; the batch transaction also runs SET CONSTRAINTS ALL DEFERRED).
|
|
436
|
+
FOR v_table, v_kind, v_sig, v_rows IN
|
|
437
|
+
SELECT
|
|
438
|
+
grouped.table_name,
|
|
439
|
+
grouped.kind,
|
|
440
|
+
grouped.sig,
|
|
441
|
+
jsonb_agg(grouped.mutation ORDER BY grouped.mutation_seq)
|
|
442
|
+
FROM (
|
|
443
|
+
SELECT
|
|
444
|
+
m->>'tableName' AS table_name,
|
|
445
|
+
m->>'kind' AS kind,
|
|
446
|
+
COALESCE((
|
|
447
|
+
SELECT string_agg(payload_key, ',' ORDER BY payload_key)
|
|
448
|
+
FROM jsonb_object_keys(COALESCE(m->'payload', '{}'::jsonb)) AS payload_key
|
|
449
|
+
), '') AS sig,
|
|
450
|
+
m AS mutation,
|
|
451
|
+
(m->>'mutationSeq')::integer AS mutation_seq
|
|
452
|
+
FROM jsonb_array_elements(p_batch->'mutations') AS m
|
|
453
|
+
) AS grouped
|
|
454
|
+
GROUP BY grouped.table_name, grouped.kind, grouped.sig
|
|
455
|
+
ORDER BY MIN(grouped.mutation_seq)
|
|
456
|
+
LOOP
|
|
457
|
+
dml_sql := NULL;
|
|
458
|
+
v_cols := NULL;
|
|
459
|
+
v_vals := NULL;
|
|
460
|
+
v_set := NULL;
|
|
461
|
+
|
|
462
|
+
IF FALSE THEN
|
|
463
|
+
NULL;
|
|
464
|
+
${tableBranches}
|
|
465
|
+
ELSE
|
|
466
|
+
RAISE EXCEPTION 'Unknown table "%" in batch mutation', v_table;
|
|
467
|
+
END IF;
|
|
468
|
+
END LOOP;
|
|
469
|
+
|
|
470
|
+
IF p_log_enabled THEN
|
|
471
|
+
-- One batched log insert (the whole batch is a single transaction, so a per-mutation loop
|
|
472
|
+
-- bought nothing): a runtime apply failure above rolls the whole transaction back, log rows
|
|
473
|
+
-- included, preserving the existing whole-batch-failure semantics.
|
|
474
|
+
INSERT INTO operations_log (
|
|
475
|
+
table_name,
|
|
476
|
+
operation_kind,
|
|
477
|
+
entity_key_json,
|
|
478
|
+
payload_json,
|
|
479
|
+
status,
|
|
480
|
+
http_status,
|
|
481
|
+
mutation_id,
|
|
482
|
+
mutation_seq,
|
|
483
|
+
client_timestamp_us,
|
|
484
|
+
request_path,
|
|
485
|
+
server_timestamp_us
|
|
486
|
+
)
|
|
487
|
+
SELECT
|
|
488
|
+
m->>'tableName',
|
|
489
|
+
m->>'kind',
|
|
490
|
+
COALESCE(m->'entityKey', '{}'::jsonb),
|
|
491
|
+
COALESCE(m->'payload', '{}'::jsonb),
|
|
492
|
+
'succeeded',
|
|
493
|
+
200,
|
|
494
|
+
-- mutation_id is text: a derived child envelope carries a composite non-UUID id
|
|
495
|
+
-- (parent-id + tag + index), so no ::uuid cast (it would raise 22P02 on such an id).
|
|
496
|
+
m->>'mutationId',
|
|
497
|
+
(m->>'mutationSeq')::integer,
|
|
498
|
+
NULLIF(m->>'clientTimestampUs', '')::bigint,
|
|
499
|
+
p_request_path,
|
|
500
|
+
-- The canonical microsecond clock (utilities migration); never the inline expression.
|
|
501
|
+
${CLOCK_US_CALL_SQL_TEXT}
|
|
502
|
+
FROM jsonb_array_elements(p_batch->'mutations') AS m;
|
|
503
|
+
END IF;
|
|
504
|
+
|
|
505
|
+
IF p_rls_enabled THEN
|
|
506
|
+
-- Restore the caller's prior role/claims captured above, so the RLS context applied for
|
|
507
|
+
-- the batch does not persist into subsequent statements of the caller's transaction.
|
|
508
|
+
BEGIN
|
|
509
|
+
PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);
|
|
510
|
+
EXCEPTION WHEN insufficient_privilege THEN NULL;
|
|
511
|
+
END;
|
|
512
|
+
PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);
|
|
513
|
+
PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);
|
|
514
|
+
END IF;
|
|
515
|
+
|
|
516
|
+
-- ADR-0015: return the collected stale-write conflicts. Empty under last-write-wins (or when no
|
|
517
|
+
-- write was stale), so the handler simply acks everything as today.
|
|
518
|
+
RETURN QUERY
|
|
519
|
+
SELECT
|
|
520
|
+
-- mutation_id is text (see RETURNS TABLE): a stale derived child envelope's id is a composite
|
|
521
|
+
-- non-UUID string, so return it verbatim — a ::uuid cast here would raise 22P02 and abort the batch.
|
|
522
|
+
c->>'mutationId',
|
|
523
|
+
c->>'tableName',
|
|
524
|
+
(c->>'currentServerVersion')::bigint
|
|
525
|
+
FROM jsonb_array_elements(v_conflicts) AS c;
|
|
526
|
+
END;
|
|
527
|
+
$$;
|
|
528
|
+
`.trim();
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* The fingerprint the installed apply function should carry for this registry + applier codegen
|
|
533
|
+
* (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape
|
|
534
|
+
* change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the
|
|
535
|
+
* two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /
|
|
536
|
+
* customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).
|
|
537
|
+
*/
|
|
538
|
+
export function expectedApplyFingerprint(
|
|
539
|
+
registry: SyncTableRegistry,
|
|
540
|
+
options: {
|
|
541
|
+
functionSchema?: string;
|
|
542
|
+
} = {},
|
|
543
|
+
): string {
|
|
544
|
+
return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export function buildPlpgsqlBatchFunctionDdl(
|
|
548
|
+
registry: SyncTableRegistry,
|
|
549
|
+
options: {
|
|
550
|
+
functionSchema?: string;
|
|
551
|
+
} = {},
|
|
552
|
+
): string {
|
|
553
|
+
const body = buildApplyFunctionBody(registry, options);
|
|
554
|
+
const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
|
|
555
|
+
const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);
|
|
556
|
+
|
|
557
|
+
// ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT
|
|
558
|
+
// because it is function-scoped, replaced atomically with the function, and read back in one line
|
|
559
|
+
// via obj_description — so the server (startup) and CI (pre-deploy) can both detect a function
|
|
560
|
+
// that is stale relative to the registry + codegen it is meant to serve.
|
|
561
|
+
return `${body}\n\nCOMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
|
|
565
|
+
db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,
|
|
566
|
+
registry: TRegistry,
|
|
567
|
+
options: {
|
|
568
|
+
functionSchema?: string;
|
|
569
|
+
} = {},
|
|
570
|
+
): Promise<void> {
|
|
571
|
+
const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);
|
|
572
|
+
await db.execute(sql.raw(ddl));
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
type AuthHelperPresenceRow = {
|
|
576
|
+
authUid: string | null;
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
export async function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(
|
|
580
|
+
db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,
|
|
581
|
+
): Promise<void> {
|
|
582
|
+
const result = await db.execute<AuthHelperPresenceRow>(sql`
|
|
583
|
+
SELECT
|
|
584
|
+
to_regprocedure('auth.uid()')::text AS "authUid"
|
|
585
|
+
`);
|
|
586
|
+
|
|
587
|
+
const row = Array.from(result as Iterable<unknown>, (entry) => entry as AuthHelperPresenceRow)[0];
|
|
588
|
+
const missingHelpers = [row?.authUid ? null : "auth.uid()"].filter((value): value is string => value !== null);
|
|
589
|
+
|
|
590
|
+
if (missingHelpers.length > 0) {
|
|
591
|
+
throw new Error(
|
|
592
|
+
`The write path requires Supabase auth helpers. Missing: ${missingHelpers.join(", ")}. ` +
|
|
593
|
+
"Ensure auth.uid() is available (standard on Supabase-managed databases).",
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the
|
|
600
|
+
* Base server version the row has since advanced past — `currentServerVersion` is the row's current
|
|
601
|
+
* version) or an UPDATE whose **target row is missing** (deleted by another writer —
|
|
602
|
+
* `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the
|
|
603
|
+
* `conflicted` ack.
|
|
604
|
+
*/
|
|
605
|
+
export interface MutationConflict {
|
|
606
|
+
mutationId: string;
|
|
607
|
+
tableName: string;
|
|
608
|
+
currentServerVersion: string | null;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
interface MutationConflictRow {
|
|
612
|
+
mutationId: string | null;
|
|
613
|
+
tableName: string | null;
|
|
614
|
+
currentServerVersion: string | null;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
export async function executePlpgsqlBatch(
|
|
618
|
+
tx: TransactionClient,
|
|
619
|
+
batch: BatchMutationRequest,
|
|
620
|
+
requestPath: string,
|
|
621
|
+
logEnabled: boolean,
|
|
622
|
+
rlsEnabled: boolean,
|
|
623
|
+
userClaims: Record<string, unknown>,
|
|
624
|
+
// ADR-0030: the fingerprint the running server expects for its registry + codegen
|
|
625
|
+
// (`expectedApplyFingerprint(registry)`, computed once per server instance). The installed apply
|
|
626
|
+
// function compares it against its own stamped comment and raises SQLSTATE 'PXS01' on a mismatch —
|
|
627
|
+
// in-body, atomic with the call, before it touches any table.
|
|
628
|
+
expectedFingerprint: string,
|
|
629
|
+
options: {
|
|
630
|
+
functionSchema?: string;
|
|
631
|
+
} = {},
|
|
632
|
+
): Promise<MutationConflict[]> {
|
|
633
|
+
const normalizedClaims = userClaims ?? {};
|
|
634
|
+
// Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases
|
|
635
|
+
// are the generated function's fixed names.
|
|
636
|
+
const functionRef = options.functionSchema
|
|
637
|
+
? sql`${sql.identifier(options.functionSchema)}.${sql.identifier("pgxsinkit_apply_mutations")}`
|
|
638
|
+
: sql`${sql.identifier("pgxsinkit_apply_mutations")}`;
|
|
639
|
+
|
|
640
|
+
// The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result
|
|
641
|
+
// set; an empty set (the last-write-wins case, or nothing stale) means every mutation applied.
|
|
642
|
+
const result = await tx.execute(
|
|
643
|
+
sql`SELECT "mutation_id"::text AS "mutationId", "table_name" AS "tableName", "current_server_version"::text AS "currentServerVersion" FROM ${functionRef}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb, ${expectedFingerprint})`,
|
|
644
|
+
);
|
|
645
|
+
|
|
646
|
+
const rows = Array.from(result as Iterable<unknown>, (row) => row as MutationConflictRow);
|
|
647
|
+
return rows.flatMap((row) =>
|
|
648
|
+
row.mutationId != null
|
|
649
|
+
? [
|
|
650
|
+
{
|
|
651
|
+
mutationId: row.mutationId,
|
|
652
|
+
tableName: row.tableName ?? "",
|
|
653
|
+
currentServerVersion: row.currentServerVersion,
|
|
654
|
+
} satisfies MutationConflict,
|
|
655
|
+
]
|
|
656
|
+
: [],
|
|
657
|
+
);
|
|
658
|
+
}
|