@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.
@@ -0,0 +1,396 @@
1
+ import { getTableName, sql } from "drizzle-orm";
2
+ import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
3
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
4
+ import { getColumns } from "drizzle-orm/utils";
5
+
6
+ import {
7
+ getProjectedColumns,
8
+ type BatchMutationRequest,
9
+ type RegistryTables,
10
+ type SyncTableEntry,
11
+ type SyncTableRegistry,
12
+ } from "@pgxsinkit/contracts";
13
+
14
+ import type { TransactionClient } from "./types";
15
+
16
+ const PG_TYPE_MAP: Record<string, string> = {
17
+ PgUUID: "uuid",
18
+ PgText: "text",
19
+ PgVarchar: "varchar",
20
+ PgChar: "char",
21
+ PgInteger: "integer",
22
+ PgSerial: "integer",
23
+ PgSmallInt: "smallint",
24
+ PgSmallIntNumber: "smallint",
25
+ PgBigInt53: "bigint",
26
+ PgBigInt64: "bigint",
27
+ PgBigIntString: "bigint",
28
+ PgBigSerial: "bigint",
29
+ PgBoolean: "boolean",
30
+ PgNumeric: "numeric",
31
+ PgReal: "real",
32
+ PgDoublePrecision: "double precision",
33
+ PgTimestamp: "timestamptz",
34
+ PgTimestampString: "timestamptz",
35
+ PgDate: "date",
36
+ PgDateString: "date",
37
+ PgTime: "time",
38
+ PgTimeString: "time",
39
+ PgJson: "json",
40
+ PgJsonb: "jsonb",
41
+ PgBytea: "bytea",
42
+ PgVector: "vector",
43
+ };
44
+
45
+ function drizzleColumnTypeToPg(columnType: string): string {
46
+ return PG_TYPE_MAP[columnType] ?? "text";
47
+ }
48
+
49
+ function drizzleColumnToPg(column: { columnType: string; getSQLType?: () => string }): string {
50
+ const sqlType = column.getSQLType?.();
51
+
52
+ if (sqlType && sqlType.length > 0) {
53
+ return sqlType;
54
+ }
55
+
56
+ return drizzleColumnTypeToPg(column.columnType);
57
+ }
58
+
59
+ function quoteIdent(name: string): string {
60
+ return `"${name.replace(/"/g, '""')}"`;
61
+ }
62
+
63
+ function qualifyIdent(schemaName: string | undefined, name: string): string {
64
+ if (!schemaName) {
65
+ return quoteIdent(name);
66
+ }
67
+
68
+ return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;
69
+ }
70
+
71
+ function toSqlLiteral(value: string): string {
72
+ return value.replace(/'/g, "''");
73
+ }
74
+
75
+ function toSqlTextOrNull(value: string): string {
76
+ return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
77
+ }
78
+
79
+ function buildManagedFieldExpression(strategy: "authUid" | "nowMicroseconds"): string {
80
+ if (strategy === "authUid") {
81
+ return "auth.uid()";
82
+ }
83
+
84
+ return "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)";
85
+ }
86
+
87
+ function getManagedFieldsForOperation(entry: SyncTableEntry, operation: "create" | "update") {
88
+ const columns = getColumns(entry.table as AnyPgTable);
89
+ const columnMap = new Map(
90
+ Object.entries(columns).map(([propertyKey, column]) => [
91
+ propertyKey,
92
+ { name: column.name, columnType: drizzleColumnToPg(column) },
93
+ ]),
94
+ );
95
+
96
+ return (entry.governance?.managedFields ?? []).flatMap((field) => {
97
+ if (!field.applyOn.includes(operation)) {
98
+ return [];
99
+ }
100
+
101
+ const column = columnMap.get(field.column);
102
+ if (!column) {
103
+ return [];
104
+ }
105
+
106
+ return [
107
+ {
108
+ propertyKey: field.column,
109
+ columnName: column.name,
110
+ columnType: drizzleColumnTypeToPg(column.columnType),
111
+ strategy: field.strategy,
112
+ },
113
+ ];
114
+ });
115
+ }
116
+
117
+ function buildTableBranch(entry: SyncTableEntry): string {
118
+ const tableName = getTableName(entry.table as AnyPgTable);
119
+ const { schema } = getTableConfig(entry.table as AnyPgTable);
120
+ const qualifiedTableName = qualifyIdent(schema, tableName);
121
+ const columns = getColumns(entry.table as AnyPgTable);
122
+ const projectedColumns = getProjectedColumns(entry);
123
+ const primaryKeyColumn = entry.primaryKey.columns[0]!;
124
+ const primaryKeyColumnObject = Object.values(columns).find((column) => column.name === primaryKeyColumn);
125
+ const primaryKeyType = primaryKeyColumnObject
126
+ ? drizzleColumnToPg(primaryKeyColumnObject)
127
+ : drizzleColumnTypeToPg("PgText");
128
+
129
+ const createManagedFields = getManagedFieldsForOperation(entry, "create");
130
+ const updateManagedFields = getManagedFieldsForOperation(entry, "update");
131
+ const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));
132
+ const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));
133
+
134
+ const allColumnPairs = projectedColumns
135
+ .map(({ column }) => column)
136
+ .filter((column) => !createManagedFieldNames.has(column.name))
137
+ .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`)
138
+ .join(",\n ");
139
+
140
+ const nonPrimaryKeyColumnPairs = projectedColumns
141
+ .map(({ column }) => column)
142
+ .filter((column) => column.name !== primaryKeyColumn && !updateManagedFieldNames.has(column.name))
143
+ .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(drizzleColumnToPg(column))}')`)
144
+ .join(",\n ");
145
+
146
+ const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
147
+ const createManagedValuesSql = createManagedFields
148
+ .map((field) => buildManagedFieldExpression(field.strategy))
149
+ .join(", ");
150
+ const updateManagedAssignmentsSql = updateManagedFields
151
+ .map((field) => `${quoteIdent(field.columnName)} = ${buildManagedFieldExpression(field.strategy)}`)
152
+ .join(", ");
153
+
154
+ const createSqlTemplate = `INSERT INTO ${qualifiedTableName} (%s) VALUES (%s)`.replace(/'/g, "''");
155
+ const updateSqlTemplate =
156
+ `UPDATE ${qualifiedTableName} SET %s WHERE ${quoteIdent(primaryKeyColumn)} = ($2->>%L)::${primaryKeyType}`.replace(
157
+ /'/g,
158
+ "''",
159
+ );
160
+
161
+ const createBranch = `
162
+ SELECT format(
163
+ '${createSqlTemplate}',
164
+ concat_ws(', ', nullif(string_agg(quote_ident(col_name), ', '), ''), ${toSqlTextOrNull(createManagedColumnsSql)}),
165
+ concat_ws(', ', nullif(string_agg(format('($1->>%L)::%s', col_name, col_type), ', '), ''), ${toSqlTextOrNull(createManagedValuesSql)})
166
+ )
167
+ INTO dml_sql
168
+ FROM (VALUES
169
+ ${allColumnPairs}
170
+ ) AS col_types(col_name, col_type)
171
+ WHERE v_payload ? col_name;
172
+
173
+ IF dml_sql IS NOT NULL THEN
174
+ EXECUTE dml_sql USING v_payload;
175
+ END IF;
176
+ `.trim();
177
+
178
+ const updateBranch = `
179
+ SELECT format(
180
+ '${updateSqlTemplate}',
181
+ concat_ws(', ', nullif(string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '), ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)}),
182
+ '${toSqlLiteral(primaryKeyColumn)}'
183
+ )
184
+ INTO dml_sql
185
+ FROM (VALUES
186
+ ${nonPrimaryKeyColumnPairs}
187
+ ) AS col_types(col_name, col_type)
188
+ WHERE v_payload ? col_name;
189
+
190
+ IF dml_sql IS NOT NULL THEN
191
+ EXECUTE dml_sql USING v_payload, v_entity_key;
192
+ END IF;
193
+ `.trim();
194
+
195
+ const deleteBranch = `
196
+ DELETE FROM ${qualifiedTableName}
197
+ WHERE ${quoteIdent(primaryKeyColumn)} = (v_entity_key->>'${toSqlLiteral(primaryKeyColumn)}')::${primaryKeyType};
198
+ `.trim();
199
+
200
+ return `
201
+ ELSIF v_table = '${toSqlLiteral(tableName)}' THEN
202
+ IF v_kind = 'create' THEN
203
+ ${createBranch}
204
+ ELSIF v_kind = 'update' THEN
205
+ ${updateBranch}
206
+ ELSIF v_kind = 'delete' THEN
207
+ ${deleteBranch}
208
+ ELSE
209
+ RAISE EXCEPTION 'Unsupported mutation kind "%" for table "%"', v_kind, v_table;
210
+ END IF;
211
+ `.trim();
212
+ }
213
+
214
+ export function buildPlpgsqlBatchFunctionDdl(
215
+ registry: SyncTableRegistry,
216
+ options: {
217
+ functionSchema?: string;
218
+ } = {},
219
+ ): string {
220
+ const tableBranches = Object.values(registry)
221
+ .map((entry) => buildTableBranch(entry as SyncTableEntry))
222
+ .join("\n");
223
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
224
+
225
+ return `
226
+ CREATE OR REPLACE FUNCTION ${functionName}(
227
+ p_batch jsonb,
228
+ p_request_path text,
229
+ p_log_enabled boolean,
230
+ p_rls_enabled boolean,
231
+ p_user_claims jsonb
232
+ ) RETURNS void LANGUAGE plpgsql AS $$
233
+ DECLARE
234
+ mutation jsonb;
235
+ dml_sql text;
236
+ v_table text;
237
+ v_kind text;
238
+ v_payload jsonb;
239
+ v_entity_key jsonb;
240
+ v_mutation_id text;
241
+ v_mutation_seq integer;
242
+ v_client_timestamp_us bigint;
243
+ BEGIN
244
+ IF p_rls_enabled THEN
245
+ PERFORM auth.set_auth_context(COALESCE(p_user_claims, '{}'::jsonb));
246
+ END IF;
247
+
248
+ IF jsonb_typeof(p_batch) <> 'object' THEN
249
+ RAISE EXCEPTION 'Batch payload must be a JSON object';
250
+ END IF;
251
+
252
+ IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN
253
+ RAISE EXCEPTION 'Batch payload mutations must be a JSON array';
254
+ END IF;
255
+
256
+ FOR mutation IN SELECT value FROM jsonb_array_elements(p_batch->'mutations')
257
+ LOOP
258
+ dml_sql := NULL;
259
+ v_table := mutation->>'tableName';
260
+ v_kind := mutation->>'kind';
261
+ v_payload := COALESCE(mutation->'payload', '{}'::jsonb);
262
+ v_entity_key := COALESCE(mutation->'entityKey', '{}'::jsonb);
263
+ v_mutation_id := mutation->>'mutationId';
264
+ v_mutation_seq := (mutation->>'mutationSeq')::integer;
265
+ v_client_timestamp_us := NULLIF(mutation->>'clientTimestampUs', '')::bigint;
266
+
267
+ IF FALSE THEN
268
+ NULL;
269
+ ${tableBranches}
270
+ ELSE
271
+ RAISE EXCEPTION 'Unknown table "%" in batch mutation', v_table;
272
+ END IF;
273
+
274
+ IF p_log_enabled THEN
275
+ INSERT INTO operations_log (
276
+ source,
277
+ backend,
278
+ table_name,
279
+ operation_kind,
280
+ entity_key_json,
281
+ payload_json,
282
+ status,
283
+ http_status,
284
+ mutation_id,
285
+ mutation_seq,
286
+ client_timestamp_us,
287
+ request_path,
288
+ server_timestamp_us
289
+ ) VALUES (
290
+ 'batch',
291
+ 'bulk-plpgsql',
292
+ v_table,
293
+ v_kind,
294
+ v_entity_key,
295
+ v_payload,
296
+ 'succeeded',
297
+ 200,
298
+ v_mutation_id::uuid,
299
+ v_mutation_seq,
300
+ v_client_timestamp_us,
301
+ p_request_path,
302
+ CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)
303
+ );
304
+ END IF;
305
+ END LOOP;
306
+ END;
307
+ $$;
308
+ `.trim();
309
+ }
310
+
311
+ export async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
312
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
313
+ registry: TRegistry,
314
+ options: {
315
+ functionSchema?: string;
316
+ } = {},
317
+ ): Promise<void> {
318
+ const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);
319
+ await db.execute(sql.raw(ddl));
320
+ }
321
+
322
+ type FunctionPresenceRow = {
323
+ functionName: string | null;
324
+ };
325
+
326
+ export async function verifyPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
327
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
328
+ options: {
329
+ functionSchema?: string;
330
+ } = {},
331
+ ): Promise<void> {
332
+ const functionSignature = `${options.functionSchema ? `${options.functionSchema}.` : "public."}pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb)`;
333
+ const result = await db.execute<FunctionPresenceRow>(sql`
334
+ SELECT to_regprocedure(${functionSignature})::text AS "functionName"
335
+ `);
336
+
337
+ const row = Array.from(result, (entry) => entry as FunctionPresenceRow)[0];
338
+
339
+ if (!row?.functionName) {
340
+ throw new Error(
341
+ "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.",
342
+ );
343
+ }
344
+ }
345
+
346
+ type AuthHelperPresenceRow = {
347
+ setAuthContext: string | null;
348
+ authUid: string | null;
349
+ authJwt: string | null;
350
+ authHasRole: string | null;
351
+ };
352
+
353
+ export async function verifyArtifactRlsAuthHelpers<TRegistry extends SyncTableRegistry>(
354
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
355
+ ): Promise<void> {
356
+ const result = await db.execute<AuthHelperPresenceRow>(sql`
357
+ SELECT
358
+ to_regprocedure('auth.set_auth_context(jsonb)')::text AS "setAuthContext",
359
+ to_regprocedure('auth.uid()')::text AS "authUid",
360
+ to_regprocedure('auth.jwt()')::text AS "authJwt",
361
+ to_regprocedure('auth.has_role(text)')::text AS "authHasRole"
362
+ `);
363
+
364
+ const row = Array.from(result, (entry) => entry as AuthHelperPresenceRow)[0];
365
+ const missingHelpers = [
366
+ row?.setAuthContext ? null : "auth.set_auth_context(jsonb)",
367
+ row?.authUid ? null : "auth.uid()",
368
+ row?.authJwt ? null : "auth.jwt()",
369
+ row?.authHasRole ? null : "auth.has_role(text)",
370
+ ].filter((value): value is string => value !== null);
371
+
372
+ if (missingHelpers.length > 0) {
373
+ throw new Error(
374
+ `bulk-plpgsql-artifact backend with RLS-enabled tables requires governance SQL to be applied. Missing: ${missingHelpers.join(", ")}. Run bun run db:apply:governance.`,
375
+ );
376
+ }
377
+ }
378
+
379
+ export async function executePlpgsqlBatch(
380
+ tx: TransactionClient,
381
+ batch: BatchMutationRequest,
382
+ requestPath: string,
383
+ logEnabled: boolean,
384
+ rlsEnabled: boolean,
385
+ userClaims: Record<string, unknown>,
386
+ options: {
387
+ functionSchema?: string;
388
+ } = {},
389
+ ): Promise<void> {
390
+ const normalizedClaims = userClaims ?? {};
391
+ const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
392
+
393
+ await tx.execute(
394
+ sql`SELECT ${sql.raw(functionName)}(${JSON.stringify(batch)}::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::jsonb)`,
395
+ );
396
+ }
@@ -0,0 +1,136 @@
1
+ import { getTableName, sql } from "drizzle-orm";
2
+ import type { AnyPgTable } from "drizzle-orm/pg-core";
3
+ import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
4
+ import { getColumns } from "drizzle-orm/utils";
5
+
6
+ import type { MutationEnvelope, RegistryTables, SyncTableEntry, SyncTableRegistry } from "@pgxsinkit/contracts";
7
+
8
+ import type { TransactionClient } from "./types";
9
+
10
+ const PG_TYPE_MAP: Record<string, string> = {
11
+ PgUUID: "uuid",
12
+ PgText: "text",
13
+ PgVarchar: "varchar",
14
+ PgChar: "char",
15
+ PgInteger: "integer",
16
+ PgSerial: "integer",
17
+ PgSmallInt: "smallint",
18
+ PgSmallIntNumber: "smallint",
19
+ PgBigInt53: "bigint",
20
+ PgBigInt64: "bigint",
21
+ PgBigIntString: "bigint",
22
+ PgBigSerial: "bigint",
23
+ PgBoolean: "boolean",
24
+ PgNumeric: "numeric",
25
+ PgReal: "real",
26
+ PgDoublePrecision: "double precision",
27
+ PgTimestamp: "timestamptz",
28
+ PgTimestampString: "timestamptz",
29
+ PgDate: "date",
30
+ PgDateString: "date",
31
+ PgTime: "time",
32
+ PgTimeString: "time",
33
+ PgJson: "json",
34
+ PgJsonb: "jsonb",
35
+ PgBytea: "bytea",
36
+ PgVector: "vector",
37
+ };
38
+
39
+ function drizzleColumnTypeToPg(columnType: string): string {
40
+ return PG_TYPE_MAP[columnType] ?? "text";
41
+ }
42
+
43
+ function safeFunctionName(tableName: string): string {
44
+ return tableName.toLowerCase().replace(/[^a-z0-9_]/g, "_");
45
+ }
46
+
47
+ function quoteIdent(name: string): string {
48
+ return `"${name.replace(/"/g, '""')}"`;
49
+ }
50
+
51
+ function buildPregeneratedFunctionDdl(entry: SyncTableEntry): string {
52
+ const tableName = getTableName(entry.table as AnyPgTable);
53
+ const fnName = `pgxsinkit_apply_${safeFunctionName(tableName)}_mutation`;
54
+ const columns = getColumns(entry.table as AnyPgTable);
55
+ const pkCol = entry.primaryKey.columns[0]!;
56
+ const pkColObj = Object.values(columns).find((col) => col.name === pkCol);
57
+ const pkType = drizzleColumnTypeToPg(pkColObj?.columnType ?? "PgText");
58
+
59
+ const sqlLit = (s: string) => s.replace(/'/g, "''");
60
+
61
+ const allColPairs = Object.values(columns)
62
+ .map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg(col.columnType))}')`)
63
+ .join(",\n ");
64
+
65
+ const nonPkColPairs = Object.values(columns)
66
+ .filter((col) => col.name !== pkCol)
67
+ .map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg(col.columnType))}')`)
68
+ .join(",\n ");
69
+
70
+ const createFormatTpl = `INSERT INTO ${quoteIdent(tableName)} (%s) VALUES (%s)`.replace(/'/g, "''");
71
+ const updateFormatTpl =
72
+ `UPDATE ${quoteIdent(tableName)} SET %s WHERE ${quoteIdent(pkCol)} = ($2->>%L)::${pkType}`.replace(/'/g, "''");
73
+
74
+ return `
75
+ CREATE OR REPLACE FUNCTION ${fnName}(p_op text, p_payload jsonb, p_entity_key jsonb) RETURNS void LANGUAGE plpgsql AS $$
76
+ DECLARE
77
+ dml_sql text;
78
+ BEGIN
79
+ IF p_op = 'create' THEN
80
+ -- Only insert columns present in the payload; DB handles defaults for the rest.
81
+ SELECT format(
82
+ '${createFormatTpl}',
83
+ string_agg(quote_ident(col_name), ', '),
84
+ string_agg(format('($1->>%L)::%s', col_name, col_type), ', ')
85
+ )
86
+ INTO dml_sql
87
+ FROM (VALUES
88
+ ${allColPairs}
89
+ ) AS t(col_name, col_type)
90
+ WHERE p_payload ? col_name;
91
+
92
+ IF dml_sql IS NOT NULL THEN
93
+ EXECUTE dml_sql USING p_payload;
94
+ END IF;
95
+
96
+ ELSIF p_op = 'update' THEN
97
+ -- Only update non-pk columns present in the payload; use entityKey for the WHERE.
98
+ SELECT format(
99
+ '${updateFormatTpl}',
100
+ string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '),
101
+ '${sqlLit(pkCol)}'
102
+ )
103
+ INTO dml_sql
104
+ FROM (VALUES
105
+ ${nonPkColPairs}
106
+ ) AS t(col_name, col_type)
107
+ WHERE p_payload ? col_name;
108
+
109
+ IF dml_sql IS NOT NULL THEN
110
+ EXECUTE dml_sql USING p_payload, p_entity_key;
111
+ END IF;
112
+
113
+ ELSIF p_op = 'delete' THEN
114
+ DELETE FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(pkCol)} = (p_entity_key->>'${sqlLit(pkCol)}')::${pkType};
115
+ END IF;
116
+ END;
117
+ $$;
118
+ `.trim();
119
+ }
120
+
121
+ export async function installPregeneratedMutationFunctions<TRegistry extends SyncTableRegistry>(
122
+ db: PostgresJsDatabase<RegistryTables<TRegistry>>,
123
+ registry: TRegistry,
124
+ ): Promise<void> {
125
+ for (const [, entry] of Object.entries(registry)) {
126
+ const ddl = buildPregeneratedFunctionDdl(entry as SyncTableEntry);
127
+ await db.execute(sql.raw(ddl));
128
+ }
129
+ }
130
+
131
+ export async function executePregeneratedMutation(tx: TransactionClient, mutation: MutationEnvelope): Promise<void> {
132
+ const fnName = `pgxsinkit_apply_${safeFunctionName(mutation.tableName)}_mutation`;
133
+ await tx.execute(
134
+ sql`SELECT ${sql.raw(fnName)}(${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb)`,
135
+ );
136
+ }