plugin-data-source-postgres 0.0.0-stage → 2.0.1
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 +9 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/constants.js +45 -0
- package/dist/externalVersion.js +29 -0
- package/dist/locale/en-US.json +141 -0
- package/dist/locale/zh-CN.json +141 -0
- package/dist/server/collections/adjacency-list-repository.js +340 -0
- package/dist/server/collections/index.js +45 -0
- package/dist/server/collections/sql-collection.js +84 -0
- package/dist/server/collections/sql-model.js +149 -0
- package/dist/server/collections/tree-collection.js +118 -0
- package/dist/server/hooks/field-hooks.js +412 -0
- package/dist/server/index.js +38 -0
- package/dist/server/plugin.js +1273 -0
- package/dist/server/postgres-collection-manager.js +868 -0
- package/dist/server/postgres-datasource.js +361 -0
- package/dist/server/utils/sql-validator.js +253 -0
- package/dist/server/utils/validation-error.js +59 -0
- package/package.json +51 -4
- package/server.js +1 -0
- package/src/client/AddCollectionAction.tsx +307 -0
- package/src/client/ConfigurationForm.tsx +203 -0
- package/src/client/PostgresCollectionTemplate.tsx +109 -0
- package/src/client/__tests__/client-v1.test.tsx +265 -0
- package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
- package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
- package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
- package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
- package/src/client/collection-templates/base-template-helper.ts +62 -0
- package/src/client/collection-templates/field-interfaces-config.ts +73 -0
- package/src/client/collection-templates/index.ts +19 -0
- package/src/client/index.tsx +69 -0
- package/src/client-v2/PostgresAddCollection.tsx +422 -0
- package/src/client-v2/PostgresConfigForm.tsx +178 -0
- package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
- package/src/client-v2/__tests__/plugin.test.tsx +372 -0
- package/src/client-v2/collection-options.ts +22 -0
- package/src/client-v2/index.tsx +10 -0
- package/src/client-v2/plugin.tsx +71 -0
- package/src/constants.ts +20 -0
- package/src/locale/en-US.json +141 -0
- package/src/locale/zh-CN.json +141 -0
- package/src/server/__tests__/field-hooks.test.ts +357 -0
- package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
- package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
- package/src/server/__tests__/sql-model.test.ts +159 -0
- package/src/server/__tests__/sql-validator.test.ts +126 -0
- package/src/server/collections/adjacency-list-repository.ts +378 -0
- package/src/server/collections/index.ts +19 -0
- package/src/server/collections/sql-collection.ts +66 -0
- package/src/server/collections/sql-model.ts +158 -0
- package/src/server/collections/tree-collection.ts +102 -0
- package/src/server/hooks/field-hooks.ts +548 -0
- package/src/server/index.ts +13 -0
- package/src/server/plugin.ts +1499 -0
- package/src/server/postgres-collection-manager.ts +1027 -0
- package/src/server/postgres-datasource.ts +410 -0
- package/src/server/utils/sql-validator.ts +258 -0
- package/src/server/utils/validation-error.ts +38 -0
|
@@ -0,0 +1,1273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
var __defProp = Object.defineProperty;
|
|
11
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
12
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
13
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
14
|
+
var __export = (target, all) => {
|
|
15
|
+
for (var name in all)
|
|
16
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
+
};
|
|
18
|
+
var __copyProps = (to, from, except, desc) => {
|
|
19
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
20
|
+
for (let key of __getOwnPropNames(from))
|
|
21
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
22
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
23
|
+
}
|
|
24
|
+
return to;
|
|
25
|
+
};
|
|
26
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
|
+
var plugin_exports = {};
|
|
28
|
+
__export(plugin_exports, {
|
|
29
|
+
PluginDataSourcePostgresServer: () => PluginDataSourcePostgresServer,
|
|
30
|
+
default: () => plugin_default
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(plugin_exports);
|
|
33
|
+
var import_server = require("@nocobase/server");
|
|
34
|
+
var import_utils = require("@nocobase/utils");
|
|
35
|
+
var import_lodash = require("lodash");
|
|
36
|
+
var import_constants = require("../constants");
|
|
37
|
+
var import_sql_collection = require("./collections/sql-collection");
|
|
38
|
+
var import_tree_collection = require("./collections/tree-collection");
|
|
39
|
+
var import_field_hooks = require("./hooks/field-hooks");
|
|
40
|
+
var import_postgres_collection_manager = require("./postgres-collection-manager");
|
|
41
|
+
var import_postgres_datasource = require("./postgres-datasource");
|
|
42
|
+
var import_sql_validator = require("./utils/sql-validator");
|
|
43
|
+
var import_validation_error = require("./utils/validation-error");
|
|
44
|
+
const FIELD_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "apply", "destroy"]);
|
|
45
|
+
const WRITE_ACTIONS = /* @__PURE__ */ new Set([
|
|
46
|
+
"create",
|
|
47
|
+
"firstOrCreate",
|
|
48
|
+
"updateOrCreate",
|
|
49
|
+
"update",
|
|
50
|
+
"destroy",
|
|
51
|
+
"destroyMany",
|
|
52
|
+
"updateMany",
|
|
53
|
+
"add",
|
|
54
|
+
"remove",
|
|
55
|
+
"set",
|
|
56
|
+
"toggle",
|
|
57
|
+
"move",
|
|
58
|
+
"importXlsx"
|
|
59
|
+
]);
|
|
60
|
+
const PRESET_FIELDS = {
|
|
61
|
+
id: { name: "id", type: "bigInt", interface: "id", primaryKey: true, autoIncrement: true, allowNull: false },
|
|
62
|
+
createdAt: { name: "createdAt", type: "date", interface: "createdAt", field: "createdAt" },
|
|
63
|
+
updatedAt: { name: "updatedAt", type: "date", interface: "updatedAt", field: "updatedAt" }
|
|
64
|
+
};
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
const UNRESOLVED_TEMPLATE_RE = /\{\{[\s\S]*\}\}/;
|
|
69
|
+
const NEGATED_ARRAY_OPERATORS = /* @__PURE__ */ new Set([
|
|
70
|
+
"$ne",
|
|
71
|
+
"$notIn",
|
|
72
|
+
"$notIncludes",
|
|
73
|
+
"$notStartsWith",
|
|
74
|
+
"$notEndWith",
|
|
75
|
+
"$empty",
|
|
76
|
+
"$noneOf"
|
|
77
|
+
]);
|
|
78
|
+
const KNOWN_FILTER_OPERATORS = /* @__PURE__ */ new Set([
|
|
79
|
+
"$eq",
|
|
80
|
+
"$ne",
|
|
81
|
+
"$in",
|
|
82
|
+
"$notIn",
|
|
83
|
+
"$includes",
|
|
84
|
+
"$notIncludes",
|
|
85
|
+
"$startsWith",
|
|
86
|
+
"$notStartsWith",
|
|
87
|
+
"$endWith",
|
|
88
|
+
"$notEndWith",
|
|
89
|
+
"$empty",
|
|
90
|
+
"$notEmpty",
|
|
91
|
+
"$isFalsy",
|
|
92
|
+
"$isTruly",
|
|
93
|
+
"$gt",
|
|
94
|
+
"$gte",
|
|
95
|
+
"$lt",
|
|
96
|
+
"$lte",
|
|
97
|
+
"$match",
|
|
98
|
+
"$notMatch",
|
|
99
|
+
"$anyOf",
|
|
100
|
+
"$noneOf",
|
|
101
|
+
"$exists",
|
|
102
|
+
"$notExists"
|
|
103
|
+
]);
|
|
104
|
+
const LOGICAL_OPERATORS = /* @__PURE__ */ new Set(["$and", "$or", "$not"]);
|
|
105
|
+
function containsUnresolvedTemplate(value) {
|
|
106
|
+
if (typeof value === "string") return UNRESOLVED_TEMPLATE_RE.test(value);
|
|
107
|
+
if (Array.isArray(value)) return value.some((item) => containsUnresolvedTemplate(item));
|
|
108
|
+
if (isRecord(value)) return Object.values(value).some((item) => containsUnresolvedTemplate(item));
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
function compareOrdered(actual, operand) {
|
|
112
|
+
if (typeof actual === "number" && typeof operand === "number" && Number.isFinite(actual) && Number.isFinite(operand)) {
|
|
113
|
+
return actual === operand ? 0 : actual < operand ? -1 : 1;
|
|
114
|
+
}
|
|
115
|
+
if (typeof actual === "string" && typeof operand === "string") {
|
|
116
|
+
return actual === operand ? 0 : actual < operand ? -1 : 1;
|
|
117
|
+
}
|
|
118
|
+
if (actual instanceof Date && operand instanceof Date) {
|
|
119
|
+
const left = actual.getTime();
|
|
120
|
+
const right = operand.getTime();
|
|
121
|
+
if (!Number.isFinite(left) || !Number.isFinite(right)) return null;
|
|
122
|
+
return left === right ? 0 : left < right ? -1 : 1;
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
function isCaseInsensitiveEqualityDialect(dialect) {
|
|
127
|
+
return dialect === "mysql" || dialect === "mariadb";
|
|
128
|
+
}
|
|
129
|
+
function valuesEqual(left, right, metadataDialect) {
|
|
130
|
+
if (isCaseInsensitiveEqualityDialect(metadataDialect) && typeof left === "string" && typeof right === "string") {
|
|
131
|
+
return left.toLowerCase() === right.toLowerCase();
|
|
132
|
+
}
|
|
133
|
+
return (0, import_lodash.isEqual)(left, right);
|
|
134
|
+
}
|
|
135
|
+
function coerceLikeActual(actual, metadataDialect) {
|
|
136
|
+
if (typeof actual === "string") return actual;
|
|
137
|
+
if ((metadataDialect === "postgres" || metadataDialect === "mysql" || metadataDialect === "mariadb" || metadataDialect === "sqlite") && (typeof actual === "number" || typeof actual === "boolean")) {
|
|
138
|
+
return String(actual);
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
function foldLikeCase(text, metadataDialect) {
|
|
143
|
+
return metadataDialect === "sqlite" ? text.replace(/[A-Z]/g, (ch) => ch.toLowerCase()) : text.toLowerCase();
|
|
144
|
+
}
|
|
145
|
+
function escapeRegExpChar(ch) {
|
|
146
|
+
return /[\\^$.*+?()[\]{}|]/.test(ch) ? `\\${ch}` : ch;
|
|
147
|
+
}
|
|
148
|
+
function buildCoreLikePattern(operand, metadataDialect, mode) {
|
|
149
|
+
const escaped = operand.replace(/[_%]/g, "\\$&");
|
|
150
|
+
if (mode === "startsWith") return `${escaped}%`;
|
|
151
|
+
if (mode === "endsWith") return `%${escaped}`;
|
|
152
|
+
return `%${escaped}%`;
|
|
153
|
+
}
|
|
154
|
+
function compileSqlLikePattern(patternFolded, metadataDialect) {
|
|
155
|
+
const escapeChar = metadataDialect === "sqlite" ? null : "\\";
|
|
156
|
+
const chars = Array.from(patternFolded);
|
|
157
|
+
let source = "^";
|
|
158
|
+
let prevWildcardMany = false;
|
|
159
|
+
for (let idx = 0; idx < chars.length; idx += 1) {
|
|
160
|
+
const ch = chars[idx];
|
|
161
|
+
if (escapeChar !== null && ch === escapeChar) {
|
|
162
|
+
if (idx + 1 >= chars.length) {
|
|
163
|
+
if (metadataDialect === "postgres") return null;
|
|
164
|
+
source += "\\\\";
|
|
165
|
+
prevWildcardMany = false;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
idx += 1;
|
|
169
|
+
source += escapeRegExpChar(chars[idx]);
|
|
170
|
+
prevWildcardMany = false;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (ch === "%") {
|
|
174
|
+
if (!prevWildcardMany) {
|
|
175
|
+
source += ".*";
|
|
176
|
+
prevWildcardMany = true;
|
|
177
|
+
}
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
prevWildcardMany = false;
|
|
181
|
+
source += ch === "_" ? "." : escapeRegExpChar(ch);
|
|
182
|
+
}
|
|
183
|
+
source += "$";
|
|
184
|
+
return new RegExp(source, "su");
|
|
185
|
+
}
|
|
186
|
+
function matchLikeValue(actualFolded, rawOperand, metadataDialect, mode) {
|
|
187
|
+
if (metadataDialect === "mssql") {
|
|
188
|
+
const foldedOperand = foldLikeCase(rawOperand, metadataDialect);
|
|
189
|
+
if (mode === "startsWith") return actualFolded.startsWith(foldedOperand);
|
|
190
|
+
if (mode === "endsWith") return actualFolded.endsWith(foldedOperand);
|
|
191
|
+
return actualFolded.includes(foldedOperand);
|
|
192
|
+
}
|
|
193
|
+
const patternFolded = foldLikeCase(buildCoreLikePattern(rawOperand, metadataDialect, mode), metadataDialect);
|
|
194
|
+
const compiled = compileSqlLikePattern(patternFolded, metadataDialect);
|
|
195
|
+
return compiled !== null && compiled.test(actualFolded);
|
|
196
|
+
}
|
|
197
|
+
function evaluateLikeOperator(actual, operand, metadataDialect, mode, negated) {
|
|
198
|
+
if (mode === "includes" && operand === null) {
|
|
199
|
+
return negated ? actual !== null && actual !== void 0 : actual === null || actual === void 0;
|
|
200
|
+
}
|
|
201
|
+
const actualText = coerceLikeActual(actual, metadataDialect);
|
|
202
|
+
if (actualText === null) return false;
|
|
203
|
+
const actualFolded = foldLikeCase(actualText, metadataDialect);
|
|
204
|
+
if (typeof operand === "string") {
|
|
205
|
+
const matched = matchLikeValue(actualFolded, operand, metadataDialect, mode);
|
|
206
|
+
return negated ? !matched : matched;
|
|
207
|
+
}
|
|
208
|
+
if (Array.isArray(operand) && operand.every((item) => typeof item === "string")) {
|
|
209
|
+
if (negated) {
|
|
210
|
+
return operand.every((item) => !matchLikeValue(actualFolded, item, metadataDialect, mode));
|
|
211
|
+
}
|
|
212
|
+
return operand.some((item) => matchLikeValue(actualFolded, item, metadataDialect, mode));
|
|
213
|
+
}
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
function evaluateSingleOperator(actual, operator, operand, metadataDialect = "postgres") {
|
|
217
|
+
if (!KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand)) return false;
|
|
218
|
+
switch (operator) {
|
|
219
|
+
case "$eq":
|
|
220
|
+
if (operand === void 0) return true;
|
|
221
|
+
if (operand === null) return actual === null || actual === void 0;
|
|
222
|
+
if (Array.isArray(operand) && !Array.isArray(actual)) {
|
|
223
|
+
return actual !== null && actual !== void 0 && operand.some((item) => item !== null && item !== void 0 && valuesEqual(actual, item, metadataDialect));
|
|
224
|
+
}
|
|
225
|
+
return valuesEqual(actual, operand, metadataDialect);
|
|
226
|
+
case "$ne":
|
|
227
|
+
if (operand === null) return actual !== null && actual !== void 0;
|
|
228
|
+
if (Array.isArray(operand) && !Array.isArray(actual)) {
|
|
229
|
+
if (operand.length === 0) return true;
|
|
230
|
+
if (actual === null || actual === void 0) return false;
|
|
231
|
+
if (operand.some((item) => item === null || item === void 0)) return false;
|
|
232
|
+
return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
|
|
233
|
+
}
|
|
234
|
+
return !Array.isArray(actual) && (actual === null || actual === void 0) ? true : !valuesEqual(actual, operand, metadataDialect);
|
|
235
|
+
case "$in": {
|
|
236
|
+
if (operand === null || operand === void 0) return false;
|
|
237
|
+
const list = Array.isArray(operand) ? operand : [operand];
|
|
238
|
+
return actual !== null && actual !== void 0 && list.some((item) => item !== null && item !== void 0 && valuesEqual(actual, item, metadataDialect));
|
|
239
|
+
}
|
|
240
|
+
case "$notIn":
|
|
241
|
+
if (!Array.isArray(operand)) return false;
|
|
242
|
+
if (actual === null || actual === void 0 || operand.length === 0) return true;
|
|
243
|
+
if (operand.some((item) => item === null || item === void 0)) return false;
|
|
244
|
+
return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
|
|
245
|
+
case "$exists": {
|
|
246
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
247
|
+
const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== void 0;
|
|
248
|
+
return operand === false ? !exists : exists;
|
|
249
|
+
}
|
|
250
|
+
case "$notExists": {
|
|
251
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
252
|
+
const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== void 0;
|
|
253
|
+
return operand === false ? exists : !exists;
|
|
254
|
+
}
|
|
255
|
+
case "$includes":
|
|
256
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "includes", false);
|
|
257
|
+
case "$notIncludes":
|
|
258
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "includes", true);
|
|
259
|
+
case "$startsWith":
|
|
260
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "startsWith", false);
|
|
261
|
+
case "$notStartsWith":
|
|
262
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "startsWith", true);
|
|
263
|
+
case "$endWith":
|
|
264
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "endsWith", false);
|
|
265
|
+
case "$notEndWith":
|
|
266
|
+
return evaluateLikeOperator(actual, operand, metadataDialect, "endsWith", true);
|
|
267
|
+
case "$empty": {
|
|
268
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
269
|
+
const empty = actual === null || actual === void 0 || actual === "" || Array.isArray(actual) && !actual.length;
|
|
270
|
+
return operand === false ? !empty : empty;
|
|
271
|
+
}
|
|
272
|
+
case "$notEmpty": {
|
|
273
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
274
|
+
const empty = actual === null || actual === void 0 || actual === "" || Array.isArray(actual) && !actual.length;
|
|
275
|
+
return operand === false ? empty : !empty;
|
|
276
|
+
}
|
|
277
|
+
case "$isFalsy":
|
|
278
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
279
|
+
return operand === false ? Boolean(actual) : !actual;
|
|
280
|
+
case "$isTruly":
|
|
281
|
+
if (operand !== void 0 && typeof operand !== "boolean") return false;
|
|
282
|
+
return operand === false ? !actual : Boolean(actual);
|
|
283
|
+
case "$gt": {
|
|
284
|
+
const cmp = compareOrdered(actual, operand);
|
|
285
|
+
return cmp !== null && cmp > 0;
|
|
286
|
+
}
|
|
287
|
+
case "$gte": {
|
|
288
|
+
const cmp = compareOrdered(actual, operand);
|
|
289
|
+
return cmp !== null && cmp >= 0;
|
|
290
|
+
}
|
|
291
|
+
case "$lt": {
|
|
292
|
+
const cmp = compareOrdered(actual, operand);
|
|
293
|
+
return cmp !== null && cmp < 0;
|
|
294
|
+
}
|
|
295
|
+
case "$lte": {
|
|
296
|
+
const cmp = compareOrdered(actual, operand);
|
|
297
|
+
return cmp !== null && cmp <= 0;
|
|
298
|
+
}
|
|
299
|
+
case "$anyOf":
|
|
300
|
+
return Array.isArray(actual) && Array.isArray(operand) && actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)));
|
|
301
|
+
case "$noneOf":
|
|
302
|
+
return Array.isArray(actual) && Array.isArray(operand) && !actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)));
|
|
303
|
+
case "$match":
|
|
304
|
+
return Array.isArray(actual) && isRecord(operand) && actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect));
|
|
305
|
+
case "$notMatch":
|
|
306
|
+
return Array.isArray(actual) && isRecord(operand) && !actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect));
|
|
307
|
+
default:
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const ARRAY_LEVEL_OPERATORS = /* @__PURE__ */ new Set([
|
|
312
|
+
"$match",
|
|
313
|
+
"$notMatch",
|
|
314
|
+
"$anyOf",
|
|
315
|
+
"$noneOf",
|
|
316
|
+
"$empty",
|
|
317
|
+
"$notEmpty",
|
|
318
|
+
"$exists",
|
|
319
|
+
"$notExists"
|
|
320
|
+
]);
|
|
321
|
+
const CONTAINER_ARRAY_KEYS = /* @__PURE__ */ new Set(["fields", "indexes"]);
|
|
322
|
+
const MAX_PINNED_FILTER_CONTEXTS = 1e4;
|
|
323
|
+
function evaluateOperatorGroup(target, entries, metadataDialect) {
|
|
324
|
+
if (!entries.length) return true;
|
|
325
|
+
if (entries.some(([operator, operand]) => !KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand))) {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
if (target.traversedArray && entries.every(([operator]) => NEGATED_ARRAY_OPERATORS.has(operator))) {
|
|
329
|
+
return target.values.every(
|
|
330
|
+
(value) => entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect))
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
return target.values.some(
|
|
334
|
+
(value) => entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect))
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
function collectPositiveArrayPrefixes(filter, out, prefix = []) {
|
|
338
|
+
if (!isRecord(filter)) return;
|
|
339
|
+
for (const [rawKey, condition] of Object.entries(filter)) {
|
|
340
|
+
if (rawKey === "$and" || rawKey === "$or") {
|
|
341
|
+
const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
|
|
342
|
+
if (items) {
|
|
343
|
+
for (const item of items) collectPositiveArrayPrefixes(item, out, prefix);
|
|
344
|
+
}
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (rawKey === "$not" || rawKey.startsWith("$")) continue;
|
|
348
|
+
const parts = rawKey.split(".");
|
|
349
|
+
const lastPart = parts[parts.length - 1];
|
|
350
|
+
const hasTrailingOp = parts.length > 1 && lastPart.startsWith("$");
|
|
351
|
+
const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
|
|
352
|
+
if (fieldParts.some((part) => !part || part.startsWith("$"))) continue;
|
|
353
|
+
const fullParts = [...prefix, ...fieldParts];
|
|
354
|
+
let arrayLevelOnly = false;
|
|
355
|
+
if (hasTrailingOp) {
|
|
356
|
+
arrayLevelOnly = ARRAY_LEVEL_OPERATORS.has(lastPart);
|
|
357
|
+
} else if (isRecord(condition)) {
|
|
358
|
+
const keys = Object.keys(condition);
|
|
359
|
+
if (keys.length && keys.every((key) => KNOWN_FILTER_OPERATORS.has(key))) {
|
|
360
|
+
arrayLevelOnly = keys.every((key) => ARRAY_LEVEL_OPERATORS.has(key));
|
|
361
|
+
} else if (keys.length && keys.every((key) => !key.startsWith("$") || LOGICAL_OPERATORS.has(key))) {
|
|
362
|
+
for (let len = 1; len <= fullParts.length; len += 1) {
|
|
363
|
+
out.push(fullParts.slice(0, len));
|
|
364
|
+
}
|
|
365
|
+
collectPositiveArrayPrefixes(condition, out, fullParts);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const maxLen = arrayLevelOnly ? fullParts.length - 1 : fullParts.length;
|
|
370
|
+
for (let len = 1; len <= maxLen; len += 1) {
|
|
371
|
+
out.push(fullParts.slice(0, len));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function readPathWithPins(record, parts, pins, ignoreLeafPin = false) {
|
|
376
|
+
let current = [record];
|
|
377
|
+
let traversedArray = false;
|
|
378
|
+
for (let idx = 0; idx < parts.length; idx += 1) {
|
|
379
|
+
const part = parts[idx];
|
|
380
|
+
const pathSoFar = parts.slice(0, idx + 1).join(".");
|
|
381
|
+
if (!(ignoreLeafPin && idx === parts.length - 1) && pins.has(pathSoFar)) {
|
|
382
|
+
current = [pins.get(pathSoFar)];
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
const next = [];
|
|
386
|
+
for (const item of current) {
|
|
387
|
+
if (Array.isArray(item)) {
|
|
388
|
+
traversedArray = true;
|
|
389
|
+
for (const entry of item) {
|
|
390
|
+
if (isRecord(entry)) {
|
|
391
|
+
if (part in entry) next.push(entry[part]);
|
|
392
|
+
else if (isRecord(entry.options) && part in entry.options) next.push(entry.options[part]);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
} else if (isRecord(item)) {
|
|
396
|
+
if (part in item) {
|
|
397
|
+
next.push(item[part]);
|
|
398
|
+
} else if (isRecord(item.options) && part in item.options) {
|
|
399
|
+
next.push(item.options[part]);
|
|
400
|
+
} else {
|
|
401
|
+
next.push(void 0);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
current = next;
|
|
406
|
+
}
|
|
407
|
+
return { values: current.length ? current : [void 0], traversedArray };
|
|
408
|
+
}
|
|
409
|
+
function expandPinsForPrefixes(record, inheritedPins, candidatePrefixes) {
|
|
410
|
+
const uniquePrefixes = /* @__PURE__ */ new Map();
|
|
411
|
+
for (const parts of candidatePrefixes) {
|
|
412
|
+
const key = parts.join(".");
|
|
413
|
+
if (!inheritedPins.has(key) && !uniquePrefixes.has(key)) {
|
|
414
|
+
uniquePrefixes.set(key, parts);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const sortedPrefixes = [...uniquePrefixes.entries()].sort((a, b) => a[1].length - b[1].length);
|
|
418
|
+
let contexts = [new Map(inheritedPins)];
|
|
419
|
+
for (const [key, parts] of sortedPrefixes) {
|
|
420
|
+
const leafKey = parts[parts.length - 1];
|
|
421
|
+
const nextContexts = [];
|
|
422
|
+
for (const ctxPins of contexts) {
|
|
423
|
+
const rawTarget = readPathWithPins(record, parts, ctxPins, true);
|
|
424
|
+
if (rawTarget.values.length === 1 && Array.isArray(rawTarget.values[0])) {
|
|
425
|
+
const arr = rawTarget.values[0];
|
|
426
|
+
if (CONTAINER_ARRAY_KEYS.has(leafKey) || arr.some((entry) => isRecord(entry))) {
|
|
427
|
+
if (arr.length === 0) {
|
|
428
|
+
const forked = new Map(ctxPins);
|
|
429
|
+
forked.set(key, void 0);
|
|
430
|
+
nextContexts.push(forked);
|
|
431
|
+
} else {
|
|
432
|
+
for (const entry of arr) {
|
|
433
|
+
const forked = new Map(ctxPins);
|
|
434
|
+
forked.set(key, entry);
|
|
435
|
+
nextContexts.push(forked);
|
|
436
|
+
if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
nextContexts.push(ctxPins);
|
|
443
|
+
if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
|
|
444
|
+
}
|
|
445
|
+
contexts = nextContexts;
|
|
446
|
+
}
|
|
447
|
+
return contexts;
|
|
448
|
+
}
|
|
449
|
+
function extractSubPins(pins, prefix) {
|
|
450
|
+
const prefixDot = `${prefix}.`;
|
|
451
|
+
const subPins = /* @__PURE__ */ new Map();
|
|
452
|
+
for (const [key, value] of pins.entries()) {
|
|
453
|
+
if (key.startsWith(prefixDot)) {
|
|
454
|
+
subPins.set(key.slice(prefixDot.length), value);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return subPins;
|
|
458
|
+
}
|
|
459
|
+
function evaluateEntriesWithPins(record, pins, filter, metadataDialect) {
|
|
460
|
+
if (!isRecord(filter)) return false;
|
|
461
|
+
for (const [rawKey, condition] of Object.entries(filter)) {
|
|
462
|
+
if (rawKey === "$and") {
|
|
463
|
+
const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
|
|
464
|
+
if (!items || !items.every((item) => evaluateEntriesWithPins(record, pins, item, metadataDialect))) return false;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (rawKey === "$or") {
|
|
468
|
+
const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
|
|
469
|
+
if (!items || !items.some((item) => matchesScope(record, pins, item, metadataDialect))) return false;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (rawKey === "$not") {
|
|
473
|
+
if (!isRecord(condition) || matchesScope(record, pins, condition, metadataDialect)) return false;
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (rawKey.startsWith("$")) return false;
|
|
477
|
+
const parts = rawKey.split(".");
|
|
478
|
+
const lastPart = parts[parts.length - 1];
|
|
479
|
+
const hasTrailingOp = parts.length > 1 && lastPart.startsWith("$");
|
|
480
|
+
const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
|
|
481
|
+
if (fieldParts.some((part) => !part || part.startsWith("$"))) return false;
|
|
482
|
+
if (hasTrailingOp) {
|
|
483
|
+
const target2 = readPathWithPins(record, fieldParts, pins, ARRAY_LEVEL_OPERATORS.has(lastPart));
|
|
484
|
+
if (!evaluateOperatorGroup(target2, [[lastPart, condition]], metadataDialect)) return false;
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
if (isRecord(condition)) {
|
|
488
|
+
const entries = Object.entries(condition);
|
|
489
|
+
if (!entries.length) continue;
|
|
490
|
+
if (entries.every(([key]) => KNOWN_FILTER_OPERATORS.has(key))) {
|
|
491
|
+
const arrayLevelEntries = entries.filter(([key]) => ARRAY_LEVEL_OPERATORS.has(key));
|
|
492
|
+
const elementEntries = entries.filter(([key]) => !ARRAY_LEVEL_OPERATORS.has(key));
|
|
493
|
+
if (arrayLevelEntries.length) {
|
|
494
|
+
const arrayTarget = readPathWithPins(record, fieldParts, pins, true);
|
|
495
|
+
if (!evaluateOperatorGroup(arrayTarget, arrayLevelEntries, metadataDialect)) return false;
|
|
496
|
+
}
|
|
497
|
+
if (elementEntries.length) {
|
|
498
|
+
const elemTarget = readPathWithPins(record, fieldParts, pins, false);
|
|
499
|
+
if (!evaluateOperatorGroup(elemTarget, elementEntries, metadataDialect)) return false;
|
|
500
|
+
}
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
if (!entries.every(([key]) => !key.startsWith("$") || LOGICAL_OPERATORS.has(key))) return false;
|
|
504
|
+
const fieldPathKey = fieldParts.join(".");
|
|
505
|
+
const subPins = extractSubPins(pins, fieldPathKey);
|
|
506
|
+
if (pins.has(fieldPathKey)) {
|
|
507
|
+
const pinnedVal = pins.get(fieldPathKey);
|
|
508
|
+
if (!isRecord(pinnedVal) || !matchesScope(pinnedVal, subPins, condition, metadataDialect)) return false;
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
const target2 = readPathWithPins(record, fieldParts, pins, false);
|
|
512
|
+
const nestedMatched = target2.values.some((value) => {
|
|
513
|
+
if (Array.isArray(value)) {
|
|
514
|
+
return value.some((entry) => isRecord(entry) && matchesScope(entry, subPins, condition, metadataDialect));
|
|
515
|
+
}
|
|
516
|
+
return isRecord(value) && matchesScope(value, subPins, condition, metadataDialect);
|
|
517
|
+
});
|
|
518
|
+
if (!nestedMatched) return false;
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
const target = readPathWithPins(record, fieldParts, pins, false);
|
|
522
|
+
if (!evaluateOperatorGroup(target, [["$eq", condition]], metadataDialect)) return false;
|
|
523
|
+
}
|
|
524
|
+
return true;
|
|
525
|
+
}
|
|
526
|
+
function matchesScope(record, inheritedPins, filter, metadataDialect) {
|
|
527
|
+
if (!isRecord(filter)) return false;
|
|
528
|
+
const prefixes = [];
|
|
529
|
+
collectPositiveArrayPrefixes(filter, prefixes);
|
|
530
|
+
const expanded = expandPinsForPrefixes(record, inheritedPins, prefixes);
|
|
531
|
+
if (!expanded) return false;
|
|
532
|
+
return expanded.some((pins) => evaluateEntriesWithPins(record, pins, filter, metadataDialect));
|
|
533
|
+
}
|
|
534
|
+
function matchesCollectionFilter(record, filter, metadataDialect = "postgres") {
|
|
535
|
+
return matchesScope(record, /* @__PURE__ */ new Map(), filter, metadataDialect);
|
|
536
|
+
}
|
|
537
|
+
function extractSql(values) {
|
|
538
|
+
if (!values) return void 0;
|
|
539
|
+
if (values.sql !== void 0) return values.sql;
|
|
540
|
+
return isRecord(values.options) ? values.options.sql : void 0;
|
|
541
|
+
}
|
|
542
|
+
function names(value) {
|
|
543
|
+
const values = Array.isArray(value) ? value : [value];
|
|
544
|
+
if (!values.length || values.some((item) => typeof item !== "string" || !item)) {
|
|
545
|
+
throw new import_validation_error.PostgresValidationError("A collection name is required");
|
|
546
|
+
}
|
|
547
|
+
return [...new Set(values)];
|
|
548
|
+
}
|
|
549
|
+
function prepareFields(values) {
|
|
550
|
+
if (!Array.isArray(values.fields)) return;
|
|
551
|
+
const hasStringPresets = values.fields.some((field) => typeof field === "string");
|
|
552
|
+
if (hasStringPresets || values.template === "general" && values.fields.length === 0) {
|
|
553
|
+
const selectedPresets = new Set(values.fields.filter((field) => typeof field === "string"));
|
|
554
|
+
values.autoGenId = selectedPresets.has("id");
|
|
555
|
+
values.createdAt = selectedPresets.has("createdAt");
|
|
556
|
+
values.updatedAt = selectedPresets.has("updatedAt");
|
|
557
|
+
values.timestamps = Boolean(values.createdAt || values.updatedAt);
|
|
558
|
+
} else if (values.createdAt === false && values.updatedAt === false && values.timestamps === void 0) {
|
|
559
|
+
values.timestamps = false;
|
|
560
|
+
}
|
|
561
|
+
const mapped = values.fields.map((field) => {
|
|
562
|
+
if (typeof field !== "string") {
|
|
563
|
+
if (isRecord(field.settings)) {
|
|
564
|
+
if (field.elementType === void 0 && typeof field.settings.elementType === "string") {
|
|
565
|
+
field.elementType = field.settings.elementType;
|
|
566
|
+
}
|
|
567
|
+
if (field.dataType === void 0 && typeof field.settings.dataType === "string") {
|
|
568
|
+
field.dataType = field.settings.dataType;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return (0, import_postgres_collection_manager.applyPostgresArrayDataType)(field);
|
|
572
|
+
}
|
|
573
|
+
const preset = PRESET_FIELDS[field];
|
|
574
|
+
if (!preset) throw new import_validation_error.PostgresValidationError("Unknown preset field {{name}}", { name: field });
|
|
575
|
+
return (0, import_lodash.cloneDeep)(preset);
|
|
576
|
+
});
|
|
577
|
+
const isSql = extractSql(values) !== void 0 || values.template === "sql";
|
|
578
|
+
if (!isSql) {
|
|
579
|
+
if (values.createdAt === true && !mapped.some((field) => field.name === "createdAt")) {
|
|
580
|
+
mapped.push((0, import_lodash.cloneDeep)(PRESET_FIELDS.createdAt));
|
|
581
|
+
}
|
|
582
|
+
if (values.updatedAt === true && !mapped.some((field) => field.name === "updatedAt")) {
|
|
583
|
+
mapped.push((0, import_lodash.cloneDeep)(PRESET_FIELDS.updatedAt));
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
values.fields = mapped;
|
|
587
|
+
}
|
|
588
|
+
async function localizeValidationErrors(ctx, next) {
|
|
589
|
+
var _a, _b, _c, _d, _e;
|
|
590
|
+
try {
|
|
591
|
+
await next();
|
|
592
|
+
} catch (error) {
|
|
593
|
+
if (error instanceof import_validation_error.PostgresValidationError) error.message = (0, import_validation_error.translateError)(ctx, error);
|
|
594
|
+
const params = ((_a = ctx.action) == null ? void 0 : _a.params) || {};
|
|
595
|
+
const postgresConnection = ((_b = ctx.action) == null ? void 0 : _b.resourceName) === "dataSources" && (((_c = params.values) == null ? void 0 : _c.type) === import_constants.DATA_SOURCE_TYPE || ((_e = (_d = ctx.app) == null ? void 0 : _d.dataSourceManager) == null ? void 0 : _e.get(params.filterByTk)) instanceof import_postgres_datasource.PostgresDataSource);
|
|
596
|
+
if (postgresConnection && error instanceof Error && error.message === "Test connection failed: Invalid PostgreSQL port") {
|
|
597
|
+
error.message = (0, import_validation_error.translate)(ctx, "Test connection failed: {{reason}}", {
|
|
598
|
+
reason: (0, import_validation_error.translate)(ctx, "Invalid PostgreSQL port")
|
|
599
|
+
});
|
|
600
|
+
const httpError = error;
|
|
601
|
+
httpError.status = 400;
|
|
602
|
+
httpError.statusCode = 400;
|
|
603
|
+
}
|
|
604
|
+
throw error;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
class PluginDataSourcePostgresServer extends import_server.Plugin {
|
|
608
|
+
selectionSyncs = /* @__PURE__ */ new Map();
|
|
609
|
+
activeSources = /* @__PURE__ */ new Map();
|
|
610
|
+
async closeDataSource(dataSourceKey, expectedSource) {
|
|
611
|
+
var _a, _b;
|
|
612
|
+
const current = this.app.dataSourceManager.get(dataSourceKey);
|
|
613
|
+
const tracked = this.activeSources.get(dataSourceKey);
|
|
614
|
+
const source = expectedSource || (current instanceof import_postgres_datasource.PostgresDataSource ? current : tracked);
|
|
615
|
+
if (!source) return;
|
|
616
|
+
if (tracked === source) {
|
|
617
|
+
this.activeSources.delete(dataSourceKey);
|
|
618
|
+
}
|
|
619
|
+
if (current === source) {
|
|
620
|
+
this.app.dataSourceManager.dataSources.delete(dataSourceKey);
|
|
621
|
+
}
|
|
622
|
+
const replacement = this.app.dataSourceManager.get(dataSourceKey);
|
|
623
|
+
if (replacement instanceof import_postgres_datasource.PostgresDataSource && replacement !== source && replacement.collectionManager.db === source.collectionManager.db) {
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
try {
|
|
627
|
+
await source.close();
|
|
628
|
+
} catch (error) {
|
|
629
|
+
(_b = (_a = this.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `Failed to close PostgreSQL data source "${dataSourceKey}"`, { cause: error });
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
async enqueueSelectionSync(key, task) {
|
|
633
|
+
const previous = this.selectionSyncs.get(key) || Promise.resolve();
|
|
634
|
+
const current = previous.catch(() => void 0).then(task);
|
|
635
|
+
this.selectionSyncs.set(key, current);
|
|
636
|
+
try {
|
|
637
|
+
await current;
|
|
638
|
+
} finally {
|
|
639
|
+
if (this.selectionSyncs.get(key) === current) this.selectionSyncs.delete(key);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
async handleSyncMessage(message) {
|
|
643
|
+
var _a, _b, _c, _d;
|
|
644
|
+
if (!(message == null ? void 0 : message.dataSourceKey)) return;
|
|
645
|
+
const key = message.dataSourceKey;
|
|
646
|
+
if (message.type === "dataSourceRemoved") {
|
|
647
|
+
const existingRecord = await ((_d = (_c = (_b = (_a = this.app.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "dataSources")) == null ? void 0 : _c.findOne) == null ? void 0 : _d.call(_c, { filterByTk: key }));
|
|
648
|
+
if (existingRecord) return;
|
|
649
|
+
await this.closeDataSource(key);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (message.type === "selectionChanged") {
|
|
653
|
+
const refreshTables = Array.isArray(message.refreshTables) ? message.refreshTables.filter((name) => typeof name === "string" && name.length > 0) : [];
|
|
654
|
+
await this.enqueueSelectionSync(key, () => this.reconcileSelection(key, refreshTables));
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (message.type === "tablesLoaded" && Array.isArray(message.tableNames)) {
|
|
658
|
+
const tableNames = message.tableNames;
|
|
659
|
+
await this.enqueueSelectionSync(key, () => this.syncLoadedTables(key, tableNames));
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
const source = this.app.dataSourceManager.get(key);
|
|
663
|
+
if (!(source instanceof import_postgres_datasource.PostgresDataSource)) return;
|
|
664
|
+
if (message.type === "collectionCreated" && message.collectionName) {
|
|
665
|
+
await this.syncCreatedCollection(source, key, message.collectionName);
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
if (message.type === "collectionRemoved" && Array.isArray(message.collectionNames)) {
|
|
669
|
+
for (const name of message.collectionNames) {
|
|
670
|
+
if (typeof name === "string" && source.collectionManager.hasCollection(name)) {
|
|
671
|
+
source.collectionManager.removeCollection(name);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
if (message.type === "fieldRemoved" && message.collectionName && message.fieldName) {
|
|
677
|
+
const collection = source.collectionManager.getCollection(message.collectionName);
|
|
678
|
+
if (collection == null ? void 0 : collection.getField(message.fieldName)) {
|
|
679
|
+
collection.removeField(message.fieldName);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
async syncLoadedTables(dataSourceKey, tableNames) {
|
|
684
|
+
const source = this.app.dataSourceManager.get(dataSourceKey);
|
|
685
|
+
if (!(source instanceof import_postgres_datasource.PostgresDataSource)) return;
|
|
686
|
+
const requested = [
|
|
687
|
+
...new Set(tableNames.filter((name) => typeof name === "string" && name.length > 0))
|
|
688
|
+
];
|
|
689
|
+
if (!requested.length) return;
|
|
690
|
+
const record = await this.app.db.getRepository("dataSources").findOne({ filterByTk: dataSourceKey });
|
|
691
|
+
if (!record) return;
|
|
692
|
+
const storedOptions = typeof record.get === "function" ? record.get("options") || {} : {};
|
|
693
|
+
const selectedFilter = storedOptions.addAllCollections === false && Array.isArray(storedOptions.selectedCollections) ? new Set(storedOptions.selectedCollections.filter((name) => typeof name === "string")) : void 0;
|
|
694
|
+
const allowed = selectedFilter ? requested.filter((name) => selectedFilter.has(name)) : requested;
|
|
695
|
+
if (!allowed.length) return;
|
|
696
|
+
const localData = typeof record.loadLocalData === "function" ? await record.loadLocalData() : {};
|
|
697
|
+
const available = new Set(await source.introspector.getTables());
|
|
698
|
+
const targets = allowed.filter((name) => available.has(name));
|
|
699
|
+
if (!targets.length) return;
|
|
700
|
+
const collections = await source.prepareTables(targets, localData);
|
|
701
|
+
if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
|
|
702
|
+
source.collectionManager.replaceCollections(collections);
|
|
703
|
+
}
|
|
704
|
+
async syncCreatedCollection(source, dataSourceKey, collectionName) {
|
|
705
|
+
const collectionRecord = await this.app.db.getRepository("dataSourcesCollections").findOne({
|
|
706
|
+
filter: { dataSourceKey, name: collectionName }
|
|
707
|
+
});
|
|
708
|
+
if (!collectionRecord) return;
|
|
709
|
+
const fieldRecords = await this.app.db.getRepository("dataSourcesFields").find({
|
|
710
|
+
filter: { dataSourceKey, collectionName }
|
|
711
|
+
});
|
|
712
|
+
const collectionOptions = {
|
|
713
|
+
...collectionRecord.toJSON(),
|
|
714
|
+
fields: fieldRecords.map((field) => field.toJSON())
|
|
715
|
+
};
|
|
716
|
+
if (typeof collectionOptions.sql === "string" && collectionOptions.sql.trim()) {
|
|
717
|
+
const existing2 = source.collectionManager.getCollection(collectionName);
|
|
718
|
+
if (existing2) {
|
|
719
|
+
existing2.updateOptions(collectionOptions);
|
|
720
|
+
} else {
|
|
721
|
+
source.collectionManager.defineCollection({
|
|
722
|
+
...collectionOptions,
|
|
723
|
+
tableName: typeof collectionOptions.tableName === "string" ? collectionOptions.tableName : collectionName,
|
|
724
|
+
introspected: true
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const tableName = typeof collectionOptions.tableName === "string" ? collectionOptions.tableName : collectionName;
|
|
730
|
+
const [prepared] = await source.prepareTables([tableName], { [collectionName]: collectionOptions });
|
|
731
|
+
if (this.app.dataSourceManager.get(dataSourceKey) !== source || !prepared) return;
|
|
732
|
+
const existing = source.collectionManager.getCollection(collectionName);
|
|
733
|
+
if (existing) {
|
|
734
|
+
existing.updateOptions(prepared);
|
|
735
|
+
} else {
|
|
736
|
+
source.collectionManager.defineCollection(prepared);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
async reconcileSelection(dataSourceKey, refreshTables = []) {
|
|
740
|
+
const source = this.app.dataSourceManager.get(dataSourceKey);
|
|
741
|
+
if (!(source instanceof import_postgres_datasource.PostgresDataSource)) return;
|
|
742
|
+
const record = await this.app.db.getRepository("dataSources").findOne({ filterByTk: dataSourceKey });
|
|
743
|
+
if (!record) return;
|
|
744
|
+
const storedOptions = record.get("options") || {};
|
|
745
|
+
if (storedOptions.addAllCollections !== false || !Array.isArray(storedOptions.selectedCollections)) return;
|
|
746
|
+
const resolvedOptions = this.app.environment.renderJsonTemplate(storedOptions);
|
|
747
|
+
const activeOptions = (0, import_lodash.pick)(source.options, Object.keys(resolvedOptions));
|
|
748
|
+
const selectAll = source.options.addAllCollections ?? source.options.autoDiscover !== false;
|
|
749
|
+
if (selectAll || !(0, import_lodash.isEqual)(
|
|
750
|
+
(0, import_lodash.omit)(activeOptions, ["selectedCollections", "addAllCollections"]),
|
|
751
|
+
(0, import_lodash.omit)(resolvedOptions, ["selectedCollections", "addAllCollections"])
|
|
752
|
+
))
|
|
753
|
+
return;
|
|
754
|
+
const selected = new Set(
|
|
755
|
+
storedOptions.selectedCollections.filter((name) => typeof name === "string")
|
|
756
|
+
);
|
|
757
|
+
const available = new Set(await source.introspector.getTables());
|
|
758
|
+
const localData = await record.loadLocalData();
|
|
759
|
+
const existing = source.collectionManager.getCollections();
|
|
760
|
+
const physicalName = (collection) => {
|
|
761
|
+
const table = collection.model.getTableName();
|
|
762
|
+
return typeof table === "string" ? table : table.tableName;
|
|
763
|
+
};
|
|
764
|
+
const missing = [...selected].filter(
|
|
765
|
+
(name) => available.has(name) && !existing.some((item) => physicalName(item) === name)
|
|
766
|
+
);
|
|
767
|
+
const refreshed = refreshTables.filter((name) => selected.has(name) && available.has(name));
|
|
768
|
+
const targets = [.../* @__PURE__ */ new Set([...missing, ...refreshed])];
|
|
769
|
+
const collections = await source.prepareTables(targets, localData);
|
|
770
|
+
if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
|
|
771
|
+
source.collectionManager.replaceCollections(collections);
|
|
772
|
+
for (const collection of existing) {
|
|
773
|
+
if (!collection.options.sql && !selected.has(physicalName(collection))) {
|
|
774
|
+
source.collectionManager.removeCollection(collection.name);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
source.options = { ...source.options, addAllCollections: false, selectedCollections: [...selected] };
|
|
778
|
+
}
|
|
779
|
+
async beforeLoad() {
|
|
780
|
+
this.app.dataSourceManager.registerDataSourceType(import_constants.DATA_SOURCE_TYPE, import_postgres_datasource.PostgresDataSource);
|
|
781
|
+
this.app.dataSourceManager.beforeAddDataSource((dataSource) => {
|
|
782
|
+
if (!(dataSource instanceof import_postgres_datasource.PostgresDataSource)) return;
|
|
783
|
+
const { db } = dataSource.collectionManager;
|
|
784
|
+
db.collectionFactory.registerCollectionType(import_sql_collection.PostgresSQLCollection, {
|
|
785
|
+
condition: (options) => Boolean(options.sql),
|
|
786
|
+
async onSync() {
|
|
787
|
+
},
|
|
788
|
+
async onDump() {
|
|
789
|
+
}
|
|
790
|
+
});
|
|
791
|
+
db.collectionFactory.registerCollectionType(import_tree_collection.PostgresTreeCollection, {
|
|
792
|
+
condition: (options) => Boolean(options.postgresTree || options.template === "tree")
|
|
793
|
+
});
|
|
794
|
+
dataSource.resourceManager.use(localizeValidationErrors, {
|
|
795
|
+
tag: "postgres-validation-errors",
|
|
796
|
+
after: ["auth"],
|
|
797
|
+
before: ["acl"]
|
|
798
|
+
});
|
|
799
|
+
dataSource.resourceManager.use(
|
|
800
|
+
async (ctx, next) => {
|
|
801
|
+
var _a, _b, _c, _d;
|
|
802
|
+
if (WRITE_ACTIONS.has((_a = ctx.action) == null ? void 0 : _a.actionName)) {
|
|
803
|
+
const resourceName = (_b = ctx.action) == null ? void 0 : _b.resourceName;
|
|
804
|
+
const [sourceName, associationName] = typeof resourceName === "string" ? resourceName.split(".") : [];
|
|
805
|
+
const sourceCollection = sourceName ? dataSource.collectionManager.getCollection(sourceName) : void 0;
|
|
806
|
+
const targetCollection = sourceCollection && associationName && resourceName ? dataSource.collectionManager.getCollection(resourceName) : void 0;
|
|
807
|
+
const throughName = associationName && ((_d = (_c = sourceCollection == null ? void 0 : sourceCollection.getField(associationName)) == null ? void 0 : _c.options) == null ? void 0 : _d.through);
|
|
808
|
+
const throughCollection = typeof throughName === "string" ? dataSource.collectionManager.getCollection(throughName) : void 0;
|
|
809
|
+
const isReadOnly = (collection) => {
|
|
810
|
+
var _a2, _b2;
|
|
811
|
+
return Boolean(((_a2 = collection == null ? void 0 : collection.options) == null ? void 0 : _a2.view) || ((_b2 = collection == null ? void 0 : collection.options) == null ? void 0 : _b2.sql));
|
|
812
|
+
};
|
|
813
|
+
if (isReadOnly(sourceCollection) || isReadOnly(targetCollection) || isReadOnly(throughCollection)) {
|
|
814
|
+
ctx.throw(403, (0, import_validation_error.translate)(ctx, "This collection is read-only"));
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
await next();
|
|
818
|
+
},
|
|
819
|
+
{ tag: "postgres-read-only-collections", after: ["acl"] }
|
|
820
|
+
);
|
|
821
|
+
});
|
|
822
|
+
this.app.dataSourceManager.afterAddDataSource((dataSource) => {
|
|
823
|
+
if (dataSource instanceof import_postgres_datasource.PostgresDataSource) {
|
|
824
|
+
this.activeSources.set(dataSource.name, dataSource);
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
async load() {
|
|
829
|
+
var _a, _b;
|
|
830
|
+
(_b = (_a = this.app.db) == null ? void 0 : _a.on) == null ? void 0 : _b.call(
|
|
831
|
+
_a,
|
|
832
|
+
"dataSources.afterDestroy",
|
|
833
|
+
async (model, options) => {
|
|
834
|
+
if (model.get("type") !== import_constants.DATA_SOURCE_TYPE) return;
|
|
835
|
+
const key = String(model.get("key") || "");
|
|
836
|
+
if (!key) return;
|
|
837
|
+
const current = this.app.dataSourceManager.get(key);
|
|
838
|
+
const target = current instanceof import_postgres_datasource.PostgresDataSource ? current : this.activeSources.get(key);
|
|
839
|
+
if (target && this.activeSources.get(key) === target) {
|
|
840
|
+
this.activeSources.delete(key);
|
|
841
|
+
}
|
|
842
|
+
const close = () => target ? this.closeDataSource(key, target) : Promise.resolve();
|
|
843
|
+
if ((options == null ? void 0 : options.transaction) && typeof options.transaction.afterCommit === "function") {
|
|
844
|
+
options.transaction.afterCommit(close);
|
|
845
|
+
} else {
|
|
846
|
+
await close();
|
|
847
|
+
}
|
|
848
|
+
await this.sendSyncMessage(
|
|
849
|
+
{ type: "dataSourceRemoved", dataSourceKey: key },
|
|
850
|
+
(options == null ? void 0 : options.transaction) ? { transaction: options.transaction } : void 0
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
);
|
|
854
|
+
this.app.resourceManager.registerPreActionHandler("dataSources:readTables", async (ctx, next) => {
|
|
855
|
+
var _a2, _b2, _c;
|
|
856
|
+
const { dataSourceKey, dbOptions } = ctx.action.params.values || {};
|
|
857
|
+
if ((dbOptions == null ? void 0 : dbOptions.type) !== import_constants.DATA_SOURCE_TYPE) {
|
|
858
|
+
await next();
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const manager = this.app.dataSourceManager;
|
|
862
|
+
const renderedOptions = ((_a2 = this.app.environment) == null ? void 0 : _a2.renderJsonTemplate) ? this.app.environment.renderJsonTemplate(dbOptions) : dbOptions;
|
|
863
|
+
const probe = manager.factory.create(import_constants.DATA_SOURCE_TYPE, {
|
|
864
|
+
name: dataSourceKey,
|
|
865
|
+
...renderedOptions,
|
|
866
|
+
pool: { max: 1, min: 0, acquire: 1e4, idle: 1e3 }
|
|
867
|
+
});
|
|
868
|
+
const owned = ![...manager.dataSources.values()].includes(probe);
|
|
869
|
+
let requestFailed = false;
|
|
870
|
+
let requestError;
|
|
871
|
+
try {
|
|
872
|
+
ctx.body = await probe.readTables();
|
|
873
|
+
} catch (error) {
|
|
874
|
+
requestFailed = true;
|
|
875
|
+
requestError = error;
|
|
876
|
+
} finally {
|
|
877
|
+
if (owned) {
|
|
878
|
+
try {
|
|
879
|
+
await probe.close();
|
|
880
|
+
} catch (error) {
|
|
881
|
+
if (requestFailed) {
|
|
882
|
+
(_c = (_b2 = this.app.log) == null ? void 0 : _b2.warn) == null ? void 0 : _c.call(_b2, "[PostgreSQL] Failed to close temporary table-list connection");
|
|
883
|
+
} else {
|
|
884
|
+
requestFailed = true;
|
|
885
|
+
requestError = error;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (requestFailed) throw requestError;
|
|
891
|
+
});
|
|
892
|
+
this.app.resourceManager.use(localizeValidationErrors, {
|
|
893
|
+
tag: "postgres-validation-errors",
|
|
894
|
+
after: ["auth"],
|
|
895
|
+
before: ["acl"]
|
|
896
|
+
});
|
|
897
|
+
this.app.resourceManager.use(
|
|
898
|
+
async (ctx, next) => {
|
|
899
|
+
var _a2, _b2, _c;
|
|
900
|
+
const { resourceName, actionName, params } = ctx.action || {};
|
|
901
|
+
if (resourceName === "dataSources.collections") {
|
|
902
|
+
const dataSourceKey = ((_a2 = ctx.action) == null ? void 0 : _a2.sourceId) || (params == null ? void 0 : params.associatedIndex);
|
|
903
|
+
const dataSource = dataSourceKey ? this.app.dataSourceManager.get(dataSourceKey) : void 0;
|
|
904
|
+
if (dataSource instanceof import_postgres_datasource.PostgresDataSource) {
|
|
905
|
+
if (actionName === "create" || actionName === "destroy") {
|
|
906
|
+
await this.mutateCollection(ctx, dataSource, next);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
if (actionName === "update") {
|
|
910
|
+
const sql = extractSql(params.values);
|
|
911
|
+
if (sql !== void 0) {
|
|
912
|
+
const existing = dataSource.collectionManager.getCollection(params.filterByTk);
|
|
913
|
+
if (!((_b2 = existing == null ? void 0 : existing.options) == null ? void 0 : _b2.sql)) {
|
|
914
|
+
ctx.throw(400, (0, import_validation_error.translate)(ctx, "Only SQL collections can update SQL queries"));
|
|
915
|
+
}
|
|
916
|
+
(0, import_sql_validator.checkSQL)(typeof sql === "string" ? sql : "");
|
|
917
|
+
}
|
|
918
|
+
await next();
|
|
919
|
+
const targetName = typeof params.filterByTk === "string" ? params.filterByTk : "";
|
|
920
|
+
if (targetName) {
|
|
921
|
+
await this.sendSyncMessage({
|
|
922
|
+
type: "collectionCreated",
|
|
923
|
+
dataSourceKey: dataSource.name,
|
|
924
|
+
collectionName: targetName
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
if (resourceName === "dataSourcesCollections.fields" && FIELD_ACTIONS.has(actionName)) {
|
|
932
|
+
const index = String(params.associatedIndex || "");
|
|
933
|
+
const separator = index.indexOf(".");
|
|
934
|
+
const indexDataSourceKey = separator !== -1 ? index.slice(0, separator) : "";
|
|
935
|
+
const indexCollectionName = separator !== -1 ? index.slice(separator + 1) : "";
|
|
936
|
+
const rawBody = (_c = ctx.request) == null ? void 0 : _c.body;
|
|
937
|
+
const input = params.values || (isRecord(rawBody) ? rawBody : {});
|
|
938
|
+
const dataSourceKey = actionName === "apply" && typeof input.dataSourceKey === "string" && input.dataSourceKey ? input.dataSourceKey : indexDataSourceKey;
|
|
939
|
+
const collectionName = actionName === "apply" && typeof input.collectionName === "string" && input.collectionName ? input.collectionName : indexCollectionName;
|
|
940
|
+
const dataSource = dataSourceKey && collectionName && this.app.dataSourceManager.get(dataSourceKey);
|
|
941
|
+
if (dataSource instanceof import_postgres_datasource.PostgresDataSource) {
|
|
942
|
+
await this.mutateField(ctx, dataSource, collectionName, input, next);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
await next();
|
|
947
|
+
},
|
|
948
|
+
{ tag: "postgres-schema-actions", after: ["acl"] }
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
async resolveCollectionsToDestroy(ctx, source) {
|
|
952
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
953
|
+
const params = ((_a = ctx.action) == null ? void 0 : _a.params) || {};
|
|
954
|
+
const permission = ctx.permission;
|
|
955
|
+
const rawFilter = params.filter;
|
|
956
|
+
const scopeFilter = ((_b = permission == null ? void 0 : permission.parsedParams) == null ? void 0 : _b.filter) ?? ((_d = (_c = permission == null ? void 0 : permission.can) == null ? void 0 : _c.params) == null ? void 0 : _d.filter);
|
|
957
|
+
const hasRawFilter = (0, import_utils.isValidFilter)(rawFilter);
|
|
958
|
+
const hasScopeFilter = (0, import_utils.isValidFilter)(scopeFilter);
|
|
959
|
+
const effectiveFilter = hasRawFilter && hasScopeFilter && !(0, import_lodash.isEqual)(rawFilter, scopeFilter) ? { $and: [rawFilter, scopeFilter] } : hasRawFilter ? rawFilter : hasScopeFilter ? scopeFilter : void 0;
|
|
960
|
+
const hasFilterByTk = params.filterByTk !== void 0 && params.filterByTk !== null;
|
|
961
|
+
let requestedNames;
|
|
962
|
+
if (hasFilterByTk) {
|
|
963
|
+
if (Array.isArray(params.filterByTk) && params.filterByTk.length === 0) {
|
|
964
|
+
return [];
|
|
965
|
+
}
|
|
966
|
+
requestedNames = names(params.filterByTk);
|
|
967
|
+
} else if (!effectiveFilter) {
|
|
968
|
+
throw new import_validation_error.PostgresValidationError("A collection name is required");
|
|
969
|
+
}
|
|
970
|
+
const manager = source.collectionManager;
|
|
971
|
+
if (!effectiveFilter) {
|
|
972
|
+
for (const name of requestedNames ?? []) {
|
|
973
|
+
if (!manager.getCollection(name)) {
|
|
974
|
+
ctx.throw(404, (0, import_validation_error.translate)(ctx, "Collection {{name}} does not exist", { name }));
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return requestedNames ?? [];
|
|
978
|
+
}
|
|
979
|
+
const db = this.app.db || ctx.db;
|
|
980
|
+
const metadataDialect = ((_f = (_e = db == null ? void 0 : db.sequelize) == null ? void 0 : _e.getDialect) == null ? void 0 : _f.call(_e)) ?? "postgres";
|
|
981
|
+
const collectionsRepo = (_g = db == null ? void 0 : db.getRepository) == null ? void 0 : _g.call(db, "dataSourcesCollections");
|
|
982
|
+
if (collectionsRepo && typeof collectionsRepo.find === "function") {
|
|
983
|
+
const baseFilter = {
|
|
984
|
+
dataSourceKey: source.name,
|
|
985
|
+
...requestedNames ? { name: { $in: requestedNames } } : {}
|
|
986
|
+
};
|
|
987
|
+
const persistedAll = await collectionsRepo.find({ filter: baseFilter, context: ctx });
|
|
988
|
+
const persistedNames = new Set(persistedAll.map((row) => String(row.get("name"))));
|
|
989
|
+
const persistedMatched = await collectionsRepo.find({
|
|
990
|
+
filter: { $and: [baseFilter, effectiveFilter] },
|
|
991
|
+
context: ctx
|
|
992
|
+
});
|
|
993
|
+
const matchedSet = new Set(persistedMatched.map((row) => String(row.get("name"))));
|
|
994
|
+
for (const collection of manager.getCollections()) {
|
|
995
|
+
if (persistedNames.has(collection.name)) continue;
|
|
996
|
+
if (requestedNames && !requestedNames.includes(collection.name)) continue;
|
|
997
|
+
const record = {
|
|
998
|
+
...collection.options,
|
|
999
|
+
name: collection.name,
|
|
1000
|
+
dataSourceKey: source.name,
|
|
1001
|
+
dataSources: { key: source.name, type: import_constants.DATA_SOURCE_TYPE },
|
|
1002
|
+
options: collection.options,
|
|
1003
|
+
fields: collection.getFields().map((field) => field.options)
|
|
1004
|
+
};
|
|
1005
|
+
if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
|
|
1006
|
+
matchedSet.add(collection.name);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
return requestedNames ? requestedNames.filter((name) => matchedSet.has(name)) : [...matchedSet];
|
|
1010
|
+
}
|
|
1011
|
+
const matchedRuntime = /* @__PURE__ */ new Set();
|
|
1012
|
+
for (const collection of manager.getCollections()) {
|
|
1013
|
+
if (requestedNames && !requestedNames.includes(collection.name)) continue;
|
|
1014
|
+
const record = {
|
|
1015
|
+
...collection.options,
|
|
1016
|
+
name: collection.name,
|
|
1017
|
+
dataSourceKey: source.name,
|
|
1018
|
+
dataSources: { key: source.name, type: import_constants.DATA_SOURCE_TYPE },
|
|
1019
|
+
options: collection.options,
|
|
1020
|
+
fields: collection.getFields().map((field) => field.options)
|
|
1021
|
+
};
|
|
1022
|
+
if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
|
|
1023
|
+
matchedRuntime.add(collection.name);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return requestedNames ? requestedNames.filter((name) => matchedRuntime.has(name)) : [...matchedRuntime];
|
|
1027
|
+
}
|
|
1028
|
+
async mutateCollection(ctx, source, next) {
|
|
1029
|
+
var _a, _b, _c, _d, _e, _f;
|
|
1030
|
+
const manager = source.collectionManager;
|
|
1031
|
+
const { actionName, params } = ctx.action;
|
|
1032
|
+
const values = params.values || {};
|
|
1033
|
+
if (actionName === "create") {
|
|
1034
|
+
const [name] = names(values.name);
|
|
1035
|
+
prepareFields(values);
|
|
1036
|
+
if (manager.hasCollection(name)) ctx.throw(409, (0, import_validation_error.translate)(ctx, "Collection {{name}} already exists", { name }));
|
|
1037
|
+
const sql = extractSql(values);
|
|
1038
|
+
if (sql !== void 0 || values.template === "sql") {
|
|
1039
|
+
(0, import_sql_validator.checkSQL)(typeof sql === "string" ? sql : "");
|
|
1040
|
+
await next();
|
|
1041
|
+
await this.sendSyncMessage({ type: "collectionCreated", dataSourceKey: source.name, collectionName: name });
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
if (values.view || values.template === "view") {
|
|
1045
|
+
ctx.throw(400, (0, import_validation_error.translate)(ctx, "Use Load tables to import an existing view"));
|
|
1046
|
+
}
|
|
1047
|
+
let createdCollection;
|
|
1048
|
+
await manager.db.sequelize.transaction(async (transaction) => {
|
|
1049
|
+
await manager.db.sequelize.query("SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))", {
|
|
1050
|
+
replacements: { table: `${manager.db.options.schema || "public"}.${String(values.tableName || name)}` },
|
|
1051
|
+
transaction
|
|
1052
|
+
});
|
|
1053
|
+
if (manager.hasCollection(name)) ctx.throw(409, (0, import_validation_error.translate)(ctx, "Collection {{name}} already exists", { name }));
|
|
1054
|
+
if (!await manager.createTable(values, transaction))
|
|
1055
|
+
ctx.throw(409, (0, import_validation_error.translate)(ctx, "Table {{name}} already exists", { name }));
|
|
1056
|
+
createdCollection = manager.getCollection(name);
|
|
1057
|
+
});
|
|
1058
|
+
try {
|
|
1059
|
+
await next();
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
try {
|
|
1062
|
+
await manager.dropTable(name, false);
|
|
1063
|
+
} catch (cleanupError) {
|
|
1064
|
+
(_b = (_a = this.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `Failed to roll back PostgreSQL table "${name}" after metadata error`, {
|
|
1065
|
+
cause: cleanupError
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
if (createdCollection && manager.getCollection(name) === createdCollection) manager.removeCollection(name);
|
|
1069
|
+
throw error;
|
|
1070
|
+
}
|
|
1071
|
+
await source.addSelectedTables(ctx, [String(values.tableName || name)]);
|
|
1072
|
+
await this.sendSyncMessage({ type: "collectionCreated", dataSourceKey: source.name, collectionName: name });
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
const collectionNames = await this.resolveCollectionsToDestroy(ctx, source);
|
|
1076
|
+
if (collectionNames.length === 0) {
|
|
1077
|
+
ctx.body = true;
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
const snapshots = collectionNames.flatMap((name) => {
|
|
1081
|
+
const collection = manager.getCollection(name);
|
|
1082
|
+
if (!collection) return [];
|
|
1083
|
+
return [
|
|
1084
|
+
{
|
|
1085
|
+
name,
|
|
1086
|
+
physicalName: String(collection.options.tableName || name),
|
|
1087
|
+
isSql: Boolean(collection.options.sql),
|
|
1088
|
+
options: (0, import_lodash.cloneDeep)({
|
|
1089
|
+
...collection.options,
|
|
1090
|
+
tableName: String(collection.options.tableName || name),
|
|
1091
|
+
fields: collection.getFields().map((field) => field.options)
|
|
1092
|
+
})
|
|
1093
|
+
}
|
|
1094
|
+
];
|
|
1095
|
+
});
|
|
1096
|
+
const cascade = params.cascade === true || params.cascade === "true";
|
|
1097
|
+
const hadFilterByTk = Object.prototype.hasOwnProperty.call(params, "filterByTk");
|
|
1098
|
+
const hadFilter = Object.prototype.hasOwnProperty.call(params, "filter");
|
|
1099
|
+
const originalFilterByTk = params.filterByTk;
|
|
1100
|
+
const originalFilter = params.filter;
|
|
1101
|
+
try {
|
|
1102
|
+
await manager.db.sequelize.transaction(async (transaction) => {
|
|
1103
|
+
for (const snapshot of [...snapshots].sort(
|
|
1104
|
+
(left, right) => left.physicalName.localeCompare(right.physicalName)
|
|
1105
|
+
)) {
|
|
1106
|
+
await manager.db.sequelize.query("SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))", {
|
|
1107
|
+
replacements: { table: `${manager.db.options.schema || "public"}.${snapshot.physicalName}` },
|
|
1108
|
+
transaction
|
|
1109
|
+
});
|
|
1110
|
+
if (!snapshot.isSql) await manager.dropTable(snapshot.name, cascade, transaction);
|
|
1111
|
+
}
|
|
1112
|
+
params.filterByTk = collectionNames;
|
|
1113
|
+
delete params.filter;
|
|
1114
|
+
await next();
|
|
1115
|
+
});
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
if (hadFilterByTk) params.filterByTk = originalFilterByTk;
|
|
1118
|
+
else delete params.filterByTk;
|
|
1119
|
+
if (hadFilter) params.filter = originalFilter;
|
|
1120
|
+
else delete params.filter;
|
|
1121
|
+
for (const snapshot of snapshots) {
|
|
1122
|
+
if (!manager.hasCollection(snapshot.name)) manager.defineCollection(snapshot.options);
|
|
1123
|
+
}
|
|
1124
|
+
throw error;
|
|
1125
|
+
}
|
|
1126
|
+
const fieldsRepo = (_d = (_c = this.app.db || ctx.db) == null ? void 0 : _c.getRepository) == null ? void 0 : _d.call(_c, "dataSourcesFields");
|
|
1127
|
+
if (fieldsRepo && typeof fieldsRepo.destroy === "function") {
|
|
1128
|
+
try {
|
|
1129
|
+
await fieldsRepo.destroy({
|
|
1130
|
+
filter: { dataSourceKey: source.name, collectionName: { $in: collectionNames } },
|
|
1131
|
+
individualHooks: false,
|
|
1132
|
+
hooks: false
|
|
1133
|
+
});
|
|
1134
|
+
} catch (cleanupError) {
|
|
1135
|
+
(_f = (_e = this.app.log) == null ? void 0 : _e.warn) == null ? void 0 : _f.call(_e, `Failed to clean up orphaned field metadata for PostgreSQL data source "${source.name}"`, {
|
|
1136
|
+
cause: cleanupError
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
for (const snapshot of snapshots) {
|
|
1141
|
+
if (manager.hasCollection(snapshot.name)) manager.removeCollection(snapshot.name);
|
|
1142
|
+
}
|
|
1143
|
+
await source.removeSelectedTables(
|
|
1144
|
+
ctx,
|
|
1145
|
+
snapshots.map((snapshot) => snapshot.physicalName)
|
|
1146
|
+
);
|
|
1147
|
+
await this.sendSyncMessage({
|
|
1148
|
+
type: "collectionRemoved",
|
|
1149
|
+
dataSourceKey: source.name,
|
|
1150
|
+
collectionNames
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
async mutateField(ctx, source, collectionName, input, next) {
|
|
1154
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
1155
|
+
const manager = source.collectionManager;
|
|
1156
|
+
const collection = manager.getCollection(collectionName);
|
|
1157
|
+
if (!collection) ctx.throw(404, (0, import_validation_error.translate)(ctx, "Collection {{name}} does not exist", { name: collectionName }));
|
|
1158
|
+
const action = ctx.action.actionName;
|
|
1159
|
+
const { params } = ctx.action;
|
|
1160
|
+
const fieldName = params.filterByTk;
|
|
1161
|
+
if (Array.isArray(fieldName)) ctx.throw(400, (0, import_validation_error.translate)(ctx, "Delete one field at a time"));
|
|
1162
|
+
if (collection.options.sql) {
|
|
1163
|
+
await next();
|
|
1164
|
+
if (action === "destroy" && typeof fieldName === "string") {
|
|
1165
|
+
if (collection.getField(fieldName)) collection.removeField(fieldName);
|
|
1166
|
+
await this.sendSyncMessage({
|
|
1167
|
+
type: "fieldRemoved",
|
|
1168
|
+
dataSourceKey: source.name,
|
|
1169
|
+
collectionName,
|
|
1170
|
+
fieldName
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
if (collection.options.view) {
|
|
1176
|
+
const targetName = fieldName || input.name;
|
|
1177
|
+
if (action === "create" || action === "destroy" || !targetName || !collection.getField(targetName)) {
|
|
1178
|
+
ctx.throw(403, (0, import_validation_error.translate)(ctx, "This collection is read-only"));
|
|
1179
|
+
}
|
|
1180
|
+
await next();
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
if (action === "destroy" && typeof fieldName === "string" && (0, import_field_hooks.removesPhysicalColumn)(collection, fieldName)) {
|
|
1184
|
+
const columnName = ((_a = collection.getField(fieldName)) == null ? void 0 : _a.columnName()) || fieldName;
|
|
1185
|
+
const references = await ctx.db.getRepository("dataSourcesFields").find({
|
|
1186
|
+
filter: { dataSourceKey: source.name }
|
|
1187
|
+
});
|
|
1188
|
+
if (references.some(
|
|
1189
|
+
(field) => (0, import_field_hooks.fieldReferencesColumn)(field.toJSON(), field.get("collectionName"), collectionName, [fieldName, columnName])
|
|
1190
|
+
)) {
|
|
1191
|
+
ctx.throw(400, (0, import_validation_error.translate)(ctx, "Field {{name}} is referenced by another field", { name: fieldName }));
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
const snapshot = (0, import_lodash.cloneDeep)({ ...collection.options, fields: collection.getFields().map((field) => field.options) });
|
|
1195
|
+
const lockTables = (0, import_field_hooks.getRelationLockTables)(
|
|
1196
|
+
manager,
|
|
1197
|
+
collectionName,
|
|
1198
|
+
input,
|
|
1199
|
+
typeof fieldName === "string" ? fieldName : void 0
|
|
1200
|
+
);
|
|
1201
|
+
let metadataActionStarted = false;
|
|
1202
|
+
try {
|
|
1203
|
+
await manager.db.sequelize.transaction(async (transaction) => {
|
|
1204
|
+
for (const table of lockTables) {
|
|
1205
|
+
await manager.db.sequelize.query("SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))", {
|
|
1206
|
+
replacements: { table },
|
|
1207
|
+
transaction
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
await (0, import_field_hooks.syncFieldAction)(manager, action, collectionName, fieldName, input, transaction);
|
|
1211
|
+
if (input.dataType === "array" && isRecord(params.values)) {
|
|
1212
|
+
if (params.values.dataType === void 0 || params.values.dataType === null || params.values.dataType === "") {
|
|
1213
|
+
params.values.dataType = "array";
|
|
1214
|
+
}
|
|
1215
|
+
if (params.values.elementType === void 0 && typeof input.elementType === "string") {
|
|
1216
|
+
params.values.elementType = input.elementType;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
metadataActionStarted = true;
|
|
1220
|
+
await next();
|
|
1221
|
+
});
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
const current = manager.getCollection(collectionName);
|
|
1224
|
+
if (metadataActionStarted && current) {
|
|
1225
|
+
current.resetFields();
|
|
1226
|
+
current.updateOptions(snapshot);
|
|
1227
|
+
}
|
|
1228
|
+
throw error;
|
|
1229
|
+
}
|
|
1230
|
+
if (action === "destroy" && typeof fieldName === "string") {
|
|
1231
|
+
if ((_b = manager.getCollection(collectionName)) == null ? void 0 : _b.getField(fieldName)) {
|
|
1232
|
+
manager.getCollection(collectionName).removeField(fieldName);
|
|
1233
|
+
}
|
|
1234
|
+
await this.sendSyncMessage({
|
|
1235
|
+
type: "fieldRemoved",
|
|
1236
|
+
dataSourceKey: source.name,
|
|
1237
|
+
collectionName,
|
|
1238
|
+
fieldName
|
|
1239
|
+
});
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
const savedName = typeof fieldName === "string" && fieldName ? fieldName : input.name;
|
|
1243
|
+
const savedRelation = savedName ? ((_d = (_c = manager.getCollection(collectionName)) == null ? void 0 : _c.getField(savedName)) == null ? void 0 : _d.options) || input : input;
|
|
1244
|
+
const companion = (0, import_field_hooks.buildArrayForeignKeyField)(manager, collectionName, savedRelation);
|
|
1245
|
+
if (companion && typeof companion.name === "string") {
|
|
1246
|
+
(_e = manager.getCollection(collectionName)) == null ? void 0 : _e.setField(companion.name, companion);
|
|
1247
|
+
const fieldsRepo = (_g = (_f = this.app.db || ctx.db) == null ? void 0 : _f.getRepository) == null ? void 0 : _g.call(_f, "dataSourcesFields");
|
|
1248
|
+
if (fieldsRepo && typeof fieldsRepo.findOne === "function" && typeof fieldsRepo.create === "function") {
|
|
1249
|
+
try {
|
|
1250
|
+
const existingRecord = await fieldsRepo.findOne({
|
|
1251
|
+
filter: { dataSourceKey: source.name, collectionName, name: companion.name }
|
|
1252
|
+
});
|
|
1253
|
+
if (!existingRecord) {
|
|
1254
|
+
await fieldsRepo.create({
|
|
1255
|
+
values: { ...companion, collectionName, dataSourceKey: source.name }
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
} catch (companionError) {
|
|
1259
|
+
(_i = (_h = this.app.log) == null ? void 0 : _h.warn) == null ? void 0 : _i.call(
|
|
1260
|
+
_h,
|
|
1261
|
+
`Failed to persist companion array field "${collectionName}.${companion.name}" for PostgreSQL data source "${source.name}"`,
|
|
1262
|
+
{ cause: companionError }
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
var plugin_default = PluginDataSourcePostgresServer;
|
|
1270
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1271
|
+
0 && (module.exports = {
|
|
1272
|
+
PluginDataSourcePostgresServer
|
|
1273
|
+
});
|