@pgxsinkit/server 0.1.3 → 0.1.5
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/experimental/index.js +195 -0
- package/dist/experimental/index.js.map +11 -0
- package/dist/index.js +67 -309
- package/dist/index.js.map +5 -7
- package/package.json +6 -2
- package/src/experimental/index.ts +6 -0
- package/src/experimental/mutations/bulk/types.ts +5 -0
- package/src/index.ts +11 -13
- package/src/mutations/bulk/route.ts +65 -134
- package/src/mutations/bulk/types.ts +1 -1
- package/src/operations-log/types.ts +1 -1
- /package/src/{mutations → experimental/mutations}/bulk/dynamic-strategy.ts +0 -0
- /package/src/{mutations → experimental/mutations}/bulk/pregenerated-strategy.ts +0 -0
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// packages/server/src/index.ts
|
|
3
|
-
import { eq, sql as
|
|
3
|
+
import { eq, sql as sql5 } from "drizzle-orm";
|
|
4
4
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
5
5
|
import { defineRelations } from "drizzle-orm/relations";
|
|
6
6
|
import { Hono } from "hono";
|
|
@@ -8,8 +8,8 @@ import { cors } from "hono/cors";
|
|
|
8
8
|
import postgres from "postgres";
|
|
9
9
|
|
|
10
10
|
// packages/server/src/mutations/bulk/route.ts
|
|
11
|
-
import { getTableName as
|
|
12
|
-
import { getColumns as
|
|
11
|
+
import { getTableName as getTableName2, sql as sql3 } from "drizzle-orm";
|
|
12
|
+
import { getColumns as getColumns2 } from "drizzle-orm/utils";
|
|
13
13
|
import {
|
|
14
14
|
batchMutationRequestSchema,
|
|
15
15
|
getOmittedProjectedColumns as getOmittedProjectionColumns
|
|
@@ -71,85 +71,8 @@ async function logOperationSafely(executor, config, entry) {
|
|
|
71
71
|
} catch {}
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
// packages/server/src/mutations/bulk/dynamic-strategy.ts
|
|
75
|
-
import { sql as sql2 } from "drizzle-orm";
|
|
76
|
-
var DYNAMIC_MUTATION_FUNCTION_DDL = `
|
|
77
|
-
CREATE OR REPLACE FUNCTION pgxsinkit_apply_mutation(
|
|
78
|
-
p_table text,
|
|
79
|
-
p_op text,
|
|
80
|
-
p_payload jsonb,
|
|
81
|
-
p_entity_key jsonb,
|
|
82
|
-
p_pk_col text
|
|
83
|
-
) RETURNS void LANGUAGE plpgsql AS $$
|
|
84
|
-
DECLARE
|
|
85
|
-
dml_sql text;
|
|
86
|
-
pk_udt text;
|
|
87
|
-
BEGIN
|
|
88
|
-
IF p_op = 'create' THEN
|
|
89
|
-
-- Insert only the columns present in the payload; DB handles defaults for the rest.
|
|
90
|
-
SELECT format(
|
|
91
|
-
'INSERT INTO %I (%s) VALUES (%s)',
|
|
92
|
-
p_table,
|
|
93
|
-
string_agg(quote_ident(c.column_name), ', '),
|
|
94
|
-
string_agg(format('($1->>%L)::%s', c.column_name, c.udt_name), ', ')
|
|
95
|
-
)
|
|
96
|
-
INTO dml_sql
|
|
97
|
-
FROM information_schema.columns c
|
|
98
|
-
WHERE c.table_schema = 'public'
|
|
99
|
-
AND c.table_name = p_table
|
|
100
|
-
AND (p_payload ? c.column_name);
|
|
101
|
-
|
|
102
|
-
IF dml_sql IS NOT NULL THEN
|
|
103
|
-
EXECUTE dml_sql USING p_payload;
|
|
104
|
-
END IF;
|
|
105
|
-
|
|
106
|
-
ELSIF p_op = 'update' THEN
|
|
107
|
-
SELECT udt_name INTO pk_udt
|
|
108
|
-
FROM information_schema.columns
|
|
109
|
-
WHERE table_schema = 'public'
|
|
110
|
-
AND table_name = p_table
|
|
111
|
-
AND column_name = p_pk_col;
|
|
112
|
-
|
|
113
|
-
-- Update only the non-pk columns present in the payload; use entityKey for the WHERE.
|
|
114
|
-
SELECT format(
|
|
115
|
-
'UPDATE %I SET %s WHERE %I = ($2->>%L)::%s',
|
|
116
|
-
p_table,
|
|
117
|
-
string_agg(format('%I = ($1->>%L)::%s', c.column_name, c.column_name, c.udt_name), ', '),
|
|
118
|
-
p_pk_col, p_pk_col, pk_udt
|
|
119
|
-
)
|
|
120
|
-
INTO dml_sql
|
|
121
|
-
FROM information_schema.columns c
|
|
122
|
-
WHERE c.table_schema = 'public'
|
|
123
|
-
AND c.table_name = p_table
|
|
124
|
-
AND c.column_name <> p_pk_col
|
|
125
|
-
AND (p_payload ? c.column_name);
|
|
126
|
-
|
|
127
|
-
IF dml_sql IS NOT NULL THEN
|
|
128
|
-
EXECUTE dml_sql USING p_payload, p_entity_key;
|
|
129
|
-
END IF;
|
|
130
|
-
|
|
131
|
-
ELSIF p_op = 'delete' THEN
|
|
132
|
-
SELECT udt_name INTO pk_udt
|
|
133
|
-
FROM information_schema.columns
|
|
134
|
-
WHERE table_schema = 'public'
|
|
135
|
-
AND table_name = p_table
|
|
136
|
-
AND column_name = p_pk_col;
|
|
137
|
-
|
|
138
|
-
EXECUTE format('DELETE FROM %I WHERE %I = ($1->>%L)::%s', p_table, p_pk_col, p_pk_col, pk_udt)
|
|
139
|
-
USING p_entity_key;
|
|
140
|
-
END IF;
|
|
141
|
-
END;
|
|
142
|
-
$$;
|
|
143
|
-
`.trim();
|
|
144
|
-
async function installDynamicMutationFunction(db) {
|
|
145
|
-
await db.execute(sql2.raw(DYNAMIC_MUTATION_FUNCTION_DDL));
|
|
146
|
-
}
|
|
147
|
-
async function executeDynamicMutation(tx, mutation, primaryKeyColumnName) {
|
|
148
|
-
await tx.execute(sql2`SELECT pgxsinkit_apply_mutation(${mutation.tableName}, ${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb, ${primaryKeyColumnName})`);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
74
|
// packages/server/src/mutations/bulk/plpgsql-strategy.ts
|
|
152
|
-
import { getTableName, sql as
|
|
75
|
+
import { getTableName, sql as sql2 } from "drizzle-orm";
|
|
153
76
|
import { getTableConfig } from "drizzle-orm/pg-core";
|
|
154
77
|
import { getColumns } from "drizzle-orm/utils";
|
|
155
78
|
import {
|
|
@@ -398,13 +321,9 @@ END;
|
|
|
398
321
|
$$;
|
|
399
322
|
`.trim();
|
|
400
323
|
}
|
|
401
|
-
async function installPlpgsqlBatchFunction(db, registry, options = {}) {
|
|
402
|
-
const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);
|
|
403
|
-
await db.execute(sql3.raw(ddl));
|
|
404
|
-
}
|
|
405
324
|
async function verifyPlpgsqlBatchFunction(db, options = {}) {
|
|
406
325
|
const functionSignature = `${options.functionSchema ? `${options.functionSchema}.` : "public."}pgxsinkit_apply_batch_mutations(jsonb,text,boolean,boolean,jsonb)`;
|
|
407
|
-
const result = await db.execute(
|
|
326
|
+
const result = await db.execute(sql2`
|
|
408
327
|
SELECT to_regprocedure(${functionSignature})::text AS "functionName"
|
|
409
328
|
`);
|
|
410
329
|
const row = Array.from(result, (entry) => entry)[0];
|
|
@@ -413,7 +332,7 @@ async function verifyPlpgsqlBatchFunction(db, options = {}) {
|
|
|
413
332
|
}
|
|
414
333
|
}
|
|
415
334
|
async function verifyArtifactRlsAuthHelpers(db) {
|
|
416
|
-
const result = await db.execute(
|
|
335
|
+
const result = await db.execute(sql2`
|
|
417
336
|
SELECT
|
|
418
337
|
to_regprocedure('auth.set_auth_context(jsonb)')::text AS "setAuthContext",
|
|
419
338
|
to_regprocedure('auth.uid()')::text AS "authUid",
|
|
@@ -434,125 +353,20 @@ async function verifyArtifactRlsAuthHelpers(db) {
|
|
|
434
353
|
async function executePlpgsqlBatch(tx, batch, requestPath, logEnabled, rlsEnabled, userClaims, options = {}) {
|
|
435
354
|
const normalizedClaims = userClaims ?? {};
|
|
436
355
|
const functionName = qualifyIdent(options.functionSchema, "pgxsinkit_apply_batch_mutations");
|
|
437
|
-
await tx.execute(
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
// packages/server/src/mutations/bulk/pregenerated-strategy.ts
|
|
441
|
-
import { getTableName as getTableName2, sql as sql4 } from "drizzle-orm";
|
|
442
|
-
import { getColumns as getColumns2 } from "drizzle-orm/utils";
|
|
443
|
-
var PG_TYPE_MAP2 = {
|
|
444
|
-
PgUUID: "uuid",
|
|
445
|
-
PgText: "text",
|
|
446
|
-
PgVarchar: "varchar",
|
|
447
|
-
PgChar: "char",
|
|
448
|
-
PgInteger: "integer",
|
|
449
|
-
PgSerial: "integer",
|
|
450
|
-
PgSmallInt: "smallint",
|
|
451
|
-
PgSmallIntNumber: "smallint",
|
|
452
|
-
PgBigInt53: "bigint",
|
|
453
|
-
PgBigInt64: "bigint",
|
|
454
|
-
PgBigIntString: "bigint",
|
|
455
|
-
PgBigSerial: "bigint",
|
|
456
|
-
PgBoolean: "boolean",
|
|
457
|
-
PgNumeric: "numeric",
|
|
458
|
-
PgReal: "real",
|
|
459
|
-
PgDoublePrecision: "double precision",
|
|
460
|
-
PgTimestamp: "timestamptz",
|
|
461
|
-
PgTimestampString: "timestamptz",
|
|
462
|
-
PgDate: "date",
|
|
463
|
-
PgDateString: "date",
|
|
464
|
-
PgTime: "time",
|
|
465
|
-
PgTimeString: "time",
|
|
466
|
-
PgJson: "json",
|
|
467
|
-
PgJsonb: "jsonb",
|
|
468
|
-
PgBytea: "bytea",
|
|
469
|
-
PgVector: "vector"
|
|
470
|
-
};
|
|
471
|
-
function drizzleColumnTypeToPg2(columnType) {
|
|
472
|
-
return PG_TYPE_MAP2[columnType] ?? "text";
|
|
473
|
-
}
|
|
474
|
-
function safeFunctionName(tableName) {
|
|
475
|
-
return tableName.toLowerCase().replace(/[^a-z0-9_]/g, "_");
|
|
476
|
-
}
|
|
477
|
-
function quoteIdent2(name) {
|
|
478
|
-
return `"${name.replace(/"/g, '""')}"`;
|
|
479
|
-
}
|
|
480
|
-
function buildPregeneratedFunctionDdl(entry) {
|
|
481
|
-
const tableName = getTableName2(entry.table);
|
|
482
|
-
const fnName = `pgxsinkit_apply_${safeFunctionName(tableName)}_mutation`;
|
|
483
|
-
const columns = getColumns2(entry.table);
|
|
484
|
-
const pkCol = entry.primaryKey.columns[0];
|
|
485
|
-
const pkColObj = Object.values(columns).find((col) => col.name === pkCol);
|
|
486
|
-
const pkType = drizzleColumnTypeToPg2(pkColObj?.columnType ?? "PgText");
|
|
487
|
-
const sqlLit = (s) => s.replace(/'/g, "''");
|
|
488
|
-
const allColPairs = Object.values(columns).map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg2(col.columnType))}')`).join(`,
|
|
489
|
-
`);
|
|
490
|
-
const nonPkColPairs = Object.values(columns).filter((col) => col.name !== pkCol).map((col) => `('${sqlLit(col.name)}', '${sqlLit(drizzleColumnTypeToPg2(col.columnType))}')`).join(`,
|
|
491
|
-
`);
|
|
492
|
-
const createFormatTpl = `INSERT INTO ${quoteIdent2(tableName)} (%s) VALUES (%s)`.replace(/'/g, "''");
|
|
493
|
-
const updateFormatTpl = `UPDATE ${quoteIdent2(tableName)} SET %s WHERE ${quoteIdent2(pkCol)} = ($2->>%L)::${pkType}`.replace(/'/g, "''");
|
|
494
|
-
return `
|
|
495
|
-
CREATE OR REPLACE FUNCTION ${fnName}(p_op text, p_payload jsonb, p_entity_key jsonb) RETURNS void LANGUAGE plpgsql AS $$
|
|
496
|
-
DECLARE
|
|
497
|
-
dml_sql text;
|
|
498
|
-
BEGIN
|
|
499
|
-
IF p_op = 'create' THEN
|
|
500
|
-
-- Only insert columns present in the payload; DB handles defaults for the rest.
|
|
501
|
-
SELECT format(
|
|
502
|
-
'${createFormatTpl}',
|
|
503
|
-
string_agg(quote_ident(col_name), ', '),
|
|
504
|
-
string_agg(format('($1->>%L)::%s', col_name, col_type), ', ')
|
|
505
|
-
)
|
|
506
|
-
INTO dml_sql
|
|
507
|
-
FROM (VALUES
|
|
508
|
-
${allColPairs}
|
|
509
|
-
) AS t(col_name, col_type)
|
|
510
|
-
WHERE p_payload ? col_name;
|
|
511
|
-
|
|
512
|
-
IF dml_sql IS NOT NULL THEN
|
|
513
|
-
EXECUTE dml_sql USING p_payload;
|
|
514
|
-
END IF;
|
|
515
|
-
|
|
516
|
-
ELSIF p_op = 'update' THEN
|
|
517
|
-
-- Only update non-pk columns present in the payload; use entityKey for the WHERE.
|
|
518
|
-
SELECT format(
|
|
519
|
-
'${updateFormatTpl}',
|
|
520
|
-
string_agg(format('%I = ($1->>%L)::%s', col_name, col_name, col_type), ', '),
|
|
521
|
-
'${sqlLit(pkCol)}'
|
|
522
|
-
)
|
|
523
|
-
INTO dml_sql
|
|
524
|
-
FROM (VALUES
|
|
525
|
-
${nonPkColPairs}
|
|
526
|
-
) AS t(col_name, col_type)
|
|
527
|
-
WHERE p_payload ? col_name;
|
|
528
|
-
|
|
529
|
-
IF dml_sql IS NOT NULL THEN
|
|
530
|
-
EXECUTE dml_sql USING p_payload, p_entity_key;
|
|
531
|
-
END IF;
|
|
532
|
-
|
|
533
|
-
ELSIF p_op = 'delete' THEN
|
|
534
|
-
DELETE FROM ${quoteIdent2(tableName)} WHERE ${quoteIdent2(pkCol)} = (p_entity_key->>'${sqlLit(pkCol)}')::${pkType};
|
|
535
|
-
END IF;
|
|
536
|
-
END;
|
|
537
|
-
$$;
|
|
538
|
-
`.trim();
|
|
539
|
-
}
|
|
540
|
-
async function installPregeneratedMutationFunctions(db, registry) {
|
|
541
|
-
for (const [, entry] of Object.entries(registry)) {
|
|
542
|
-
const ddl = buildPregeneratedFunctionDdl(entry);
|
|
543
|
-
await db.execute(sql4.raw(ddl));
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
async function executePregeneratedMutation(tx, mutation) {
|
|
547
|
-
const fnName = `pgxsinkit_apply_${safeFunctionName(mutation.tableName)}_mutation`;
|
|
548
|
-
await tx.execute(sql4`SELECT ${sql4.raw(fnName)}(${mutation.kind}, ${JSON.stringify(mutation.payload)}::jsonb, ${JSON.stringify(mutation.entityKey)}::jsonb)`);
|
|
356
|
+
await tx.execute(sql2`SELECT ${sql2.raw(functionName)}(${JSON.stringify(batch)}::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::jsonb)`);
|
|
549
357
|
}
|
|
550
358
|
|
|
551
359
|
// packages/server/src/mutations/bulk/route.ts
|
|
552
360
|
function registerBulkMutationRoute(app, db, registry, backend, operationsLogConfig, operationsLogReady, resolveAuthClaims) {
|
|
553
|
-
|
|
361
|
+
let startupReadyPromise;
|
|
362
|
+
const startupReady = () => {
|
|
363
|
+
if (!startupReadyPromise) {
|
|
364
|
+
startupReadyPromise = installBulkStartupDdl(db, registry, backend);
|
|
365
|
+
}
|
|
366
|
+
return startupReadyPromise;
|
|
367
|
+
};
|
|
554
368
|
app.post("/api/mutations", async (context) => {
|
|
555
|
-
await Promise.all([startupReady, operationsLogReady]);
|
|
369
|
+
await Promise.all([startupReady(), operationsLogReady]);
|
|
556
370
|
let rawBody;
|
|
557
371
|
try {
|
|
558
372
|
rawBody = await context.req.json();
|
|
@@ -615,14 +429,12 @@ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConf
|
|
|
615
429
|
invalidMutations.push({ mutation, message });
|
|
616
430
|
continue;
|
|
617
431
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
continue;
|
|
625
|
-
}
|
|
432
|
+
const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);
|
|
433
|
+
if (managedFieldViolations.length > 0) {
|
|
434
|
+
const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(", ")}`;
|
|
435
|
+
validationErrors.push(message);
|
|
436
|
+
invalidMutations.push({ mutation, message });
|
|
437
|
+
continue;
|
|
626
438
|
}
|
|
627
439
|
try {
|
|
628
440
|
if (mutation.kind === "create" && schemas?.createSchema) {
|
|
@@ -659,78 +471,39 @@ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConf
|
|
|
659
471
|
}
|
|
660
472
|
const acks = [];
|
|
661
473
|
let actorUserId = null;
|
|
662
|
-
const artifactAuthContextRequired =
|
|
474
|
+
const artifactAuthContextRequired = isArtifactAuthContextRequired(registry);
|
|
663
475
|
try {
|
|
664
476
|
await db.transaction(async (tx) => {
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
requestPath: context.req.path
|
|
682
|
-
});
|
|
683
|
-
throw new UnauthorizedBatchMutationError("RLS-enabled artifact backend requires validated JWT claims in request context");
|
|
684
|
-
}
|
|
685
|
-
userClaims = resolvedClaims;
|
|
686
|
-
actorUserId = getUuidClaim(userClaims, "sub");
|
|
687
|
-
}
|
|
688
|
-
const batchRequest = backend === "bulk-plpgsql-artifact" ? sanitizeArtifactRestrictedFields(body, registry) : body;
|
|
689
|
-
if (backend === "bulk-plpgsql-artifact") {
|
|
690
|
-
await tx.execute(sql5`SET CONSTRAINTS ALL DEFERRED`);
|
|
691
|
-
}
|
|
692
|
-
await executePlpgsqlBatch(tx, batchRequest, context.req.path, operationsLogConfig.enabled && backend === "bulk-plpgsql", shouldApplyRlsContext, userClaims);
|
|
693
|
-
if (shouldApplyRlsContext) {
|
|
694
|
-
await tx.execute(sql5`RESET ROLE`);
|
|
695
|
-
}
|
|
696
|
-
for (const mutation of batchRequest.mutations) {
|
|
697
|
-
const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, registry[mutation.tableName], mutation.entityKey);
|
|
698
|
-
if (backend === "bulk-plpgsql-artifact") {
|
|
699
|
-
await logOperation(tx, operationsLogConfig, {
|
|
700
|
-
source: "batch",
|
|
701
|
-
backend,
|
|
702
|
-
tableName: mutation.tableName,
|
|
703
|
-
operationKind: mutation.kind,
|
|
704
|
-
entityKey: mutation.entityKey,
|
|
705
|
-
payload: mutation.payload,
|
|
706
|
-
status: "succeeded",
|
|
707
|
-
httpStatus: 200,
|
|
708
|
-
mutationId: mutation.mutationId,
|
|
709
|
-
mutationSeq: mutation.mutationSeq,
|
|
710
|
-
clientTimestampUs: mutation.clientTimestampUs,
|
|
711
|
-
requestPath: context.req.path,
|
|
712
|
-
userId: actorUserId
|
|
713
|
-
});
|
|
714
|
-
}
|
|
715
|
-
acks.push({
|
|
716
|
-
tableName: mutation.tableName,
|
|
717
|
-
entityKey: mutation.entityKey,
|
|
718
|
-
mutationId: mutation.mutationId,
|
|
719
|
-
mutationSeq: mutation.mutationSeq,
|
|
720
|
-
status: "acked",
|
|
721
|
-
...serverUpdatedAtUs ? { serverUpdatedAtUs } : {}
|
|
477
|
+
const shouldApplyRlsContext = artifactAuthContextRequired;
|
|
478
|
+
let userClaims = {};
|
|
479
|
+
if (shouldApplyRlsContext) {
|
|
480
|
+
const resolvedClaims = await resolveAuthClaims?.(context.req.raw);
|
|
481
|
+
if (!isPlainObject(resolvedClaims)) {
|
|
482
|
+
await logOperationSafely(db, operationsLogConfig, {
|
|
483
|
+
source: "batch",
|
|
484
|
+
backend,
|
|
485
|
+
tableName: null,
|
|
486
|
+
operationKind: null,
|
|
487
|
+
entityKey: null,
|
|
488
|
+
payload: rawBody,
|
|
489
|
+
status: "validation_failed",
|
|
490
|
+
errorMessage: "Missing validated JWT claims for RLS-enabled artifact backend",
|
|
491
|
+
httpStatus: 401,
|
|
492
|
+
requestPath: context.req.path
|
|
722
493
|
});
|
|
494
|
+
throw new UnauthorizedBatchMutationError("RLS-enabled artifact backend requires validated JWT claims in request context");
|
|
723
495
|
}
|
|
724
|
-
|
|
496
|
+
userClaims = resolvedClaims;
|
|
497
|
+
actorUserId = getUuidClaim(userClaims, "sub");
|
|
725
498
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
499
|
+
const batchRequest = sanitizeArtifactRestrictedFields(body, registry);
|
|
500
|
+
await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
|
|
501
|
+
await executePlpgsqlBatch(tx, batchRequest, context.req.path, false, shouldApplyRlsContext, userClaims);
|
|
502
|
+
if (shouldApplyRlsContext) {
|
|
503
|
+
await tx.execute(sql3`RESET ROLE`);
|
|
504
|
+
}
|
|
505
|
+
for (const mutation of batchRequest.mutations) {
|
|
506
|
+
const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, registry[mutation.tableName], mutation.entityKey);
|
|
734
507
|
await logOperation(tx, operationsLogConfig, {
|
|
735
508
|
source: "batch",
|
|
736
509
|
backend,
|
|
@@ -746,7 +519,6 @@ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConf
|
|
|
746
519
|
requestPath: context.req.path,
|
|
747
520
|
userId: actorUserId
|
|
748
521
|
});
|
|
749
|
-
const serverUpdatedAtUs = await readServerUpdatedAtUs(tx, entry, mutation.entityKey);
|
|
750
522
|
acks.push({
|
|
751
523
|
tableName: mutation.tableName,
|
|
752
524
|
entityKey: mutation.entityKey,
|
|
@@ -901,7 +673,7 @@ function getManagedFieldsForOperation2(entry, mutationKind) {
|
|
|
901
673
|
if (mutationKind === "delete") {
|
|
902
674
|
return [];
|
|
903
675
|
}
|
|
904
|
-
const columns =
|
|
676
|
+
const columns = getColumns2(entry.table);
|
|
905
677
|
const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
|
|
906
678
|
return (entry.governance?.managedFields ?? []).filter((field) => field.applyOn.includes(mutationKind)).map((field) => ({
|
|
907
679
|
propertyKey: field.column,
|
|
@@ -919,7 +691,7 @@ function toSchemaPayload(entry, payload) {
|
|
|
919
691
|
if (!isPlainObject(payload)) {
|
|
920
692
|
return payload;
|
|
921
693
|
}
|
|
922
|
-
const columns =
|
|
694
|
+
const columns = getColumns2(entry.table);
|
|
923
695
|
const keyMap = new Map;
|
|
924
696
|
for (const [propertyKey, column] of Object.entries(columns)) {
|
|
925
697
|
keyMap.set(propertyKey, propertyKey);
|
|
@@ -928,7 +700,7 @@ function toSchemaPayload(entry, payload) {
|
|
|
928
700
|
return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));
|
|
929
701
|
}
|
|
930
702
|
async function readServerUpdatedAtUs(tx, entry, entityKey) {
|
|
931
|
-
const columns =
|
|
703
|
+
const columns = getColumns2(entry.table);
|
|
932
704
|
const updatedAtColumn = Object.values(columns).find((column) => column.name === "updated_at_us");
|
|
933
705
|
if (!updatedAtColumn) {
|
|
934
706
|
return;
|
|
@@ -938,46 +710,34 @@ async function readServerUpdatedAtUs(tx, entry, entityKey) {
|
|
|
938
710
|
if (rawValue === undefined) {
|
|
939
711
|
throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);
|
|
940
712
|
}
|
|
941
|
-
return
|
|
713
|
+
return sql3`${quoteIdentifier(primaryKeyColumn)} = ${rawValue}`;
|
|
942
714
|
});
|
|
943
|
-
const result = await tx.execute(
|
|
715
|
+
const result = await tx.execute(sql3`
|
|
944
716
|
SELECT ${quoteIdentifier("updated_at_us")}::text AS "updatedAtUs"
|
|
945
|
-
FROM ${quoteIdentifier(
|
|
946
|
-
WHERE ${
|
|
717
|
+
FROM ${quoteIdentifier(getTableName2(entry.table))}
|
|
718
|
+
WHERE ${sql3.join(conditions, sql3` AND `)}
|
|
947
719
|
LIMIT 1
|
|
948
720
|
`);
|
|
949
721
|
const row = Array.from(result)[0];
|
|
950
722
|
return row?.updatedAtUs ?? undefined;
|
|
951
723
|
}
|
|
952
724
|
function quoteIdentifier(identifier) {
|
|
953
|
-
return
|
|
725
|
+
return sql3.raw(`"${identifier.replace(/"/g, '""')}"`);
|
|
954
726
|
}
|
|
955
|
-
async function installBulkStartupDdl(db, registry,
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
727
|
+
async function installBulkStartupDdl(db, registry, _backend) {
|
|
728
|
+
await verifyPlpgsqlBatchFunction(db);
|
|
729
|
+
if (isArtifactAuthContextRequired(registry)) {
|
|
730
|
+
await verifyArtifactRlsAuthHelpers(db);
|
|
959
731
|
}
|
|
960
|
-
if (backend === "bulk-plpgsql") {
|
|
961
|
-
await installPlpgsqlBatchFunction(db, registry);
|
|
962
|
-
return;
|
|
963
|
-
}
|
|
964
|
-
if (backend === "bulk-plpgsql-artifact") {
|
|
965
|
-
await verifyPlpgsqlBatchFunction(db);
|
|
966
|
-
if (isArtifactAuthContextRequired(registry)) {
|
|
967
|
-
await verifyArtifactRlsAuthHelpers(db);
|
|
968
|
-
}
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
await installPregeneratedMutationFunctions(db, registry);
|
|
972
732
|
}
|
|
973
733
|
|
|
974
734
|
// packages/server/src/operations-log/ddl.ts
|
|
975
|
-
import { sql as
|
|
735
|
+
import { sql as sql4 } from "drizzle-orm";
|
|
976
736
|
async function ensureOperationsLogSchema(db, config) {
|
|
977
737
|
if (!config.enabled) {
|
|
978
738
|
return;
|
|
979
739
|
}
|
|
980
|
-
const result = await db.execute(
|
|
740
|
+
const result = await db.execute(sql4`
|
|
981
741
|
SELECT to_regclass('public.operations_log')::text AS "tableName"
|
|
982
742
|
`);
|
|
983
743
|
const row = Array.from(result, (entry) => entry)[0];
|
|
@@ -1001,7 +761,7 @@ function createSyncServer(options) {
|
|
|
1001
761
|
let address = null;
|
|
1002
762
|
const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
|
|
1003
763
|
const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
|
|
1004
|
-
const backend = options.backend ?? "
|
|
764
|
+
const backend = options.backend ?? "bulk-plpgsql-artifact";
|
|
1005
765
|
app.use("/api/*", cors({
|
|
1006
766
|
origin: options.allowedOrigins ?? defaultAllowedOrigins,
|
|
1007
767
|
allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
|
|
@@ -1031,9 +791,7 @@ function createSyncServer(options) {
|
|
|
1031
791
|
operationsLogReady
|
|
1032
792
|
});
|
|
1033
793
|
}
|
|
1034
|
-
|
|
1035
|
-
registerBulkMutationRoute(app, db, options.registry, backend, operationsLogConfig, operationsLogReady, options.resolveAuthClaims);
|
|
1036
|
-
}
|
|
794
|
+
registerBulkMutationRoute(app, db, options.registry, backend, operationsLogConfig, operationsLogReady, options.resolveAuthClaims);
|
|
1037
795
|
const fetch = async (request) => app.fetch(request);
|
|
1038
796
|
return {
|
|
1039
797
|
drizzle: db,
|
|
@@ -1363,7 +1121,7 @@ function withUpdatedAtUs(table, payload) {
|
|
|
1363
1121
|
...isRecord(payload) ? payload : {}
|
|
1364
1122
|
};
|
|
1365
1123
|
if ("updatedAtUs" in table) {
|
|
1366
|
-
values.updatedAtUs =
|
|
1124
|
+
values.updatedAtUs = sql5`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
|
|
1367
1125
|
}
|
|
1368
1126
|
return values;
|
|
1369
1127
|
}
|
|
@@ -1417,4 +1175,4 @@ export {
|
|
|
1417
1175
|
buildPlpgsqlBatchFunctionDdl
|
|
1418
1176
|
};
|
|
1419
1177
|
|
|
1420
|
-
//# debugId=
|
|
1178
|
+
//# debugId=BA7E7DC63BEEBF8964756E2164756E21
|