@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/dist/index.js ADDED
@@ -0,0 +1,1414 @@
1
+ // @bun
2
+ // packages/server/src/index.ts
3
+ import { eq, sql as sql7 } from "drizzle-orm";
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
+ // packages/server/src/mutations/bulk/route.ts
10
+ import { getTableName as getTableName3, sql as sql5 } from "drizzle-orm";
11
+ import { getColumns as getColumns3 } from "drizzle-orm/utils";
12
+ import {
13
+ batchMutationRequestSchema,
14
+ getOmittedProjectedColumns as getOmittedProjectionColumns
15
+ } from "@pgxsinkit/contracts";
16
+
17
+ // packages/server/src/operations-log/writer.ts
18
+ import { sql } from "drizzle-orm";
19
+ function toJson(value) {
20
+ if (value === undefined) {
21
+ return null;
22
+ }
23
+ return JSON.stringify(value);
24
+ }
25
+ async function logOperation(executor, config, entry) {
26
+ if (!config.enabled) {
27
+ return;
28
+ }
29
+ const entityKeyJson = toJson(entry.entityKey ?? null);
30
+ const payloadJson = toJson(entry.payload);
31
+ await executor.execute(sql`
32
+ INSERT INTO operations_log (
33
+ source,
34
+ backend,
35
+ table_name,
36
+ operation_kind,
37
+ user_id,
38
+ entity_key_json,
39
+ payload_json,
40
+ status,
41
+ error_message,
42
+ http_status,
43
+ mutation_id,
44
+ mutation_seq,
45
+ client_timestamp_us,
46
+ request_path,
47
+ server_timestamp_us
48
+ ) VALUES (
49
+ ${entry.source},
50
+ ${entry.backend},
51
+ ${entry.tableName ?? null},
52
+ ${entry.operationKind ?? null},
53
+ ${entry.userId ?? null},
54
+ ${entityKeyJson}::jsonb,
55
+ ${payloadJson}::jsonb,
56
+ ${entry.status},
57
+ ${entry.errorMessage ?? null},
58
+ ${entry.httpStatus ?? null},
59
+ ${entry.mutationId ?? null},
60
+ ${entry.mutationSeq ?? null},
61
+ ${entry.clientTimestampUs ?? null},
62
+ ${entry.requestPath ?? null},
63
+ CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)
64
+ )
65
+ `);
66
+ }
67
+ async function logOperationSafely(executor, config, entry) {
68
+ try {
69
+ await logOperation(executor, config, entry);
70
+ } catch {}
71
+ }
72
+
73
+ // packages/server/src/mutations/bulk/dynamic-strategy.ts
74
+ import { sql as sql2 } from "drizzle-orm";
75
+ var DYNAMIC_MUTATION_FUNCTION_DDL = `
76
+ CREATE OR REPLACE FUNCTION pgxsinkit_apply_mutation(
77
+ p_table text,
78
+ p_op text,
79
+ p_payload jsonb,
80
+ p_entity_key jsonb,
81
+ p_pk_col text
82
+ ) RETURNS void LANGUAGE plpgsql AS $$
83
+ DECLARE
84
+ dml_sql text;
85
+ pk_udt text;
86
+ BEGIN
87
+ IF p_op = 'create' THEN
88
+ -- Insert only the columns present in the payload; DB handles defaults for the rest.
89
+ SELECT format(
90
+ 'INSERT INTO %I (%s) VALUES (%s)',
91
+ p_table,
92
+ string_agg(quote_ident(c.column_name), ', '),
93
+ string_agg(format('($1->>%L)::%s', c.column_name, c.udt_name), ', ')
94
+ )
95
+ INTO dml_sql
96
+ FROM information_schema.columns c
97
+ WHERE c.table_schema = 'public'
98
+ AND c.table_name = p_table
99
+ AND (p_payload ? c.column_name);
100
+
101
+ IF dml_sql IS NOT NULL THEN
102
+ EXECUTE dml_sql USING p_payload;
103
+ END IF;
104
+
105
+ ELSIF p_op = 'update' THEN
106
+ SELECT udt_name INTO pk_udt
107
+ FROM information_schema.columns
108
+ WHERE table_schema = 'public'
109
+ AND table_name = p_table
110
+ AND column_name = p_pk_col;
111
+
112
+ -- Update only the non-pk columns present in the payload; use entityKey for the WHERE.
113
+ SELECT format(
114
+ 'UPDATE %I SET %s WHERE %I = ($2->>%L)::%s',
115
+ p_table,
116
+ string_agg(format('%I = ($1->>%L)::%s', c.column_name, c.column_name, c.udt_name), ', '),
117
+ p_pk_col, p_pk_col, pk_udt
118
+ )
119
+ INTO dml_sql
120
+ FROM information_schema.columns c
121
+ WHERE c.table_schema = 'public'
122
+ AND c.table_name = p_table
123
+ AND c.column_name <> p_pk_col
124
+ AND (p_payload ? c.column_name);
125
+
126
+ IF dml_sql IS NOT NULL THEN
127
+ EXECUTE dml_sql USING p_payload, p_entity_key;
128
+ END IF;
129
+
130
+ ELSIF p_op = 'delete' THEN
131
+ SELECT udt_name INTO pk_udt
132
+ FROM information_schema.columns
133
+ WHERE table_schema = 'public'
134
+ AND table_name = p_table
135
+ AND column_name = p_pk_col;
136
+
137
+ EXECUTE format('DELETE FROM %I WHERE %I = ($1->>%L)::%s', p_table, p_pk_col, p_pk_col, pk_udt)
138
+ USING p_entity_key;
139
+ END IF;
140
+ END;
141
+ $$;
142
+ `.trim();
143
+ async function installDynamicMutationFunction(db) {
144
+ await db.execute(sql2.raw(DYNAMIC_MUTATION_FUNCTION_DDL));
145
+ }
146
+ async function executeDynamicMutation(tx, mutation, primaryKeyColumnName) {
147
+ await tx.execute(sql2`SELECT pgxsinkit_apply_mutation(${mutation.tableName}, ${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb, ${primaryKeyColumnName})`);
148
+ }
149
+
150
+ // packages/server/src/mutations/bulk/plpgsql-strategy.ts
151
+ import { getTableName, sql as sql3 } from "drizzle-orm";
152
+ import { getTableConfig } from "drizzle-orm/pg-core";
153
+ import { getColumns } from "drizzle-orm/utils";
154
+ import {
155
+ getProjectedColumns
156
+ } from "@pgxsinkit/contracts";
157
+ var PG_TYPE_MAP = {
158
+ PgUUID: "uuid",
159
+ PgText: "text",
160
+ PgVarchar: "varchar",
161
+ PgChar: "char",
162
+ PgInteger: "integer",
163
+ PgSerial: "integer",
164
+ PgSmallInt: "smallint",
165
+ PgSmallIntNumber: "smallint",
166
+ PgBigInt53: "bigint",
167
+ PgBigInt64: "bigint",
168
+ PgBigIntString: "bigint",
169
+ PgBigSerial: "bigint",
170
+ PgBoolean: "boolean",
171
+ PgNumeric: "numeric",
172
+ PgReal: "real",
173
+ PgDoublePrecision: "double precision",
174
+ PgTimestamp: "timestamptz",
175
+ PgTimestampString: "timestamptz",
176
+ PgDate: "date",
177
+ PgDateString: "date",
178
+ PgTime: "time",
179
+ PgTimeString: "time",
180
+ PgJson: "json",
181
+ PgJsonb: "jsonb",
182
+ PgBytea: "bytea",
183
+ PgVector: "vector"
184
+ };
185
+ function drizzleColumnTypeToPg(columnType) {
186
+ return PG_TYPE_MAP[columnType] ?? "text";
187
+ }
188
+ function drizzleColumnToPg(column) {
189
+ const sqlType = column.getSQLType?.();
190
+ if (sqlType && sqlType.length > 0) {
191
+ return sqlType;
192
+ }
193
+ return drizzleColumnTypeToPg(column.columnType);
194
+ }
195
+ function quoteIdent(name) {
196
+ return `"${name.replace(/"/g, '""')}"`;
197
+ }
198
+ function qualifyIdent(schemaName, name) {
199
+ if (!schemaName) {
200
+ return quoteIdent(name);
201
+ }
202
+ return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;
203
+ }
204
+ function toSqlLiteral(value) {
205
+ return value.replace(/'/g, "''");
206
+ }
207
+ function toSqlTextOrNull(value) {
208
+ return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
209
+ }
210
+ function buildManagedFieldExpression(strategy) {
211
+ if (strategy === "authUid") {
212
+ return "auth.uid()";
213
+ }
214
+ return "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)";
215
+ }
216
+ function getManagedFieldsForOperation(entry, operation) {
217
+ const columns = getColumns(entry.table);
218
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [
219
+ propertyKey,
220
+ { name: column.name, columnType: drizzleColumnToPg(column) }
221
+ ]));
222
+ return (entry.governance?.managedFields ?? []).flatMap((field) => {
223
+ if (!field.applyOn.includes(operation)) {
224
+ return [];
225
+ }
226
+ const column = columnMap.get(field.column);
227
+ if (!column) {
228
+ return [];
229
+ }
230
+ return [
231
+ {
232
+ propertyKey: field.column,
233
+ columnName: column.name,
234
+ columnType: drizzleColumnTypeToPg(column.columnType),
235
+ strategy: field.strategy
236
+ }
237
+ ];
238
+ });
239
+ }
240
+ function buildTableBranch(entry) {
241
+ const tableName = getTableName(entry.table);
242
+ const { schema } = getTableConfig(entry.table);
243
+ const qualifiedTableName = qualifyIdent(schema, tableName);
244
+ const columns = getColumns(entry.table);
245
+ const projectedColumns = getProjectedColumns(entry);
246
+ const primaryKeyColumn = entry.primaryKey.columns[0];
247
+ const primaryKeyColumnObject = Object.values(columns).find((column) => column.name === primaryKeyColumn);
248
+ const primaryKeyType = primaryKeyColumnObject ? drizzleColumnToPg(primaryKeyColumnObject) : drizzleColumnTypeToPg("PgText");
249
+ const createManagedFields = getManagedFieldsForOperation(entry, "create");
250
+ const updateManagedFields = getManagedFieldsForOperation(entry, "update");
251
+ const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));
252
+ const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));
253
+ const allColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => !createManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`).join(`,
254
+ `);
255
+ const nonPrimaryKeyColumnPairs = projectedColumns.map(({ column }) => column).filter((column) => column.name !== primaryKeyColumn && !updateManagedFieldNames.has(column.name)).map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`).join(`,
256
+ `);
257
+ const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
258
+ const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field.strategy)).join(", ");
259
+ const updateManagedAssignmentsSql = updateManagedFields.map((field) => `${quoteIdent(field.columnName)} = ${buildManagedFieldExpression(field.strategy)}`).join(", ");
260
+ const createSqlTemplate = `INSERT INTO ${qualifiedTableName} (%s) VALUES (%s)`.replace(/'/g, "''");
261
+ const updateSqlTemplate = `UPDATE ${qualifiedTableName} SET %s WHERE ${quoteIdent(primaryKeyColumn)} = ($2->>%L)::${primaryKeyType}`.replace(/'/g, "''");
262
+ const createBranch = `
263
+ SELECT format(
264
+ '${createSqlTemplate}',
265
+ concat_ws(', ', nullif(string_agg(quote_ident(col_name), ', '), ''), ${toSqlTextOrNull(createManagedColumnsSql)}),
266
+ concat_ws(', ', nullif(string_agg(format('($1->>%L)::%s', col_name, col_type), ', '), ''), ${toSqlTextOrNull(createManagedValuesSql)})
267
+ )
268
+ INTO dml_sql
269
+ FROM (VALUES
270
+ ${allColumnPairs}
271
+ ) AS col_types(col_name, col_type)
272
+ WHERE v_payload ? col_name;
273
+
274
+ IF dml_sql IS NOT NULL THEN
275
+ EXECUTE dml_sql USING v_payload;
276
+ END IF;
277
+ `.trim();
278
+ const updateBranch = `
279
+ SELECT format(
280
+ '${updateSqlTemplate}',
281
+ concat_ws(', ', nullif(string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '), ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)}),
282
+ '${toSqlLiteral(primaryKeyColumn)}'
283
+ )
284
+ INTO dml_sql
285
+ FROM (VALUES
286
+ ${nonPrimaryKeyColumnPairs}
287
+ ) AS col_types(col_name, col_type)
288
+ WHERE v_payload ? col_name;
289
+
290
+ IF dml_sql IS NOT NULL THEN
291
+ EXECUTE dml_sql USING v_payload, v_entity_key;
292
+ END IF;
293
+ `.trim();
294
+ const deleteBranch = `
295
+ DELETE FROM ${qualifiedTableName}
296
+ WHERE ${quoteIdent(primaryKeyColumn)} = (v_entity_key->>'${toSqlLiteral(primaryKeyColumn)}')::${primaryKeyType};
297
+ `.trim();
298
+ return `
299
+ ELSIF v_table = '${toSqlLiteral(tableName)}' THEN
300
+ IF v_kind = 'create' THEN
301
+ ${createBranch}
302
+ ELSIF v_kind = 'update' THEN
303
+ ${updateBranch}
304
+ ELSIF v_kind = 'delete' THEN
305
+ ${deleteBranch}
306
+ ELSE
307
+ RAISE EXCEPTION 'Unsupported mutation kind "%" for table "%"', v_kind, v_table;
308
+ END IF;
309
+ `.trim();
310
+ }
311
+ function buildPlpgsqlBatchFunctionDdl(registry, options = {}) {
312
+ const tableBranches = Object.values(registry).map((entry) => buildTableBranch(entry)).join(`
313
+ `);
314
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
315
+ return `
316
+ CREATE OR REPLACE FUNCTION ${functionName}(
317
+ p_batch jsonb,
318
+ p_request_path text,
319
+ p_log_enabled boolean,
320
+ p_rls_enabled boolean,
321
+ p_user_claims jsonb
322
+ ) RETURNS void LANGUAGE plpgsql AS $$
323
+ DECLARE
324
+ mutation jsonb;
325
+ dml_sql text;
326
+ v_table text;
327
+ v_kind text;
328
+ v_payload jsonb;
329
+ v_entity_key jsonb;
330
+ v_mutation_id text;
331
+ v_mutation_seq integer;
332
+ v_client_timestamp_us bigint;
333
+ BEGIN
334
+ IF p_rls_enabled THEN
335
+ PERFORM auth.set_auth_context(COALESCE(p_user_claims, '{}'::jsonb));
336
+ END IF;
337
+
338
+ IF jsonb_typeof(p_batch) <> 'object' THEN
339
+ RAISE EXCEPTION 'Batch payload must be a JSON object';
340
+ END IF;
341
+
342
+ IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN
343
+ RAISE EXCEPTION 'Batch payload mutations must be a JSON array';
344
+ END IF;
345
+
346
+ FOR mutation IN SELECT value FROM jsonb_array_elements(p_batch->'mutations')
347
+ LOOP
348
+ dml_sql := NULL;
349
+ v_table := mutation->>'tableName';
350
+ v_kind := mutation->>'kind';
351
+ v_payload := COALESCE(mutation->'payload', '{}'::jsonb);
352
+ v_entity_key := COALESCE(mutation->'entityKey', '{}'::jsonb);
353
+ v_mutation_id := mutation->>'mutationId';
354
+ v_mutation_seq := (mutation->>'mutationSeq')::integer;
355
+ v_client_timestamp_us := NULLIF(mutation->>'clientTimestampUs', '')::bigint;
356
+
357
+ IF FALSE THEN
358
+ NULL;
359
+ ${tableBranches}
360
+ ELSE
361
+ RAISE EXCEPTION 'Unknown table "%" in batch mutation', v_table;
362
+ END IF;
363
+
364
+ IF p_log_enabled THEN
365
+ INSERT INTO operations_log (
366
+ source,
367
+ backend,
368
+ table_name,
369
+ operation_kind,
370
+ entity_key_json,
371
+ payload_json,
372
+ status,
373
+ http_status,
374
+ mutation_id,
375
+ mutation_seq,
376
+ client_timestamp_us,
377
+ request_path,
378
+ server_timestamp_us
379
+ ) VALUES (
380
+ 'batch',
381
+ 'bulk-plpgsql',
382
+ v_table,
383
+ v_kind,
384
+ v_entity_key,
385
+ v_payload,
386
+ 'succeeded',
387
+ 200,
388
+ v_mutation_id::uuid,
389
+ v_mutation_seq,
390
+ v_client_timestamp_us,
391
+ p_request_path,
392
+ CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)
393
+ );
394
+ END IF;
395
+ END LOOP;
396
+ END;
397
+ $$;
398
+ `.trim();
399
+ }
400
+ async function installPlpgsqlBatchFunction(db, registry, options = {}) {
401
+ const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);
402
+ await db.execute(sql3.raw(ddl));
403
+ }
404
+ async function verifyPlpgsqlBatchFunction(db, options = {}) {
405
+ const functionSignature = `${options.functionSchema ? `${options.functionSchema}.` : "public."}pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb)`;
406
+ const result = await db.execute(sql3`
407
+ SELECT to_regprocedure(${functionSignature})::text AS "functionName"
408
+ `);
409
+ const row = Array.from(result, (entry) => entry)[0];
410
+ if (!row?.functionName) {
411
+ throw new Error("bulk-plpgsql-artifact backend requires preinstalled function pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb). Apply sync function migrations before starting the write API.");
412
+ }
413
+ }
414
+ async function verifyArtifactRlsAuthHelpers(db) {
415
+ const result = await db.execute(sql3`
416
+ SELECT
417
+ to_regprocedure('auth.set_auth_context(jsonb)')::text AS "setAuthContext",
418
+ to_regprocedure('auth.uid()')::text AS "authUid",
419
+ to_regprocedure('auth.jwt()')::text AS "authJwt",
420
+ to_regprocedure('auth.has_role(text)')::text AS "authHasRole"
421
+ `);
422
+ const row = Array.from(result, (entry) => entry)[0];
423
+ const missingHelpers = [
424
+ row?.setAuthContext ? null : "auth.set_auth_context(jsonb)",
425
+ row?.authUid ? null : "auth.uid()",
426
+ row?.authJwt ? null : "auth.jwt()",
427
+ row?.authHasRole ? null : "auth.has_role(text)"
428
+ ].filter((value) => value !== null);
429
+ if (missingHelpers.length > 0) {
430
+ throw new Error(`bulk-plpgsql-artifact backend with RLS-enabled tables requires governance SQL to be applied. Missing: ${missingHelpers.join(", ")}. Run bun run db:apply:governance.`);
431
+ }
432
+ }
433
+ async function executePlpgsqlBatch(tx, batch, requestPath, logEnabled, rlsEnabled, userClaims, options = {}) {
434
+ const normalizedClaims = userClaims ?? {};
435
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
436
+ await tx.execute(sql3`SELECT ${sql3.raw(functionName)}(${JSON.stringify(batch)}::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::jsonb)`);
437
+ }
438
+
439
+ // packages/server/src/mutations/bulk/pregenerated-strategy.ts
440
+ import { getTableName as getTableName2, sql as sql4 } from "drizzle-orm";
441
+ import { getColumns as getColumns2 } from "drizzle-orm/utils";
442
+ var PG_TYPE_MAP2 = {
443
+ PgUUID: "uuid",
444
+ PgText: "text",
445
+ PgVarchar: "varchar",
446
+ PgChar: "char",
447
+ PgInteger: "integer",
448
+ PgSerial: "integer",
449
+ PgSmallInt: "smallint",
450
+ PgSmallIntNumber: "smallint",
451
+ PgBigInt53: "bigint",
452
+ PgBigInt64: "bigint",
453
+ PgBigIntString: "bigint",
454
+ PgBigSerial: "bigint",
455
+ PgBoolean: "boolean",
456
+ PgNumeric: "numeric",
457
+ PgReal: "real",
458
+ PgDoublePrecision: "double precision",
459
+ PgTimestamp: "timestamptz",
460
+ PgTimestampString: "timestamptz",
461
+ PgDate: "date",
462
+ PgDateString: "date",
463
+ PgTime: "time",
464
+ PgTimeString: "time",
465
+ PgJson: "json",
466
+ PgJsonb: "jsonb",
467
+ PgBytea: "bytea",
468
+ PgVector: "vector"
469
+ };
470
+ function drizzleColumnTypeToPg2(columnType) {
471
+ return PG_TYPE_MAP2[columnType] ?? "text";
472
+ }
473
+ function safeFunctionName(tableName) {
474
+ return tableName.toLowerCase().replace(/[^a-z0-9_]/g, "_");
475
+ }
476
+ function quoteIdent2(name) {
477
+ return `"${name.replace(/"/g, '""')}"`;
478
+ }
479
+ function buildPregeneratedFunctionDdl(entry) {
480
+ const tableName = getTableName2(entry.table);
481
+ const fnName = `pgxsinkit_apply_${safeFunctionName(tableName)}_mutation`;
482
+ const columns = getColumns2(entry.table);
483
+ const pkCol = entry.primaryKey.columns[0];
484
+ const pkColObj = Object.values(columns).find((col) => col.name === pkCol);
485
+ const pkType = drizzleColumnTypeToPg2(pkColObj?.columnType ?? "PgText");
486
+ const sqlLit = (s) => s.replace(/'/g, "''");
487
+ const allColPairs = Object.values(columns).map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg2(col.columnType))}')`).join(`,
488
+ `);
489
+ const nonPkColPairs = Object.values(columns).filter((col) => col.name !== pkCol).map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg2(col.columnType))}')`).join(`,
490
+ `);
491
+ const createFormatTpl = `INSERT INTO ${quoteIdent2(tableName)} (%s) VALUES (%s)`.replace(/'/g, "''");
492
+ const updateFormatTpl = `UPDATE ${quoteIdent2(tableName)} SET %s WHERE ${quoteIdent2(pkCol)} = ($2->>%L)::${pkType}`.replace(/'/g, "''");
493
+ return `
494
+ CREATE OR REPLACE FUNCTION ${fnName}(p_op text, p_payload jsonb, p_entity_key jsonb) RETURNS void LANGUAGE plpgsql AS $$
495
+ DECLARE
496
+ dml_sql text;
497
+ BEGIN
498
+ IF p_op = 'create' THEN
499
+ -- Only insert columns present in the payload; DB handles defaults for the rest.
500
+ SELECT format(
501
+ '${createFormatTpl}',
502
+ string_agg(quote_ident(col_name), ', '),
503
+ string_agg(format('($1->>%L)::%s', col_name, col_type), ', ')
504
+ )
505
+ INTO dml_sql
506
+ FROM (VALUES
507
+ ${allColPairs}
508
+ ) AS t(col_name, col_type)
509
+ WHERE p_payload ? col_name;
510
+
511
+ IF dml_sql IS NOT NULL THEN
512
+ EXECUTE dml_sql USING p_payload;
513
+ END IF;
514
+
515
+ ELSIF p_op = 'update' THEN
516
+ -- Only update non-pk columns present in the payload; use entityKey for the WHERE.
517
+ SELECT format(
518
+ '${updateFormatTpl}',
519
+ string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '),
520
+ '${sqlLit(pkCol)}'
521
+ )
522
+ INTO dml_sql
523
+ FROM (VALUES
524
+ ${nonPkColPairs}
525
+ ) AS t(col_name, col_type)
526
+ WHERE p_payload ? col_name;
527
+
528
+ IF dml_sql IS NOT NULL THEN
529
+ EXECUTE dml_sql USING p_payload, p_entity_key;
530
+ END IF;
531
+
532
+ ELSIF p_op = 'delete' THEN
533
+ DELETE FROM ${quoteIdent2(tableName)} WHERE ${quoteIdent2(pkCol)} = (p_entity_key->>'${sqlLit(pkCol)}')::${pkType};
534
+ END IF;
535
+ END;
536
+ $$;
537
+ `.trim();
538
+ }
539
+ async function installPregeneratedMutationFunctions(db, registry) {
540
+ for (const [, entry] of Object.entries(registry)) {
541
+ const ddl = buildPregeneratedFunctionDdl(entry);
542
+ await db.execute(sql4.raw(ddl));
543
+ }
544
+ }
545
+ async function executePregeneratedMutation(tx, mutation) {
546
+ const fnName = `pgxsinkit_apply_${safeFunctionName(mutation.tableName)}_mutation`;
547
+ await tx.execute(sql4`SELECT ${sql4.raw(fnName)}(${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb)`);
548
+ }
549
+
550
+ // packages/server/src/mutations/bulk/route.ts
551
+ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConfig, operationsLogReady, resolveAuthClaims) {
552
+ const startupReady = installBulkStartupDdl(db, registry, backend);
553
+ app.post("/api/mutations", async (context) => {
554
+ await Promise.all([startupReady, operationsLogReady]);
555
+ let rawBody;
556
+ try {
557
+ rawBody = await context.req.json();
558
+ } catch (error) {
559
+ await logOperationSafely(db, operationsLogConfig, {
560
+ source: "batch",
561
+ backend,
562
+ tableName: null,
563
+ operationKind: null,
564
+ entityKey: null,
565
+ payload: null,
566
+ status: "validation_failed",
567
+ errorMessage: error instanceof Error ? error.message : "Invalid JSON request body",
568
+ httpStatus: 400,
569
+ requestPath: context.req.path
570
+ });
571
+ return context.json({
572
+ message: "Invalid batch mutation request",
573
+ issues: []
574
+ }, 400);
575
+ }
576
+ let body;
577
+ try {
578
+ body = batchMutationRequestSchema.parse(rawBody);
579
+ } catch (error) {
580
+ await logOperationSafely(db, operationsLogConfig, {
581
+ source: "batch",
582
+ backend,
583
+ tableName: null,
584
+ operationKind: null,
585
+ entityKey: null,
586
+ payload: rawBody,
587
+ status: "validation_failed",
588
+ errorMessage: error instanceof Error ? error.message : "Invalid batch mutation request",
589
+ httpStatus: 400,
590
+ requestPath: context.req.path
591
+ });
592
+ return context.json({
593
+ message: "Invalid batch mutation request",
594
+ issues: isValidationError(error) ? error.issues : []
595
+ }, 400);
596
+ }
597
+ const validationErrors = [];
598
+ const invalidMutations = [];
599
+ for (const mutation of body.mutations) {
600
+ if (!(mutation.tableName in registry)) {
601
+ const message = `Unknown table: ${mutation.tableName}`;
602
+ validationErrors.push(message);
603
+ invalidMutations.push({ mutation, message });
604
+ continue;
605
+ }
606
+ const entry = registry[mutation.tableName];
607
+ const syncEntry = entry;
608
+ const schemas = syncEntry.schemas;
609
+ const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);
610
+ const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
611
+ if (projectedFieldViolations.length > 0) {
612
+ const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(", ")}`;
613
+ validationErrors.push(message);
614
+ invalidMutations.push({ mutation, message });
615
+ continue;
616
+ }
617
+ if (backend === "bulk-plpgsql-artifact") {
618
+ const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
619
+ if (managedFieldViolations.length > 0) {
620
+ const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
621
+ validationErrors.push(message);
622
+ invalidMutations.push({ mutation, message });
623
+ continue;
624
+ }
625
+ }
626
+ try {
627
+ if (mutation.kind === "create" && schemas?.createSchema) {
628
+ schemas.createSchema.parse(normalizedPayload);
629
+ } else if (mutation.kind === "update" && schemas?.updateSchema) {
630
+ schemas.updateSchema.parse(normalizedPayload);
631
+ }
632
+ } catch (error) {
633
+ const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : "";
634
+ const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;
635
+ validationErrors.push(message);
636
+ invalidMutations.push({ mutation, message });
637
+ }
638
+ }
639
+ if (validationErrors.length > 0) {
640
+ for (const invalidMutation of invalidMutations) {
641
+ await logOperationSafely(db, operationsLogConfig, {
642
+ source: "batch",
643
+ backend,
644
+ tableName: invalidMutation.mutation.tableName,
645
+ operationKind: invalidMutation.mutation.kind,
646
+ entityKey: invalidMutation.mutation.entityKey,
647
+ payload: invalidMutation.mutation.payload,
648
+ status: "validation_failed",
649
+ errorMessage: invalidMutation.message,
650
+ httpStatus: 400,
651
+ mutationId: invalidMutation.mutation.mutationId,
652
+ mutationSeq: invalidMutation.mutation.mutationSeq,
653
+ clientTimestampUs: invalidMutation.mutation.clientTimestampUs,
654
+ requestPath: context.req.path
655
+ });
656
+ }
657
+ return context.json({ message: `Payload validation failed: ${validationErrors.join("; ")}` }, 400);
658
+ }
659
+ const acks = [];
660
+ let actorUserId = null;
661
+ const artifactAuthContextRequired = backend === "bulk-plpgsql-artifact" && isArtifactAuthContextRequired(registry);
662
+ try {
663
+ await db.transaction(async (tx) => {
664
+ if (backend === "bulk-plpgsql" || backend === "bulk-plpgsql-artifact") {
665
+ const shouldApplyRlsContext = artifactAuthContextRequired;
666
+ let userClaims = {};
667
+ if (shouldApplyRlsContext) {
668
+ const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
669
+ if (!isPlainObject(resolvedClaims)) {
670
+ await logOperationSafely(db, operationsLogConfig, {
671
+ source: "batch",
672
+ backend,
673
+ tableName: null,
674
+ operationKind: null,
675
+ entityKey: null,
676
+ payload: rawBody,
677
+ status: "validation_failed",
678
+ errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
679
+ httpStatus: 401,
680
+ requestPath: context.req.path
681
+ });
682
+ throw new UnauthorizedBatchMutationError("RLS-enabled artifact backend requires validated JWT claims in request context");
683
+ }
684
+ userClaims = resolvedClaims;
685
+ actorUserId = getUuidClaim(userClaims, "sub");
686
+ }
687
+ const batchRequest = backend === "bulk-plpgsql-artifact" ? sanitizeArtifactRestrictedFields(body, registry) : body;
688
+ if (backend === "bulk-plpgsql-artifact") {
689
+ await tx.execute(sql5`SET CONSTRAINTS ALL DEFERRED`);
690
+ }
691
+ await executePlpgsqlBatch(tx, batchRequest, context.req.path, operationsLogConfig.enabled && backend === "bulk-plpgsql", shouldApplyRlsContext, userClaims);
692
+ if (shouldApplyRlsContext) {
693
+ await tx.execute(sql5`RESET ROLE`);
694
+ }
695
+ for (const mutation of batchRequest.mutations) {
696
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, registry[mutation.tableName], mutation.entityKey);
697
+ if (backend === "bulk-plpgsql-artifact") {
698
+ await logOperation(tx, operationsLogConfig, {
699
+ source: "batch",
700
+ backend,
701
+ tableName: mutation.tableName,
702
+ operationKind: mutation.kind,
703
+ entityKey: mutation.entityKey,
704
+ payload: mutation.payload,
705
+ status: "succeeded",
706
+ httpStatus: 200,
707
+ mutationId: mutation.mutationId,
708
+ mutationSeq: mutation.mutationSeq,
709
+ clientTimestampUs: mutation.clientTimestampUs,
710
+ requestPath: context.req.path,
711
+ userId: actorUserId
712
+ });
713
+ }
714
+ acks.push({
715
+ tableName: mutation.tableName,
716
+ entityKey: mutation.entityKey,
717
+ mutationId: mutation.mutationId,
718
+ mutationSeq: mutation.mutationSeq,
719
+ status: "acked",
720
+ ...serverUpdatedAtUs ? { serverUpdatedAtUs } : {}
721
+ });
722
+ }
723
+ return;
724
+ }
725
+ for (const mutation of body.mutations) {
726
+ const entry = registry[mutation.tableName];
727
+ const primaryKeyColumnName = entry.primaryKey.columns[0];
728
+ if (backend === "bulk-dynamic") {
729
+ await executeDynamicMutation(tx, mutation, primaryKeyColumnName);
730
+ } else {
731
+ await executePregeneratedMutation(tx, mutation);
732
+ }
733
+ await logOperation(tx, operationsLogConfig, {
734
+ source: "batch",
735
+ backend,
736
+ tableName: mutation.tableName,
737
+ operationKind: mutation.kind,
738
+ entityKey: mutation.entityKey,
739
+ payload: mutation.payload,
740
+ status: "succeeded",
741
+ httpStatus: 200,
742
+ mutationId: mutation.mutationId,
743
+ mutationSeq: mutation.mutationSeq,
744
+ clientTimestampUs: mutation.clientTimestampUs,
745
+ requestPath: context.req.path,
746
+ userId: actorUserId
747
+ });
748
+ const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, entry, mutation.entityKey);
749
+ acks.push({
750
+ tableName: mutation.tableName,
751
+ entityKey: mutation.entityKey,
752
+ mutationId: mutation.mutationId,
753
+ mutationSeq: mutation.mutationSeq,
754
+ status: "acked",
755
+ ...serverUpdatedAtUs ? { serverUpdatedAtUs } : {}
756
+ });
757
+ }
758
+ });
759
+ } catch (error) {
760
+ if (error instanceof UnauthorizedBatchMutationError) {
761
+ return context.json({ message: error.message }, 401);
762
+ }
763
+ const errorMessage = formatBatchExecutionError(error);
764
+ for (const mutation of body.mutations) {
765
+ await logOperationSafely(db, operationsLogConfig, {
766
+ source: "batch",
767
+ backend,
768
+ tableName: mutation.tableName,
769
+ operationKind: mutation.kind,
770
+ entityKey: mutation.entityKey,
771
+ payload: mutation.payload,
772
+ status: "execution_failed",
773
+ errorMessage,
774
+ httpStatus: 500,
775
+ mutationId: mutation.mutationId,
776
+ mutationSeq: mutation.mutationSeq,
777
+ clientTimestampUs: mutation.clientTimestampUs,
778
+ requestPath: context.req.path,
779
+ userId: actorUserId
780
+ });
781
+ }
782
+ return context.json({ message: errorMessage }, 500);
783
+ }
784
+ return context.json({ acks });
785
+ });
786
+ }
787
+ function isValidationError(error) {
788
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
789
+ }
790
+ function isPlainObject(value) {
791
+ return typeof value === "object" && value !== null && !Array.isArray(value);
792
+ }
793
+ function formatBatchExecutionError(error) {
794
+ const rootCause = getRootCauseError(error);
795
+ if (!rootCause) {
796
+ return "Batch mutation failed";
797
+ }
798
+ const details = [rootCause.message];
799
+ const errorCode = getErrorStringProperty(rootCause, "code");
800
+ const errorDetail = getErrorStringProperty(rootCause, "detail");
801
+ const errorHint = getErrorStringProperty(rootCause, "hint");
802
+ if (errorCode) {
803
+ details.push(`code: ${errorCode}`);
804
+ }
805
+ if (errorDetail) {
806
+ details.push(`detail: ${errorDetail}`);
807
+ }
808
+ if (errorHint) {
809
+ details.push(`hint: ${errorHint}`);
810
+ }
811
+ return details.join(" | ");
812
+ }
813
+ function getRootCauseError(error) {
814
+ let current = error;
815
+ let lastError = null;
816
+ const seen = new Set;
817
+ while (current instanceof Error && !seen.has(current)) {
818
+ seen.add(current);
819
+ lastError = current;
820
+ current = current.cause;
821
+ }
822
+ return lastError;
823
+ }
824
+ function getErrorStringProperty(error, key) {
825
+ if (!(key in error)) {
826
+ return null;
827
+ }
828
+ const value = error[key];
829
+ return typeof value === "string" && value.length > 0 ? value : null;
830
+ }
831
+ function isArtifactAuthContextRequired(registry) {
832
+ return Object.values(registry).some((entry) => entry.governance?.rls?.enabled === true || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authUid"));
833
+ }
834
+
835
+ class UnauthorizedBatchMutationError extends Error {
836
+ }
837
+ function getUuidClaim(claims, key) {
838
+ const value = claims[key];
839
+ if (typeof value !== "string") {
840
+ return null;
841
+ }
842
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
843
+ }
844
+ function findManagedFieldViolations(entry, mutationKind, payload) {
845
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
846
+ return [];
847
+ }
848
+ const managedFields = getManagedFieldsForOperation2(entry, mutationKind);
849
+ if (managedFields.length === 0) {
850
+ return [];
851
+ }
852
+ const payloadKeys = new Set(Object.keys(payload));
853
+ return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);
854
+ }
855
+ function findProjectedFieldViolations(entry, mutationKind, payload) {
856
+ if (mutationKind === "delete" || !isPlainObject(payload)) {
857
+ return [];
858
+ }
859
+ const projectedFields = getProjectedAwayFields(entry);
860
+ if (projectedFields.length === 0) {
861
+ return [];
862
+ }
863
+ const payloadKeys = new Set(Object.keys(payload));
864
+ return [
865
+ ...new Set(projectedFields.filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName)).map((field) => field.propertyKey))
866
+ ];
867
+ }
868
+ function sanitizeArtifactRestrictedFields(batch, registry) {
869
+ return {
870
+ mutations: batch.mutations.map((mutation) => {
871
+ if (mutation.kind === "delete") {
872
+ return mutation;
873
+ }
874
+ const entry = registry[mutation.tableName];
875
+ if (!entry) {
876
+ return mutation;
877
+ }
878
+ const managedFields = getManagedFieldsForOperation2(entry, mutation.kind);
879
+ const projectedFields = getProjectedAwayFields(entry);
880
+ if (managedFields.length === 0 && projectedFields.length === 0) {
881
+ return mutation;
882
+ }
883
+ const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};
884
+ for (const field of managedFields) {
885
+ delete payload[field.propertyKey];
886
+ delete payload[field.columnName];
887
+ }
888
+ for (const field of projectedFields) {
889
+ delete payload[field.propertyKey];
890
+ delete payload[field.columnName];
891
+ }
892
+ return {
893
+ ...mutation,
894
+ payload
895
+ };
896
+ })
897
+ };
898
+ }
899
+ function getManagedFieldsForOperation2(entry, mutationKind) {
900
+ if (mutationKind === "delete") {
901
+ return [];
902
+ }
903
+ const columns = getColumns3(entry.table);
904
+ const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
905
+ return (entry.governance?.managedFields ?? []).filter((field) => field.applyOn.includes(mutationKind)).map((field) => ({
906
+ propertyKey: field.column,
907
+ columnName: columnMap.get(field.column) ?? field.column,
908
+ strategy: field.strategy
909
+ }));
910
+ }
911
+ function getProjectedAwayFields(entry) {
912
+ return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
913
+ propertyKey,
914
+ columnName
915
+ }));
916
+ }
917
+ function toSchemaPayload(entry, payload) {
918
+ if (!isPlainObject(payload)) {
919
+ return payload;
920
+ }
921
+ const columns = getColumns3(entry.table);
922
+ const keyMap = new Map;
923
+ for (const [propertyKey, column] of Object.entries(columns)) {
924
+ keyMap.set(propertyKey, propertyKey);
925
+ keyMap.set(column.name, propertyKey);
926
+ }
927
+ return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));
928
+ }
929
+ async function readServerUpdatedAtUs(tx, entry, entityKey) {
930
+ const columns = getColumns3(entry.table);
931
+ const updatedAtColumn = Object.values(columns).find((column) => column.name === "updated_at_us");
932
+ if (!updatedAtColumn) {
933
+ return;
934
+ }
935
+ const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {
936
+ const rawValue = entityKey[primaryKeyColumn];
937
+ if (rawValue === undefined) {
938
+ throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);
939
+ }
940
+ return sql5`${quoteIdentifier(primaryKeyColumn)} = ${rawValue}`;
941
+ });
942
+ const result = await tx.execute(sql5`
943
+ SELECT ${quoteIdentifier("updated_at_us")}::text AS "updatedAtUs"
944
+ FROM ${quoteIdentifier(getTableName3(entry.table))}
945
+ WHERE ${sql5.join(conditions, sql5` AND `)}
946
+ LIMIT 1
947
+ `);
948
+ const row = Array.from(result)[0];
949
+ return row?.updatedAtUs ?? undefined;
950
+ }
951
+ function quoteIdentifier(identifier) {
952
+ return sql5.raw(`"${identifier.replace(/"/g, '""')}"`);
953
+ }
954
+ async function installBulkStartupDdl(db, registry, backend) {
955
+ if (backend === "bulk-dynamic") {
956
+ await installDynamicMutationFunction(db);
957
+ return;
958
+ }
959
+ if (backend === "bulk-plpgsql") {
960
+ await installPlpgsqlBatchFunction(db, registry);
961
+ return;
962
+ }
963
+ if (backend === "bulk-plpgsql-artifact") {
964
+ await verifyPlpgsqlBatchFunction(db);
965
+ if (isArtifactAuthContextRequired(registry)) {
966
+ await verifyArtifactRlsAuthHelpers(db);
967
+ }
968
+ return;
969
+ }
970
+ await installPregeneratedMutationFunctions(db, registry);
971
+ }
972
+
973
+ // packages/server/src/operations-log/ddl.ts
974
+ import { sql as sql6 } from "drizzle-orm";
975
+ async function ensureOperationsLogSchema(db, config) {
976
+ if (!config.enabled) {
977
+ return;
978
+ }
979
+ const result = await db.execute(sql6`
980
+ SELECT to_regclass('public.operations_log')::text AS "tableName"
981
+ `);
982
+ const row = Array.from(result, (entry) => entry)[0];
983
+ if (!row?.tableName) {
984
+ throw new Error("operations_log table is missing. Run bun run db:push before starting the write API.");
985
+ }
986
+ }
987
+
988
+ // packages/server/src/index.ts
989
+ var defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
990
+ function createSyncServer(options) {
991
+ const client = createPostgresClient(options.databaseUrl);
992
+ const schema = buildSchema(options.registry);
993
+ const db = drizzle({ client, schema });
994
+ const app = new Hono;
995
+ let bunServer;
996
+ const status = {
997
+ phase: "ready",
998
+ isRunning: false
999
+ };
1000
+ let address = null;
1001
+ const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
1002
+ const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
1003
+ const backend = options.backend ?? "drizzle";
1004
+ app.use("/api/*", cors({
1005
+ origin: options.allowedOrigins ?? defaultAllowedOrigins,
1006
+ allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
1007
+ allowHeaders: ["Content-Type", "Authorization"]
1008
+ }));
1009
+ app.onError((error, context) => {
1010
+ status.phase = "degraded";
1011
+ status.lastError = error instanceof Error ? error.message : "Unexpected error";
1012
+ options.onStatusChange?.(status);
1013
+ if (isValidationError2(error)) {
1014
+ return context.json({
1015
+ message: "Validation failed",
1016
+ issues: error.issues
1017
+ }, 400);
1018
+ }
1019
+ return context.json({
1020
+ message: error instanceof Error ? error.message : "Unexpected error"
1021
+ }, 500);
1022
+ });
1023
+ app.get("/health", (context) => {
1024
+ return context.json({ ok: true });
1025
+ });
1026
+ for (const [tableKey, entry] of Object.entries(options.registry)) {
1027
+ registerTableRoutes(app, db, tableKey, entry, {
1028
+ backend,
1029
+ operationsLogConfig,
1030
+ operationsLogReady
1031
+ });
1032
+ }
1033
+ if (backend !== "drizzle") {
1034
+ registerBulkMutationRoute(app, db, options.registry, backend, operationsLogConfig, operationsLogReady, options.resolveAuthClaims);
1035
+ }
1036
+ const fetch = async (request) => app.fetch(request);
1037
+ return {
1038
+ drizzle: db,
1039
+ fetch,
1040
+ request: (path, init) => {
1041
+ const baseUrl = address === null ? "http://localhost" : `http://${address.host}:${address.port}`;
1042
+ return fetch(new Request(new URL(path, baseUrl), init));
1043
+ },
1044
+ start: async () => {
1045
+ if (bunServer) {
1046
+ return;
1047
+ }
1048
+ const bun = getBunNamespace();
1049
+ if (!bun) {
1050
+ throw new Error("createSyncServer.start() requires the Bun runtime");
1051
+ }
1052
+ const host = options.host ?? "0.0.0.0";
1053
+ const port = options.port ?? 3001;
1054
+ const idleTimeout = options.idleTimeoutSeconds;
1055
+ bunServer = bun.serve({
1056
+ hostname: host,
1057
+ port,
1058
+ ...idleTimeout !== undefined ? { idleTimeout } : {},
1059
+ fetch: app.fetch
1060
+ });
1061
+ status.isRunning = true;
1062
+ status.phase = "ready";
1063
+ delete status.lastError;
1064
+ address = { host, port };
1065
+ options.onStatusChange?.(status);
1066
+ },
1067
+ stop: async () => {
1068
+ bunServer?.stop();
1069
+ bunServer = undefined;
1070
+ status.isRunning = false;
1071
+ await client.end();
1072
+ options.onStatusChange?.(status);
1073
+ },
1074
+ status,
1075
+ get address() {
1076
+ return address;
1077
+ },
1078
+ diagnostics: () => ({
1079
+ tables: Object.keys(options.registry),
1080
+ modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),
1081
+ routes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.routes]))
1082
+ })
1083
+ };
1084
+ }
1085
+ function createPostgresClient(connectionString) {
1086
+ const url = new URL(connectionString);
1087
+ const sslmode = url.searchParams.get("sslmode");
1088
+ return postgres({
1089
+ host: url.hostname,
1090
+ port: Number(url.port || "5432"),
1091
+ database: url.pathname.replace(/^\//, ""),
1092
+ user: decodeURIComponent(url.username),
1093
+ password: decodeURIComponent(url.password),
1094
+ ssl: sslmode === "disable" ? false : "prefer",
1095
+ max: 10
1096
+ });
1097
+ }
1098
+ function buildSchema(registry) {
1099
+ return Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, entry.table]));
1100
+ }
1101
+ function registerTableRoutes(app, db, tableKey, entry, options) {
1102
+ const basePath = entry.routes?.basePath;
1103
+ if (!basePath) {
1104
+ return;
1105
+ }
1106
+ const primaryKeyColumnName = getSinglePrimaryKeyColumnName(entry, tableKey);
1107
+ const primaryKeyColumn = getTableColumn(entry.table, primaryKeyColumnName, tableKey);
1108
+ const crudWritesAllowed = options.backend !== "bulk-plpgsql-artifact";
1109
+ if (entry.mode !== "writeonly") {
1110
+ app.get(basePath, async (context) => {
1111
+ const rows = await db.select().from(entry.table);
1112
+ return context.json(parseRows(entry, rows));
1113
+ });
1114
+ }
1115
+ if (entry.mode !== "readonly") {
1116
+ if (!crudWritesAllowed) {
1117
+ registerMethodNotAllowed(app, basePath, ["POST", "PATCH", "DELETE"], tableKey);
1118
+ registerMethodNotAllowed(app, `${basePath}/:id`, ["PATCH", "DELETE"], tableKey);
1119
+ return;
1120
+ }
1121
+ app.post(basePath, async (context) => {
1122
+ await options.operationsLogReady;
1123
+ const requestBody = await context.req.json();
1124
+ let payload;
1125
+ try {
1126
+ payload = parseCreatePayload(entry, requestBody);
1127
+ } catch (error) {
1128
+ await logOperationSafely(db, options.operationsLogConfig, {
1129
+ source: "crud",
1130
+ backend: options.backend,
1131
+ tableName: tableKey,
1132
+ operationKind: "create",
1133
+ entityKey: extractEntityKeyFromRecord(entry, requestBody),
1134
+ payload: requestBody,
1135
+ status: "validation_failed",
1136
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
1137
+ httpStatus: 400,
1138
+ requestPath: context.req.path
1139
+ });
1140
+ return context.json({
1141
+ message: "Validation failed",
1142
+ issues: isValidationError2(error) ? error.issues : []
1143
+ }, 400);
1144
+ }
1145
+ try {
1146
+ const insertedRow = await db.transaction(async (tx) => {
1147
+ const inserted = await tx.insert(entry.table).values(payload).returning();
1148
+ const row = inserted[0];
1149
+ if (!row) {
1150
+ throw new Error(`Failed to insert ${tableKey}`);
1151
+ }
1152
+ await logOperation(tx, options.operationsLogConfig, {
1153
+ source: "crud",
1154
+ backend: options.backend,
1155
+ tableName: tableKey,
1156
+ operationKind: "create",
1157
+ entityKey: extractEntityKeyFromRecord(entry, row),
1158
+ payload,
1159
+ status: "succeeded",
1160
+ httpStatus: 201,
1161
+ requestPath: context.req.path
1162
+ });
1163
+ return row;
1164
+ });
1165
+ return context.json(parseRow(entry, insertedRow), 201);
1166
+ } catch (error) {
1167
+ await logOperationSafely(db, options.operationsLogConfig, {
1168
+ source: "crud",
1169
+ backend: options.backend,
1170
+ tableName: tableKey,
1171
+ operationKind: "create",
1172
+ entityKey: extractEntityKeyFromRecord(entry, payload),
1173
+ payload,
1174
+ status: "execution_failed",
1175
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
1176
+ httpStatus: 500,
1177
+ requestPath: context.req.path
1178
+ });
1179
+ throw error;
1180
+ }
1181
+ });
1182
+ app.patch(`${basePath}/:id`, async (context) => {
1183
+ await options.operationsLogReady;
1184
+ const id = context.req.param("id");
1185
+ const entityKey = {
1186
+ [primaryKeyColumnName]: id
1187
+ };
1188
+ const requestBody = await context.req.json();
1189
+ let payload;
1190
+ try {
1191
+ payload = parseUpdatePayload(entry, requestBody);
1192
+ } catch (error) {
1193
+ await logOperationSafely(db, options.operationsLogConfig, {
1194
+ source: "crud",
1195
+ backend: options.backend,
1196
+ tableName: tableKey,
1197
+ operationKind: "update",
1198
+ entityKey,
1199
+ payload: requestBody,
1200
+ status: "validation_failed",
1201
+ errorMessage: error instanceof Error ? error.message : "Validation failed",
1202
+ httpStatus: 400,
1203
+ requestPath: context.req.path
1204
+ });
1205
+ return context.json({
1206
+ message: "Validation failed",
1207
+ issues: isValidationError2(error) ? error.issues : []
1208
+ }, 400);
1209
+ }
1210
+ try {
1211
+ const updatedRow = await db.transaction(async (tx) => {
1212
+ const updated = await tx.update(entry.table).set(withUpdatedAtUs(entry.table, payload)).where(eq(primaryKeyColumn, id)).returning();
1213
+ if (updated.length === 0) {
1214
+ await logOperation(tx, options.operationsLogConfig, {
1215
+ source: "crud",
1216
+ backend: options.backend,
1217
+ tableName: tableKey,
1218
+ operationKind: "update",
1219
+ entityKey,
1220
+ payload,
1221
+ status: "not_found",
1222
+ httpStatus: 404,
1223
+ requestPath: context.req.path
1224
+ });
1225
+ return null;
1226
+ }
1227
+ const row = updated[0];
1228
+ await logOperation(tx, options.operationsLogConfig, {
1229
+ source: "crud",
1230
+ backend: options.backend,
1231
+ tableName: tableKey,
1232
+ operationKind: "update",
1233
+ entityKey: extractEntityKeyFromRecord(entry, row) ?? entityKey,
1234
+ payload,
1235
+ status: "succeeded",
1236
+ httpStatus: 200,
1237
+ requestPath: context.req.path
1238
+ });
1239
+ return row;
1240
+ });
1241
+ if (updatedRow === null) {
1242
+ return context.json({ message: `${tableKey} record not found` }, 404);
1243
+ }
1244
+ return context.json(parseRow(entry, updatedRow));
1245
+ } catch (error) {
1246
+ await logOperationSafely(db, options.operationsLogConfig, {
1247
+ source: "crud",
1248
+ backend: options.backend,
1249
+ tableName: tableKey,
1250
+ operationKind: "update",
1251
+ entityKey,
1252
+ payload,
1253
+ status: "execution_failed",
1254
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
1255
+ httpStatus: 500,
1256
+ requestPath: context.req.path
1257
+ });
1258
+ throw error;
1259
+ }
1260
+ });
1261
+ app.delete(`${basePath}/:id`, async (context) => {
1262
+ await options.operationsLogReady;
1263
+ const id = context.req.param("id");
1264
+ const entityKey = {
1265
+ [primaryKeyColumnName]: id
1266
+ };
1267
+ try {
1268
+ const deleted = await db.transaction(async (tx) => {
1269
+ const deletedRows = await tx.delete(entry.table).where(eq(primaryKeyColumn, id)).returning();
1270
+ if (deletedRows.length === 0) {
1271
+ await logOperation(tx, options.operationsLogConfig, {
1272
+ source: "crud",
1273
+ backend: options.backend,
1274
+ tableName: tableKey,
1275
+ operationKind: "delete",
1276
+ entityKey,
1277
+ payload: entityKey,
1278
+ status: "not_found",
1279
+ httpStatus: 404,
1280
+ requestPath: context.req.path
1281
+ });
1282
+ return false;
1283
+ }
1284
+ await logOperation(tx, options.operationsLogConfig, {
1285
+ source: "crud",
1286
+ backend: options.backend,
1287
+ tableName: tableKey,
1288
+ operationKind: "delete",
1289
+ entityKey,
1290
+ payload: entityKey,
1291
+ status: "succeeded",
1292
+ httpStatus: 204,
1293
+ requestPath: context.req.path
1294
+ });
1295
+ return true;
1296
+ });
1297
+ if (!deleted) {
1298
+ return context.json({ message: `${tableKey} record not found` }, 404);
1299
+ }
1300
+ return context.body(null, 204);
1301
+ } catch (error) {
1302
+ await logOperationSafely(db, options.operationsLogConfig, {
1303
+ source: "crud",
1304
+ backend: options.backend,
1305
+ tableName: tableKey,
1306
+ operationKind: "delete",
1307
+ entityKey,
1308
+ payload: entityKey,
1309
+ status: "execution_failed",
1310
+ errorMessage: error instanceof Error ? error.message : "Execution failed",
1311
+ httpStatus: 500,
1312
+ requestPath: context.req.path
1313
+ });
1314
+ throw error;
1315
+ }
1316
+ });
1317
+ }
1318
+ }
1319
+ function getSinglePrimaryKeyColumnName(entry, tableKey) {
1320
+ if (entry.primaryKey.columns.length !== 1) {
1321
+ throw new Error(`@pgxsinkit/server currently supports single-column primary keys only: ${tableKey}`);
1322
+ }
1323
+ return entry.primaryKey.columns[0];
1324
+ }
1325
+ function getTableColumn(table, columnName, tableKey) {
1326
+ const column = table[columnName];
1327
+ if (!column) {
1328
+ throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
1329
+ }
1330
+ return column;
1331
+ }
1332
+ function parseCreatePayload(entry, input) {
1333
+ return entry.schemas?.createSchema ? entry.schemas.createSchema.parse(input) : input;
1334
+ }
1335
+ function parseUpdatePayload(entry, input) {
1336
+ return entry.schemas?.updateSchema ? entry.schemas.updateSchema.parse(input) : input;
1337
+ }
1338
+ function registerMethodNotAllowed(app, path, methods, tableKey) {
1339
+ for (const method of methods) {
1340
+ app.on(method, path, (context) => {
1341
+ context.header("Allow", "GET, OPTIONS");
1342
+ return context.json({
1343
+ message: `CRUD ${method} routes are disabled for ${tableKey} when WRITE_API_BACKEND=bulk-plpgsql-artifact. Use POST /api/mutations instead.`
1344
+ }, 405);
1345
+ });
1346
+ }
1347
+ }
1348
+ function parseRows(entry, rows) {
1349
+ return rows.map((row) => parseRow(entry, row));
1350
+ }
1351
+ function parseRow(entry, row) {
1352
+ const normalized = normalizeBigInts(row);
1353
+ return entry.schemas?.recordSchema ? entry.schemas.recordSchema.parse(normalized) : normalized;
1354
+ }
1355
+ function withUpdatedAtUs(table, payload) {
1356
+ const values = {
1357
+ ...isRecord(payload) ? payload : {}
1358
+ };
1359
+ if ("updatedAtUs" in table) {
1360
+ values.updatedAtUs = sql7`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
1361
+ }
1362
+ return values;
1363
+ }
1364
+ function normalizeBigInts(value) {
1365
+ if (typeof value === "bigint") {
1366
+ return value.toString();
1367
+ }
1368
+ if (Array.isArray(value)) {
1369
+ return value.map((entry) => normalizeBigInts(entry));
1370
+ }
1371
+ if (isRecord(value)) {
1372
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, normalizeBigInts(entry)]));
1373
+ }
1374
+ return value;
1375
+ }
1376
+ function isRecord(value) {
1377
+ return typeof value === "object" && value !== null;
1378
+ }
1379
+ function getBunNamespace() {
1380
+ const maybeBun = globalThis.Bun;
1381
+ return maybeBun;
1382
+ }
1383
+ function isValidationError2(error) {
1384
+ return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
1385
+ }
1386
+ function resolveOperationsLogConfig(options) {
1387
+ return {
1388
+ enabled: options?.enabled ?? true
1389
+ };
1390
+ }
1391
+ function extractEntityKeyFromRecord(entry, value) {
1392
+ if (!isRecord(value)) {
1393
+ return null;
1394
+ }
1395
+ const entityKey = {};
1396
+ for (const primaryKeyColumn of entry.primaryKey.columns) {
1397
+ const rawValue = value[primaryKeyColumn];
1398
+ if (rawValue === undefined || rawValue === null) {
1399
+ return null;
1400
+ }
1401
+ if (typeof rawValue === "string" || typeof rawValue === "number" || typeof rawValue === "bigint" || typeof rawValue === "boolean") {
1402
+ entityKey[primaryKeyColumn] = String(rawValue);
1403
+ continue;
1404
+ }
1405
+ return null;
1406
+ }
1407
+ return entityKey;
1408
+ }
1409
+ export {
1410
+ createSyncServer,
1411
+ buildPlpgsqlBatchFunctionDdl
1412
+ };
1413
+
1414
+ //# debugId=85EE2493A865B9B264756E2164756E21