@pgxsinkit/server 0.1.0

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/src/index.ts ADDED
@@ -0,0 +1,628 @@
1
+ import { eq, sql } from "drizzle-orm";
2
+ import type { AnyPgTable } from "drizzle-orm/pg-core";
3
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
4
+ import { drizzle } from "drizzle-orm/postgres-js";
5
+ import { Hono } from "hono";
6
+ import { cors } from "hono/cors";
7
+ import postgres from "postgres";
8
+
9
+ import type {
10
+ RegistryTables,
11
+ ServerRouteSpec,
12
+ SyncRuntimeStatus,
13
+ SyncServerAddress,
14
+ SyncTableEntry,
15
+ SyncTableRegistry,
16
+ } from "@pgxsinkit/contracts";
17
+
18
+ import { registerBulkMutationRoute } from "./mutations/bulk/route";
19
+ import type { BulkMutationBackend } from "./mutations/bulk/types";
20
+ import { ensureOperationsLogSchema } from "./operations-log/ddl";
21
+ import type { OpsLogBackend, OperationsLogConfig } from "./operations-log/types";
22
+ import { logOperation, logOperationSafely } from "./operations-log/writer";
23
+
24
+ const defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
25
+
26
+ interface BunServerHandle {
27
+ stop: () => void;
28
+ }
29
+
30
+ interface BunNamespace {
31
+ serve: (options: {
32
+ port: number;
33
+ hostname?: string;
34
+ idleTimeout?: number;
35
+ fetch: (request: Request) => Response | Promise<Response>;
36
+ }) => BunServerHandle;
37
+ }
38
+
39
+ export interface CreateSyncServerOptions<TRegistry extends SyncTableRegistry> {
40
+ registry: TRegistry;
41
+ databaseUrl: string;
42
+ backend?: "drizzle" | BulkMutationBackend;
43
+ resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
44
+ operationsLog?: {
45
+ enabled?: boolean;
46
+ };
47
+ port?: number;
48
+ host?: string;
49
+ idleTimeoutSeconds?: number;
50
+ allowedOrigins?: string[];
51
+ onStatusChange?: (status: SyncRuntimeStatus) => void;
52
+ }
53
+
54
+ export interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {
55
+ tables: Array<keyof TRegistry & string>;
56
+ modes: Record<string, TRegistry[keyof TRegistry]["mode"]>;
57
+ routes: Record<string, ServerRouteSpec | undefined>;
58
+ }
59
+
60
+ export interface SyncServer<TRegistry extends SyncTableRegistry> {
61
+ drizzle: PostgresJsDatabase<RegistryTables<TRegistry>>;
62
+ fetch: (request: Request) => Promise<Response>;
63
+ request: (path: string, init?: RequestInit) => Promise<Response>;
64
+ start: () => Promise<void>;
65
+ stop: () => Promise<void>;
66
+ status: SyncRuntimeStatus;
67
+ address: SyncServerAddress | null;
68
+ diagnostics: () => ServerDiagnostics<TRegistry>;
69
+ }
70
+
71
+ export function createSyncServer<TRegistry extends SyncTableRegistry>(
72
+ options: CreateSyncServerOptions<TRegistry>,
73
+ ): SyncServer<TRegistry> {
74
+ const client = createPostgresClient(options.databaseUrl);
75
+ const schema = buildSchema(options.registry);
76
+ const db = drizzle({ client, schema });
77
+ const app = new Hono();
78
+ let bunServer: BunServerHandle | undefined;
79
+
80
+ const status: SyncRuntimeStatus = {
81
+ phase: "ready",
82
+ isRunning: false,
83
+ };
84
+
85
+ let address: SyncServerAddress | null = null;
86
+ const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
87
+ const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
88
+ const backend = options.backend ?? "drizzle";
89
+
90
+ app.use(
91
+ "/api/*",
92
+ cors({
93
+ origin: options.allowedOrigins ?? defaultAllowedOrigins,
94
+ allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
95
+ allowHeaders: ["Content-Type", "Authorization"],
96
+ }),
97
+ );
98
+
99
+ app.onError((error, context) => {
100
+ status.phase = "degraded";
101
+ status.lastError = error instanceof Error ? error.message : "Unexpected error";
102
+ options.onStatusChange?.(status);
103
+
104
+ if (isValidationError(error)) {
105
+ return context.json(
106
+ {
107
+ message: "Validation failed",
108
+ issues: error.issues,
109
+ },
110
+ 400,
111
+ );
112
+ }
113
+
114
+ return context.json(
115
+ {
116
+ message: error instanceof Error ? error.message : "Unexpected error",
117
+ },
118
+ 500,
119
+ );
120
+ });
121
+
122
+ app.get("/health", (context) => {
123
+ return context.json({ ok: true });
124
+ });
125
+
126
+ for (const [tableKey, entry] of Object.entries(options.registry)) {
127
+ registerTableRoutes(app, db, tableKey, entry, {
128
+ backend,
129
+ operationsLogConfig,
130
+ operationsLogReady,
131
+ });
132
+ }
133
+
134
+ if (backend !== "drizzle") {
135
+ registerBulkMutationRoute(
136
+ app,
137
+ db,
138
+ options.registry,
139
+ backend,
140
+ operationsLogConfig,
141
+ operationsLogReady,
142
+ options.resolveAuthClaims,
143
+ );
144
+ }
145
+
146
+ const fetch = async (request: Request) => app.fetch(request);
147
+
148
+ return {
149
+ drizzle: db,
150
+ fetch,
151
+ request: (path, init) => {
152
+ const baseUrl = address === null ? "http://localhost" : `http://${address.host}:${address.port}`;
153
+ return fetch(new Request(new URL(path, baseUrl), init));
154
+ },
155
+ start: async () => {
156
+ if (bunServer) {
157
+ return;
158
+ }
159
+
160
+ const bun = getBunNamespace();
161
+ if (!bun) {
162
+ throw new Error("createSyncServer.start() requires the Bun runtime");
163
+ }
164
+
165
+ const host = options.host ?? "0.0.0.0";
166
+ const port = options.port ?? 3001;
167
+ const idleTimeout = options.idleTimeoutSeconds;
168
+
169
+ bunServer = bun.serve({
170
+ hostname: host,
171
+ port,
172
+ ...(idleTimeout !== undefined ? { idleTimeout } : {}),
173
+ fetch: app.fetch,
174
+ });
175
+
176
+ status.isRunning = true;
177
+ status.phase = "ready";
178
+ delete status.lastError;
179
+ address = { host, port };
180
+ options.onStatusChange?.(status);
181
+ },
182
+ stop: async () => {
183
+ bunServer?.stop();
184
+ bunServer = undefined;
185
+ status.isRunning = false;
186
+ await client.end();
187
+ options.onStatusChange?.(status);
188
+ },
189
+ status,
190
+ get address() {
191
+ return address;
192
+ },
193
+ diagnostics: () => ({
194
+ tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,
195
+ modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),
196
+ routes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.routes])),
197
+ }),
198
+ };
199
+ }
200
+
201
+ function createPostgresClient(connectionString: string) {
202
+ const url = new URL(connectionString);
203
+ const sslmode = url.searchParams.get("sslmode");
204
+
205
+ return postgres({
206
+ host: url.hostname,
207
+ port: Number(url.port || "5432"),
208
+ database: url.pathname.replace(/^\//, ""),
209
+ user: decodeURIComponent(url.username),
210
+ password: decodeURIComponent(url.password),
211
+ ssl: sslmode === "disable" ? false : "prefer",
212
+ max: 10,
213
+ });
214
+ }
215
+
216
+ function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
217
+ return Object.fromEntries(
218
+ Object.entries(registry).map(([key, entry]) => [key, entry.table]),
219
+ ) as RegistryTables<TRegistry>;
220
+ }
221
+
222
+ function registerTableRoutes<TRegistry extends SyncTableRegistry>(
223
+ app: Hono,
224
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
225
+ tableKey: string,
226
+ entry: SyncTableEntry<AnyPgTable>,
227
+ options: {
228
+ backend: OpsLogBackend;
229
+ operationsLogConfig: OperationsLogConfig;
230
+ operationsLogReady: Promise<void>;
231
+ },
232
+ ) {
233
+ const basePath = entry.routes?.basePath;
234
+
235
+ if (!basePath) {
236
+ return;
237
+ }
238
+
239
+ const primaryKeyColumnName = getSinglePrimaryKeyColumnName(entry, tableKey);
240
+ const primaryKeyColumn = getTableColumn(entry.table, primaryKeyColumnName, tableKey);
241
+ const crudWritesAllowed = options.backend !== "bulk-plpgsql-artifact";
242
+
243
+ if (entry.mode !== "writeonly") {
244
+ app.get(basePath, async (context) => {
245
+ const rows = await db.select().from(entry.table);
246
+ return context.json(parseRows(entry, rows));
247
+ });
248
+ }
249
+
250
+ if (entry.mode !== "readonly") {
251
+ if (!crudWritesAllowed) {
252
+ registerMethodNotAllowed(app, basePath, ["POST", "PATCH", "DELETE"], tableKey);
253
+ registerMethodNotAllowed(app, `${basePath}/:id`, ["PATCH", "DELETE"], tableKey);
254
+ return;
255
+ }
256
+
257
+ app.post(basePath, async (context) => {
258
+ await options.operationsLogReady;
259
+
260
+ const requestBody = await context.req.json();
261
+ let payload: unknown;
262
+
263
+ try {
264
+ payload = parseCreatePayload(entry, requestBody);
265
+ } catch (error) {
266
+ await logOperationSafely(db, options.operationsLogConfig, {
267
+ source: "crud",
268
+ backend: options.backend,
269
+ tableName: tableKey,
270
+ operationKind: "create",
271
+ entityKey: extractEntityKeyFromRecord(entry, requestBody),
272
+ payload: requestBody,
273
+ status: "validation_failed",
274
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
275
+ httpStatus: 400,
276
+ requestPath: context.req.path,
277
+ });
278
+
279
+ return context.json(
280
+ {
281
+ message: "Validation failed",
282
+ issues: isValidationError(error) ? error.issues : [],
283
+ },
284
+ 400,
285
+ );
286
+ }
287
+
288
+ try {
289
+ const insertedRow = await db.transaction(async (tx) => {
290
+ const inserted = await tx
291
+ .insert(entry.table)
292
+ .values(payload as never)
293
+ .returning();
294
+
295
+ const row = inserted[0];
296
+ if (!row) {
297
+ throw new Error(`Failed to insert ${tableKey}`);
298
+ }
299
+
300
+ await logOperation(tx, options.operationsLogConfig, {
301
+ source: "crud",
302
+ backend: options.backend,
303
+ tableName: tableKey,
304
+ operationKind: "create",
305
+ entityKey: extractEntityKeyFromRecord(entry, row),
306
+ payload,
307
+ status: "succeeded",
308
+ httpStatus: 201,
309
+ requestPath: context.req.path,
310
+ });
311
+
312
+ return row;
313
+ });
314
+
315
+ return context.json(parseRow(entry, insertedRow), 201);
316
+ } catch (error) {
317
+ await logOperationSafely(db, options.operationsLogConfig, {
318
+ source: "crud",
319
+ backend: options.backend,
320
+ tableName: tableKey,
321
+ operationKind: "create",
322
+ entityKey: extractEntityKeyFromRecord(entry, payload),
323
+ payload,
324
+ status: "execution_failed",
325
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
326
+ httpStatus: 500,
327
+ requestPath: context.req.path,
328
+ });
329
+
330
+ throw error;
331
+ }
332
+ });
333
+
334
+ app.patch(`${basePath}/:id`, async (context) => {
335
+ await options.operationsLogReady;
336
+
337
+ const id = context.req.param("id");
338
+ const entityKey = {
339
+ [primaryKeyColumnName]: id,
340
+ };
341
+ const requestBody = await context.req.json();
342
+ let payload: unknown;
343
+
344
+ try {
345
+ payload = parseUpdatePayload(entry, requestBody);
346
+ } catch (error) {
347
+ await logOperationSafely(db, options.operationsLogConfig, {
348
+ source: "crud",
349
+ backend: options.backend,
350
+ tableName: tableKey,
351
+ operationKind: "update",
352
+ entityKey,
353
+ payload: requestBody,
354
+ status: "validation_failed",
355
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
356
+ httpStatus: 400,
357
+ requestPath: context.req.path,
358
+ });
359
+
360
+ return context.json(
361
+ {
362
+ message: "Validation failed",
363
+ issues: isValidationError(error) ? error.issues : [],
364
+ },
365
+ 400,
366
+ );
367
+ }
368
+
369
+ try {
370
+ const updatedRow = await db.transaction(async (tx) => {
371
+ const updated = await tx
372
+ .update(entry.table)
373
+ .set(withUpdatedAtUs(entry.table, payload))
374
+ .where(eq(primaryKeyColumn, id))
375
+ .returning();
376
+
377
+ if (updated.length === 0) {
378
+ await logOperation(tx, options.operationsLogConfig, {
379
+ source: "crud",
380
+ backend: options.backend,
381
+ tableName: tableKey,
382
+ operationKind: "update",
383
+ entityKey,
384
+ payload,
385
+ status: "not_found",
386
+ httpStatus: 404,
387
+ requestPath: context.req.path,
388
+ });
389
+
390
+ return null;
391
+ }
392
+
393
+ const row = updated[0]!;
394
+
395
+ await logOperation(tx, options.operationsLogConfig, {
396
+ source: "crud",
397
+ backend: options.backend,
398
+ tableName: tableKey,
399
+ operationKind: "update",
400
+ entityKey: extractEntityKeyFromRecord(entry, row) ?? entityKey,
401
+ payload,
402
+ status: "succeeded",
403
+ httpStatus: 200,
404
+ requestPath: context.req.path,
405
+ });
406
+
407
+ return row;
408
+ });
409
+
410
+ if (updatedRow === null) {
411
+ return context.json({ message: `${tableKey} record not found` }, 404);
412
+ }
413
+
414
+ return context.json(parseRow(entry, updatedRow));
415
+ } catch (error) {
416
+ await logOperationSafely(db, options.operationsLogConfig, {
417
+ source: "crud",
418
+ backend: options.backend,
419
+ tableName: tableKey,
420
+ operationKind: "update",
421
+ entityKey,
422
+ payload,
423
+ status: "execution_failed",
424
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
425
+ httpStatus: 500,
426
+ requestPath: context.req.path,
427
+ });
428
+
429
+ throw error;
430
+ }
431
+ });
432
+
433
+ app.delete(`${basePath}/:id`, async (context) => {
434
+ await options.operationsLogReady;
435
+
436
+ const id = context.req.param("id");
437
+ const entityKey = {
438
+ [primaryKeyColumnName]: id,
439
+ };
440
+
441
+ try {
442
+ const deleted = await db.transaction(async (tx) => {
443
+ const deletedRows = await tx.delete(entry.table).where(eq(primaryKeyColumn, id)).returning();
444
+
445
+ if (deletedRows.length === 0) {
446
+ await logOperation(tx, options.operationsLogConfig, {
447
+ source: "crud",
448
+ backend: options.backend,
449
+ tableName: tableKey,
450
+ operationKind: "delete",
451
+ entityKey,
452
+ payload: entityKey,
453
+ status: "not_found",
454
+ httpStatus: 404,
455
+ requestPath: context.req.path,
456
+ });
457
+
458
+ return false;
459
+ }
460
+
461
+ await logOperation(tx, options.operationsLogConfig, {
462
+ source: "crud",
463
+ backend: options.backend,
464
+ tableName: tableKey,
465
+ operationKind: "delete",
466
+ entityKey,
467
+ payload: entityKey,
468
+ status: "succeeded",
469
+ httpStatus: 204,
470
+ requestPath: context.req.path,
471
+ });
472
+
473
+ return true;
474
+ });
475
+
476
+ if (!deleted) {
477
+ return context.json({ message: `${tableKey} record not found` }, 404);
478
+ }
479
+
480
+ return context.body(null, 204);
481
+ } catch (error) {
482
+ await logOperationSafely(db, options.operationsLogConfig, {
483
+ source: "crud",
484
+ backend: options.backend,
485
+ tableName: tableKey,
486
+ operationKind: "delete",
487
+ entityKey,
488
+ payload: entityKey,
489
+ status: "execution_failed",
490
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
491
+ httpStatus: 500,
492
+ requestPath: context.req.path,
493
+ });
494
+
495
+ throw error;
496
+ }
497
+ });
498
+ }
499
+ }
500
+
501
+ function getSinglePrimaryKeyColumnName(entry: SyncTableEntry, tableKey: string) {
502
+ if (entry.primaryKey.columns.length !== 1) {
503
+ throw new Error(`@pgxsinkit/server currently supports single-column primary keys only: ${tableKey}`);
504
+ }
505
+
506
+ return entry.primaryKey.columns[0]!;
507
+ }
508
+
509
+ function getTableColumn(table: AnyPgTable, columnName: string, tableKey: string) {
510
+ const column = (table as unknown as Record<string, unknown>)[columnName];
511
+
512
+ if (!column) {
513
+ throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
514
+ }
515
+
516
+ return column as never;
517
+ }
518
+
519
+ function parseCreatePayload(entry: SyncTableEntry, input: unknown) {
520
+ return entry.schemas?.createSchema ? entry.schemas.createSchema.parse(input) : input;
521
+ }
522
+
523
+ function parseUpdatePayload(entry: SyncTableEntry, input: unknown) {
524
+ return entry.schemas?.updateSchema ? entry.schemas.updateSchema.parse(input) : input;
525
+ }
526
+
527
+ function registerMethodNotAllowed(app: Hono, path: string, methods: string[], tableKey: string) {
528
+ for (const method of methods) {
529
+ app.on(method as "POST" | "PATCH" | "DELETE", path, (context) => {
530
+ context.header("Allow", "GET, OPTIONS");
531
+
532
+ return context.json(
533
+ {
534
+ message: `CRUD ${method} routes are disabled for ${tableKey} when WRITE_API_BACKEND=bulk-plpgsql-artifact. Use POST /api/mutations instead.`,
535
+ },
536
+ 405,
537
+ );
538
+ });
539
+ }
540
+ }
541
+
542
+ function parseRows(entry: SyncTableEntry, rows: unknown[]) {
543
+ return rows.map((row) => parseRow(entry, row));
544
+ }
545
+
546
+ function parseRow(entry: SyncTableEntry, row: unknown) {
547
+ const normalized = normalizeBigInts(row);
548
+ return entry.schemas?.recordSchema ? entry.schemas.recordSchema.parse(normalized) : normalized;
549
+ }
550
+
551
+ function withUpdatedAtUs(table: AnyPgTable, payload: unknown) {
552
+ const values = {
553
+ ...(isRecord(payload) ? payload : {}),
554
+ };
555
+
556
+ if ("updatedAtUs" in table) {
557
+ values.updatedAtUs = sql`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
558
+ }
559
+
560
+ return values as never;
561
+ }
562
+
563
+ function normalizeBigInts(value: unknown): unknown {
564
+ if (typeof value === "bigint") {
565
+ return value.toString();
566
+ }
567
+
568
+ if (Array.isArray(value)) {
569
+ return value.map((entry) => normalizeBigInts(entry));
570
+ }
571
+
572
+ if (isRecord(value)) {
573
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, normalizeBigInts(entry)]));
574
+ }
575
+
576
+ return value;
577
+ }
578
+
579
+ function isRecord(value: unknown): value is Record<string, unknown> {
580
+ return typeof value === "object" && value !== null;
581
+ }
582
+
583
+ function getBunNamespace(): BunNamespace | undefined {
584
+ const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;
585
+ return maybeBun;
586
+ }
587
+
588
+ function isValidationError(error: unknown): error is { issues: unknown[] } {
589
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
590
+ }
591
+
592
+ function resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {
593
+ return {
594
+ enabled: options?.enabled ?? true,
595
+ };
596
+ }
597
+
598
+ function extractEntityKeyFromRecord(entry: SyncTableEntry, value: unknown): Record<string, string> | null {
599
+ if (!isRecord(value)) {
600
+ return null;
601
+ }
602
+
603
+ const entityKey: Record<string, string> = {};
604
+
605
+ for (const primaryKeyColumn of entry.primaryKey.columns) {
606
+ const rawValue = value[primaryKeyColumn];
607
+
608
+ if (rawValue === undefined || rawValue === null) {
609
+ return null;
610
+ }
611
+
612
+ if (
613
+ typeof rawValue === "string" ||
614
+ typeof rawValue === "number" ||
615
+ typeof rawValue === "bigint" ||
616
+ typeof rawValue === "boolean"
617
+ ) {
618
+ entityKey[primaryKeyColumn] = String(rawValue);
619
+ continue;
620
+ }
621
+
622
+ return null;
623
+ }
624
+
625
+ return entityKey;
626
+ }
627
+
628
+ export { buildPlpgsqlBatchFunctionDdl } from "./mutations/bulk/plpgsql-strategy";
@@ -0,0 +1,91 @@
1
+ import { sql } from "drizzle-orm";
2
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
3
+
4
+ import type { MutationEnvelope, RegistryTables, SyncTableRegistry } from "@pgxsinkit/contracts";
5
+
6
+ import type { TransactionClient } from "./types";
7
+
8
+ const DYNAMIC_MUTATION_FUNCTION_DDL = `
9
+ CREATE OR REPLACE FUNCTION pgxsinkit_apply_mutation(
10
+ p_table text,
11
+ p_op text,
12
+ p_payload jsonb,
13
+ p_entity_key jsonb,
14
+ p_pk_col text
15
+ ) RETURNS void LANGUAGE plpgsql AS $$
16
+ DECLARE
17
+ dml_sql text;
18
+ pk_udt text;
19
+ BEGIN
20
+ IF p_op = 'create' THEN
21
+ -- Insert only the columns present in the payload; DB handles defaults for the rest.
22
+ SELECT format(
23
+ 'INSERT INTO %I (%s) VALUES (%s)',
24
+ p_table,
25
+ string_agg(quote_ident(c.column_name), ', '),
26
+ string_agg(format('($1->>%L)::%s', c.column_name, c.udt_name), ', ')
27
+ )
28
+ INTO dml_sql
29
+ FROM information_schema.columns c
30
+ WHERE c.table_schema = 'public'
31
+ AND c.table_name = p_table
32
+ AND (p_payload ? c.column_name);
33
+
34
+ IF dml_sql IS NOT NULL THEN
35
+ EXECUTE dml_sql USING p_payload;
36
+ END IF;
37
+
38
+ ELSIF p_op = 'update' THEN
39
+ SELECT udt_name INTO pk_udt
40
+ FROM information_schema.columns
41
+ WHERE table_schema = 'public'
42
+ AND table_name = p_table
43
+ AND column_name = p_pk_col;
44
+
45
+ -- Update only the non-pk columns present in the payload; use entityKey for the WHERE.
46
+ SELECT format(
47
+ 'UPDATE %I SET %s WHERE %I = ($2->>%L)::%s',
48
+ p_table,
49
+ string_agg(format('%I = ($1->>%L)::%s', c.column_name, c.column_name, c.udt_name), ', '),
50
+ p_pk_col, p_pk_col, pk_udt
51
+ )
52
+ INTO dml_sql
53
+ FROM information_schema.columns c
54
+ WHERE c.table_schema = 'public'
55
+ AND c.table_name = p_table
56
+ AND c.column_name <> p_pk_col
57
+ AND (p_payload ? c.column_name);
58
+
59
+ IF dml_sql IS NOT NULL THEN
60
+ EXECUTE dml_sql USING p_payload, p_entity_key;
61
+ END IF;
62
+
63
+ ELSIF p_op = 'delete' THEN
64
+ SELECT udt_name INTO pk_udt
65
+ FROM information_schema.columns
66
+ WHERE table_schema = 'public'
67
+ AND table_name = p_table
68
+ AND column_name = p_pk_col;
69
+
70
+ EXECUTE format('DELETE FROM %I WHERE %I = ($1->>%L)::%s', p_table, p_pk_col, p_pk_col, pk_udt)
71
+ USING p_entity_key;
72
+ END IF;
73
+ END;
74
+ $$;
75
+ `.trim();
76
+
77
+ export async function installDynamicMutationFunction<TRegistry extends SyncTableRegistry>(
78
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
79
+ ): Promise<void> {
80
+ await db.execute(sql.raw(DYNAMIC_MUTATION_FUNCTION_DDL));
81
+ }
82
+
83
+ export async function executeDynamicMutation(
84
+ tx: TransactionClient,
85
+ mutation: MutationEnvelope,
86
+ primaryKeyColumnName: string,
87
+ ): Promise<void> {
88
+ await tx.execute(
89
+ sql`SELECT pgxsinkit_apply_mutation(${mutation.tableName}, ${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb, ${primaryKeyColumnName})`,
90
+ );
91
+ }