@cadenza.io/service 2.11.0 → 2.12.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/README.md +12 -0
- package/dist/index.d.mts +48 -8
- package/dist/index.d.ts +48 -8
- package/dist/index.js +1572 -1349
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1573 -1350
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1649,7 +1649,7 @@ var ServiceRegistry = class _ServiceRegistry {
|
|
|
1649
1649
|
}
|
|
1650
1650
|
).emits("meta.service_registry.service_inserted").emitsOnFail("meta.service_registry.service_insertion_failed");
|
|
1651
1651
|
this.insertServiceInstanceTask = CadenzaService.createCadenzaDBInsertTask(
|
|
1652
|
-
"
|
|
1652
|
+
"service_instance",
|
|
1653
1653
|
{},
|
|
1654
1654
|
{
|
|
1655
1655
|
inputSchema: {
|
|
@@ -2593,20 +2593,44 @@ var RestController = class _RestController {
|
|
|
2593
2593
|
let ctx2;
|
|
2594
2594
|
ctx2 = req.body;
|
|
2595
2595
|
deputyExecId = ctx2.__metadata.__deputyExecId;
|
|
2596
|
+
const remoteRoutineName = ctx2.__remoteRoutineName;
|
|
2597
|
+
const targetNotFoundSignal = `meta.rest.delegation_target_not_found:${deputyExecId}`;
|
|
2598
|
+
let resolved = false;
|
|
2599
|
+
const resolveDelegation = (endCtx, status) => {
|
|
2600
|
+
if (resolved || res.headersSent) {
|
|
2601
|
+
return;
|
|
2602
|
+
}
|
|
2603
|
+
resolved = true;
|
|
2604
|
+
const metadata = endCtx?.__metadata && typeof endCtx.__metadata === "object" ? endCtx.__metadata : {};
|
|
2605
|
+
if (endCtx?.__metadata) {
|
|
2606
|
+
delete endCtx.__metadata;
|
|
2607
|
+
}
|
|
2608
|
+
res.json({
|
|
2609
|
+
...endCtx,
|
|
2610
|
+
...metadata,
|
|
2611
|
+
__status: status
|
|
2612
|
+
});
|
|
2613
|
+
};
|
|
2596
2614
|
CadenzaService.createEphemeralMetaTask(
|
|
2597
2615
|
"Resolve delegation",
|
|
2598
|
-
(endCtx) =>
|
|
2599
|
-
const metadata = endCtx.__metadata;
|
|
2600
|
-
delete endCtx.__metadata;
|
|
2601
|
-
res.json({
|
|
2602
|
-
...endCtx,
|
|
2603
|
-
...metadata,
|
|
2604
|
-
__status: "success"
|
|
2605
|
-
});
|
|
2606
|
-
},
|
|
2616
|
+
(endCtx) => resolveDelegation(endCtx, "success"),
|
|
2607
2617
|
"Resolves a delegation request",
|
|
2608
2618
|
{ register: false }
|
|
2609
2619
|
).doOn(`meta.node.graph_completed:${deputyExecId}`).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
|
|
2620
|
+
CadenzaService.createEphemeralMetaTask(
|
|
2621
|
+
"Resolve delegation target lookup failure",
|
|
2622
|
+
(endCtx) => resolveDelegation(endCtx, "error"),
|
|
2623
|
+
"Resolves delegation requests that cannot find a local task or routine",
|
|
2624
|
+
{ register: false }
|
|
2625
|
+
).doOn(targetNotFoundSignal);
|
|
2626
|
+
if (!CadenzaService.get(remoteRoutineName) && !CadenzaService.registry.routines.get(remoteRoutineName)) {
|
|
2627
|
+
CadenzaService.emit(targetNotFoundSignal, {
|
|
2628
|
+
...ctx2,
|
|
2629
|
+
__error: `No task or routine registered for delegation target ${remoteRoutineName}.`,
|
|
2630
|
+
errored: true
|
|
2631
|
+
});
|
|
2632
|
+
return;
|
|
2633
|
+
}
|
|
2610
2634
|
CadenzaService.emit("meta.rest.delegation_requested", {
|
|
2611
2635
|
...ctx2,
|
|
2612
2636
|
__name: ctx2.__remoteRoutineName
|
|
@@ -2777,8 +2801,16 @@ var RestController = class _RestController {
|
|
|
2777
2801
|
CadenzaService.runner.run(routine, context);
|
|
2778
2802
|
return true;
|
|
2779
2803
|
} else {
|
|
2804
|
+
const deputyExecId = context.__metadata?.__deputyExecId ?? context.__deputyExecId;
|
|
2805
|
+
const remoteRoutineName = context.__remoteRoutineName ?? context.__name ?? "unknown";
|
|
2780
2806
|
context.errored = true;
|
|
2781
|
-
context.__error =
|
|
2807
|
+
context.__error = `No task or routine registered for delegation target ${remoteRoutineName}.`;
|
|
2808
|
+
if (deputyExecId) {
|
|
2809
|
+
emit(
|
|
2810
|
+
`meta.rest.delegation_target_not_found:${deputyExecId}`,
|
|
2811
|
+
context
|
|
2812
|
+
);
|
|
2813
|
+
}
|
|
2782
2814
|
emit("meta.runner.failed", context);
|
|
2783
2815
|
return false;
|
|
2784
2816
|
}
|
|
@@ -2801,25 +2833,25 @@ var RestController = class _RestController {
|
|
|
2801
2833
|
(ctx) => {
|
|
2802
2834
|
const { serviceName, serviceAddress, servicePort, protocol } = ctx;
|
|
2803
2835
|
const port = protocol === "https" ? 443 : servicePort;
|
|
2804
|
-
const
|
|
2836
|
+
const URL2 = `${protocol}://${serviceAddress}:${port}`;
|
|
2805
2837
|
const fetchId = `${serviceAddress}_${port}`;
|
|
2806
2838
|
const fetchDiagnostics = this.ensureFetchClientDiagnostics(
|
|
2807
2839
|
fetchId,
|
|
2808
2840
|
serviceName,
|
|
2809
|
-
|
|
2841
|
+
URL2
|
|
2810
2842
|
);
|
|
2811
2843
|
fetchDiagnostics.destroyed = false;
|
|
2812
2844
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2813
|
-
if (CadenzaService.get(`Send Handshake to ${
|
|
2814
|
-
console.error("Fetch client already exists",
|
|
2845
|
+
if (CadenzaService.get(`Send Handshake to ${URL2}`)) {
|
|
2846
|
+
console.error("Fetch client already exists", URL2);
|
|
2815
2847
|
return;
|
|
2816
2848
|
}
|
|
2817
2849
|
const handshakeTask = CadenzaService.createMetaTask(
|
|
2818
|
-
`Send Handshake to ${
|
|
2850
|
+
`Send Handshake to ${URL2}`,
|
|
2819
2851
|
async (ctx2, emit) => {
|
|
2820
2852
|
try {
|
|
2821
2853
|
const response = await this.fetchDataWithTimeout(
|
|
2822
|
-
`${
|
|
2854
|
+
`${URL2}/handshake`,
|
|
2823
2855
|
{
|
|
2824
2856
|
headers: {
|
|
2825
2857
|
"Content-Type": "application/json"
|
|
@@ -2834,10 +2866,10 @@ var RestController = class _RestController {
|
|
|
2834
2866
|
fetchDiagnostics.connected = false;
|
|
2835
2867
|
fetchDiagnostics.lastHandshakeError = error;
|
|
2836
2868
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2837
|
-
this.recordFetchClientError(fetchId, serviceName,
|
|
2869
|
+
this.recordFetchClientError(fetchId, serviceName, URL2, error);
|
|
2838
2870
|
CadenzaService.log(
|
|
2839
2871
|
"Fetch handshake failed.",
|
|
2840
|
-
{ error, serviceName, URL },
|
|
2872
|
+
{ error, serviceName, URL: URL2 },
|
|
2841
2873
|
"warning"
|
|
2842
2874
|
);
|
|
2843
2875
|
emit(`meta.fetch.handshake_failed:${fetchId}`, response);
|
|
@@ -2852,7 +2884,7 @@ var RestController = class _RestController {
|
|
|
2852
2884
|
CadenzaService.log("Fetch client connected.", {
|
|
2853
2885
|
response,
|
|
2854
2886
|
serviceName,
|
|
2855
|
-
URL
|
|
2887
|
+
URL: URL2
|
|
2856
2888
|
});
|
|
2857
2889
|
for (const communicationType of ctx2.communicationTypes) {
|
|
2858
2890
|
emit("global.meta.fetch.service_communication_established", {
|
|
@@ -2867,10 +2899,10 @@ var RestController = class _RestController {
|
|
|
2867
2899
|
fetchDiagnostics.connected = false;
|
|
2868
2900
|
fetchDiagnostics.lastHandshakeError = this.getErrorMessage(e);
|
|
2869
2901
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2870
|
-
this.recordFetchClientError(fetchId, serviceName,
|
|
2902
|
+
this.recordFetchClientError(fetchId, serviceName, URL2, e);
|
|
2871
2903
|
CadenzaService.log(
|
|
2872
2904
|
"Error in fetch handshake",
|
|
2873
|
-
{ error: e, serviceName, URL, ctx: ctx2 },
|
|
2905
|
+
{ error: e, serviceName, URL: URL2, ctx: ctx2 },
|
|
2874
2906
|
"error"
|
|
2875
2907
|
);
|
|
2876
2908
|
return { ...ctx2, __error: e, errored: true };
|
|
@@ -2884,7 +2916,7 @@ var RestController = class _RestController {
|
|
|
2884
2916
|
"global.meta.fetch.service_communication_established"
|
|
2885
2917
|
);
|
|
2886
2918
|
const delegateTask = CadenzaService.createMetaTask(
|
|
2887
|
-
`Delegate flow to REST server ${
|
|
2919
|
+
`Delegate flow to REST server ${URL2}`,
|
|
2888
2920
|
async (ctx2, emit) => {
|
|
2889
2921
|
if (ctx2.__remoteRoutineName === void 0) {
|
|
2890
2922
|
return;
|
|
@@ -2894,7 +2926,7 @@ var RestController = class _RestController {
|
|
|
2894
2926
|
let resultContext;
|
|
2895
2927
|
try {
|
|
2896
2928
|
resultContext = await this.fetchDataWithTimeout(
|
|
2897
|
-
`${
|
|
2929
|
+
`${URL2}/delegation`,
|
|
2898
2930
|
{
|
|
2899
2931
|
headers: {
|
|
2900
2932
|
"Content-Type": "application/json"
|
|
@@ -2910,7 +2942,7 @@ var RestController = class _RestController {
|
|
|
2910
2942
|
this.recordFetchClientError(
|
|
2911
2943
|
fetchId,
|
|
2912
2944
|
serviceName,
|
|
2913
|
-
|
|
2945
|
+
URL2,
|
|
2914
2946
|
resultContext?.__error ?? resultContext?.error ?? "Delegation failed"
|
|
2915
2947
|
);
|
|
2916
2948
|
}
|
|
@@ -2918,7 +2950,7 @@ var RestController = class _RestController {
|
|
|
2918
2950
|
console.error("Error in delegation", e);
|
|
2919
2951
|
fetchDiagnostics.delegationFailures++;
|
|
2920
2952
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2921
|
-
this.recordFetchClientError(fetchId, serviceName,
|
|
2953
|
+
this.recordFetchClientError(fetchId, serviceName, URL2, e);
|
|
2922
2954
|
resultContext = {
|
|
2923
2955
|
__error: `Error: ${e}`,
|
|
2924
2956
|
errored: true,
|
|
@@ -2939,7 +2971,7 @@ var RestController = class _RestController {
|
|
|
2939
2971
|
`meta.service_registry.socket_failed:${fetchId}`
|
|
2940
2972
|
).emitsOnFail("meta.fetch.delegate_failed").attachSignal("meta.fetch.delegated");
|
|
2941
2973
|
const transmitTask = CadenzaService.createMetaTask(
|
|
2942
|
-
`Transmit signal to server ${
|
|
2974
|
+
`Transmit signal to server ${URL2}`,
|
|
2943
2975
|
async (ctx2, emit) => {
|
|
2944
2976
|
if (ctx2.__signalName === void 0) {
|
|
2945
2977
|
return;
|
|
@@ -2949,7 +2981,7 @@ var RestController = class _RestController {
|
|
|
2949
2981
|
let response;
|
|
2950
2982
|
try {
|
|
2951
2983
|
response = await this.fetchDataWithTimeout(
|
|
2952
|
-
`${
|
|
2984
|
+
`${URL2}/signal`,
|
|
2953
2985
|
{
|
|
2954
2986
|
headers: {
|
|
2955
2987
|
"Content-Type": "application/json"
|
|
@@ -2968,7 +3000,7 @@ var RestController = class _RestController {
|
|
|
2968
3000
|
this.recordFetchClientError(
|
|
2969
3001
|
fetchId,
|
|
2970
3002
|
serviceName,
|
|
2971
|
-
|
|
3003
|
+
URL2,
|
|
2972
3004
|
response?.__error ?? response?.error ?? "Signal transmission failed"
|
|
2973
3005
|
);
|
|
2974
3006
|
}
|
|
@@ -2976,7 +3008,7 @@ var RestController = class _RestController {
|
|
|
2976
3008
|
console.error("Error in transmission", e);
|
|
2977
3009
|
fetchDiagnostics.signalFailures++;
|
|
2978
3010
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2979
|
-
this.recordFetchClientError(fetchId, serviceName,
|
|
3011
|
+
this.recordFetchClientError(fetchId, serviceName, URL2, e);
|
|
2980
3012
|
response = {
|
|
2981
3013
|
__error: `Error: ${e}`,
|
|
2982
3014
|
errored: true,
|
|
@@ -2992,14 +3024,14 @@ var RestController = class _RestController {
|
|
|
2992
3024
|
"meta.signal_controller.wildcard_signal_registered"
|
|
2993
3025
|
).emitsOnFail("meta.fetch.signal_transmission_failed").attachSignal("meta.fetch.transmitted");
|
|
2994
3026
|
const statusTask = CadenzaService.createMetaTask(
|
|
2995
|
-
`Request status from ${
|
|
3027
|
+
`Request status from ${URL2}`,
|
|
2996
3028
|
async (ctx2) => {
|
|
2997
3029
|
fetchDiagnostics.statusChecks++;
|
|
2998
3030
|
fetchDiagnostics.updatedAt = Date.now();
|
|
2999
3031
|
let status;
|
|
3000
3032
|
try {
|
|
3001
3033
|
status = await this.fetchDataWithTimeout(
|
|
3002
|
-
`${
|
|
3034
|
+
`${URL2}/status`,
|
|
3003
3035
|
{
|
|
3004
3036
|
method: "GET"
|
|
3005
3037
|
},
|
|
@@ -3011,14 +3043,14 @@ var RestController = class _RestController {
|
|
|
3011
3043
|
this.recordFetchClientError(
|
|
3012
3044
|
fetchId,
|
|
3013
3045
|
serviceName,
|
|
3014
|
-
|
|
3046
|
+
URL2,
|
|
3015
3047
|
status?.__error ?? status?.error ?? "Status check failed"
|
|
3016
3048
|
);
|
|
3017
3049
|
}
|
|
3018
3050
|
} catch (e) {
|
|
3019
3051
|
fetchDiagnostics.statusFailures++;
|
|
3020
3052
|
fetchDiagnostics.updatedAt = Date.now();
|
|
3021
|
-
this.recordFetchClientError(fetchId, serviceName,
|
|
3053
|
+
this.recordFetchClientError(fetchId, serviceName, URL2, e);
|
|
3022
3054
|
status = {
|
|
3023
3055
|
__error: `Error: ${e}`,
|
|
3024
3056
|
errored: true,
|
|
@@ -3033,7 +3065,7 @@ var RestController = class _RestController {
|
|
|
3033
3065
|
fetchDiagnostics.connected = false;
|
|
3034
3066
|
fetchDiagnostics.destroyed = true;
|
|
3035
3067
|
fetchDiagnostics.updatedAt = Date.now();
|
|
3036
|
-
CadenzaService.log("Destroying fetch client", { URL, serviceName });
|
|
3068
|
+
CadenzaService.log("Destroying fetch client", { URL: URL2, serviceName });
|
|
3037
3069
|
handshakeTask.destroy();
|
|
3038
3070
|
delegateTask.destroy();
|
|
3039
3071
|
transmitTask.destroy();
|
|
@@ -3435,13 +3467,13 @@ var SocketController = class _SocketController {
|
|
|
3435
3467
|
Object.assign(base, patch);
|
|
3436
3468
|
base.fetchId = fetchId;
|
|
3437
3469
|
base.updatedAt = now;
|
|
3438
|
-
const
|
|
3439
|
-
if (
|
|
3440
|
-
base.lastError =
|
|
3470
|
+
const errorMessage2 = input.error !== void 0 ? this.getErrorMessage(input.error) : void 0;
|
|
3471
|
+
if (errorMessage2) {
|
|
3472
|
+
base.lastError = errorMessage2;
|
|
3441
3473
|
base.lastErrorAt = now;
|
|
3442
3474
|
base.errorHistory.push({
|
|
3443
3475
|
at: new Date(now).toISOString(),
|
|
3444
|
-
message:
|
|
3476
|
+
message: errorMessage2
|
|
3445
3477
|
});
|
|
3446
3478
|
if (base.errorHistory.length > this.diagnosticsErrorHistoryLimit) {
|
|
3447
3479
|
base.errorHistory.splice(
|
|
@@ -3943,12 +3975,12 @@ var SocketController = class _SocketController {
|
|
|
3943
3975
|
if (ack) ack(response);
|
|
3944
3976
|
resolve(response);
|
|
3945
3977
|
};
|
|
3946
|
-
const resolveWithError = (
|
|
3978
|
+
const resolveWithError = (errorMessage2, fallbackError) => {
|
|
3947
3979
|
settle({
|
|
3948
3980
|
...data,
|
|
3949
3981
|
errored: true,
|
|
3950
|
-
__error:
|
|
3951
|
-
error: fallbackError instanceof Error ? fallbackError.message :
|
|
3982
|
+
__error: errorMessage2,
|
|
3983
|
+
error: fallbackError instanceof Error ? fallbackError.message : errorMessage2,
|
|
3952
3984
|
socketId: runtimeHandle.socket.id,
|
|
3953
3985
|
serviceName,
|
|
3954
3986
|
url
|
|
@@ -4253,19 +4285,19 @@ var SocketController = class _SocketController {
|
|
|
4253
4285
|
url
|
|
4254
4286
|
});
|
|
4255
4287
|
} else {
|
|
4256
|
-
const
|
|
4288
|
+
const errorMessage2 = result?.__error ?? result?.error ?? "Socket handshake failed";
|
|
4257
4289
|
upsertDiagnostics(
|
|
4258
4290
|
{
|
|
4259
4291
|
connected: false,
|
|
4260
4292
|
handshake: false,
|
|
4261
|
-
lastHandshakeError:
|
|
4293
|
+
lastHandshakeError: errorMessage2
|
|
4262
4294
|
},
|
|
4263
|
-
|
|
4295
|
+
errorMessage2
|
|
4264
4296
|
);
|
|
4265
4297
|
applySessionOperation("handshake", {
|
|
4266
4298
|
connected: false,
|
|
4267
4299
|
handshake: false,
|
|
4268
|
-
lastHandshakeError:
|
|
4300
|
+
lastHandshakeError: errorMessage2
|
|
4269
4301
|
});
|
|
4270
4302
|
CadenzaService.log(
|
|
4271
4303
|
"Socket handshake failed",
|
|
@@ -4313,15 +4345,15 @@ var SocketController = class _SocketController {
|
|
|
4313
4345
|
});
|
|
4314
4346
|
}
|
|
4315
4347
|
if (resultContext?.errored || resultContext?.failed) {
|
|
4316
|
-
const
|
|
4348
|
+
const errorMessage2 = resultContext?.__error ?? resultContext?.error ?? "Socket delegation failed";
|
|
4317
4349
|
upsertDiagnostics(
|
|
4318
4350
|
{
|
|
4319
|
-
lastHandshakeError: String(
|
|
4351
|
+
lastHandshakeError: String(errorMessage2)
|
|
4320
4352
|
},
|
|
4321
|
-
|
|
4353
|
+
errorMessage2
|
|
4322
4354
|
);
|
|
4323
4355
|
applySessionOperation("delegate", {
|
|
4324
|
-
lastHandshakeError: String(
|
|
4356
|
+
lastHandshakeError: String(errorMessage2)
|
|
4325
4357
|
});
|
|
4326
4358
|
}
|
|
4327
4359
|
return resultContext;
|
|
@@ -5155,566 +5187,175 @@ var SCHEMA_TYPES = [
|
|
|
5155
5187
|
|
|
5156
5188
|
// src/database/DatabaseController.ts
|
|
5157
5189
|
import { Pool } from "pg";
|
|
5158
|
-
import { camelCase, snakeCase } from "lodash-es";
|
|
5159
|
-
function
|
|
5160
|
-
const
|
|
5161
|
-
|
|
5162
|
-
|
|
5190
|
+
import { camelCase, kebabCase, snakeCase } from "lodash-es";
|
|
5191
|
+
function normalizeIntentToken(value) {
|
|
5192
|
+
const normalized = kebabCase(String(value ?? "").trim());
|
|
5193
|
+
if (!normalized) {
|
|
5194
|
+
throw new Error("Actor token cannot be empty");
|
|
5195
|
+
}
|
|
5196
|
+
return normalized;
|
|
5197
|
+
}
|
|
5198
|
+
function validateIntentName(intentName) {
|
|
5199
|
+
if (!intentName || typeof intentName !== "string") {
|
|
5200
|
+
throw new Error("Intent name must be a non-empty string");
|
|
5201
|
+
}
|
|
5202
|
+
if (intentName.length > 100) {
|
|
5203
|
+
throw new Error(`Intent name must be <= 100 characters: ${intentName}`);
|
|
5204
|
+
}
|
|
5205
|
+
if (intentName.includes(" ") || intentName.includes(".") || intentName.includes("\\")) {
|
|
5206
|
+
throw new Error(
|
|
5207
|
+
`Intent name cannot contain spaces, dots or backslashes: ${intentName}`
|
|
5208
|
+
);
|
|
5209
|
+
}
|
|
5210
|
+
}
|
|
5211
|
+
function defaultOperationIntentDescription(operation, tableName) {
|
|
5212
|
+
return `Perform a ${operation} operation on the ${tableName} table`;
|
|
5213
|
+
}
|
|
5214
|
+
function readCustomIntentConfig(customIntent) {
|
|
5215
|
+
if (typeof customIntent === "string") {
|
|
5216
|
+
return {
|
|
5217
|
+
intent: customIntent
|
|
5218
|
+
};
|
|
5219
|
+
}
|
|
5220
|
+
return {
|
|
5221
|
+
intent: customIntent.intent,
|
|
5222
|
+
description: customIntent.description,
|
|
5223
|
+
input: customIntent.input
|
|
5224
|
+
};
|
|
5225
|
+
}
|
|
5226
|
+
function resolveTableOperationIntents(actorName, tableName, table, operation, defaultInputSchema) {
|
|
5227
|
+
const actorToken = normalizeIntentToken(actorName);
|
|
5228
|
+
const defaultIntentName = `${operation}-pg-${actorToken}-${tableName}`;
|
|
5229
|
+
validateIntentName(defaultIntentName);
|
|
5163
5230
|
const intents = [
|
|
5164
5231
|
{
|
|
5165
5232
|
name: defaultIntentName,
|
|
5166
|
-
description:
|
|
5233
|
+
description: defaultOperationIntentDescription(operation, tableName),
|
|
5167
5234
|
input: defaultInputSchema
|
|
5168
5235
|
}
|
|
5169
5236
|
];
|
|
5170
|
-
const
|
|
5171
|
-
const
|
|
5172
|
-
for (const
|
|
5173
|
-
const
|
|
5174
|
-
|
|
5175
|
-
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
continue;
|
|
5179
|
-
}
|
|
5180
|
-
if (name.length > 100) {
|
|
5181
|
-
warnings.push(
|
|
5182
|
-
`Skipped custom query intent '${name}' for table '${tableName}': name must be <= 100 characters.`
|
|
5183
|
-
);
|
|
5184
|
-
continue;
|
|
5185
|
-
}
|
|
5186
|
-
if (name.includes(" ") || name.includes(".") || name.includes("\\")) {
|
|
5187
|
-
warnings.push(
|
|
5188
|
-
`Skipped custom query intent '${name}' for table '${tableName}': name cannot contain spaces, dots or backslashes.`
|
|
5237
|
+
const seenNames = /* @__PURE__ */ new Set([defaultIntentName]);
|
|
5238
|
+
const customIntentList = table.customIntents?.[operation] ?? [];
|
|
5239
|
+
for (const rawCustomIntent of customIntentList) {
|
|
5240
|
+
const customIntent = readCustomIntentConfig(rawCustomIntent);
|
|
5241
|
+
const intentName = String(customIntent.intent ?? "").trim();
|
|
5242
|
+
if (!intentName) {
|
|
5243
|
+
throw new Error(
|
|
5244
|
+
`Invalid custom ${operation} intent on table '${tableName}': intent must be a non-empty string`
|
|
5189
5245
|
);
|
|
5190
|
-
continue;
|
|
5191
5246
|
}
|
|
5192
|
-
|
|
5193
|
-
|
|
5194
|
-
|
|
5247
|
+
validateIntentName(intentName);
|
|
5248
|
+
if (seenNames.has(intentName)) {
|
|
5249
|
+
throw new Error(
|
|
5250
|
+
`Duplicate ${operation} intent '${intentName}' on table '${tableName}'`
|
|
5195
5251
|
);
|
|
5196
|
-
continue;
|
|
5197
5252
|
}
|
|
5198
|
-
|
|
5253
|
+
seenNames.add(intentName);
|
|
5199
5254
|
intents.push({
|
|
5200
|
-
name,
|
|
5201
|
-
description:
|
|
5202
|
-
input:
|
|
5255
|
+
name: intentName,
|
|
5256
|
+
description: customIntent.description ?? defaultOperationIntentDescription(operation, tableName),
|
|
5257
|
+
input: customIntent.input ?? defaultInputSchema
|
|
5203
5258
|
});
|
|
5204
5259
|
}
|
|
5205
|
-
return { intents
|
|
5260
|
+
return { intents };
|
|
5261
|
+
}
|
|
5262
|
+
function ensurePlainObject(value, label) {
|
|
5263
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
5264
|
+
throw new Error(`${label} must be an object`);
|
|
5265
|
+
}
|
|
5266
|
+
return value;
|
|
5267
|
+
}
|
|
5268
|
+
function sleep(timeoutMs) {
|
|
5269
|
+
return new Promise((resolve) => {
|
|
5270
|
+
setTimeout(resolve, timeoutMs);
|
|
5271
|
+
});
|
|
5272
|
+
}
|
|
5273
|
+
function normalizePositiveInteger(value, fallback, min = 1) {
|
|
5274
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
5275
|
+
return fallback;
|
|
5276
|
+
}
|
|
5277
|
+
const normalized = Math.trunc(value);
|
|
5278
|
+
if (normalized < min) {
|
|
5279
|
+
return fallback;
|
|
5280
|
+
}
|
|
5281
|
+
return normalized;
|
|
5282
|
+
}
|
|
5283
|
+
function errorMessage(error) {
|
|
5284
|
+
if (error instanceof Error) {
|
|
5285
|
+
return error.message;
|
|
5286
|
+
}
|
|
5287
|
+
return String(error);
|
|
5288
|
+
}
|
|
5289
|
+
function isTransientDatabaseError(error) {
|
|
5290
|
+
if (!error || typeof error !== "object") {
|
|
5291
|
+
return false;
|
|
5292
|
+
}
|
|
5293
|
+
const dbError = error;
|
|
5294
|
+
const code = String(dbError.code ?? "");
|
|
5295
|
+
if (["40001", "40P01", "57P03", "53300", "08006", "08001"].includes(code)) {
|
|
5296
|
+
return true;
|
|
5297
|
+
}
|
|
5298
|
+
const message = String(dbError.message ?? "").toLowerCase();
|
|
5299
|
+
return message.includes("timeout") || message.includes("terminating connection") || message.includes("connection reset");
|
|
5300
|
+
}
|
|
5301
|
+
function isSqlIdentifier(value) {
|
|
5302
|
+
return /^[a-z_][a-z0-9_]*$/.test(value);
|
|
5303
|
+
}
|
|
5304
|
+
function toSafeSqlIdentifier(value, fallback) {
|
|
5305
|
+
const normalized = snakeCase(value || "").replace(/[^a-z0-9_]/g, "_");
|
|
5306
|
+
const candidate = normalized || fallback;
|
|
5307
|
+
if (!isSqlIdentifier(candidate)) {
|
|
5308
|
+
throw new Error(`Invalid SQL identifier: ${value}`);
|
|
5309
|
+
}
|
|
5310
|
+
return candidate;
|
|
5311
|
+
}
|
|
5312
|
+
function isSupportedAggregateFunction(value) {
|
|
5313
|
+
const fn = String(value ?? "").toLowerCase();
|
|
5314
|
+
return ["count", "sum", "avg", "min", "max"].includes(fn);
|
|
5315
|
+
}
|
|
5316
|
+
function buildAggregateAlias(aggregate, index) {
|
|
5317
|
+
const fn = String(aggregate.fn ?? "").toLowerCase();
|
|
5318
|
+
const hasField = typeof aggregate.field === "string" && aggregate.field.trim().length > 0;
|
|
5319
|
+
return toSafeSqlIdentifier(
|
|
5320
|
+
String(aggregate.as ?? `${fn}_${hasField ? aggregate.field : "all"}_${index}`),
|
|
5321
|
+
`${fn || "aggregate"}_${index}`
|
|
5322
|
+
);
|
|
5323
|
+
}
|
|
5324
|
+
function resolveDataRows(data) {
|
|
5325
|
+
if (!data) {
|
|
5326
|
+
return [];
|
|
5327
|
+
}
|
|
5328
|
+
if (Array.isArray(data)) {
|
|
5329
|
+
return data.map((entry) => ensurePlainObject(entry, "data item"));
|
|
5330
|
+
}
|
|
5331
|
+
return [ensurePlainObject(data, "data")];
|
|
5206
5332
|
}
|
|
5207
5333
|
var DatabaseController = class _DatabaseController {
|
|
5208
|
-
/**
|
|
5209
|
-
* Constructor for initializing the `DatabaseService` class.
|
|
5210
|
-
*
|
|
5211
|
-
* This constructor method initializes a sequence of meta tasks to perform the following database-related operations:
|
|
5212
|
-
*
|
|
5213
|
-
* 1. **Database Creation**: Creates a new database with the specified name if it doesn't already exist.
|
|
5214
|
-
* Validates the database name to ensure it conforms to the required format.
|
|
5215
|
-
* 2. **Database Schema Validation**: Validates the structure and constraints of the schema definition provided.
|
|
5216
|
-
* 3. **Table Dependency Management**: Sorts tables within the schema by their dependencies to ensure proper creation order.
|
|
5217
|
-
* 4. **Schema Definition Processing**:
|
|
5218
|
-
* - Converts schema definitions into Data Definition Language (DDL) based on table and field specifications.
|
|
5219
|
-
* - Handles constraints, relationships, and field attributes such as uniqueness, primary keys, nullable fields, etc.
|
|
5220
|
-
* 5. **Index and Primary Key Definition**: Generates SQL for indices and primary keys based on the schema configuration.
|
|
5221
|
-
*
|
|
5222
|
-
* These tasks are encapsulated within a meta routine to provide a structured and procedural approach to database initialization and schema management.
|
|
5223
|
-
*/
|
|
5224
5334
|
constructor() {
|
|
5225
|
-
this.
|
|
5226
|
-
this.
|
|
5335
|
+
this.registrationsByService = /* @__PURE__ */ new Map();
|
|
5336
|
+
this.adminDbClient = new Pool({
|
|
5227
5337
|
connectionString: process.env.DATABASE_ADDRESS ?? "",
|
|
5228
5338
|
database: "postgres",
|
|
5229
5339
|
ssl: {
|
|
5230
5340
|
rejectUnauthorized: false
|
|
5231
|
-
// ← This bypasses the chain validation error
|
|
5232
5341
|
}
|
|
5233
5342
|
});
|
|
5234
|
-
CadenzaService.
|
|
5235
|
-
"
|
|
5236
|
-
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
console.log(`Creating database ${databaseName}`, {
|
|
5251
|
-
connectionString: process.env.DATABASE_ADDRESS ?? "",
|
|
5252
|
-
database: "postgres"
|
|
5253
|
-
});
|
|
5254
|
-
await this.dbClient.query(`CREATE DATABASE ${databaseName}`);
|
|
5255
|
-
console.log(`Database ${databaseName} created`);
|
|
5256
|
-
this.dbClient = new Pool({
|
|
5257
|
-
connectionString: process.env.DATABASE_ADDRESS ? process.env.DATABASE_ADDRESS.slice(
|
|
5258
|
-
0,
|
|
5259
|
-
process.env.DATABASE_ADDRESS.lastIndexOf("/")
|
|
5260
|
-
) + "/" + databaseName + "?sslmode=disable" : "",
|
|
5261
|
-
ssl: {
|
|
5262
|
-
rejectUnauthorized: false
|
|
5263
|
-
// ← This bypasses the chain validation error
|
|
5264
|
-
}
|
|
5265
|
-
});
|
|
5266
|
-
this.databaseName = databaseName;
|
|
5267
|
-
return true;
|
|
5268
|
-
} catch (error) {
|
|
5269
|
-
if (error.code === "42P04") {
|
|
5270
|
-
console.log("Database already exists");
|
|
5271
|
-
return true;
|
|
5272
|
-
}
|
|
5273
|
-
console.error("Failed to create database", error);
|
|
5274
|
-
throw new Error(`Failed to create database: ${error.message}`);
|
|
5275
|
-
}
|
|
5276
|
-
},
|
|
5277
|
-
"Creates the target database if it doesn't exist"
|
|
5278
|
-
).then(
|
|
5279
|
-
CadenzaService.createMetaTask(
|
|
5280
|
-
"Validate schema",
|
|
5281
|
-
(ctx) => {
|
|
5282
|
-
const { schema } = ctx;
|
|
5283
|
-
if (!schema?.tables || typeof schema.tables !== "object") {
|
|
5284
|
-
throw new Error("Invalid schema: missing or invalid tables");
|
|
5285
|
-
}
|
|
5286
|
-
for (const [tableName, table] of Object.entries(schema.tables)) {
|
|
5287
|
-
if (!table.fields || typeof table.fields !== "object") {
|
|
5288
|
-
console.log(tableName, "missing fields");
|
|
5289
|
-
throw new Error(`Invalid table ${tableName}: missing fields`);
|
|
5290
|
-
}
|
|
5291
|
-
for (const [fieldName, field] of Object.entries(table.fields)) {
|
|
5292
|
-
if (!fieldName.split("").every((c) => /[a-z_]/.test(c))) {
|
|
5293
|
-
console.log(tableName, "field not lowercase", fieldName);
|
|
5294
|
-
throw new Error(
|
|
5295
|
-
`Invalid field name ${fieldName} for ${tableName}. Field names must only contain lowercase alphanumeric characters and underscores`
|
|
5296
|
-
);
|
|
5297
|
-
}
|
|
5298
|
-
if (!Object.values(SCHEMA_TYPES).includes(field.type)) {
|
|
5299
|
-
console.log(
|
|
5300
|
-
tableName,
|
|
5301
|
-
"field invalid type",
|
|
5302
|
-
fieldName,
|
|
5303
|
-
field.type
|
|
5304
|
-
);
|
|
5305
|
-
throw new Error(
|
|
5306
|
-
`Invalid type ${field.type} for ${tableName}.${fieldName}`
|
|
5307
|
-
);
|
|
5308
|
-
}
|
|
5309
|
-
if (field.references && !field.references.match(/^[\w]+[(\w)]+$/)) {
|
|
5310
|
-
console.log(
|
|
5311
|
-
tableName,
|
|
5312
|
-
"invalid reference",
|
|
5313
|
-
fieldName,
|
|
5314
|
-
field.references
|
|
5315
|
-
);
|
|
5316
|
-
throw new Error(
|
|
5317
|
-
`Invalid reference ${field.references} for ${tableName}.${fieldName}`
|
|
5318
|
-
);
|
|
5319
|
-
}
|
|
5320
|
-
if (table.customSignals) {
|
|
5321
|
-
for (const op of ["query", "insert", "update", "delete"]) {
|
|
5322
|
-
const triggers = table.customSignals.triggers?.[op];
|
|
5323
|
-
const emissions = table.customSignals.emissions?.[op];
|
|
5324
|
-
if (triggers && !Array.isArray(triggers) && typeof triggers !== "object") {
|
|
5325
|
-
console.log(
|
|
5326
|
-
tableName,
|
|
5327
|
-
"invalid triggers",
|
|
5328
|
-
op,
|
|
5329
|
-
triggers
|
|
5330
|
-
);
|
|
5331
|
-
throw new Error(
|
|
5332
|
-
`Invalid triggers for ${tableName}.${op}`
|
|
5333
|
-
);
|
|
5334
|
-
}
|
|
5335
|
-
if (emissions && !Array.isArray(emissions) && typeof emissions !== "object") {
|
|
5336
|
-
console.log(
|
|
5337
|
-
tableName,
|
|
5338
|
-
"invalid emissions",
|
|
5339
|
-
op,
|
|
5340
|
-
emissions
|
|
5341
|
-
);
|
|
5342
|
-
throw new Error(
|
|
5343
|
-
`Invalid emissions for ${tableName}.${op}`
|
|
5344
|
-
);
|
|
5345
|
-
}
|
|
5346
|
-
}
|
|
5347
|
-
}
|
|
5348
|
-
if (table.customIntents?.query) {
|
|
5349
|
-
if (!Array.isArray(table.customIntents.query)) {
|
|
5350
|
-
throw new Error(
|
|
5351
|
-
`Invalid customIntents.query for ${tableName}: expected array`
|
|
5352
|
-
);
|
|
5353
|
-
}
|
|
5354
|
-
for (const customIntent of table.customIntents.query) {
|
|
5355
|
-
if (typeof customIntent !== "string" && (typeof customIntent !== "object" || !customIntent || typeof customIntent.intent !== "string")) {
|
|
5356
|
-
throw new Error(
|
|
5357
|
-
`Invalid custom query intent on ${tableName}: expected string or object with intent`
|
|
5358
|
-
);
|
|
5359
|
-
}
|
|
5360
|
-
}
|
|
5361
|
-
}
|
|
5362
|
-
}
|
|
5363
|
-
}
|
|
5364
|
-
console.log("SCHEMA VALIDATED");
|
|
5365
|
-
return true;
|
|
5366
|
-
},
|
|
5367
|
-
"Validates database schema structure and content"
|
|
5368
|
-
).then(
|
|
5369
|
-
CadenzaService.createMetaTask(
|
|
5370
|
-
"Sort tables by dependencies",
|
|
5371
|
-
this.sortTablesByReferences.bind(this),
|
|
5372
|
-
"Sorts tables by dependencies"
|
|
5373
|
-
).then(
|
|
5374
|
-
CadenzaService.createMetaTask(
|
|
5375
|
-
"Split schema into tables",
|
|
5376
|
-
this.splitTables.bind(this),
|
|
5377
|
-
"Generates DDL for database schema"
|
|
5378
|
-
).then(
|
|
5379
|
-
CadenzaService.createMetaTask(
|
|
5380
|
-
"Generate DDL from table",
|
|
5381
|
-
async (ctx) => {
|
|
5382
|
-
const {
|
|
5383
|
-
ddl,
|
|
5384
|
-
table,
|
|
5385
|
-
tableName,
|
|
5386
|
-
schema,
|
|
5387
|
-
options,
|
|
5388
|
-
sortedTables
|
|
5389
|
-
} = ctx;
|
|
5390
|
-
const fieldDefs = Object.entries(table.fields).map((value) => {
|
|
5391
|
-
const [fieldName, field] = value;
|
|
5392
|
-
let def = `${fieldName} ${field.type.toUpperCase()}`;
|
|
5393
|
-
if (field.type === "varchar")
|
|
5394
|
-
def += `(${field.constraints?.maxLength ?? 255})`;
|
|
5395
|
-
if (field.type === "decimal")
|
|
5396
|
-
def += `(${field.constraints?.precision ?? 10},${field.constraints?.scale ?? 2})`;
|
|
5397
|
-
if (field.primary) def += " PRIMARY KEY";
|
|
5398
|
-
if (field.unique) def += " UNIQUE";
|
|
5399
|
-
if (field.default !== void 0)
|
|
5400
|
-
def += ` DEFAULT ${field.default === "" ? "''" : String(field.default)}`;
|
|
5401
|
-
if (field.required && !field.nullable)
|
|
5402
|
-
def += " NOT NULL";
|
|
5403
|
-
if (field.nullable) def += " NULL";
|
|
5404
|
-
if (field.generated)
|
|
5405
|
-
def += ` GENERATED ALWAYS AS ${field.generated.toUpperCase()} STORED`;
|
|
5406
|
-
if (field.references)
|
|
5407
|
-
def += ` REFERENCES ${field.references} ON DELETE ${field.onDelete || "CASCADE"}`;
|
|
5408
|
-
if (field.encrypted) def += " ENCRYPTED";
|
|
5409
|
-
if (field.constraints?.check) {
|
|
5410
|
-
def += ` CHECK (${field.constraints.check})`;
|
|
5411
|
-
}
|
|
5412
|
-
return def;
|
|
5413
|
-
}).join(", ");
|
|
5414
|
-
if (schema.meta?.dropExisting) {
|
|
5415
|
-
const result = await this.dbClient.query(
|
|
5416
|
-
`DELETE FROM ${tableName};`
|
|
5417
|
-
);
|
|
5418
|
-
console.log("DROP TABLE", tableName, result);
|
|
5419
|
-
}
|
|
5420
|
-
const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${fieldDefs})`;
|
|
5421
|
-
ddl.push(sql);
|
|
5422
|
-
return {
|
|
5423
|
-
ddl,
|
|
5424
|
-
table,
|
|
5425
|
-
tableName,
|
|
5426
|
-
schema,
|
|
5427
|
-
options,
|
|
5428
|
-
sortedTables
|
|
5429
|
-
};
|
|
5430
|
-
}
|
|
5431
|
-
).then(
|
|
5432
|
-
CadenzaService.createMetaTask("Generate index DDL", (ctx) => {
|
|
5433
|
-
const {
|
|
5434
|
-
ddl,
|
|
5435
|
-
table,
|
|
5436
|
-
tableName,
|
|
5437
|
-
schema,
|
|
5438
|
-
options,
|
|
5439
|
-
sortedTables
|
|
5440
|
-
} = ctx;
|
|
5441
|
-
if (table.indexes) {
|
|
5442
|
-
table.indexes.forEach((fields) => {
|
|
5443
|
-
ddl.push(
|
|
5444
|
-
`CREATE INDEX IF NOT EXISTS idx_${tableName}_${fields.join("_")} ON ${tableName} (${fields.join(", ")});`
|
|
5445
|
-
);
|
|
5446
|
-
});
|
|
5447
|
-
}
|
|
5448
|
-
return {
|
|
5449
|
-
ddl,
|
|
5450
|
-
table,
|
|
5451
|
-
tableName,
|
|
5452
|
-
schema,
|
|
5453
|
-
options,
|
|
5454
|
-
sortedTables
|
|
5455
|
-
};
|
|
5456
|
-
}).then(
|
|
5457
|
-
CadenzaService.createMetaTask(
|
|
5458
|
-
"Generate primary key ddl",
|
|
5459
|
-
(ctx) => {
|
|
5460
|
-
const {
|
|
5461
|
-
ddl,
|
|
5462
|
-
table,
|
|
5463
|
-
tableName,
|
|
5464
|
-
schema,
|
|
5465
|
-
options,
|
|
5466
|
-
sortedTables
|
|
5467
|
-
} = ctx;
|
|
5468
|
-
if (table.primaryKey) {
|
|
5469
|
-
ddl.push(
|
|
5470
|
-
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS unique_${tableName}_${table.primaryKey.join("_")};`,
|
|
5471
|
-
// TODO: should be cascade?
|
|
5472
|
-
`ALTER TABLE ${tableName} ADD CONSTRAINT unique_${tableName}_${table.primaryKey.join("_")} PRIMARY KEY (${table.primaryKey.join(", ")});`
|
|
5473
|
-
);
|
|
5474
|
-
}
|
|
5475
|
-
return {
|
|
5476
|
-
ddl,
|
|
5477
|
-
table,
|
|
5478
|
-
tableName,
|
|
5479
|
-
schema,
|
|
5480
|
-
options,
|
|
5481
|
-
sortedTables
|
|
5482
|
-
};
|
|
5483
|
-
}
|
|
5484
|
-
).then(
|
|
5485
|
-
CadenzaService.createMetaTask(
|
|
5486
|
-
"Generate unique index DDL",
|
|
5487
|
-
(ctx) => {
|
|
5488
|
-
const {
|
|
5489
|
-
ddl,
|
|
5490
|
-
table,
|
|
5491
|
-
tableName,
|
|
5492
|
-
schema,
|
|
5493
|
-
options,
|
|
5494
|
-
sortedTables
|
|
5495
|
-
} = ctx;
|
|
5496
|
-
if (table.uniqueConstraints) {
|
|
5497
|
-
table.uniqueConstraints.forEach(
|
|
5498
|
-
(fields) => {
|
|
5499
|
-
ddl.push(
|
|
5500
|
-
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS unique_${tableName}_${fields.join("_")};`,
|
|
5501
|
-
// TODO: should be cascade?
|
|
5502
|
-
`ALTER TABLE ${tableName} ADD CONSTRAINT unique_${tableName}_${fields.join("_")} UNIQUE (${fields.join(", ")});`
|
|
5503
|
-
);
|
|
5504
|
-
}
|
|
5505
|
-
);
|
|
5506
|
-
}
|
|
5507
|
-
return {
|
|
5508
|
-
ddl,
|
|
5509
|
-
table,
|
|
5510
|
-
tableName,
|
|
5511
|
-
schema,
|
|
5512
|
-
options,
|
|
5513
|
-
sortedTables
|
|
5514
|
-
};
|
|
5515
|
-
}
|
|
5516
|
-
).then(
|
|
5517
|
-
CadenzaService.createMetaTask(
|
|
5518
|
-
"Generate foreign key DDL",
|
|
5519
|
-
(ctx) => {
|
|
5520
|
-
const {
|
|
5521
|
-
ddl,
|
|
5522
|
-
table,
|
|
5523
|
-
tableName,
|
|
5524
|
-
schema,
|
|
5525
|
-
options,
|
|
5526
|
-
sortedTables
|
|
5527
|
-
} = ctx;
|
|
5528
|
-
if (table.foreignKeys) {
|
|
5529
|
-
for (const foreignKey of table.foreignKeys) {
|
|
5530
|
-
const foreignKeyName = `fk_${tableName}_${foreignKey.fields.join("_")}`;
|
|
5531
|
-
ddl.push(
|
|
5532
|
-
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS ${foreignKeyName};`,
|
|
5533
|
-
// TODO: should be cascade?
|
|
5534
|
-
`ALTER TABLE ${tableName} ADD CONSTRAINT ${foreignKeyName} FOREIGN KEY (${foreignKey.fields.join(
|
|
5535
|
-
", "
|
|
5536
|
-
)}) REFERENCES ${foreignKey.tableName} (${foreignKey.referenceFields.join(
|
|
5537
|
-
", "
|
|
5538
|
-
)});`
|
|
5539
|
-
);
|
|
5540
|
-
}
|
|
5541
|
-
}
|
|
5542
|
-
return {
|
|
5543
|
-
ddl,
|
|
5544
|
-
table,
|
|
5545
|
-
tableName,
|
|
5546
|
-
schema,
|
|
5547
|
-
options,
|
|
5548
|
-
sortedTables
|
|
5549
|
-
};
|
|
5550
|
-
}
|
|
5551
|
-
).then(
|
|
5552
|
-
CadenzaService.createMetaTask(
|
|
5553
|
-
"Generate trigger DDL",
|
|
5554
|
-
(ctx) => {
|
|
5555
|
-
const {
|
|
5556
|
-
ddl,
|
|
5557
|
-
table,
|
|
5558
|
-
tableName,
|
|
5559
|
-
schema,
|
|
5560
|
-
options,
|
|
5561
|
-
sortedTables
|
|
5562
|
-
} = ctx;
|
|
5563
|
-
if (table.triggers) {
|
|
5564
|
-
for (const [
|
|
5565
|
-
triggerName,
|
|
5566
|
-
trigger
|
|
5567
|
-
] of Object.entries(table.triggers)) {
|
|
5568
|
-
ddl.push(
|
|
5569
|
-
`CREATE TRIGGER ${triggerName} ${trigger.when} ${trigger.event} ON ${tableName} FOR EACH STATEMENT EXECUTE FUNCTION ${trigger.function};`
|
|
5570
|
-
);
|
|
5571
|
-
}
|
|
5572
|
-
}
|
|
5573
|
-
return {
|
|
5574
|
-
ddl,
|
|
5575
|
-
table,
|
|
5576
|
-
tableName,
|
|
5577
|
-
schema,
|
|
5578
|
-
options,
|
|
5579
|
-
sortedTables
|
|
5580
|
-
};
|
|
5581
|
-
}
|
|
5582
|
-
).then(
|
|
5583
|
-
CadenzaService.createMetaTask(
|
|
5584
|
-
"Generate initial data DDL",
|
|
5585
|
-
(ctx) => {
|
|
5586
|
-
const {
|
|
5587
|
-
ddl,
|
|
5588
|
-
table,
|
|
5589
|
-
tableName,
|
|
5590
|
-
schema,
|
|
5591
|
-
options,
|
|
5592
|
-
sortedTables
|
|
5593
|
-
} = ctx;
|
|
5594
|
-
if (table.initialData) {
|
|
5595
|
-
ddl.push(
|
|
5596
|
-
`INSERT INTO ${tableName} (${table.initialData.fields.join(", ")}) VALUES ${table.initialData.data.map(
|
|
5597
|
-
(row) => `(${row.map(
|
|
5598
|
-
(value) => value === void 0 ? "NULL" : value.charAt(0) === "'" ? value : `'${value}'`
|
|
5599
|
-
).join(", ")})`
|
|
5600
|
-
// TODO: handle non string data
|
|
5601
|
-
).join(", ")} ON CONFLICT DO NOTHING;`
|
|
5602
|
-
);
|
|
5603
|
-
}
|
|
5604
|
-
return {
|
|
5605
|
-
ddl,
|
|
5606
|
-
table,
|
|
5607
|
-
tableName,
|
|
5608
|
-
schema,
|
|
5609
|
-
options,
|
|
5610
|
-
sortedTables
|
|
5611
|
-
};
|
|
5612
|
-
}
|
|
5613
|
-
).then(
|
|
5614
|
-
CadenzaService.createUniqueMetaTask(
|
|
5615
|
-
"Join DDL",
|
|
5616
|
-
(ctx) => {
|
|
5617
|
-
const { joinedContexts } = ctx;
|
|
5618
|
-
const ddl = [];
|
|
5619
|
-
for (const joinedContext of joinedContexts) {
|
|
5620
|
-
ddl.push(...joinedContext.ddl);
|
|
5621
|
-
}
|
|
5622
|
-
ddl.flat();
|
|
5623
|
-
return {
|
|
5624
|
-
ddl,
|
|
5625
|
-
schema: joinedContexts[0].schema,
|
|
5626
|
-
options: joinedContexts[0].options,
|
|
5627
|
-
table: joinedContexts[0].table,
|
|
5628
|
-
tableName: joinedContexts[0].tableName,
|
|
5629
|
-
sortedTables: joinedContexts[0].sortedTables
|
|
5630
|
-
};
|
|
5631
|
-
}
|
|
5632
|
-
).then(
|
|
5633
|
-
CadenzaService.createMetaTask(
|
|
5634
|
-
"Apply Database Changes",
|
|
5635
|
-
async (ctx) => {
|
|
5636
|
-
const { ddl } = ctx;
|
|
5637
|
-
if (ddl && ddl.length > 0) {
|
|
5638
|
-
for (const sql of ddl) {
|
|
5639
|
-
try {
|
|
5640
|
-
await this.dbClient.query(sql);
|
|
5641
|
-
} catch (error) {
|
|
5642
|
-
console.error(
|
|
5643
|
-
"Error applying DDL",
|
|
5644
|
-
sql,
|
|
5645
|
-
error
|
|
5646
|
-
);
|
|
5647
|
-
}
|
|
5648
|
-
}
|
|
5649
|
-
}
|
|
5650
|
-
return true;
|
|
5651
|
-
},
|
|
5652
|
-
"Applies generated DDL to the database"
|
|
5653
|
-
).then(
|
|
5654
|
-
CadenzaService.createMetaTask(
|
|
5655
|
-
"Split schema into tables for task creation",
|
|
5656
|
-
this.splitTables.bind(this),
|
|
5657
|
-
"Splits schema into tables for task creation"
|
|
5658
|
-
).then(
|
|
5659
|
-
CadenzaService.createMetaTask(
|
|
5660
|
-
"Generate tasks",
|
|
5661
|
-
(ctx) => {
|
|
5662
|
-
const { table, tableName, options } = ctx;
|
|
5663
|
-
this.createDatabaseTask(
|
|
5664
|
-
"query",
|
|
5665
|
-
tableName,
|
|
5666
|
-
table,
|
|
5667
|
-
this.queryFunction.bind(this),
|
|
5668
|
-
options
|
|
5669
|
-
);
|
|
5670
|
-
this.createDatabaseTask(
|
|
5671
|
-
"insert",
|
|
5672
|
-
tableName,
|
|
5673
|
-
table,
|
|
5674
|
-
this.insertFunction.bind(this),
|
|
5675
|
-
options
|
|
5676
|
-
);
|
|
5677
|
-
this.createDatabaseTask(
|
|
5678
|
-
"update",
|
|
5679
|
-
tableName,
|
|
5680
|
-
table,
|
|
5681
|
-
this.updateFunction.bind(this),
|
|
5682
|
-
options
|
|
5683
|
-
);
|
|
5684
|
-
this.createDatabaseTask(
|
|
5685
|
-
"delete",
|
|
5686
|
-
tableName,
|
|
5687
|
-
table,
|
|
5688
|
-
this.deleteFunction.bind(this),
|
|
5689
|
-
options
|
|
5690
|
-
);
|
|
5691
|
-
return true;
|
|
5692
|
-
},
|
|
5693
|
-
"Generates auto-tasks for database schema"
|
|
5694
|
-
).then(
|
|
5695
|
-
CadenzaService.createUniqueMetaTask(
|
|
5696
|
-
"Join table tasks",
|
|
5697
|
-
() => {
|
|
5698
|
-
return true;
|
|
5699
|
-
}
|
|
5700
|
-
).emits("meta.database.setup_done")
|
|
5701
|
-
)
|
|
5702
|
-
)
|
|
5703
|
-
)
|
|
5704
|
-
)
|
|
5705
|
-
)
|
|
5706
|
-
)
|
|
5707
|
-
)
|
|
5708
|
-
)
|
|
5709
|
-
)
|
|
5710
|
-
)
|
|
5711
|
-
)
|
|
5712
|
-
)
|
|
5713
|
-
)
|
|
5714
|
-
)
|
|
5715
|
-
)
|
|
5716
|
-
],
|
|
5717
|
-
"Initializes the database service with schema parsing and task/signal generation"
|
|
5343
|
+
CadenzaService.createMetaTask(
|
|
5344
|
+
"Route PostgresActor setup requests",
|
|
5345
|
+
(ctx) => {
|
|
5346
|
+
const serviceName = String(ctx.options?.serviceName ?? ctx.serviceName ?? "");
|
|
5347
|
+
if (!serviceName) {
|
|
5348
|
+
return ctx;
|
|
5349
|
+
}
|
|
5350
|
+
const registration = this.registrationsByService.get(serviceName);
|
|
5351
|
+
if (!registration) {
|
|
5352
|
+
return ctx;
|
|
5353
|
+
}
|
|
5354
|
+
CadenzaService.emit(`meta.postgres_actor.setup_requested.${registration.actorToken}`, ctx);
|
|
5355
|
+
return ctx;
|
|
5356
|
+
},
|
|
5357
|
+
"Routes generic database init requests to actor-scoped setup signal.",
|
|
5358
|
+
{ isMeta: true, isSubMeta: true }
|
|
5718
5359
|
).doOn("meta.database_init_requested");
|
|
5719
5360
|
}
|
|
5720
5361
|
static get instance() {
|
|
@@ -5722,704 +5363,1299 @@ var DatabaseController = class _DatabaseController {
|
|
|
5722
5363
|
return this._instance;
|
|
5723
5364
|
}
|
|
5724
5365
|
reset() {
|
|
5725
|
-
this.
|
|
5366
|
+
for (const registration of this.registrationsByService.values()) {
|
|
5367
|
+
const runtimeState = registration.actor.getRuntimeState(registration.actorKey);
|
|
5368
|
+
if (runtimeState?.pool) {
|
|
5369
|
+
runtimeState.pool.end().catch(() => void 0);
|
|
5370
|
+
}
|
|
5371
|
+
}
|
|
5372
|
+
this.registrationsByService.clear();
|
|
5373
|
+
this.adminDbClient.end().catch(() => void 0);
|
|
5726
5374
|
}
|
|
5727
|
-
|
|
5728
|
-
|
|
5729
|
-
|
|
5730
|
-
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
const
|
|
5736
|
-
const
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
|
|
5743
|
-
|
|
5744
|
-
|
|
5745
|
-
|
|
5746
|
-
|
|
5747
|
-
)
|
|
5748
|
-
}, 5e3);
|
|
5749
|
-
client.query = (...args) => {
|
|
5750
|
-
client.lastQuery = args;
|
|
5751
|
-
return query.apply(client, args);
|
|
5375
|
+
createPostgresActor(serviceName, schema, options) {
|
|
5376
|
+
const existing = this.registrationsByService.get(serviceName);
|
|
5377
|
+
if (existing) {
|
|
5378
|
+
return existing;
|
|
5379
|
+
}
|
|
5380
|
+
const actorName = `${serviceName}PostgresActor`;
|
|
5381
|
+
const actorToken = normalizeIntentToken(actorName);
|
|
5382
|
+
const actorKey = String(options.databaseName ?? snakeCase(serviceName));
|
|
5383
|
+
const optionTimeout = typeof options.timeoutMs === "number" ? Number(options.timeoutMs) : Number(options.timeout);
|
|
5384
|
+
const safetyPolicy = {
|
|
5385
|
+
statementTimeoutMs: normalizePositiveInteger(
|
|
5386
|
+
optionTimeout,
|
|
5387
|
+
normalizePositiveInteger(Number(process.env.DATABASE_STATEMENT_TIMEOUT_MS ?? 15e3), 15e3)
|
|
5388
|
+
),
|
|
5389
|
+
retryCount: normalizePositiveInteger(options.retryCount, 3, 0),
|
|
5390
|
+
retryDelayMs: normalizePositiveInteger(Number(process.env.DATABASE_RETRY_DELAY_MS ?? 100), 100),
|
|
5391
|
+
retryDelayMaxMs: normalizePositiveInteger(
|
|
5392
|
+
Number(process.env.DATABASE_RETRY_DELAY_MAX_MS ?? 1e3),
|
|
5393
|
+
1e3
|
|
5394
|
+
),
|
|
5395
|
+
retryDelayFactor: Number(process.env.DATABASE_RETRY_DELAY_FACTOR ?? 2)
|
|
5752
5396
|
};
|
|
5753
|
-
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5397
|
+
const actor = CadenzaService.createActor(
|
|
5398
|
+
{
|
|
5399
|
+
name: actorName,
|
|
5400
|
+
description: "Specialized PostgresActor owning pool runtime state and schema-driven DB task generation.",
|
|
5401
|
+
defaultKey: actorKey,
|
|
5402
|
+
keyResolver: (input) => typeof input.databaseName === "string" ? input.databaseName : void 0,
|
|
5403
|
+
loadPolicy: "eager",
|
|
5404
|
+
writeContract: "overwrite",
|
|
5405
|
+
initState: {
|
|
5406
|
+
actorName,
|
|
5407
|
+
actorToken,
|
|
5408
|
+
serviceName,
|
|
5409
|
+
databaseName: actorKey,
|
|
5410
|
+
status: "idle",
|
|
5411
|
+
schemaVersion: Number(schema.version ?? 1),
|
|
5412
|
+
setupStartedAt: null,
|
|
5413
|
+
setupCompletedAt: null,
|
|
5414
|
+
lastHealthCheckAt: null,
|
|
5415
|
+
lastError: null,
|
|
5416
|
+
tables: Object.keys(schema.tables ?? {}),
|
|
5417
|
+
safetyPolicy
|
|
5418
|
+
}
|
|
5419
|
+
},
|
|
5420
|
+
{ isMeta: Boolean(options.isMeta) }
|
|
5421
|
+
);
|
|
5422
|
+
const registration = {
|
|
5423
|
+
serviceName,
|
|
5424
|
+
databaseName: actorKey,
|
|
5425
|
+
actorName,
|
|
5426
|
+
actorToken,
|
|
5427
|
+
actorKey,
|
|
5428
|
+
actor,
|
|
5429
|
+
schema,
|
|
5430
|
+
options,
|
|
5431
|
+
tasksGenerated: false,
|
|
5432
|
+
intentNames: /* @__PURE__ */ new Set()
|
|
5758
5433
|
};
|
|
5759
|
-
|
|
5434
|
+
this.registrationsByService.set(serviceName, registration);
|
|
5435
|
+
this.registerSetupTask(registration);
|
|
5436
|
+
return registration;
|
|
5760
5437
|
}
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
} else {
|
|
5770
|
-
CadenzaService.log(
|
|
5771
|
-
"Database query errored",
|
|
5772
|
-
{ error: err, context },
|
|
5773
|
-
"warning"
|
|
5438
|
+
registerSetupTask(registration) {
|
|
5439
|
+
const setupSignal = `meta.postgres_actor.setup_requested.${registration.actorToken}`;
|
|
5440
|
+
CadenzaService.createMetaTask(
|
|
5441
|
+
`Setup ${registration.actorName}`,
|
|
5442
|
+
registration.actor.task(
|
|
5443
|
+
async ({ input, state, runtimeState, setState, setRuntimeState, emit }) => {
|
|
5444
|
+
const requestedDatabaseName = String(
|
|
5445
|
+
input.options?.databaseName ?? input.databaseName ?? registration.databaseName
|
|
5774
5446
|
);
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
}
|
|
5778
|
-
}
|
|
5779
|
-
throw new Error(`Timeout waiting for database to be ready`);
|
|
5780
|
-
}
|
|
5781
|
-
/**
|
|
5782
|
-
* Sorts database tables based on their reference dependencies using a topological sort.
|
|
5783
|
-
*
|
|
5784
|
-
* Tables are reordered such that dependent tables appear later in the list
|
|
5785
|
-
* to ensure a dependency hierarchy. If cycles are detected in the dependency graph,
|
|
5786
|
-
* they will be noted but the process will not stop. Unreferenced tables are included at the end.
|
|
5787
|
-
*
|
|
5788
|
-
* @param {Object} ctx - The context object containing the database schema definition and table metadata.
|
|
5789
|
-
* ctx.schema {Object} - The schema definition object.
|
|
5790
|
-
* ctx.schema.tables {Object} - A mapping of table names to table definitions.
|
|
5791
|
-
* Each table definition may contain `fields` (with `references` info)
|
|
5792
|
-
* and `foreignKeys` indicating cross-table relationships.
|
|
5793
|
-
*
|
|
5794
|
-
* @return {Object} - The modified context object with an additional property:
|
|
5795
|
-
* sortedTables {string[]} - An array of table names sorted in dependency order.
|
|
5796
|
-
* hasCycles {boolean} - Indicates if the dependency graph contains cycles.
|
|
5797
|
-
*/
|
|
5798
|
-
sortTablesByReferences(ctx) {
|
|
5799
|
-
const schema = ctx.schema;
|
|
5800
|
-
const graph = /* @__PURE__ */ new Map();
|
|
5801
|
-
const allTables = Object.keys(schema.tables);
|
|
5802
|
-
allTables.forEach((table) => graph.set(table, /* @__PURE__ */ new Set()));
|
|
5803
|
-
for (const [tableName, table] of Object.entries(schema.tables)) {
|
|
5804
|
-
for (const field of Object.values(table.fields)) {
|
|
5805
|
-
if (field.references) {
|
|
5806
|
-
const [refTable] = field.references.split("(");
|
|
5807
|
-
if (refTable !== tableName && allTables.includes(refTable)) {
|
|
5808
|
-
graph.get(refTable)?.add(tableName);
|
|
5447
|
+
if (requestedDatabaseName !== registration.databaseName) {
|
|
5448
|
+
return input;
|
|
5809
5449
|
}
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
|
|
5450
|
+
setState({
|
|
5451
|
+
...state,
|
|
5452
|
+
status: "initializing",
|
|
5453
|
+
setupStartedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5454
|
+
lastError: null
|
|
5455
|
+
});
|
|
5456
|
+
const priorRuntimePool = runtimeState?.pool ?? null;
|
|
5457
|
+
if (priorRuntimePool) {
|
|
5458
|
+
await priorRuntimePool.end().catch(() => void 0);
|
|
5817
5459
|
}
|
|
5818
|
-
|
|
5460
|
+
try {
|
|
5461
|
+
await this.createDatabaseIfMissing(requestedDatabaseName);
|
|
5462
|
+
const pool = this.createTargetPool(
|
|
5463
|
+
requestedDatabaseName,
|
|
5464
|
+
state.safetyPolicy.statementTimeoutMs
|
|
5465
|
+
);
|
|
5466
|
+
await this.checkPoolHealth(pool, state.safetyPolicy);
|
|
5467
|
+
this.validateSchema({
|
|
5468
|
+
schema: registration.schema,
|
|
5469
|
+
options: registration.options
|
|
5470
|
+
});
|
|
5471
|
+
const sortedTables = this.sortTablesByReferences({
|
|
5472
|
+
schema: registration.schema
|
|
5473
|
+
}).sortedTables;
|
|
5474
|
+
const ddlStatements = this.buildSchemaDdlStatements(
|
|
5475
|
+
registration.schema,
|
|
5476
|
+
sortedTables
|
|
5477
|
+
);
|
|
5478
|
+
await this.applyDdlStatements(pool, ddlStatements);
|
|
5479
|
+
if (!registration.tasksGenerated) {
|
|
5480
|
+
this.generateDatabaseTasks(registration);
|
|
5481
|
+
registration.tasksGenerated = true;
|
|
5482
|
+
}
|
|
5483
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
5484
|
+
setRuntimeState({
|
|
5485
|
+
pool,
|
|
5486
|
+
ready: true,
|
|
5487
|
+
pendingQueries: 0,
|
|
5488
|
+
lastHealthCheckAt: Date.now(),
|
|
5489
|
+
lastError: null
|
|
5490
|
+
});
|
|
5491
|
+
setState({
|
|
5492
|
+
...state,
|
|
5493
|
+
status: "ready",
|
|
5494
|
+
setupCompletedAt: nowIso,
|
|
5495
|
+
lastHealthCheckAt: nowIso,
|
|
5496
|
+
lastError: null,
|
|
5497
|
+
tables: Object.keys(registration.schema.tables ?? {})
|
|
5498
|
+
});
|
|
5499
|
+
emit("meta.database.setup_done", {
|
|
5500
|
+
serviceName: registration.serviceName,
|
|
5501
|
+
databaseName: registration.databaseName,
|
|
5502
|
+
actorName: registration.actorName,
|
|
5503
|
+
__success: true
|
|
5504
|
+
});
|
|
5505
|
+
return {
|
|
5506
|
+
...input,
|
|
5507
|
+
__success: true,
|
|
5508
|
+
actorName: registration.actorName,
|
|
5509
|
+
databaseName: registration.databaseName
|
|
5510
|
+
};
|
|
5511
|
+
} catch (error) {
|
|
5512
|
+
const message = errorMessage(error);
|
|
5513
|
+
setRuntimeState({
|
|
5514
|
+
pool: null,
|
|
5515
|
+
ready: false,
|
|
5516
|
+
pendingQueries: 0,
|
|
5517
|
+
lastHealthCheckAt: runtimeState?.lastHealthCheckAt ?? null,
|
|
5518
|
+
lastError: message
|
|
5519
|
+
});
|
|
5520
|
+
setState({
|
|
5521
|
+
...state,
|
|
5522
|
+
status: "error",
|
|
5523
|
+
setupCompletedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5524
|
+
lastError: message
|
|
5525
|
+
});
|
|
5526
|
+
throw error;
|
|
5527
|
+
}
|
|
5528
|
+
},
|
|
5529
|
+
{ mode: "write" }
|
|
5530
|
+
),
|
|
5531
|
+
"Initializes PostgresActor runtime pool, applies schema, and generates CRUD tasks/intents.",
|
|
5532
|
+
{ isMeta: true }
|
|
5533
|
+
).doOn(setupSignal);
|
|
5534
|
+
}
|
|
5535
|
+
createTargetPool(databaseName, statementTimeoutMs) {
|
|
5536
|
+
const connectionString = this.buildDatabaseConnectionString(databaseName);
|
|
5537
|
+
return new Pool({
|
|
5538
|
+
connectionString,
|
|
5539
|
+
statement_timeout: statementTimeoutMs,
|
|
5540
|
+
query_timeout: statementTimeoutMs,
|
|
5541
|
+
ssl: {
|
|
5542
|
+
rejectUnauthorized: false
|
|
5819
5543
|
}
|
|
5544
|
+
});
|
|
5545
|
+
}
|
|
5546
|
+
buildDatabaseConnectionString(databaseName) {
|
|
5547
|
+
const base = process.env.DATABASE_ADDRESS ?? "";
|
|
5548
|
+
if (!base) {
|
|
5549
|
+
throw new Error("DATABASE_ADDRESS environment variable is required");
|
|
5820
5550
|
}
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
if (tempMark.has(table)) {
|
|
5827
|
-
hasCycles = true;
|
|
5828
|
-
return;
|
|
5551
|
+
try {
|
|
5552
|
+
const parsed = new URL(base);
|
|
5553
|
+
parsed.pathname = `/${databaseName}`;
|
|
5554
|
+
if (!parsed.searchParams.has("sslmode")) {
|
|
5555
|
+
parsed.searchParams.set("sslmode", "disable");
|
|
5829
5556
|
}
|
|
5830
|
-
|
|
5831
|
-
|
|
5832
|
-
|
|
5833
|
-
|
|
5557
|
+
return parsed.toString();
|
|
5558
|
+
} catch {
|
|
5559
|
+
const lastSlashIndex = base.lastIndexOf("/");
|
|
5560
|
+
if (lastSlashIndex === -1) {
|
|
5561
|
+
throw new Error("DATABASE_ADDRESS must be a valid postgres connection string");
|
|
5834
5562
|
}
|
|
5835
|
-
|
|
5836
|
-
|
|
5837
|
-
sorted.push(table);
|
|
5563
|
+
const root = base.slice(0, lastSlashIndex + 1);
|
|
5564
|
+
return `${root}${databaseName}?sslmode=disable`;
|
|
5838
5565
|
}
|
|
5839
|
-
|
|
5840
|
-
|
|
5841
|
-
|
|
5842
|
-
|
|
5566
|
+
}
|
|
5567
|
+
async createDatabaseIfMissing(databaseName) {
|
|
5568
|
+
if (!isSqlIdentifier(databaseName)) {
|
|
5569
|
+
throw new Error(
|
|
5570
|
+
`Invalid database name '${databaseName}'. Names must contain only lowercase alphanumerics and underscores and cannot start with a number.`
|
|
5571
|
+
);
|
|
5843
5572
|
}
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5573
|
+
try {
|
|
5574
|
+
await this.adminDbClient.query(`CREATE DATABASE ${databaseName}`);
|
|
5575
|
+
CadenzaService.log(`Database ${databaseName} created.`);
|
|
5576
|
+
} catch (error) {
|
|
5577
|
+
if (error?.code === "42P04") {
|
|
5578
|
+
CadenzaService.log(`Database ${databaseName} already exists.`);
|
|
5579
|
+
return;
|
|
5847
5580
|
}
|
|
5581
|
+
throw new Error(`Failed to create database '${databaseName}': ${errorMessage(error)}`);
|
|
5848
5582
|
}
|
|
5849
|
-
sorted.reverse();
|
|
5850
|
-
return { ...ctx, sortedTables: sorted, hasCycles };
|
|
5851
5583
|
}
|
|
5852
|
-
|
|
5853
|
-
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5584
|
+
async checkPoolHealth(pool, safetyPolicy) {
|
|
5585
|
+
await this.runWithRetries(
|
|
5586
|
+
async () => {
|
|
5587
|
+
await this.withTimeout(
|
|
5588
|
+
() => pool.query("SELECT 1 as health"),
|
|
5589
|
+
safetyPolicy.statementTimeoutMs,
|
|
5590
|
+
"Database health check timed out"
|
|
5591
|
+
);
|
|
5592
|
+
},
|
|
5593
|
+
safetyPolicy,
|
|
5594
|
+
"Health check"
|
|
5595
|
+
);
|
|
5596
|
+
}
|
|
5597
|
+
getPoolOrThrow(registration) {
|
|
5598
|
+
const runtimeState = registration.actor.getRuntimeState(
|
|
5599
|
+
registration.actorKey
|
|
5600
|
+
);
|
|
5601
|
+
if (!runtimeState || !runtimeState.ready || !runtimeState.pool) {
|
|
5602
|
+
throw new Error(
|
|
5603
|
+
`PostgresActor '${registration.actorName}' is not ready. Ensure setup completed before running DB tasks.`
|
|
5604
|
+
);
|
|
5867
5605
|
}
|
|
5606
|
+
return runtimeState.pool;
|
|
5868
5607
|
}
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5608
|
+
async withTimeout(work, timeoutMs, timeoutMessage) {
|
|
5609
|
+
let timeoutHandle = null;
|
|
5610
|
+
try {
|
|
5611
|
+
return await Promise.race([
|
|
5612
|
+
work(),
|
|
5613
|
+
new Promise((_, reject) => {
|
|
5614
|
+
timeoutHandle = setTimeout(() => {
|
|
5615
|
+
reject(new Error(timeoutMessage));
|
|
5616
|
+
}, timeoutMs);
|
|
5617
|
+
})
|
|
5618
|
+
]);
|
|
5619
|
+
} finally {
|
|
5620
|
+
if (timeoutHandle) {
|
|
5621
|
+
clearTimeout(timeoutHandle);
|
|
5880
5622
|
}
|
|
5881
|
-
|
|
5882
|
-
});
|
|
5623
|
+
}
|
|
5883
5624
|
}
|
|
5884
|
-
|
|
5885
|
-
|
|
5886
|
-
|
|
5887
|
-
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
5891
|
-
|
|
5625
|
+
async runWithRetries(work, safetyPolicy, operationLabel) {
|
|
5626
|
+
const attempts = normalizePositiveInteger(safetyPolicy.retryCount, 0, 0) + 1;
|
|
5627
|
+
let delayMs = normalizePositiveInteger(safetyPolicy.retryDelayMs, 100);
|
|
5628
|
+
const maxDelayMs = normalizePositiveInteger(safetyPolicy.retryDelayMaxMs, 1e3);
|
|
5629
|
+
const factor = Number.isFinite(safetyPolicy.retryDelayFactor) ? Math.max(1, safetyPolicy.retryDelayFactor) : 1;
|
|
5630
|
+
let lastError;
|
|
5631
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
5632
|
+
try {
|
|
5633
|
+
return await work();
|
|
5634
|
+
} catch (error) {
|
|
5635
|
+
lastError = error;
|
|
5636
|
+
const transient = isTransientDatabaseError(error);
|
|
5637
|
+
if (!transient || attempt >= attempts) {
|
|
5638
|
+
break;
|
|
5639
|
+
}
|
|
5640
|
+
CadenzaService.log(
|
|
5641
|
+
`${operationLabel} failed with transient error. Retrying...`,
|
|
5642
|
+
{
|
|
5643
|
+
attempt,
|
|
5644
|
+
attempts,
|
|
5645
|
+
delayMs,
|
|
5646
|
+
error: errorMessage(error)
|
|
5647
|
+
},
|
|
5648
|
+
"warning"
|
|
5649
|
+
);
|
|
5650
|
+
await sleep(delayMs);
|
|
5651
|
+
delayMs = Math.min(Math.trunc(delayMs * factor), maxDelayMs);
|
|
5652
|
+
}
|
|
5653
|
+
}
|
|
5654
|
+
throw lastError;
|
|
5655
|
+
}
|
|
5656
|
+
async executeWithTransaction(pool, transaction, callback) {
|
|
5657
|
+
if (!transaction) {
|
|
5658
|
+
return callback(pool);
|
|
5659
|
+
}
|
|
5660
|
+
const client = await pool.connect();
|
|
5661
|
+
try {
|
|
5662
|
+
await client.query("BEGIN");
|
|
5663
|
+
const result = await callback(client);
|
|
5664
|
+
await client.query("COMMIT");
|
|
5665
|
+
return result;
|
|
5666
|
+
} catch (error) {
|
|
5667
|
+
await client.query("ROLLBACK");
|
|
5668
|
+
throw error;
|
|
5669
|
+
} finally {
|
|
5670
|
+
client.release();
|
|
5671
|
+
}
|
|
5672
|
+
}
|
|
5673
|
+
async queryFunction(registration, tableName, context) {
|
|
5892
5674
|
const {
|
|
5893
5675
|
filter = {},
|
|
5894
5676
|
fields = [],
|
|
5895
5677
|
joins = {},
|
|
5896
5678
|
sort = {},
|
|
5897
5679
|
limit,
|
|
5898
|
-
offset
|
|
5680
|
+
offset,
|
|
5681
|
+
queryMode = "rows",
|
|
5682
|
+
aggregates = [],
|
|
5683
|
+
groupBy = []
|
|
5899
5684
|
} = context;
|
|
5900
|
-
|
|
5685
|
+
const pool = this.getPoolOrThrow(registration);
|
|
5686
|
+
const statementTimeoutMs = this.resolveSafetyPolicy(registration).statementTimeoutMs;
|
|
5687
|
+
const resolvedMode = queryMode;
|
|
5688
|
+
const aggregateDefinitions = Array.isArray(aggregates) ? aggregates : [];
|
|
5689
|
+
const groupByFields = Array.isArray(groupBy) ? groupBy : [];
|
|
5901
5690
|
const params = [];
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
|
|
5905
|
-
if (
|
|
5906
|
-
sql
|
|
5691
|
+
const whereClause = Object.keys(filter).length > 0 ? this.buildWhereClause(filter, params) : "";
|
|
5692
|
+
const joinClause = Object.keys(joins).length > 0 ? this.buildJoinClause(joins) : "";
|
|
5693
|
+
let sql;
|
|
5694
|
+
if (resolvedMode === "count") {
|
|
5695
|
+
sql = `SELECT COUNT(*)::bigint AS count FROM ${tableName} ${joinClause} ${whereClause}`;
|
|
5696
|
+
} else if (resolvedMode === "exists") {
|
|
5697
|
+
sql = `SELECT EXISTS(SELECT 1 FROM ${tableName} ${joinClause} ${whereClause}) AS exists`;
|
|
5698
|
+
} else if (resolvedMode === "aggregate") {
|
|
5699
|
+
if (aggregateDefinitions.length === 0) {
|
|
5700
|
+
throw new Error("Aggregate queries require at least one aggregate definition");
|
|
5701
|
+
}
|
|
5702
|
+
const aggregateExpressions = aggregateDefinitions.map(
|
|
5703
|
+
(aggregate, index) => {
|
|
5704
|
+
const fn = String(aggregate.fn ?? "").toLowerCase();
|
|
5705
|
+
if (!isSupportedAggregateFunction(fn)) {
|
|
5706
|
+
throw new Error(`Unsupported aggregate function '${aggregate.fn}'`);
|
|
5707
|
+
}
|
|
5708
|
+
const hasField = typeof aggregate.field === "string" && aggregate.field.trim().length > 0;
|
|
5709
|
+
if (fn !== "count" && !hasField) {
|
|
5710
|
+
throw new Error(`Aggregate '${fn}' requires a field`);
|
|
5711
|
+
}
|
|
5712
|
+
const fieldExpression = hasField ? snakeCase(String(aggregate.field)) : "*";
|
|
5713
|
+
const distinctPrefix = aggregate.distinct ? "DISTINCT " : "";
|
|
5714
|
+
const expression = fn === "count" && !hasField ? "COUNT(*)" : `${fn.toUpperCase()}(${distinctPrefix}${fieldExpression})`;
|
|
5715
|
+
const alias = buildAggregateAlias(aggregate, index);
|
|
5716
|
+
return `${expression} AS ${alias}`;
|
|
5717
|
+
}
|
|
5718
|
+
);
|
|
5719
|
+
const groupByExpressions = groupByFields.map((field) => snakeCase(field));
|
|
5720
|
+
const selectExpressions = [...groupByExpressions, ...aggregateExpressions];
|
|
5721
|
+
sql = `SELECT ${selectExpressions.join(", ")} FROM ${tableName} ${joinClause} ${whereClause}`;
|
|
5722
|
+
if (groupByExpressions.length > 0) {
|
|
5723
|
+
sql += ` GROUP BY ${groupByExpressions.join(", ")}`;
|
|
5724
|
+
}
|
|
5725
|
+
} else {
|
|
5726
|
+
sql = `SELECT ${fields.length ? fields.map(snakeCase).join(", ") : "*"} FROM ${tableName} ${joinClause} ${whereClause}`;
|
|
5907
5727
|
}
|
|
5908
|
-
if (Object.keys(sort).length > 0) {
|
|
5909
|
-
sql += " ORDER BY " + Object.entries(sort).map(([field, direction]) => `${field} ${direction}`).join(", ");
|
|
5728
|
+
if (Object.keys(sort).length > 0 && resolvedMode !== "count" && resolvedMode !== "exists") {
|
|
5729
|
+
sql += " ORDER BY " + Object.entries(sort).map(([field, direction]) => `${snakeCase(field)} ${direction}`).join(", ");
|
|
5910
5730
|
}
|
|
5911
|
-
if (
|
|
5731
|
+
if (resolvedMode === "one") {
|
|
5732
|
+
sql += ` LIMIT $${params.length + 1}`;
|
|
5733
|
+
params.push(1);
|
|
5734
|
+
} else if (resolvedMode !== "count" && resolvedMode !== "exists" && limit !== void 0) {
|
|
5912
5735
|
sql += ` LIMIT $${params.length + 1}`;
|
|
5913
5736
|
params.push(limit);
|
|
5914
5737
|
}
|
|
5915
|
-
if (offset !== void 0) {
|
|
5738
|
+
if (resolvedMode !== "count" && resolvedMode !== "exists" && offset !== void 0) {
|
|
5916
5739
|
sql += ` OFFSET $${params.length + 1}`;
|
|
5917
5740
|
params.push(offset);
|
|
5918
5741
|
}
|
|
5919
5742
|
try {
|
|
5920
|
-
const result = await this.
|
|
5743
|
+
const result = await this.withTimeout(
|
|
5744
|
+
() => pool.query(sql, params),
|
|
5745
|
+
statementTimeoutMs,
|
|
5746
|
+
`Query timeout on table ${tableName}`
|
|
5747
|
+
);
|
|
5921
5748
|
const rows = this.toCamelCase(result.rows);
|
|
5749
|
+
const rowCount = Number(result.rowCount ?? 0);
|
|
5750
|
+
if (resolvedMode === "count") {
|
|
5751
|
+
return {
|
|
5752
|
+
count: Number(rows[0]?.count ?? 0),
|
|
5753
|
+
rowCount: Number(rows[0]?.count ?? 0),
|
|
5754
|
+
__success: true
|
|
5755
|
+
};
|
|
5756
|
+
}
|
|
5757
|
+
if (resolvedMode === "exists") {
|
|
5758
|
+
const exists = Boolean(rows[0]?.exists);
|
|
5759
|
+
return {
|
|
5760
|
+
exists,
|
|
5761
|
+
rowCount: exists ? 1 : 0,
|
|
5762
|
+
__success: true
|
|
5763
|
+
};
|
|
5764
|
+
}
|
|
5765
|
+
if (resolvedMode === "one") {
|
|
5766
|
+
return {
|
|
5767
|
+
[`${camelCase(tableName)}`]: rows[0] ?? null,
|
|
5768
|
+
rowCount,
|
|
5769
|
+
__success: true
|
|
5770
|
+
};
|
|
5771
|
+
}
|
|
5772
|
+
if (resolvedMode === "aggregate") {
|
|
5773
|
+
return {
|
|
5774
|
+
aggregates: rows,
|
|
5775
|
+
rowCount,
|
|
5776
|
+
__success: true
|
|
5777
|
+
};
|
|
5778
|
+
}
|
|
5922
5779
|
return {
|
|
5923
5780
|
[`${camelCase(tableName)}s`]: rows,
|
|
5924
|
-
rowCount
|
|
5925
|
-
__success: true
|
|
5926
|
-
...context
|
|
5781
|
+
rowCount,
|
|
5782
|
+
__success: true
|
|
5927
5783
|
};
|
|
5928
5784
|
} catch (error) {
|
|
5929
5785
|
return {
|
|
5930
|
-
|
|
5786
|
+
rowCount: 0,
|
|
5931
5787
|
errored: true,
|
|
5932
|
-
__error: `Query failed: ${error
|
|
5788
|
+
__error: `Query failed: ${errorMessage(error)}`,
|
|
5933
5789
|
__success: false
|
|
5934
5790
|
};
|
|
5935
5791
|
}
|
|
5936
5792
|
}
|
|
5937
|
-
|
|
5938
|
-
* Inserts data into the specified database table with optional conflict handling.
|
|
5939
|
-
*
|
|
5940
|
-
* @param {string} tableName - The name of the target database table.
|
|
5941
|
-
* @param {DbOperationPayload} context - The context containing data to insert, transaction settings, field mappings, conflict resolution options, and other configurations.
|
|
5942
|
-
* - `data` (object | array): The data to be inserted into the database.
|
|
5943
|
-
* - `transaction` (boolean): Specifies whether the operation should use a transaction. Defaults to true.
|
|
5944
|
-
* - `fields` (array): The fields to return in the result after insertion.
|
|
5945
|
-
* - `onConflict` (object): Options for handling conflicts on insert.
|
|
5946
|
-
* - `target` (array): Columns to determine conflicts.
|
|
5947
|
-
* - `action` (object): Specifies the action to take on conflict, such as updating specified fields.
|
|
5948
|
-
* - `awaitExists` (object): Specifies foreign key references to wait for to ensure existence before insertion.
|
|
5949
|
-
*
|
|
5950
|
-
* @return {Promise<any>} A promise resolving to the result of the database insert operation, including the inserted rows, the row count, and metadata indicating success or error.
|
|
5951
|
-
*/
|
|
5952
|
-
async insertFunction(tableName, context) {
|
|
5793
|
+
async insertFunction(registration, tableName, context) {
|
|
5953
5794
|
const { data, transaction = true, fields = [], onConflict } = context;
|
|
5954
5795
|
if (!data || Array.isArray(data) && data.length === 0) {
|
|
5955
|
-
return {
|
|
5796
|
+
return {
|
|
5797
|
+
rowCount: 0,
|
|
5798
|
+
errored: true,
|
|
5799
|
+
__error: "No data provided for insert",
|
|
5800
|
+
__success: false
|
|
5801
|
+
};
|
|
5956
5802
|
}
|
|
5957
|
-
|
|
5958
|
-
const
|
|
5803
|
+
const pool = this.getPoolOrThrow(registration);
|
|
5804
|
+
const safetyPolicy = this.resolveSafetyPolicy(registration);
|
|
5959
5805
|
try {
|
|
5960
|
-
|
|
5961
|
-
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
}
|
|
5971
|
-
if (value.__effect === "decrement") {
|
|
5972
|
-
return `${Object.keys(row)[i]} - 1`;
|
|
5973
|
-
}
|
|
5974
|
-
if (value.__effect === "set") {
|
|
5975
|
-
return `${Object.keys(row)[i]} = ${value.__value}`;
|
|
5976
|
-
}
|
|
5806
|
+
const resultContext = await this.runWithRetries(
|
|
5807
|
+
async () => this.executeWithTransaction(pool, Boolean(transaction), async (client) => {
|
|
5808
|
+
const resolvedData = await this.resolveNestedData(
|
|
5809
|
+
registration,
|
|
5810
|
+
data,
|
|
5811
|
+
tableName
|
|
5812
|
+
);
|
|
5813
|
+
const rows = Array.isArray(resolvedData) ? resolvedData : [resolvedData];
|
|
5814
|
+
if (rows.length === 0) {
|
|
5815
|
+
throw new Error("No rows available for insert after resolving data");
|
|
5977
5816
|
}
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5817
|
+
const keys = Object.keys(rows[0]);
|
|
5818
|
+
const sqlPrefix = `INSERT INTO ${tableName} (${keys.map((key) => snakeCase(key)).join(", ")}) VALUES `;
|
|
5819
|
+
const params = [];
|
|
5820
|
+
const placeholders = rows.map((row) => {
|
|
5821
|
+
const tuple = keys.map((key) => {
|
|
5822
|
+
params.push(row[key]);
|
|
5823
|
+
return `$${params.length}`;
|
|
5824
|
+
}).join(", ");
|
|
5825
|
+
return `(${tuple})`;
|
|
5826
|
+
}).join(", ");
|
|
5827
|
+
let onConflictSql = "";
|
|
5828
|
+
if (onConflict) {
|
|
5829
|
+
onConflictSql = this.buildOnConflictClause(onConflict, params);
|
|
5989
5830
|
}
|
|
5990
|
-
const
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
(v) => typeof v !== "string" || !v.startsWith("excluded.")
|
|
5996
|
-
)
|
|
5831
|
+
const sql = `${sqlPrefix}${placeholders}${onConflictSql} RETURNING ${fields.length ? fields.map(snakeCase).join(", ") : "*"}`;
|
|
5832
|
+
const result = await this.withTimeout(
|
|
5833
|
+
() => client.query(sql, params),
|
|
5834
|
+
safetyPolicy.statementTimeoutMs,
|
|
5835
|
+
`Insert timeout on table ${tableName}`
|
|
5997
5836
|
);
|
|
5998
|
-
|
|
5999
|
-
|
|
6000
|
-
|
|
6001
|
-
|
|
6002
|
-
|
|
6003
|
-
|
|
6004
|
-
|
|
6005
|
-
|
|
6006
|
-
|
|
5837
|
+
const resultRows = this.toCamelCase(result.rows);
|
|
5838
|
+
return {
|
|
5839
|
+
[`${camelCase(tableName)}${rows.length > 1 ? "s" : ""}`]: rows.length > 1 ? resultRows : resultRows[0] ?? null,
|
|
5840
|
+
rowCount: result.rowCount,
|
|
5841
|
+
__success: true
|
|
5842
|
+
};
|
|
5843
|
+
}),
|
|
5844
|
+
safetyPolicy,
|
|
5845
|
+
`Insert ${tableName}`
|
|
6007
5846
|
);
|
|
6008
|
-
|
|
6009
|
-
const resultRows = this.toCamelCase(result.rows);
|
|
6010
|
-
resultContext = {
|
|
6011
|
-
[`${camelCase(tableName)}${isBatch ? "s" : ""}`]: isBatch ? resultRows : resultRows[0],
|
|
6012
|
-
rowCount: result.rowCount,
|
|
6013
|
-
__success: true
|
|
6014
|
-
};
|
|
5847
|
+
return resultContext;
|
|
6015
5848
|
} catch (error) {
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
} else {
|
|
6023
|
-
resultContext = {
|
|
6024
|
-
...context,
|
|
6025
|
-
errored: true,
|
|
6026
|
-
__error: `Insert failed: ${error.message}`,
|
|
6027
|
-
__success: false
|
|
6028
|
-
};
|
|
6029
|
-
}
|
|
6030
|
-
} finally {
|
|
6031
|
-
if (transaction && client) {
|
|
6032
|
-
client.release();
|
|
6033
|
-
}
|
|
5849
|
+
return {
|
|
5850
|
+
rowCount: 0,
|
|
5851
|
+
errored: true,
|
|
5852
|
+
__error: `Insert failed: ${errorMessage(error)}`,
|
|
5853
|
+
__success: false
|
|
5854
|
+
};
|
|
6034
5855
|
}
|
|
6035
|
-
return resultContext;
|
|
6036
5856
|
}
|
|
6037
|
-
|
|
6038
|
-
* Updates a database table with the provided data and filter conditions.
|
|
6039
|
-
*
|
|
6040
|
-
* @param {string} tableName - The name of the database table to update.
|
|
6041
|
-
* @param {DbOperationPayload} context - The payload for the update operation, which includes:
|
|
6042
|
-
* - data: The data to update in the table.
|
|
6043
|
-
* - filter: The conditions to identify the rows to update (default is an empty object).
|
|
6044
|
-
* - transaction: Whether the operation should run within a database transaction (default is true).
|
|
6045
|
-
* @return {Promise<any>} Returns a Promise resolving to an object that includes:
|
|
6046
|
-
* - The updated data if the update is successful.
|
|
6047
|
-
* - In case of error:
|
|
6048
|
-
* - Error details.
|
|
6049
|
-
* - The SQL query and parameters if applicable.
|
|
6050
|
-
* - A flag indicating if the update succeeded or failed.
|
|
6051
|
-
*/
|
|
6052
|
-
async updateFunction(tableName, context) {
|
|
5857
|
+
async updateFunction(registration, tableName, context) {
|
|
6053
5858
|
const { data, filter = {}, transaction = true } = context;
|
|
6054
5859
|
if (!data || Object.keys(data).length === 0) {
|
|
6055
5860
|
return {
|
|
5861
|
+
rowCount: 0,
|
|
6056
5862
|
errored: true,
|
|
6057
|
-
__error: `No data provided for update of ${tableName}
|
|
5863
|
+
__error: `No data provided for update of ${tableName}`,
|
|
5864
|
+
__success: false
|
|
6058
5865
|
};
|
|
6059
5866
|
}
|
|
6060
|
-
|
|
6061
|
-
const
|
|
5867
|
+
const pool = this.getPoolOrThrow(registration);
|
|
5868
|
+
const safetyPolicy = this.resolveSafetyPolicy(registration);
|
|
6062
5869
|
try {
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
|
|
6099
|
-
|
|
6100
|
-
|
|
6101
|
-
|
|
6102
|
-
|
|
6103
|
-
|
|
5870
|
+
return await this.runWithRetries(
|
|
5871
|
+
async () => this.executeWithTransaction(pool, Boolean(transaction), async (client) => {
|
|
5872
|
+
const resolvedData = await this.resolveNestedData(
|
|
5873
|
+
registration,
|
|
5874
|
+
data,
|
|
5875
|
+
tableName
|
|
5876
|
+
);
|
|
5877
|
+
const params = Object.values(resolvedData);
|
|
5878
|
+
let offset = 0;
|
|
5879
|
+
const setClause = Object.keys(resolvedData).map((key, index) => {
|
|
5880
|
+
const value = resolvedData[key];
|
|
5881
|
+
const offsetIndex = index - offset;
|
|
5882
|
+
if (value?.__effect === "increment") {
|
|
5883
|
+
params.splice(offsetIndex, 1);
|
|
5884
|
+
offset += 1;
|
|
5885
|
+
return `${snakeCase(key)} = ${snakeCase(key)} + 1`;
|
|
5886
|
+
}
|
|
5887
|
+
if (value?.__effect === "decrement") {
|
|
5888
|
+
params.splice(offsetIndex, 1);
|
|
5889
|
+
offset += 1;
|
|
5890
|
+
return `${snakeCase(key)} = ${snakeCase(key)} - 1`;
|
|
5891
|
+
}
|
|
5892
|
+
if (value?.__effect === "set") {
|
|
5893
|
+
params.splice(offsetIndex, 1);
|
|
5894
|
+
offset += 1;
|
|
5895
|
+
return `${snakeCase(key)} = ${value.__value}`;
|
|
5896
|
+
}
|
|
5897
|
+
return `${snakeCase(key)} = $${offsetIndex + 1}`;
|
|
5898
|
+
}).join(", ");
|
|
5899
|
+
const whereClause = this.buildWhereClause(filter, params);
|
|
5900
|
+
const sql = `UPDATE ${tableName} SET ${setClause} ${whereClause} RETURNING *`;
|
|
5901
|
+
const result = await this.withTimeout(
|
|
5902
|
+
() => client.query(sql, params),
|
|
5903
|
+
safetyPolicy.statementTimeoutMs,
|
|
5904
|
+
`Update timeout on table ${tableName}`
|
|
5905
|
+
);
|
|
5906
|
+
const rows = this.toCamelCase(result.rows);
|
|
5907
|
+
const rowCount = Number(result.rowCount ?? 0);
|
|
5908
|
+
return {
|
|
5909
|
+
[`${camelCase(tableName)}`]: rows[0] ?? null,
|
|
5910
|
+
rowCount,
|
|
5911
|
+
__success: rowCount > 0
|
|
5912
|
+
};
|
|
5913
|
+
}),
|
|
5914
|
+
safetyPolicy,
|
|
5915
|
+
`Update ${tableName}`
|
|
5916
|
+
);
|
|
6104
5917
|
} catch (error) {
|
|
6105
|
-
|
|
6106
|
-
|
|
6107
|
-
...context,
|
|
5918
|
+
return {
|
|
5919
|
+
rowCount: 0,
|
|
6108
5920
|
errored: true,
|
|
6109
|
-
__error: `Update failed: ${error
|
|
5921
|
+
__error: `Update failed: ${errorMessage(error)}`,
|
|
6110
5922
|
__success: false
|
|
6111
5923
|
};
|
|
6112
|
-
} finally {
|
|
6113
|
-
if (transaction && client) {
|
|
6114
|
-
client.release();
|
|
6115
|
-
}
|
|
6116
5924
|
}
|
|
6117
|
-
return resultContext;
|
|
6118
5925
|
}
|
|
6119
|
-
|
|
6120
|
-
* Deletes a record from the specified database table based on the given filter criteria.
|
|
6121
|
-
*
|
|
6122
|
-
* @param {string} tableName - The name of the database table from which records should be deleted.
|
|
6123
|
-
* @param {DbOperationPayload} context - The context for the operation, including filter conditions and transaction settings.
|
|
6124
|
-
* @param {Object} context.filter - The filter criteria to identify the records to delete.
|
|
6125
|
-
* @param {boolean} [context.transaction=true] - Indicates if the operation should be executed within a transaction.
|
|
6126
|
-
* @return {Promise<any>} A promise that resolves to an object containing information about the deleted record
|
|
6127
|
-
* or an error object if the delete operation fails.
|
|
6128
|
-
*/
|
|
6129
|
-
async deleteFunction(tableName, context) {
|
|
5926
|
+
async deleteFunction(registration, tableName, context) {
|
|
6130
5927
|
const { filter = {}, transaction = true } = context;
|
|
6131
5928
|
if (Object.keys(filter).length === 0) {
|
|
6132
|
-
return {
|
|
5929
|
+
return {
|
|
5930
|
+
rowCount: 0,
|
|
5931
|
+
errored: true,
|
|
5932
|
+
__error: "No filter provided for delete",
|
|
5933
|
+
__success: false
|
|
5934
|
+
};
|
|
6133
5935
|
}
|
|
6134
|
-
|
|
6135
|
-
const
|
|
5936
|
+
const pool = this.getPoolOrThrow(registration);
|
|
5937
|
+
const safetyPolicy = this.resolveSafetyPolicy(registration);
|
|
6136
5938
|
try {
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6145
|
-
|
|
6146
|
-
|
|
6147
|
-
|
|
5939
|
+
return await this.runWithRetries(
|
|
5940
|
+
async () => this.executeWithTransaction(pool, Boolean(transaction), async (client) => {
|
|
5941
|
+
const params = [];
|
|
5942
|
+
const whereClause = this.buildWhereClause(filter, params);
|
|
5943
|
+
const sql = `DELETE FROM ${tableName} ${whereClause} RETURNING *`;
|
|
5944
|
+
const result = await this.withTimeout(
|
|
5945
|
+
() => client.query(sql, params),
|
|
5946
|
+
safetyPolicy.statementTimeoutMs,
|
|
5947
|
+
`Delete timeout on table ${tableName}`
|
|
5948
|
+
);
|
|
5949
|
+
const rows = this.toCamelCase(result.rows);
|
|
5950
|
+
return {
|
|
5951
|
+
[`${camelCase(tableName)}`]: rows[0] ?? null,
|
|
5952
|
+
rowCount: result.rowCount,
|
|
5953
|
+
__success: true
|
|
5954
|
+
};
|
|
5955
|
+
}),
|
|
5956
|
+
safetyPolicy,
|
|
5957
|
+
`Delete ${tableName}`
|
|
5958
|
+
);
|
|
6148
5959
|
} catch (error) {
|
|
6149
|
-
|
|
6150
|
-
|
|
5960
|
+
return {
|
|
5961
|
+
rowCount: 0,
|
|
6151
5962
|
errored: true,
|
|
6152
|
-
__error: `Delete failed: ${error
|
|
6153
|
-
__errors: { delete: error.message },
|
|
5963
|
+
__error: `Delete failed: ${errorMessage(error)}`,
|
|
6154
5964
|
__success: false
|
|
6155
5965
|
};
|
|
6156
|
-
}
|
|
6157
|
-
|
|
6158
|
-
|
|
5966
|
+
}
|
|
5967
|
+
}
|
|
5968
|
+
resolveSafetyPolicy(registration) {
|
|
5969
|
+
const durableState = registration.actor.getState(
|
|
5970
|
+
registration.actorKey
|
|
5971
|
+
);
|
|
5972
|
+
return {
|
|
5973
|
+
statementTimeoutMs: normalizePositiveInteger(
|
|
5974
|
+
durableState.safetyPolicy?.statementTimeoutMs,
|
|
5975
|
+
15e3
|
|
5976
|
+
),
|
|
5977
|
+
retryCount: normalizePositiveInteger(durableState.safetyPolicy?.retryCount, 3, 0),
|
|
5978
|
+
retryDelayMs: normalizePositiveInteger(durableState.safetyPolicy?.retryDelayMs, 100),
|
|
5979
|
+
retryDelayMaxMs: normalizePositiveInteger(
|
|
5980
|
+
durableState.safetyPolicy?.retryDelayMaxMs,
|
|
5981
|
+
1e3
|
|
5982
|
+
),
|
|
5983
|
+
retryDelayFactor: Number.isFinite(durableState.safetyPolicy?.retryDelayFactor) ? Math.max(1, Number(durableState.safetyPolicy?.retryDelayFactor)) : 1
|
|
5984
|
+
};
|
|
5985
|
+
}
|
|
5986
|
+
buildOnConflictClause(onConflict, params) {
|
|
5987
|
+
const { target, action } = onConflict;
|
|
5988
|
+
let sql = ` ON CONFLICT (${target.map(snakeCase).join(", ")})`;
|
|
5989
|
+
if (action.do === "update") {
|
|
5990
|
+
if (!action.set || Object.keys(action.set).length === 0) {
|
|
5991
|
+
throw new Error("Update action requires 'set' fields");
|
|
5992
|
+
}
|
|
5993
|
+
const assignments = Object.entries(action.set).map(([field, value]) => {
|
|
5994
|
+
if (typeof value === "string" && value === "excluded") {
|
|
5995
|
+
return `${snakeCase(field)} = excluded.${snakeCase(field)}`;
|
|
5996
|
+
}
|
|
5997
|
+
params.push(value);
|
|
5998
|
+
return `${snakeCase(field)} = $${params.length}`;
|
|
5999
|
+
});
|
|
6000
|
+
sql += ` DO UPDATE SET ${assignments.join(", ")}`;
|
|
6001
|
+
if (action.where) {
|
|
6002
|
+
sql += ` WHERE ${action.where}`;
|
|
6159
6003
|
}
|
|
6004
|
+
return sql;
|
|
6160
6005
|
}
|
|
6161
|
-
|
|
6006
|
+
sql += " DO NOTHING";
|
|
6007
|
+
return sql;
|
|
6162
6008
|
}
|
|
6163
6009
|
/**
|
|
6164
|
-
*
|
|
6165
|
-
* Builds parameterized queries to prevent SQL injection, appending parameters
|
|
6166
|
-
* to the provided params array and utilizing placeholders.
|
|
6167
|
-
*
|
|
6168
|
-
* @param {Object} filter - An object representing the filtering conditions with
|
|
6169
|
-
* keys as column names and values as their corresponding
|
|
6170
|
-
* desired values. Values can also be arrays for `IN` queries.
|
|
6171
|
-
* @param {any[]} params - An array for storing parameterized values, which will be
|
|
6172
|
-
* populated with the filter values for the constructed SQL clause.
|
|
6173
|
-
* @return {string} The constructed SQL WHERE clause as a string. If no conditions
|
|
6174
|
-
* are provided, an empty string is returned.
|
|
6010
|
+
* Validates database schema structure and content.
|
|
6175
6011
|
*/
|
|
6012
|
+
validateSchema(ctx) {
|
|
6013
|
+
const schema = ctx.schema;
|
|
6014
|
+
if (!schema?.tables || typeof schema.tables !== "object") {
|
|
6015
|
+
throw new Error("Invalid schema: missing or invalid tables");
|
|
6016
|
+
}
|
|
6017
|
+
for (const [tableName, table] of Object.entries(schema.tables)) {
|
|
6018
|
+
if (!isSqlIdentifier(tableName)) {
|
|
6019
|
+
throw new Error(
|
|
6020
|
+
`Invalid table name ${tableName}. Table names must use lowercase snake_case identifiers.`
|
|
6021
|
+
);
|
|
6022
|
+
}
|
|
6023
|
+
if (!table.fields || typeof table.fields !== "object") {
|
|
6024
|
+
throw new Error(`Invalid table ${tableName}: missing fields`);
|
|
6025
|
+
}
|
|
6026
|
+
for (const [fieldName, field] of Object.entries(table.fields)) {
|
|
6027
|
+
if (!isSqlIdentifier(fieldName)) {
|
|
6028
|
+
throw new Error(
|
|
6029
|
+
`Invalid field name ${fieldName} for ${tableName}. Field names must use lowercase snake_case identifiers.`
|
|
6030
|
+
);
|
|
6031
|
+
}
|
|
6032
|
+
if (!SCHEMA_TYPES.includes(field.type)) {
|
|
6033
|
+
throw new Error(`Invalid type ${field.type} for ${tableName}.${fieldName}`);
|
|
6034
|
+
}
|
|
6035
|
+
if (field.references && !field.references.match(/^[\w]+\([\w]+\)$/)) {
|
|
6036
|
+
throw new Error(
|
|
6037
|
+
`Invalid reference ${field.references} for ${tableName}.${fieldName}`
|
|
6038
|
+
);
|
|
6039
|
+
}
|
|
6040
|
+
}
|
|
6041
|
+
for (const operation of ["query", "insert", "update", "delete"]) {
|
|
6042
|
+
const customIntents = table.customIntents?.[operation] ?? [];
|
|
6043
|
+
if (!Array.isArray(customIntents)) {
|
|
6044
|
+
throw new Error(
|
|
6045
|
+
`Invalid customIntents.${operation} for table ${tableName}: expected array`
|
|
6046
|
+
);
|
|
6047
|
+
}
|
|
6048
|
+
for (const customIntent of customIntents) {
|
|
6049
|
+
const parsed = readCustomIntentConfig(
|
|
6050
|
+
customIntent
|
|
6051
|
+
);
|
|
6052
|
+
validateIntentName(String(parsed.intent ?? ""));
|
|
6053
|
+
}
|
|
6054
|
+
}
|
|
6055
|
+
}
|
|
6056
|
+
return true;
|
|
6057
|
+
}
|
|
6058
|
+
sortTablesByReferences(ctx) {
|
|
6059
|
+
const schema = ctx.schema;
|
|
6060
|
+
const graph = /* @__PURE__ */ new Map();
|
|
6061
|
+
const allTables = Object.keys(schema.tables);
|
|
6062
|
+
allTables.forEach((table) => graph.set(table, /* @__PURE__ */ new Set()));
|
|
6063
|
+
for (const [tableName, table] of Object.entries(schema.tables)) {
|
|
6064
|
+
for (const field of Object.values(table.fields)) {
|
|
6065
|
+
if (field.references) {
|
|
6066
|
+
const [refTable] = field.references.split("(");
|
|
6067
|
+
if (refTable !== tableName && allTables.includes(refTable)) {
|
|
6068
|
+
graph.get(refTable)?.add(tableName);
|
|
6069
|
+
}
|
|
6070
|
+
}
|
|
6071
|
+
}
|
|
6072
|
+
if (table.foreignKeys) {
|
|
6073
|
+
for (const foreignKey of table.foreignKeys) {
|
|
6074
|
+
const refTable = foreignKey.tableName;
|
|
6075
|
+
if (refTable !== tableName && allTables.includes(refTable)) {
|
|
6076
|
+
graph.get(refTable)?.add(tableName);
|
|
6077
|
+
}
|
|
6078
|
+
}
|
|
6079
|
+
}
|
|
6080
|
+
}
|
|
6081
|
+
const visited = /* @__PURE__ */ new Set();
|
|
6082
|
+
const tempMark = /* @__PURE__ */ new Set();
|
|
6083
|
+
const sorted = [];
|
|
6084
|
+
let hasCycles = false;
|
|
6085
|
+
const visit = (table) => {
|
|
6086
|
+
if (tempMark.has(table)) {
|
|
6087
|
+
hasCycles = true;
|
|
6088
|
+
return;
|
|
6089
|
+
}
|
|
6090
|
+
if (visited.has(table)) return;
|
|
6091
|
+
tempMark.add(table);
|
|
6092
|
+
for (const dependent of graph.get(table) || []) {
|
|
6093
|
+
visit(dependent);
|
|
6094
|
+
}
|
|
6095
|
+
tempMark.delete(table);
|
|
6096
|
+
visited.add(table);
|
|
6097
|
+
sorted.push(table);
|
|
6098
|
+
};
|
|
6099
|
+
for (const table of allTables) {
|
|
6100
|
+
if (!visited.has(table)) {
|
|
6101
|
+
visit(table);
|
|
6102
|
+
}
|
|
6103
|
+
}
|
|
6104
|
+
for (const table of allTables) {
|
|
6105
|
+
if (!visited.has(table)) {
|
|
6106
|
+
sorted.push(table);
|
|
6107
|
+
}
|
|
6108
|
+
}
|
|
6109
|
+
sorted.reverse();
|
|
6110
|
+
return { ...ctx, sortedTables: sorted, hasCycles };
|
|
6111
|
+
}
|
|
6112
|
+
buildSchemaDdlStatements(schema, sortedTables) {
|
|
6113
|
+
const ddl = [];
|
|
6114
|
+
for (const tableName of sortedTables) {
|
|
6115
|
+
const table = schema.tables[tableName];
|
|
6116
|
+
const fieldDefs = Object.entries(table.fields).map(([fieldName, field]) => this.fieldDefinitionToSql(fieldName, field)).join(", ");
|
|
6117
|
+
ddl.push(`CREATE TABLE IF NOT EXISTS ${tableName} (${fieldDefs});`);
|
|
6118
|
+
for (const indexFields of table.indexes ?? []) {
|
|
6119
|
+
ddl.push(
|
|
6120
|
+
`CREATE INDEX IF NOT EXISTS idx_${tableName}_${indexFields.join("_")} ON ${tableName} (${indexFields.map(snakeCase).join(", ")});`
|
|
6121
|
+
);
|
|
6122
|
+
}
|
|
6123
|
+
if (table.primaryKey) {
|
|
6124
|
+
ddl.push(
|
|
6125
|
+
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS pk_${tableName}_${table.primaryKey.join("_")};`,
|
|
6126
|
+
`ALTER TABLE ${tableName} ADD CONSTRAINT pk_${tableName}_${table.primaryKey.join("_")} PRIMARY KEY (${table.primaryKey.map(snakeCase).join(", ")});`
|
|
6127
|
+
);
|
|
6128
|
+
}
|
|
6129
|
+
for (const uniqueFields of table.uniqueConstraints ?? []) {
|
|
6130
|
+
ddl.push(
|
|
6131
|
+
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS uq_${tableName}_${uniqueFields.join("_")};`,
|
|
6132
|
+
`ALTER TABLE ${tableName} ADD CONSTRAINT uq_${tableName}_${uniqueFields.join("_")} UNIQUE (${uniqueFields.map(snakeCase).join(", ")});`
|
|
6133
|
+
);
|
|
6134
|
+
}
|
|
6135
|
+
for (const foreignKey of table.foreignKeys ?? []) {
|
|
6136
|
+
const fkName = `fk_${tableName}_${foreignKey.fields.join("_")}`;
|
|
6137
|
+
ddl.push(
|
|
6138
|
+
`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS ${fkName};`,
|
|
6139
|
+
`ALTER TABLE ${tableName} ADD CONSTRAINT ${fkName} FOREIGN KEY (${foreignKey.fields.map(snakeCase).join(", ")}) REFERENCES ${foreignKey.tableName} (${foreignKey.referenceFields.map(snakeCase).join(", ")});`
|
|
6140
|
+
);
|
|
6141
|
+
}
|
|
6142
|
+
for (const [triggerName, trigger] of Object.entries(table.triggers ?? {})) {
|
|
6143
|
+
ddl.push(
|
|
6144
|
+
`CREATE OR REPLACE TRIGGER ${triggerName} ${trigger.when} ${trigger.event} ON ${tableName} FOR EACH STATEMENT EXECUTE FUNCTION ${trigger.function};`
|
|
6145
|
+
);
|
|
6146
|
+
}
|
|
6147
|
+
if (table.initialData) {
|
|
6148
|
+
ddl.push(
|
|
6149
|
+
`INSERT INTO ${tableName} (${table.initialData.fields.map(snakeCase).join(", ")}) VALUES ${table.initialData.data.map(
|
|
6150
|
+
(row) => `(${row.map((value) => {
|
|
6151
|
+
if (value === void 0) return "NULL";
|
|
6152
|
+
if (value === null) return "NULL";
|
|
6153
|
+
if (typeof value === "number") return String(value);
|
|
6154
|
+
if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
|
|
6155
|
+
const stringValue = String(value);
|
|
6156
|
+
return `'${stringValue.replace(/'/g, "''")}'`;
|
|
6157
|
+
}).join(", ")})`
|
|
6158
|
+
).join(", ")} ON CONFLICT DO NOTHING;`
|
|
6159
|
+
);
|
|
6160
|
+
}
|
|
6161
|
+
}
|
|
6162
|
+
return ddl;
|
|
6163
|
+
}
|
|
6164
|
+
fieldDefinitionToSql(fieldName, field) {
|
|
6165
|
+
let definition = `${snakeCase(fieldName)} ${field.type.toUpperCase()}`;
|
|
6166
|
+
if (field.type === "varchar") {
|
|
6167
|
+
definition += `(${field.constraints?.maxLength ?? 255})`;
|
|
6168
|
+
}
|
|
6169
|
+
if (field.type === "decimal") {
|
|
6170
|
+
definition += `(${field.constraints?.precision ?? 10},${field.constraints?.scale ?? 2})`;
|
|
6171
|
+
}
|
|
6172
|
+
if (field.primary) definition += " PRIMARY KEY";
|
|
6173
|
+
if (field.unique) definition += " UNIQUE";
|
|
6174
|
+
if (field.default !== void 0) {
|
|
6175
|
+
definition += ` DEFAULT ${field.default === "" ? "''" : String(field.default)}`;
|
|
6176
|
+
}
|
|
6177
|
+
if (field.required && !field.nullable) definition += " NOT NULL";
|
|
6178
|
+
if (field.nullable) definition += " NULL";
|
|
6179
|
+
if (field.generated) {
|
|
6180
|
+
definition += ` GENERATED ALWAYS AS ${field.generated.toUpperCase()} STORED`;
|
|
6181
|
+
}
|
|
6182
|
+
if (field.references) {
|
|
6183
|
+
definition += ` REFERENCES ${field.references} ON DELETE ${field.onDelete || "CASCADE"}`;
|
|
6184
|
+
}
|
|
6185
|
+
if (field.constraints?.check) {
|
|
6186
|
+
definition += ` CHECK (${field.constraints.check})`;
|
|
6187
|
+
}
|
|
6188
|
+
return definition;
|
|
6189
|
+
}
|
|
6190
|
+
async applyDdlStatements(pool, statements) {
|
|
6191
|
+
for (const sql of statements) {
|
|
6192
|
+
try {
|
|
6193
|
+
await pool.query(sql);
|
|
6194
|
+
} catch (error) {
|
|
6195
|
+
CadenzaService.log(
|
|
6196
|
+
"Error applying DDL statement",
|
|
6197
|
+
{
|
|
6198
|
+
sql,
|
|
6199
|
+
error: errorMessage(error)
|
|
6200
|
+
},
|
|
6201
|
+
"error"
|
|
6202
|
+
);
|
|
6203
|
+
throw error;
|
|
6204
|
+
}
|
|
6205
|
+
}
|
|
6206
|
+
}
|
|
6207
|
+
generateDatabaseTasks(registration) {
|
|
6208
|
+
for (const [tableName, table] of Object.entries(registration.schema.tables)) {
|
|
6209
|
+
this.createDatabaseTask(registration, "query", tableName, table);
|
|
6210
|
+
this.createDatabaseTask(registration, "insert", tableName, table);
|
|
6211
|
+
this.createDatabaseTask(registration, "update", tableName, table);
|
|
6212
|
+
this.createDatabaseTask(registration, "delete", tableName, table);
|
|
6213
|
+
this.createDatabaseMacroTasks(registration, tableName, table);
|
|
6214
|
+
}
|
|
6215
|
+
}
|
|
6216
|
+
createDatabaseMacroTasks(registration, tableName, table) {
|
|
6217
|
+
const querySchema = this.getInputSchema("query", tableName, table);
|
|
6218
|
+
const insertSchema = this.getInputSchema("insert", tableName, table);
|
|
6219
|
+
const queryMacroOperations = [
|
|
6220
|
+
"count",
|
|
6221
|
+
"exists",
|
|
6222
|
+
"one",
|
|
6223
|
+
"aggregate"
|
|
6224
|
+
];
|
|
6225
|
+
for (const macroOperation of queryMacroOperations) {
|
|
6226
|
+
const intentName = `${macroOperation}-pg-${registration.actorToken}-${tableName}`;
|
|
6227
|
+
if (registration.intentNames.has(intentName)) {
|
|
6228
|
+
throw new Error(
|
|
6229
|
+
`Duplicate macro intent '${intentName}' detected for table '${tableName}' in actor '${registration.actorName}'`
|
|
6230
|
+
);
|
|
6231
|
+
}
|
|
6232
|
+
registration.intentNames.add(intentName);
|
|
6233
|
+
CadenzaService.defineIntent({
|
|
6234
|
+
name: intentName,
|
|
6235
|
+
description: `Macro ${macroOperation} operation for table ${tableName}`,
|
|
6236
|
+
input: querySchema
|
|
6237
|
+
});
|
|
6238
|
+
CadenzaService.createThrottledTask(
|
|
6239
|
+
`${macroOperation.toUpperCase()} ${tableName}`,
|
|
6240
|
+
registration.actor.task(
|
|
6241
|
+
async ({ input }) => {
|
|
6242
|
+
const payload = typeof input.queryData === "object" && input.queryData ? input.queryData : input;
|
|
6243
|
+
const result = await this.queryFunction(registration, tableName, {
|
|
6244
|
+
...payload,
|
|
6245
|
+
queryMode: macroOperation
|
|
6246
|
+
});
|
|
6247
|
+
return {
|
|
6248
|
+
...input,
|
|
6249
|
+
...result
|
|
6250
|
+
};
|
|
6251
|
+
},
|
|
6252
|
+
{ mode: "read" }
|
|
6253
|
+
),
|
|
6254
|
+
(context) => context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default",
|
|
6255
|
+
`Macro ${macroOperation} task for ${tableName}`,
|
|
6256
|
+
{
|
|
6257
|
+
isMeta: registration.options.isMeta,
|
|
6258
|
+
isSubMeta: registration.options.isMeta,
|
|
6259
|
+
validateInputContext: registration.options.securityProfile !== "low",
|
|
6260
|
+
inputSchema: querySchema
|
|
6261
|
+
}
|
|
6262
|
+
).respondsTo(intentName);
|
|
6263
|
+
}
|
|
6264
|
+
const upsertIntentName = `upsert-pg-${registration.actorToken}-${tableName}`;
|
|
6265
|
+
if (registration.intentNames.has(upsertIntentName)) {
|
|
6266
|
+
throw new Error(
|
|
6267
|
+
`Duplicate macro intent '${upsertIntentName}' detected for table '${tableName}' in actor '${registration.actorName}'`
|
|
6268
|
+
);
|
|
6269
|
+
}
|
|
6270
|
+
registration.intentNames.add(upsertIntentName);
|
|
6271
|
+
CadenzaService.defineIntent({
|
|
6272
|
+
name: upsertIntentName,
|
|
6273
|
+
description: `Macro upsert operation for table ${tableName}`,
|
|
6274
|
+
input: insertSchema
|
|
6275
|
+
});
|
|
6276
|
+
CadenzaService.createThrottledTask(
|
|
6277
|
+
`UPSERT ${tableName}`,
|
|
6278
|
+
registration.actor.task(
|
|
6279
|
+
async ({ input }) => {
|
|
6280
|
+
const payload = typeof input.queryData === "object" && input.queryData ? input.queryData : input;
|
|
6281
|
+
if (!payload.onConflict) {
|
|
6282
|
+
return {
|
|
6283
|
+
...input,
|
|
6284
|
+
errored: true,
|
|
6285
|
+
__success: false,
|
|
6286
|
+
__error: `Macro upsert requires 'onConflict' payload for table '${tableName}'`
|
|
6287
|
+
};
|
|
6288
|
+
}
|
|
6289
|
+
const result = await this.insertFunction(registration, tableName, payload);
|
|
6290
|
+
return {
|
|
6291
|
+
...input,
|
|
6292
|
+
...result
|
|
6293
|
+
};
|
|
6294
|
+
},
|
|
6295
|
+
{ mode: "write" }
|
|
6296
|
+
),
|
|
6297
|
+
(context) => context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default",
|
|
6298
|
+
`Macro upsert task for ${tableName}`,
|
|
6299
|
+
{
|
|
6300
|
+
isMeta: registration.options.isMeta,
|
|
6301
|
+
isSubMeta: registration.options.isMeta,
|
|
6302
|
+
validateInputContext: registration.options.securityProfile !== "low",
|
|
6303
|
+
inputSchema: insertSchema
|
|
6304
|
+
}
|
|
6305
|
+
).respondsTo(upsertIntentName);
|
|
6306
|
+
}
|
|
6307
|
+
createDatabaseTask(registration, op, tableName, table) {
|
|
6308
|
+
const opAction = op === "query" ? "queried" : op === "insert" ? "inserted" : op === "update" ? "updated" : "deleted";
|
|
6309
|
+
const defaultSignal = `global.${registration.options.isMeta ? "meta." : ""}${tableName}.${opAction}`;
|
|
6310
|
+
const taskName = `${op.charAt(0).toUpperCase() + op.slice(1)} ${tableName}`;
|
|
6311
|
+
const schema = this.getInputSchema(op, tableName, table);
|
|
6312
|
+
const databaseTaskFunction = registration.actor.task(
|
|
6313
|
+
async ({ input, emit }) => {
|
|
6314
|
+
let context = { ...input };
|
|
6315
|
+
let payloadModifiedByTriggers = false;
|
|
6316
|
+
for (const action of Object.keys(table.customSignals?.triggers ?? {})) {
|
|
6317
|
+
const triggerDefinitions = table.customSignals?.triggers?.[action];
|
|
6318
|
+
for (const trigger of triggerDefinitions ?? []) {
|
|
6319
|
+
if (typeof trigger === "string") {
|
|
6320
|
+
continue;
|
|
6321
|
+
}
|
|
6322
|
+
if (trigger.condition && !trigger.condition(context)) {
|
|
6323
|
+
return {
|
|
6324
|
+
failed: true,
|
|
6325
|
+
__success: false,
|
|
6326
|
+
__error: `Condition for signal trigger failed: ${trigger.signal}`
|
|
6327
|
+
};
|
|
6328
|
+
}
|
|
6329
|
+
if (trigger.queryData) {
|
|
6330
|
+
context.queryData = {
|
|
6331
|
+
...context.queryData ?? {},
|
|
6332
|
+
...trigger.queryData
|
|
6333
|
+
};
|
|
6334
|
+
payloadModifiedByTriggers = true;
|
|
6335
|
+
}
|
|
6336
|
+
}
|
|
6337
|
+
}
|
|
6338
|
+
const operationPayload = typeof context.queryData === "object" && context.queryData ? context.queryData : context;
|
|
6339
|
+
this.validateOperationPayload(
|
|
6340
|
+
registration,
|
|
6341
|
+
op,
|
|
6342
|
+
tableName,
|
|
6343
|
+
table,
|
|
6344
|
+
operationPayload,
|
|
6345
|
+
{
|
|
6346
|
+
enforceFieldAllowlist: registration.options.securityProfile === "low" || payloadModifiedByTriggers
|
|
6347
|
+
}
|
|
6348
|
+
);
|
|
6349
|
+
let result;
|
|
6350
|
+
if (op === "query") {
|
|
6351
|
+
result = await this.queryFunction(registration, tableName, operationPayload);
|
|
6352
|
+
} else if (op === "insert") {
|
|
6353
|
+
result = await this.insertFunction(registration, tableName, operationPayload);
|
|
6354
|
+
} else if (op === "update") {
|
|
6355
|
+
result = await this.updateFunction(registration, tableName, operationPayload);
|
|
6356
|
+
} else {
|
|
6357
|
+
result = await this.deleteFunction(registration, tableName, operationPayload);
|
|
6358
|
+
}
|
|
6359
|
+
context = {
|
|
6360
|
+
...context,
|
|
6361
|
+
...result
|
|
6362
|
+
};
|
|
6363
|
+
if (!context.errored) {
|
|
6364
|
+
for (const signal of table.customSignals?.emissions?.[op] ?? []) {
|
|
6365
|
+
if (typeof signal === "string") {
|
|
6366
|
+
emit(signal, context);
|
|
6367
|
+
continue;
|
|
6368
|
+
}
|
|
6369
|
+
if (signal.condition && !signal.condition(context)) {
|
|
6370
|
+
continue;
|
|
6371
|
+
}
|
|
6372
|
+
emit(signal.signal, context);
|
|
6373
|
+
}
|
|
6374
|
+
}
|
|
6375
|
+
if (tableName !== "system_log" && context.errored) {
|
|
6376
|
+
CadenzaService.log(
|
|
6377
|
+
`ERROR in ${taskName}`,
|
|
6378
|
+
JSON.stringify({
|
|
6379
|
+
data: context.data,
|
|
6380
|
+
queryData: context.queryData,
|
|
6381
|
+
filter: context.filter,
|
|
6382
|
+
fields: context.fields,
|
|
6383
|
+
joins: context.joins,
|
|
6384
|
+
sort: context.sort,
|
|
6385
|
+
limit: context.limit,
|
|
6386
|
+
offset: context.offset,
|
|
6387
|
+
error: context.__error
|
|
6388
|
+
}),
|
|
6389
|
+
"error"
|
|
6390
|
+
);
|
|
6391
|
+
}
|
|
6392
|
+
delete context.queryData;
|
|
6393
|
+
delete context.data;
|
|
6394
|
+
delete context.filter;
|
|
6395
|
+
delete context.fields;
|
|
6396
|
+
delete context.joins;
|
|
6397
|
+
delete context.sort;
|
|
6398
|
+
delete context.limit;
|
|
6399
|
+
delete context.offset;
|
|
6400
|
+
return context;
|
|
6401
|
+
},
|
|
6402
|
+
{ mode: op === "query" ? "read" : "write" }
|
|
6403
|
+
);
|
|
6404
|
+
const task = CadenzaService.createThrottledTask(
|
|
6405
|
+
taskName,
|
|
6406
|
+
databaseTaskFunction,
|
|
6407
|
+
(context) => context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default",
|
|
6408
|
+
`Auto-generated ${op} task for ${tableName} (PostgresActor)`,
|
|
6409
|
+
{
|
|
6410
|
+
isMeta: registration.options.isMeta,
|
|
6411
|
+
isSubMeta: registration.options.isMeta,
|
|
6412
|
+
validateInputContext: registration.options.securityProfile !== "low",
|
|
6413
|
+
inputSchema: schema
|
|
6414
|
+
}
|
|
6415
|
+
).doOn(
|
|
6416
|
+
...table.customSignals?.triggers?.[op]?.map(
|
|
6417
|
+
(signal) => typeof signal === "string" ? signal : signal.signal
|
|
6418
|
+
) ?? []
|
|
6419
|
+
).emits(defaultSignal).attachSignal(
|
|
6420
|
+
...table.customSignals?.emissions?.[op]?.map(
|
|
6421
|
+
(signal) => typeof signal === "string" ? signal : signal.signal
|
|
6422
|
+
) ?? []
|
|
6423
|
+
);
|
|
6424
|
+
const { intents } = resolveTableOperationIntents(
|
|
6425
|
+
registration.actorName,
|
|
6426
|
+
tableName,
|
|
6427
|
+
table,
|
|
6428
|
+
op,
|
|
6429
|
+
schema
|
|
6430
|
+
);
|
|
6431
|
+
for (const intent of intents) {
|
|
6432
|
+
if (registration.intentNames.has(intent.name)) {
|
|
6433
|
+
throw new Error(
|
|
6434
|
+
`Duplicate auto/custom intent '${intent.name}' detected while generating ${op} task for table '${tableName}' in actor '${registration.actorName}'`
|
|
6435
|
+
);
|
|
6436
|
+
}
|
|
6437
|
+
registration.intentNames.add(intent.name);
|
|
6438
|
+
CadenzaService.defineIntent({
|
|
6439
|
+
name: intent.name,
|
|
6440
|
+
description: intent.description,
|
|
6441
|
+
input: intent.input
|
|
6442
|
+
});
|
|
6443
|
+
}
|
|
6444
|
+
task.respondsTo(...intents.map((intent) => intent.name));
|
|
6445
|
+
}
|
|
6446
|
+
validateOperationPayload(registration, operation, tableName, table, payload, options) {
|
|
6447
|
+
const allowedFields = new Set(Object.keys(table.fields));
|
|
6448
|
+
const resolvedMode = payload.queryMode ?? "rows";
|
|
6449
|
+
if (!["rows", "count", "exists", "one", "aggregate"].includes(resolvedMode)) {
|
|
6450
|
+
throw new Error(`Unsupported queryMode '${String(payload.queryMode)}'`);
|
|
6451
|
+
}
|
|
6452
|
+
const assertAllowedField = (fieldName, label) => {
|
|
6453
|
+
if (!allowedFields.has(fieldName)) {
|
|
6454
|
+
throw new Error(
|
|
6455
|
+
`Invalid field '${fieldName}' in ${label} for ${operation} on ${tableName}`
|
|
6456
|
+
);
|
|
6457
|
+
}
|
|
6458
|
+
};
|
|
6459
|
+
const aggregateDefinitions = Array.isArray(payload.aggregates) ? payload.aggregates : [];
|
|
6460
|
+
const aggregateSortAllowlist = /* @__PURE__ */ new Set();
|
|
6461
|
+
if (resolvedMode === "aggregate") {
|
|
6462
|
+
if (aggregateDefinitions.length === 0) {
|
|
6463
|
+
throw new Error(
|
|
6464
|
+
`Aggregate queryMode requires at least one aggregate on table '${tableName}'`
|
|
6465
|
+
);
|
|
6466
|
+
}
|
|
6467
|
+
for (const groupField of payload.groupBy ?? []) {
|
|
6468
|
+
assertAllowedField(groupField, "groupBy");
|
|
6469
|
+
aggregateSortAllowlist.add(groupField);
|
|
6470
|
+
}
|
|
6471
|
+
for (const [index, aggregate] of aggregateDefinitions.entries()) {
|
|
6472
|
+
if (!isSupportedAggregateFunction(aggregate.fn)) {
|
|
6473
|
+
throw new Error(
|
|
6474
|
+
`Unsupported aggregate function '${String(aggregate.fn)}' on table '${tableName}'`
|
|
6475
|
+
);
|
|
6476
|
+
}
|
|
6477
|
+
if (aggregate.fn !== "count" && !aggregate.field) {
|
|
6478
|
+
throw new Error(
|
|
6479
|
+
`Aggregate '${aggregate.fn}' requires field on table '${tableName}'`
|
|
6480
|
+
);
|
|
6481
|
+
}
|
|
6482
|
+
if (aggregate.field) {
|
|
6483
|
+
assertAllowedField(aggregate.field, "aggregates.field");
|
|
6484
|
+
}
|
|
6485
|
+
aggregateSortAllowlist.add(buildAggregateAlias(aggregate, index));
|
|
6486
|
+
}
|
|
6487
|
+
} else if (aggregateDefinitions.length > 0 || (payload.groupBy ?? []).length > 0) {
|
|
6488
|
+
throw new Error(
|
|
6489
|
+
`aggregates/groupBy payload requires queryMode='aggregate' on table '${tableName}'`
|
|
6490
|
+
);
|
|
6491
|
+
}
|
|
6492
|
+
if (options.enforceFieldAllowlist) {
|
|
6493
|
+
if (payload.fields) {
|
|
6494
|
+
for (const field of payload.fields) {
|
|
6495
|
+
assertAllowedField(field, "fields");
|
|
6496
|
+
}
|
|
6497
|
+
}
|
|
6498
|
+
if (payload.filter) {
|
|
6499
|
+
for (const field of Object.keys(payload.filter)) {
|
|
6500
|
+
assertAllowedField(field, "filter");
|
|
6501
|
+
}
|
|
6502
|
+
}
|
|
6503
|
+
if (payload.data) {
|
|
6504
|
+
const rows = resolveDataRows(payload.data);
|
|
6505
|
+
for (const row of rows) {
|
|
6506
|
+
for (const field of Object.keys(row)) {
|
|
6507
|
+
assertAllowedField(field, "data");
|
|
6508
|
+
}
|
|
6509
|
+
}
|
|
6510
|
+
}
|
|
6511
|
+
}
|
|
6512
|
+
if (payload.sort) {
|
|
6513
|
+
for (const field of Object.keys(payload.sort)) {
|
|
6514
|
+
if (resolvedMode === "aggregate" && aggregateSortAllowlist.has(field)) {
|
|
6515
|
+
continue;
|
|
6516
|
+
}
|
|
6517
|
+
assertAllowedField(field, "sort");
|
|
6518
|
+
}
|
|
6519
|
+
}
|
|
6520
|
+
if (payload.onConflict) {
|
|
6521
|
+
for (const conflictField of payload.onConflict.target ?? []) {
|
|
6522
|
+
assertAllowedField(conflictField, "onConflict.target");
|
|
6523
|
+
}
|
|
6524
|
+
for (const setField of Object.keys(payload.onConflict.action?.set ?? {})) {
|
|
6525
|
+
assertAllowedField(setField, "onConflict.action.set");
|
|
6526
|
+
}
|
|
6527
|
+
}
|
|
6528
|
+
if (payload.joins) {
|
|
6529
|
+
this.validateJoinPayload(registration.schema, payload.joins);
|
|
6530
|
+
}
|
|
6531
|
+
}
|
|
6532
|
+
validateJoinPayload(schema, joins) {
|
|
6533
|
+
for (const [joinTableName, joinDefinition] of Object.entries(joins)) {
|
|
6534
|
+
if (!schema.tables[joinTableName]) {
|
|
6535
|
+
throw new Error(`Invalid join table '${joinTableName}'. Table does not exist in schema.`);
|
|
6536
|
+
}
|
|
6537
|
+
const joinTable = schema.tables[joinTableName];
|
|
6538
|
+
for (const field of joinDefinition.fields ?? []) {
|
|
6539
|
+
if (!joinTable.fields[field]) {
|
|
6540
|
+
throw new Error(
|
|
6541
|
+
`Invalid join field '${field}' on joined table '${joinTableName}'`
|
|
6542
|
+
);
|
|
6543
|
+
}
|
|
6544
|
+
}
|
|
6545
|
+
if (joinDefinition.filter) {
|
|
6546
|
+
for (const filterField of Object.keys(joinDefinition.filter)) {
|
|
6547
|
+
if (!joinTable.fields[filterField]) {
|
|
6548
|
+
throw new Error(
|
|
6549
|
+
`Invalid join filter field '${filterField}' on joined table '${joinTableName}'`
|
|
6550
|
+
);
|
|
6551
|
+
}
|
|
6552
|
+
}
|
|
6553
|
+
}
|
|
6554
|
+
if (joinDefinition.joins) {
|
|
6555
|
+
this.validateJoinPayload(schema, joinDefinition.joins);
|
|
6556
|
+
}
|
|
6557
|
+
}
|
|
6558
|
+
}
|
|
6559
|
+
toCamelCase(rows) {
|
|
6560
|
+
return rows.map((row) => {
|
|
6561
|
+
const camelCasedRow = {};
|
|
6562
|
+
for (const [key, value] of Object.entries(row)) {
|
|
6563
|
+
camelCasedRow[camelCase(key)] = value;
|
|
6564
|
+
}
|
|
6565
|
+
return camelCasedRow;
|
|
6566
|
+
});
|
|
6567
|
+
}
|
|
6176
6568
|
buildWhereClause(filter, params) {
|
|
6177
6569
|
const conditions = [];
|
|
6178
6570
|
for (const [key, value] of Object.entries(filter)) {
|
|
6179
6571
|
if (value !== void 0) {
|
|
6180
6572
|
if (Array.isArray(value)) {
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
|
|
6185
|
-
|
|
6186
|
-
}).join(", ")})`
|
|
6187
|
-
);
|
|
6573
|
+
const placeholders = value.map((entry) => {
|
|
6574
|
+
params.push(entry);
|
|
6575
|
+
return `$${params.length}`;
|
|
6576
|
+
}).join(", ");
|
|
6577
|
+
conditions.push(`${snakeCase(key)} IN (${placeholders})`);
|
|
6188
6578
|
} else {
|
|
6189
|
-
conditions.push(`${snakeCase(key)} = $${params.length + 1}`);
|
|
6190
6579
|
params.push(value);
|
|
6580
|
+
conditions.push(`${snakeCase(key)} = $${params.length}`);
|
|
6191
6581
|
}
|
|
6192
6582
|
}
|
|
6193
6583
|
}
|
|
6194
6584
|
return conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
6195
6585
|
}
|
|
6196
|
-
/**
|
|
6197
|
-
* Constructs a SQL join clause from a given set of join definitions.
|
|
6198
|
-
*
|
|
6199
|
-
* @param {Record<string, JoinDefinition>} joins - An object where keys are table names
|
|
6200
|
-
* and values are definitions of join conditions.
|
|
6201
|
-
* @return {string} The constructed SQL join clause as a string.
|
|
6202
|
-
*/
|
|
6203
6586
|
buildJoinClause(joins) {
|
|
6204
6587
|
let joinSql = "";
|
|
6205
6588
|
for (const [table, join] of Object.entries(joins)) {
|
|
6206
|
-
|
|
6589
|
+
const alias = join.alias ? ` ${join.alias}` : "";
|
|
6590
|
+
joinSql += ` LEFT JOIN ${snakeCase(table)}${alias} ON ${join.on}`;
|
|
6207
6591
|
if (join.joins) joinSql += " " + this.buildJoinClause(join.joins);
|
|
6208
6592
|
}
|
|
6209
6593
|
return joinSql;
|
|
6210
6594
|
}
|
|
6211
|
-
|
|
6212
|
-
|
|
6213
|
-
|
|
6214
|
-
|
|
6215
|
-
|
|
6216
|
-
|
|
6217
|
-
|
|
6218
|
-
|
|
6219
|
-
|
|
6220
|
-
if (Array.isArray(data))
|
|
6221
|
-
return Promise.all(data.map((d) => this.resolveNestedData(d, tableName)));
|
|
6222
|
-
if (typeof data !== "object" || data === null) return data;
|
|
6595
|
+
async resolveNestedData(registration, data, tableName) {
|
|
6596
|
+
if (Array.isArray(data)) {
|
|
6597
|
+
return Promise.all(
|
|
6598
|
+
data.map((entry) => this.resolveNestedData(registration, entry, tableName))
|
|
6599
|
+
);
|
|
6600
|
+
}
|
|
6601
|
+
if (typeof data !== "object" || data === null) {
|
|
6602
|
+
return data;
|
|
6603
|
+
}
|
|
6223
6604
|
const resolved = { ...data };
|
|
6224
6605
|
for (const [key, value] of Object.entries(data)) {
|
|
6225
6606
|
if (typeof value === "object" && value !== null && "subOperation" in value) {
|
|
6226
|
-
const
|
|
6227
|
-
resolved[key] = await this.executeSubOperation(
|
|
6607
|
+
const subOperation = value;
|
|
6608
|
+
resolved[key] = await this.executeSubOperation(registration, subOperation);
|
|
6228
6609
|
} else if (typeof value === "string" && ["increment", "decrement", "set"].includes(value)) {
|
|
6229
6610
|
resolved[key] = { __effect: value };
|
|
6230
|
-
} else if (typeof value === "object") {
|
|
6231
|
-
resolved[key] = await this.resolveNestedData(value, tableName);
|
|
6611
|
+
} else if (typeof value === "object" && value !== null) {
|
|
6612
|
+
resolved[key] = await this.resolveNestedData(registration, value, tableName);
|
|
6232
6613
|
}
|
|
6233
6614
|
}
|
|
6234
6615
|
return resolved;
|
|
6235
6616
|
}
|
|
6236
|
-
|
|
6237
|
-
|
|
6238
|
-
|
|
6239
|
-
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
* For "insert", the result will include the inserted row or a partial response for uuid conflicts.
|
|
6243
|
-
* For "query", the result will include the first row that matches the query condition. If no result is found,
|
|
6244
|
-
* resolves with an empty object.
|
|
6245
|
-
* @throws Throws an error if the operation fails. Rolls back the transaction in case of an error.
|
|
6246
|
-
*/
|
|
6247
|
-
async executeSubOperation(op) {
|
|
6248
|
-
const client = await this.getClient();
|
|
6249
|
-
try {
|
|
6250
|
-
await client.query("BEGIN");
|
|
6251
|
-
let result;
|
|
6252
|
-
if (op.subOperation === "insert") {
|
|
6253
|
-
const resolvedData = await this.resolveNestedData(op.data, op.table);
|
|
6254
|
-
const sql = `INSERT INTO ${op.table} (${Object.keys(resolvedData).map((k) => snakeCase(k)).join(", ")}) VALUES (${Object.values(resolvedData).map((_, i) => `$${i + 1}`).join(", ")}) ON CONFLICT DO NOTHING RETURNING ${op.return ?? "*"}`;
|
|
6255
|
-
result = await client.query(sql, Object.values(resolvedData));
|
|
6256
|
-
result = result.rows[0]?.[op.return ?? "uuid"];
|
|
6257
|
-
if (!result) {
|
|
6258
|
-
result = op.return && op.return in resolvedData ? resolvedData[op.return] : resolvedData["uuid"];
|
|
6259
|
-
}
|
|
6260
|
-
} else if (op.subOperation === "query") {
|
|
6261
|
-
const params = [];
|
|
6262
|
-
const whereClause = this.buildWhereClause(op.filter || {}, params);
|
|
6263
|
-
const sql = `SELECT ${op.fields?.join(", ") || "*"} FROM ${op.table} ${whereClause} LIMIT 1`;
|
|
6264
|
-
result = (await client.query(sql, params)).rows[0]?.[op.return ?? "uuid"];
|
|
6265
|
-
}
|
|
6266
|
-
await client.query("COMMIT");
|
|
6267
|
-
return result || {};
|
|
6268
|
-
} catch (error) {
|
|
6269
|
-
await client.query("ROLLBACK");
|
|
6270
|
-
throw error;
|
|
6271
|
-
} finally {
|
|
6272
|
-
client.release();
|
|
6617
|
+
async executeSubOperation(registration, operation) {
|
|
6618
|
+
const targetTableName = operation.table;
|
|
6619
|
+
if (!registration.schema.tables[targetTableName]) {
|
|
6620
|
+
throw new Error(
|
|
6621
|
+
`Sub-operation table '${targetTableName}' does not exist in actor schema`
|
|
6622
|
+
);
|
|
6273
6623
|
}
|
|
6274
|
-
|
|
6275
|
-
|
|
6276
|
-
|
|
6277
|
-
|
|
6278
|
-
|
|
6279
|
-
|
|
6280
|
-
|
|
6281
|
-
|
|
6282
|
-
|
|
6283
|
-
|
|
6284
|
-
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
// @ts-ignore
|
|
6296
|
-
table.customSignals?.triggers?.[action].filter(
|
|
6297
|
-
(trigger) => trigger.condition
|
|
6298
|
-
)
|
|
6299
|
-
);
|
|
6300
|
-
for (const triggerCondition of triggerConditions ?? []) {
|
|
6301
|
-
if (triggerCondition.condition && !triggerCondition.condition(context)) {
|
|
6302
|
-
return {
|
|
6303
|
-
failed: true,
|
|
6304
|
-
error: `Condition for signal trigger failed: ${triggerCondition.signal}`
|
|
6305
|
-
};
|
|
6306
|
-
}
|
|
6307
|
-
}
|
|
6308
|
-
const triggerQueryData = (
|
|
6309
|
-
// @ts-ignore
|
|
6310
|
-
table.customSignals?.triggers?.[action].filter(
|
|
6311
|
-
(trigger) => trigger.queryData
|
|
6312
|
-
)
|
|
6313
|
-
);
|
|
6314
|
-
for (const queryData of triggerQueryData ?? []) {
|
|
6315
|
-
if (context.queryData) {
|
|
6316
|
-
context.queryData = {
|
|
6317
|
-
...context.queryData,
|
|
6318
|
-
...queryData
|
|
6319
|
-
};
|
|
6320
|
-
} else {
|
|
6321
|
-
context = {
|
|
6322
|
-
...context,
|
|
6323
|
-
...queryData
|
|
6324
|
-
};
|
|
6325
|
-
}
|
|
6326
|
-
}
|
|
6327
|
-
}
|
|
6328
|
-
try {
|
|
6329
|
-
const result = await queryFunction(
|
|
6330
|
-
tableName,
|
|
6331
|
-
context.queryData ?? context
|
|
6332
|
-
);
|
|
6333
|
-
context = {
|
|
6334
|
-
...context,
|
|
6335
|
-
...result
|
|
6336
|
-
};
|
|
6337
|
-
} catch (e) {
|
|
6338
|
-
CadenzaService.log(
|
|
6339
|
-
"Database task errored.",
|
|
6340
|
-
{ taskName, error: e },
|
|
6341
|
-
"error"
|
|
6342
|
-
);
|
|
6343
|
-
throw e;
|
|
6344
|
-
}
|
|
6345
|
-
if (!context.errored) {
|
|
6346
|
-
for (const signal of table.customSignals?.emissions?.[op] ?? []) {
|
|
6347
|
-
if (signal.condition && !signal.condition(context)) {
|
|
6348
|
-
continue;
|
|
6349
|
-
}
|
|
6350
|
-
emit(signal.signal ?? signal, context);
|
|
6351
|
-
}
|
|
6352
|
-
}
|
|
6353
|
-
if (tableName !== "system_log" && context.errored) {
|
|
6354
|
-
CadenzaService.log(
|
|
6355
|
-
`ERROR in ${taskName}`,
|
|
6356
|
-
JSON.stringify({
|
|
6357
|
-
data: context.data,
|
|
6358
|
-
queryData: context.queryData,
|
|
6359
|
-
filter: context.filter,
|
|
6360
|
-
fields: context.fields,
|
|
6361
|
-
joins: context.joins,
|
|
6362
|
-
sort: context.sort,
|
|
6363
|
-
limit: context.limit,
|
|
6364
|
-
offset: context.offset,
|
|
6365
|
-
error: context.__error
|
|
6366
|
-
}),
|
|
6367
|
-
"error"
|
|
6368
|
-
);
|
|
6624
|
+
const pool = this.getPoolOrThrow(registration);
|
|
6625
|
+
const safetyPolicy = this.resolveSafetyPolicy(registration);
|
|
6626
|
+
return this.executeWithTransaction(pool, true, async (client) => {
|
|
6627
|
+
if (operation.subOperation === "insert") {
|
|
6628
|
+
const resolvedData = await this.resolveNestedData(
|
|
6629
|
+
registration,
|
|
6630
|
+
operation.data,
|
|
6631
|
+
operation.table
|
|
6632
|
+
);
|
|
6633
|
+
const row = ensurePlainObject(resolvedData, "sub-operation insert data");
|
|
6634
|
+
const keys = Object.keys(row);
|
|
6635
|
+
const params = Object.values(row);
|
|
6636
|
+
const sql2 = `INSERT INTO ${operation.table} (${keys.map((key) => snakeCase(key)).join(", ")}) VALUES (${params.map((_, index) => `$${index + 1}`).join(", ")}) ON CONFLICT DO NOTHING RETURNING ${operation.return ?? "*"}`;
|
|
6637
|
+
const result2 = await this.withTimeout(
|
|
6638
|
+
() => client.query(sql2, params),
|
|
6639
|
+
safetyPolicy.statementTimeoutMs,
|
|
6640
|
+
`Sub-operation insert timeout on table ${operation.table}`
|
|
6641
|
+
);
|
|
6642
|
+
const returnKey2 = operation.return ?? "uuid";
|
|
6643
|
+
if (result2.rows[0]?.[returnKey2] !== void 0) {
|
|
6644
|
+
return result2.rows[0][returnKey2];
|
|
6369
6645
|
}
|
|
6370
|
-
|
|
6371
|
-
delete context.data;
|
|
6372
|
-
delete context.filter;
|
|
6373
|
-
delete context.fields;
|
|
6374
|
-
delete context.joins;
|
|
6375
|
-
delete context.sort;
|
|
6376
|
-
delete context.limit;
|
|
6377
|
-
delete context.offset;
|
|
6378
|
-
return context;
|
|
6379
|
-
},
|
|
6380
|
-
(context) => context?.__metadata?.__executionTraceId ?? context?.__executionTraceId ?? "default",
|
|
6381
|
-
`Auto-generated ${op} task for ${tableName}`,
|
|
6382
|
-
{
|
|
6383
|
-
isMeta: options.isMeta,
|
|
6384
|
-
isSubMeta: options.isMeta,
|
|
6385
|
-
validateInputContext: options.securityProfile !== "low",
|
|
6386
|
-
inputSchema: schema
|
|
6646
|
+
return row[returnKey2] ?? row.uuid ?? {};
|
|
6387
6647
|
}
|
|
6388
|
-
|
|
6389
|
-
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
|
|
6395
|
-
}) ?? []
|
|
6396
|
-
);
|
|
6397
|
-
if (op === "query") {
|
|
6398
|
-
const { intents, warnings } = resolveTableQueryIntents(
|
|
6399
|
-
CadenzaService.serviceRegistry?.serviceName,
|
|
6400
|
-
tableName,
|
|
6401
|
-
table,
|
|
6402
|
-
schema
|
|
6648
|
+
const queryParams = [];
|
|
6649
|
+
const whereClause = this.buildWhereClause(operation.filter || {}, queryParams);
|
|
6650
|
+
const sql = `SELECT ${(operation.fields ?? ["*"]).map((field) => field === "*" ? field : snakeCase(field)).join(", ")} FROM ${operation.table} ${whereClause} LIMIT 1`;
|
|
6651
|
+
const result = await this.withTimeout(
|
|
6652
|
+
() => client.query(sql, queryParams),
|
|
6653
|
+
safetyPolicy.statementTimeoutMs,
|
|
6654
|
+
`Sub-operation query timeout on table ${operation.table}`
|
|
6403
6655
|
);
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
{
|
|
6408
|
-
tableName,
|
|
6409
|
-
warning
|
|
6410
|
-
},
|
|
6411
|
-
"warning"
|
|
6412
|
-
);
|
|
6413
|
-
}
|
|
6414
|
-
for (const intent of intents) {
|
|
6415
|
-
CadenzaService.defineIntent({
|
|
6416
|
-
name: intent.name,
|
|
6417
|
-
description: intent.description,
|
|
6418
|
-
input: intent.input
|
|
6419
|
-
});
|
|
6420
|
-
}
|
|
6421
|
-
task.respondsTo(...intents.map((intent) => intent.name));
|
|
6422
|
-
}
|
|
6656
|
+
const returnKey = operation.return ?? "uuid";
|
|
6657
|
+
return result.rows[0]?.[returnKey] ?? {};
|
|
6658
|
+
});
|
|
6423
6659
|
}
|
|
6424
6660
|
getInputSchema(op, tableName, table) {
|
|
6425
6661
|
const inputSchema = {
|
|
@@ -6438,66 +6674,43 @@ var DatabaseController = class _DatabaseController {
|
|
|
6438
6674
|
}
|
|
6439
6675
|
inputSchema.properties.transaction = getTransactionSchema();
|
|
6440
6676
|
inputSchema.properties.queryData.properties.transaction = inputSchema.properties.transaction;
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6444
|
-
|
|
6445
|
-
|
|
6446
|
-
|
|
6447
|
-
|
|
6448
|
-
|
|
6449
|
-
|
|
6450
|
-
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
|
|
6454
|
-
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
|
|
6461
|
-
|
|
6462
|
-
|
|
6463
|
-
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
|
|
6471
|
-
|
|
6472
|
-
|
|
6473
|
-
|
|
6474
|
-
|
|
6475
|
-
|
|
6476
|
-
|
|
6477
|
-
|
|
6478
|
-
inputSchema.properties.queryData.properties.limit = inputSchema.properties.limit;
|
|
6479
|
-
inputSchema.properties.offset = getQueryOffsetSchemaFromTable();
|
|
6480
|
-
inputSchema.properties.queryData.properties.offset = inputSchema.properties.offset;
|
|
6481
|
-
break;
|
|
6482
|
-
case "update":
|
|
6483
|
-
inputSchema.properties.filter = getQueryFilterSchemaFromTable(
|
|
6484
|
-
table,
|
|
6485
|
-
tableName
|
|
6486
|
-
);
|
|
6487
|
-
inputSchema.properties.queryData.properties.filter = inputSchema.properties.filter;
|
|
6488
|
-
inputSchema.properties.fields = getQueryFieldsSchemaFromTable(
|
|
6489
|
-
table,
|
|
6490
|
-
tableName
|
|
6491
|
-
);
|
|
6492
|
-
inputSchema.properties.queryData.properties.fields = inputSchema.properties.fields;
|
|
6493
|
-
break;
|
|
6494
|
-
case "delete":
|
|
6495
|
-
inputSchema.properties.filter = getQueryFilterSchemaFromTable(
|
|
6496
|
-
table,
|
|
6497
|
-
tableName
|
|
6498
|
-
);
|
|
6499
|
-
inputSchema.properties.queryData.properties.filter = inputSchema.properties.filter;
|
|
6500
|
-
break;
|
|
6677
|
+
if (op === "insert" || op === "update") {
|
|
6678
|
+
inputSchema.properties.data = getInsertDataSchemaFromTable(table, tableName);
|
|
6679
|
+
inputSchema.properties.queryData.properties.data = inputSchema.properties.data;
|
|
6680
|
+
}
|
|
6681
|
+
if (op === "insert") {
|
|
6682
|
+
inputSchema.properties.batch = getQueryBatchSchemaFromTable();
|
|
6683
|
+
inputSchema.properties.queryData.properties.batch = inputSchema.properties.batch;
|
|
6684
|
+
inputSchema.properties.onConflict = getQueryOnConflictSchemaFromTable(
|
|
6685
|
+
table,
|
|
6686
|
+
tableName
|
|
6687
|
+
);
|
|
6688
|
+
inputSchema.properties.queryData.properties.onConflict = inputSchema.properties.onConflict;
|
|
6689
|
+
}
|
|
6690
|
+
if (op === "query" || op === "update" || op === "delete") {
|
|
6691
|
+
inputSchema.properties.filter = getQueryFilterSchemaFromTable(table, tableName);
|
|
6692
|
+
inputSchema.properties.queryData.properties.filter = inputSchema.properties.filter;
|
|
6693
|
+
}
|
|
6694
|
+
if (op === "query") {
|
|
6695
|
+
inputSchema.properties.queryMode = getQueryModeSchema();
|
|
6696
|
+
inputSchema.properties.queryData.properties.queryMode = inputSchema.properties.queryMode;
|
|
6697
|
+
inputSchema.properties.fields = getQueryFieldsSchemaFromTable(table, tableName);
|
|
6698
|
+
inputSchema.properties.queryData.properties.fields = inputSchema.properties.fields;
|
|
6699
|
+
inputSchema.properties.joins = getQueryJoinsSchemaFromTable(table, tableName);
|
|
6700
|
+
inputSchema.properties.queryData.properties.joins = inputSchema.properties.joins;
|
|
6701
|
+
inputSchema.properties.sort = getQuerySortSchemaFromTable(table, tableName);
|
|
6702
|
+
inputSchema.properties.queryData.properties.sort = inputSchema.properties.sort;
|
|
6703
|
+
inputSchema.properties.aggregates = getQueryAggregatesSchemaFromTable(
|
|
6704
|
+
table,
|
|
6705
|
+
tableName
|
|
6706
|
+
);
|
|
6707
|
+
inputSchema.properties.queryData.properties.aggregates = inputSchema.properties.aggregates;
|
|
6708
|
+
inputSchema.properties.groupBy = getQueryGroupBySchemaFromTable(table, tableName);
|
|
6709
|
+
inputSchema.properties.queryData.properties.groupBy = inputSchema.properties.groupBy;
|
|
6710
|
+
inputSchema.properties.limit = getQueryLimitSchemaFromTable();
|
|
6711
|
+
inputSchema.properties.queryData.properties.limit = inputSchema.properties.limit;
|
|
6712
|
+
inputSchema.properties.offset = getQueryOffsetSchemaFromTable();
|
|
6713
|
+
inputSchema.properties.queryData.properties.offset = inputSchema.properties.offset;
|
|
6501
6714
|
}
|
|
6502
6715
|
return inputSchema;
|
|
6503
6716
|
}
|
|
@@ -6507,13 +6720,13 @@ function getInsertDataSchemaFromTable(table, tableName) {
|
|
|
6507
6720
|
type: "object",
|
|
6508
6721
|
properties: {
|
|
6509
6722
|
...Object.fromEntries(
|
|
6510
|
-
Object.entries(table.fields).map((field) => {
|
|
6723
|
+
Object.entries(table.fields).map(([fieldName, field]) => {
|
|
6511
6724
|
return [
|
|
6512
|
-
|
|
6725
|
+
fieldName,
|
|
6513
6726
|
{
|
|
6514
6727
|
value: {
|
|
6515
|
-
type: tableFieldTypeToSchemaType(field
|
|
6516
|
-
description: `Inferred from field '${
|
|
6728
|
+
type: tableFieldTypeToSchemaType(field.type),
|
|
6729
|
+
description: `Inferred from field '${fieldName}' of type [${field.type}] on table ${tableName}.`
|
|
6517
6730
|
},
|
|
6518
6731
|
effect: {
|
|
6519
6732
|
type: "string",
|
|
@@ -6562,7 +6775,7 @@ function getInsertDataSchemaFromTable(table, tableName) {
|
|
|
6562
6775
|
})
|
|
6563
6776
|
)
|
|
6564
6777
|
},
|
|
6565
|
-
required: Object.entries(table.fields).filter((field) => field
|
|
6778
|
+
required: Object.entries(table.fields).filter(([, field]) => field.required || field.primary).map(([fieldName]) => fieldName),
|
|
6566
6779
|
strict: true
|
|
6567
6780
|
};
|
|
6568
6781
|
return {
|
|
@@ -6578,18 +6791,18 @@ function getQueryFilterSchemaFromTable(table, tableName) {
|
|
|
6578
6791
|
type: "object",
|
|
6579
6792
|
properties: {
|
|
6580
6793
|
...Object.fromEntries(
|
|
6581
|
-
Object.entries(table.fields).map((field) => {
|
|
6794
|
+
Object.entries(table.fields).map(([fieldName, field]) => {
|
|
6582
6795
|
return [
|
|
6583
|
-
|
|
6796
|
+
fieldName,
|
|
6584
6797
|
{
|
|
6585
6798
|
value: {
|
|
6586
|
-
type: tableFieldTypeToSchemaType(field
|
|
6587
|
-
description: `Inferred from field '${
|
|
6799
|
+
type: tableFieldTypeToSchemaType(field.type),
|
|
6800
|
+
description: `Inferred from field '${fieldName}' of type [${field.type}] on table ${tableName}.`
|
|
6588
6801
|
},
|
|
6589
6802
|
in: {
|
|
6590
6803
|
type: "array",
|
|
6591
6804
|
items: {
|
|
6592
|
-
type: tableFieldTypeToSchemaType(field
|
|
6805
|
+
type: tableFieldTypeToSchemaType(field.type)
|
|
6593
6806
|
}
|
|
6594
6807
|
}
|
|
6595
6808
|
}
|
|
@@ -6598,7 +6811,7 @@ function getQueryFilterSchemaFromTable(table, tableName) {
|
|
|
6598
6811
|
)
|
|
6599
6812
|
},
|
|
6600
6813
|
strict: true,
|
|
6601
|
-
description: `Inferred from table '${tableName}' on
|
|
6814
|
+
description: `Inferred from table '${tableName}' on postgres actor table contract.`
|
|
6602
6815
|
};
|
|
6603
6816
|
}
|
|
6604
6817
|
function getQueryFieldsSchemaFromTable(table, tableName) {
|
|
@@ -6610,106 +6823,100 @@ function getQueryFieldsSchemaFromTable(table, tableName) {
|
|
|
6610
6823
|
oneOf: Object.keys(table.fields)
|
|
6611
6824
|
}
|
|
6612
6825
|
},
|
|
6613
|
-
description: `Inferred from table '${tableName}'
|
|
6826
|
+
description: `Inferred field projection from table '${tableName}'.`
|
|
6614
6827
|
};
|
|
6615
6828
|
}
|
|
6616
|
-
function
|
|
6829
|
+
function getQueryModeSchema() {
|
|
6617
6830
|
return {
|
|
6618
|
-
type: "
|
|
6619
|
-
|
|
6620
|
-
|
|
6621
|
-
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
|
|
6629
|
-
|
|
6630
|
-
|
|
6631
|
-
|
|
6632
|
-
|
|
6633
|
-
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
|
|
6638
|
-
|
|
6639
|
-
|
|
6640
|
-
|
|
6641
|
-
|
|
6642
|
-
|
|
6643
|
-
|
|
6644
|
-
|
|
6645
|
-
|
|
6646
|
-
|
|
6647
|
-
|
|
6648
|
-
|
|
6649
|
-
|
|
6650
|
-
|
|
6651
|
-
},
|
|
6652
|
-
required: ["on", "fields"],
|
|
6653
|
-
strict: true
|
|
6654
|
-
}
|
|
6655
|
-
];
|
|
6656
|
-
})
|
|
6657
|
-
)
|
|
6831
|
+
type: "string",
|
|
6832
|
+
constraints: {
|
|
6833
|
+
oneOf: ["rows", "count", "exists", "one", "aggregate"]
|
|
6834
|
+
}
|
|
6835
|
+
};
|
|
6836
|
+
}
|
|
6837
|
+
function getQueryAggregatesSchemaFromTable(table, tableName) {
|
|
6838
|
+
return {
|
|
6839
|
+
type: "array",
|
|
6840
|
+
items: {
|
|
6841
|
+
type: "object",
|
|
6842
|
+
properties: {
|
|
6843
|
+
fn: {
|
|
6844
|
+
type: "string",
|
|
6845
|
+
constraints: {
|
|
6846
|
+
oneOf: ["count", "sum", "avg", "min", "max"]
|
|
6847
|
+
}
|
|
6848
|
+
},
|
|
6849
|
+
field: {
|
|
6850
|
+
type: "string",
|
|
6851
|
+
constraints: {
|
|
6852
|
+
oneOf: Object.keys(table.fields)
|
|
6853
|
+
}
|
|
6854
|
+
},
|
|
6855
|
+
as: {
|
|
6856
|
+
type: "string"
|
|
6857
|
+
},
|
|
6858
|
+
distinct: {
|
|
6859
|
+
type: "boolean"
|
|
6860
|
+
}
|
|
6861
|
+
},
|
|
6862
|
+
required: ["fn"],
|
|
6863
|
+
strict: true
|
|
6658
6864
|
},
|
|
6659
|
-
|
|
6660
|
-
description: `Inferred from table '${tableName}' on database service ${CadenzaService.serviceRegistry?.serviceName ?? "unknown-service"}.`
|
|
6865
|
+
description: `Aggregate definitions inferred from table '${tableName}'.`
|
|
6661
6866
|
};
|
|
6662
6867
|
}
|
|
6663
|
-
function
|
|
6868
|
+
function getQueryGroupBySchemaFromTable(table, tableName) {
|
|
6664
6869
|
return {
|
|
6665
|
-
type: "
|
|
6666
|
-
|
|
6667
|
-
|
|
6668
|
-
|
|
6669
|
-
|
|
6670
|
-
|
|
6671
|
-
{
|
|
6672
|
-
type: "string",
|
|
6673
|
-
constraints: {
|
|
6674
|
-
oneOf: ["asc", "desc"]
|
|
6675
|
-
}
|
|
6676
|
-
}
|
|
6677
|
-
];
|
|
6678
|
-
})
|
|
6679
|
-
)
|
|
6870
|
+
type: "array",
|
|
6871
|
+
items: {
|
|
6872
|
+
type: "string",
|
|
6873
|
+
constraints: {
|
|
6874
|
+
oneOf: Object.keys(table.fields)
|
|
6875
|
+
}
|
|
6680
6876
|
},
|
|
6681
|
-
|
|
6682
|
-
|
|
6877
|
+
description: `Group by fields inferred from table '${tableName}'.`
|
|
6878
|
+
};
|
|
6879
|
+
}
|
|
6880
|
+
function getQueryJoinsSchemaFromTable(_table, tableName) {
|
|
6881
|
+
return {
|
|
6882
|
+
type: "object",
|
|
6883
|
+
description: `Join definitions for table '${tableName}'.`
|
|
6884
|
+
};
|
|
6885
|
+
}
|
|
6886
|
+
function getQuerySortSchemaFromTable(_table, tableName) {
|
|
6887
|
+
return {
|
|
6888
|
+
type: "object",
|
|
6889
|
+
strict: false,
|
|
6890
|
+
description: `Sort definition for table '${tableName}'. Keys are validated at runtime against allowlists and aggregate aliases.`
|
|
6683
6891
|
};
|
|
6684
6892
|
}
|
|
6685
6893
|
function getQueryLimitSchemaFromTable() {
|
|
6686
6894
|
return {
|
|
6687
6895
|
type: "number",
|
|
6688
6896
|
constraints: {
|
|
6689
|
-
min:
|
|
6690
|
-
|
|
6691
|
-
|
|
6897
|
+
min: 0,
|
|
6898
|
+
max: 1e3
|
|
6899
|
+
}
|
|
6692
6900
|
};
|
|
6693
6901
|
}
|
|
6694
6902
|
function getQueryOffsetSchemaFromTable() {
|
|
6695
6903
|
return {
|
|
6696
6904
|
type: "number",
|
|
6697
6905
|
constraints: {
|
|
6698
|
-
min: 0
|
|
6699
|
-
|
|
6700
|
-
|
|
6906
|
+
min: 0,
|
|
6907
|
+
max: 1e6
|
|
6908
|
+
}
|
|
6701
6909
|
};
|
|
6702
6910
|
}
|
|
6703
|
-
function
|
|
6911
|
+
function getQueryBatchSchemaFromTable() {
|
|
6704
6912
|
return {
|
|
6705
|
-
type: "boolean"
|
|
6706
|
-
description: "Whether to run the query in a transaction"
|
|
6913
|
+
type: "boolean"
|
|
6707
6914
|
};
|
|
6708
6915
|
}
|
|
6709
|
-
function
|
|
6916
|
+
function getTransactionSchema() {
|
|
6710
6917
|
return {
|
|
6711
6918
|
type: "boolean",
|
|
6712
|
-
description: "
|
|
6919
|
+
description: "Execute the operation in a transaction."
|
|
6713
6920
|
};
|
|
6714
6921
|
}
|
|
6715
6922
|
function getQueryOnConflictSchemaFromTable(table, tableName) {
|
|
@@ -6735,55 +6942,43 @@ function getQueryOnConflictSchemaFromTable(table, tableName) {
|
|
|
6735
6942
|
}
|
|
6736
6943
|
},
|
|
6737
6944
|
set: {
|
|
6738
|
-
type: "object"
|
|
6739
|
-
properties: {
|
|
6740
|
-
...Object.fromEntries(
|
|
6741
|
-
Object.entries(table.fields).map((field) => {
|
|
6742
|
-
return [
|
|
6743
|
-
field[0],
|
|
6744
|
-
{
|
|
6745
|
-
type: tableFieldTypeToSchemaType(field[1].type),
|
|
6746
|
-
description: `Inferred from field '${field[0]}' of type [${field[1].type}] on table ${tableName}.`
|
|
6747
|
-
}
|
|
6748
|
-
];
|
|
6749
|
-
})
|
|
6750
|
-
)
|
|
6751
|
-
}
|
|
6945
|
+
type: "object"
|
|
6752
6946
|
},
|
|
6753
6947
|
where: {
|
|
6754
6948
|
type: "string"
|
|
6755
6949
|
}
|
|
6756
|
-
}
|
|
6757
|
-
required: ["do"]
|
|
6950
|
+
}
|
|
6758
6951
|
}
|
|
6759
6952
|
},
|
|
6760
|
-
|
|
6761
|
-
|
|
6953
|
+
strict: true,
|
|
6954
|
+
description: `Conflict strategy for inserts on table '${tableName}'.`
|
|
6762
6955
|
};
|
|
6763
6956
|
}
|
|
6764
6957
|
function tableFieldTypeToSchemaType(type) {
|
|
6765
6958
|
switch (type) {
|
|
6766
6959
|
case "varchar":
|
|
6767
6960
|
case "text":
|
|
6768
|
-
case "jsonb":
|
|
6769
6961
|
case "uuid":
|
|
6962
|
+
case "timestamp":
|
|
6770
6963
|
case "date":
|
|
6771
6964
|
case "geo_point":
|
|
6772
|
-
case "bytea":
|
|
6773
6965
|
return "string";
|
|
6774
6966
|
case "int":
|
|
6775
6967
|
case "bigint":
|
|
6776
6968
|
case "decimal":
|
|
6777
|
-
case "timestamp":
|
|
6778
6969
|
return "number";
|
|
6779
6970
|
case "boolean":
|
|
6780
6971
|
return "boolean";
|
|
6781
6972
|
case "array":
|
|
6782
6973
|
return "array";
|
|
6783
6974
|
case "object":
|
|
6975
|
+
case "jsonb":
|
|
6784
6976
|
return "object";
|
|
6977
|
+
case "bytea":
|
|
6978
|
+
return "string";
|
|
6979
|
+
default:
|
|
6980
|
+
return "any";
|
|
6785
6981
|
}
|
|
6786
|
-
return "any";
|
|
6787
6982
|
}
|
|
6788
6983
|
|
|
6789
6984
|
// src/Cadenza.ts
|
|
@@ -8359,16 +8554,16 @@ var CadenzaService = class {
|
|
|
8359
8554
|
this.createCadenzaService(serviceName, description, options);
|
|
8360
8555
|
}
|
|
8361
8556
|
/**
|
|
8362
|
-
* Creates and initializes a database service
|
|
8363
|
-
* This
|
|
8557
|
+
* Creates and initializes a PostgresActor-backed database service.
|
|
8558
|
+
* This is the canonical API for schema-driven postgres setup in cadenza-service.
|
|
8364
8559
|
*
|
|
8365
|
-
* @param {string} name -
|
|
8366
|
-
* @param {DatabaseSchemaDefinition} schema -
|
|
8367
|
-
* @param {string} [description=""] -
|
|
8368
|
-
* @param {ServerOptions & DatabaseOptions} [options={}] -
|
|
8369
|
-
* @return {void}
|
|
8560
|
+
* @param {string} name - Logical actor/service name.
|
|
8561
|
+
* @param {DatabaseSchemaDefinition} schema - Database schema definition.
|
|
8562
|
+
* @param {string} [description=""] - Optional human-readable description.
|
|
8563
|
+
* @param {ServerOptions & DatabaseOptions} [options={}] - Server/database runtime options.
|
|
8564
|
+
* @return {void}
|
|
8370
8565
|
*/
|
|
8371
|
-
static
|
|
8566
|
+
static createPostgresActor(name, schema, description = "", options = {}) {
|
|
8372
8567
|
if (isBrowser) {
|
|
8373
8568
|
console.warn(
|
|
8374
8569
|
"Database service creation is not supported in the browser. Use the CadenzaDB service instead."
|
|
@@ -8378,7 +8573,7 @@ var CadenzaService = class {
|
|
|
8378
8573
|
if (this.serviceCreated) return;
|
|
8379
8574
|
this.bootstrap();
|
|
8380
8575
|
this.serviceRegistry.serviceName = name;
|
|
8381
|
-
DatabaseController.instance;
|
|
8576
|
+
const databaseController = DatabaseController.instance;
|
|
8382
8577
|
options = {
|
|
8383
8578
|
loadBalance: true,
|
|
8384
8579
|
useSocket: true,
|
|
@@ -8399,14 +8594,23 @@ var CadenzaService = class {
|
|
|
8399
8594
|
isDatabase: true,
|
|
8400
8595
|
...options
|
|
8401
8596
|
};
|
|
8402
|
-
|
|
8597
|
+
const registration = databaseController.createPostgresActor(
|
|
8598
|
+
name,
|
|
8599
|
+
schema,
|
|
8600
|
+
options
|
|
8601
|
+
);
|
|
8602
|
+
console.log("Creating PostgresActor", {
|
|
8603
|
+
serviceName: name,
|
|
8604
|
+
actorName: registration.actorName,
|
|
8605
|
+
options
|
|
8606
|
+
});
|
|
8403
8607
|
this.emit("meta.database_init_requested", {
|
|
8404
8608
|
schema,
|
|
8405
8609
|
databaseName: options.databaseName,
|
|
8406
8610
|
options
|
|
8407
8611
|
});
|
|
8408
8612
|
this.createMetaTask("Set database connection", () => {
|
|
8409
|
-
this.createMetaTask("Insert database service", (_, emit) => {
|
|
8613
|
+
this.createMetaTask("Insert database service bridge", (_, emit) => {
|
|
8410
8614
|
emit("global.meta.created_database_service", {
|
|
8411
8615
|
data: {
|
|
8412
8616
|
service_name: name,
|
|
@@ -8417,12 +8621,33 @@ var CadenzaService = class {
|
|
|
8417
8621
|
});
|
|
8418
8622
|
this.log("Database service created", {
|
|
8419
8623
|
name,
|
|
8420
|
-
isMeta: options.isMeta
|
|
8624
|
+
isMeta: options.isMeta,
|
|
8625
|
+
actorName: registration.actorName
|
|
8421
8626
|
});
|
|
8422
8627
|
}).doOn("meta.service_registry.service_inserted");
|
|
8423
8628
|
this.createCadenzaService(name, description, options);
|
|
8424
8629
|
}).doOn("meta.database.setup_done");
|
|
8425
8630
|
}
|
|
8631
|
+
/**
|
|
8632
|
+
* Creates a meta PostgresActor service.
|
|
8633
|
+
*
|
|
8634
|
+
* @param {string} name - Logical actor/service name.
|
|
8635
|
+
* @param {DatabaseSchemaDefinition} schema - Database schema definition.
|
|
8636
|
+
* @param {string} [description=""] - Optional description.
|
|
8637
|
+
* @param {ServerOptions & DatabaseOptions} [options={}] - Optional server/database options.
|
|
8638
|
+
* @return {void}
|
|
8639
|
+
*/
|
|
8640
|
+
static createMetaPostgresActor(name, schema, description = "", options = {}) {
|
|
8641
|
+
this.bootstrap();
|
|
8642
|
+
options.isMeta = true;
|
|
8643
|
+
this.createPostgresActor(name, schema, description, options);
|
|
8644
|
+
}
|
|
8645
|
+
/**
|
|
8646
|
+
* Legacy compatibility wrapper. Prefer {@link createPostgresActor}.
|
|
8647
|
+
*/
|
|
8648
|
+
static createDatabaseService(name, schema, description = "", options = {}) {
|
|
8649
|
+
this.createPostgresActor(name, schema, description, options);
|
|
8650
|
+
}
|
|
8426
8651
|
/**
|
|
8427
8652
|
* Creates a meta database service with the specified configuration.
|
|
8428
8653
|
*
|
|
@@ -8433,9 +8658,7 @@ var CadenzaService = class {
|
|
|
8433
8658
|
* @return {void} - This method does not return a value.
|
|
8434
8659
|
*/
|
|
8435
8660
|
static createMetaDatabaseService(name, schema, description = "", options = {}) {
|
|
8436
|
-
this.
|
|
8437
|
-
options.isMeta = true;
|
|
8438
|
-
this.createDatabaseService(name, schema, description, options);
|
|
8661
|
+
this.createMetaPostgresActor(name, schema, description, options);
|
|
8439
8662
|
}
|
|
8440
8663
|
static createActor(spec, options = {}) {
|
|
8441
8664
|
this.bootstrap();
|