plugin-data-source-postgres 2.0.0 → 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 +1 -1
- package/dist/externalVersion.js +1 -0
- package/dist/server/collections/sql-collection.js +2 -2
- package/dist/server/collections/sql-model.js +4 -2
- package/dist/server/hooks/field-hooks.js +20 -0
- package/dist/server/plugin.js +603 -20
- package/dist/server/postgres-collection-manager.js +192 -25
- package/dist/server/postgres-datasource.js +47 -13
- package/dist/server/utils/sql-validator.js +119 -69
- package/package.json +2 -2
- package/src/server/__tests__/postgres-datasource.unit.test.ts +885 -0
- package/src/server/__tests__/sql-model.test.ts +47 -3
- package/src/server/__tests__/sql-validator.test.ts +8 -1
- package/src/server/collections/sql-collection.ts +2 -2
- package/src/server/collections/sql-model.ts +2 -2
- package/src/server/hooks/field-hooks.ts +36 -2
- package/src/server/plugin.ts +752 -17
- package/src/server/postgres-collection-manager.ts +228 -28
- package/src/server/postgres-datasource.ts +57 -12
- package/src/server/utils/sql-validator.ts +123 -68
|
@@ -26,7 +26,9 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
26
26
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
27
|
var postgres_collection_manager_exports = {};
|
|
28
28
|
__export(postgres_collection_manager_exports, {
|
|
29
|
-
PostgresCollectionManager: () => PostgresCollectionManager
|
|
29
|
+
PostgresCollectionManager: () => PostgresCollectionManager,
|
|
30
|
+
applyPostgresArrayDataType: () => applyPostgresArrayDataType,
|
|
31
|
+
isPostgresPhysicalArrayRawType: () => isPostgresPhysicalArrayRawType
|
|
30
32
|
});
|
|
31
33
|
module.exports = __toCommonJS(postgres_collection_manager_exports);
|
|
32
34
|
var import_data_source_manager = require("@nocobase/data-source-manager");
|
|
@@ -34,13 +36,70 @@ var import_lodash = require("lodash");
|
|
|
34
36
|
var import_sequelize = require("sequelize");
|
|
35
37
|
var import_crypto = require("crypto");
|
|
36
38
|
var import_validation_error = require("./utils/validation-error");
|
|
39
|
+
const POSTGRES_BUILD_FIELD_NORMALIZED = Symbol("postgresBuildFieldNormalized");
|
|
40
|
+
function isPostgresPhysicalArrayRawType(rawType) {
|
|
41
|
+
if (typeof rawType !== "string") return false;
|
|
42
|
+
const trimmed = rawType.trim();
|
|
43
|
+
return trimmed.toUpperCase() === "ARRAY" || trimmed.endsWith("[]");
|
|
44
|
+
}
|
|
45
|
+
function applyPostgresArrayDataType(field) {
|
|
46
|
+
const type = field.type;
|
|
47
|
+
if (type !== "array" && type !== "set") {
|
|
48
|
+
return field;
|
|
49
|
+
}
|
|
50
|
+
const hasRawType = typeof field.rawType === "string" && field.rawType.trim().length > 0;
|
|
51
|
+
if (hasRawType && !isPostgresPhysicalArrayRawType(field.rawType)) {
|
|
52
|
+
if (field.dataType === void 0 || field.dataType === null || field.dataType === "") {
|
|
53
|
+
Object.assign(field, { dataType: "json" });
|
|
54
|
+
}
|
|
55
|
+
return field;
|
|
56
|
+
}
|
|
57
|
+
const elementType = field.elementType;
|
|
58
|
+
if (typeof elementType === "string" && elementType.trim().length > 0 && (field.dataType === void 0 || field.dataType === null || field.dataType === "")) {
|
|
59
|
+
Object.assign(field, { dataType: "array" });
|
|
60
|
+
}
|
|
61
|
+
return field;
|
|
62
|
+
}
|
|
63
|
+
const SAFE_ARRAY_TYPE_RE = /^[a-zA-Z_][a-zA-Z0-9_]*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\[\])+$/;
|
|
64
|
+
const INTEGER_ELEMENT_TYPES = /* @__PURE__ */ new Set(["smallint", "integer", "int", "int2", "int4", "bigint", "int8"]);
|
|
65
|
+
const NUMERIC_ELEMENT_TYPES = /* @__PURE__ */ new Set(["real", "float", "float4", "float8", "double precision", "numeric", "decimal"]);
|
|
66
|
+
const BOOLEAN_ELEMENT_TYPES = /* @__PURE__ */ new Set(["boolean", "bool"]);
|
|
37
67
|
class PostgresCollectionManager extends import_data_source_manager.SequelizeCollectionManager {
|
|
68
|
+
constructor(options) {
|
|
69
|
+
super(options);
|
|
70
|
+
this.installArrayFieldNormalizer();
|
|
71
|
+
}
|
|
72
|
+
installArrayFieldNormalizer() {
|
|
73
|
+
const dbRecord = this.db;
|
|
74
|
+
const originalBuildField = dbRecord == null ? void 0 : dbRecord.buildField;
|
|
75
|
+
if (typeof originalBuildField !== "function" || originalBuildField[POSTGRES_BUILD_FIELD_NORMALIZED]) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const wrappedBuildField = function(fieldOptions, context) {
|
|
79
|
+
if (fieldOptions && typeof fieldOptions === "object") {
|
|
80
|
+
applyPostgresArrayDataType(fieldOptions);
|
|
81
|
+
}
|
|
82
|
+
return originalBuildField.call(this, fieldOptions, context);
|
|
83
|
+
};
|
|
84
|
+
wrappedBuildField[POSTGRES_BUILD_FIELD_NORMALIZED] = true;
|
|
85
|
+
dbRecord.buildField = wrappedBuildField;
|
|
86
|
+
}
|
|
38
87
|
defineCollection(options) {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
88
|
+
const normalizedOptions = Array.isArray(options.fields) ? {
|
|
89
|
+
...options,
|
|
90
|
+
fields: options.fields.map(
|
|
91
|
+
(field) => field && typeof field === "object" ? applyPostgresArrayDataType({ ...field }) : field
|
|
92
|
+
)
|
|
93
|
+
} : options;
|
|
94
|
+
if (normalizedOptions.tree) {
|
|
95
|
+
const { tree, ...rest } = normalizedOptions;
|
|
96
|
+
return super.defineCollection({
|
|
97
|
+
...rest,
|
|
98
|
+
postgresTree: tree,
|
|
99
|
+
template: normalizedOptions.template || "tree"
|
|
100
|
+
});
|
|
42
101
|
}
|
|
43
|
-
return super.defineCollection(
|
|
102
|
+
return super.defineCollection(normalizedOptions);
|
|
44
103
|
}
|
|
45
104
|
replaceCollections(collections) {
|
|
46
105
|
const snapshots = [];
|
|
@@ -95,21 +154,24 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
95
154
|
return `${this.quoteIdentifier(schema)}.${this.quoteIdentifier(tableName)}`;
|
|
96
155
|
}
|
|
97
156
|
fieldType(collectionName, options) {
|
|
157
|
+
var _a, _b;
|
|
98
158
|
const collection = this.getCollection(collectionName);
|
|
99
159
|
if (!collection) throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: collectionName });
|
|
100
|
-
const
|
|
160
|
+
const buildOptions = applyPostgresArrayDataType({ ...options });
|
|
161
|
+
const field = this.db.buildField(buildOptions, { collection, database: this.db });
|
|
101
162
|
if (field.isRelationField() || !field.dataType) {
|
|
102
163
|
throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
|
|
103
164
|
type: options.type || ""
|
|
104
165
|
});
|
|
105
166
|
}
|
|
106
167
|
const sequelizeField = field.toSequelize();
|
|
107
|
-
|
|
168
|
+
const normalizedType = ((_b = (_a = this.db.sequelize).normalizeDataType) == null ? void 0 : _b.call(_a, sequelizeField.type)) ?? sequelizeField.type;
|
|
169
|
+
if (!normalizedType || normalizedType.key === "VIRTUAL" || typeof normalizedType.toSql !== "function") {
|
|
108
170
|
throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
|
|
109
171
|
type: options.type || ""
|
|
110
172
|
});
|
|
111
173
|
}
|
|
112
|
-
const sqlType =
|
|
174
|
+
const sqlType = normalizedType.toSql();
|
|
113
175
|
if (!sqlType || sqlType.toUpperCase() === "VIRTUAL") {
|
|
114
176
|
throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
|
|
115
177
|
type: options.type || ""
|
|
@@ -134,6 +196,12 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
134
196
|
);
|
|
135
197
|
return (_a = columns[0]) == null ? void 0 : _a.dataType;
|
|
136
198
|
}
|
|
199
|
+
async isPhysicalArrayColumn(collectionName, columnName, transaction) {
|
|
200
|
+
const { schema, tableName } = this.tableInfo(collectionName);
|
|
201
|
+
const columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
|
|
202
|
+
if (columnType === void 0) return void 0;
|
|
203
|
+
return isPostgresPhysicalArrayRawType(columnType);
|
|
204
|
+
}
|
|
137
205
|
async isColumnNotNull(schema, tableName, columnName, transaction) {
|
|
138
206
|
var _a;
|
|
139
207
|
const columns = await this.db.sequelize.query(
|
|
@@ -151,13 +219,93 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
151
219
|
);
|
|
152
220
|
return ((_a = columns[0]) == null ? void 0 : _a.notNull) === true;
|
|
153
221
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
if (
|
|
160
|
-
|
|
222
|
+
formatArrayDefaultElement(element, elementType) {
|
|
223
|
+
if (element === null) return "NULL";
|
|
224
|
+
if (element === void 0 || typeof element === "function" || typeof element === "symbol") {
|
|
225
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
226
|
+
}
|
|
227
|
+
if (elementType.endsWith("[]")) {
|
|
228
|
+
if (!Array.isArray(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
229
|
+
if (!element.length) return `ARRAY[]::${elementType}`;
|
|
230
|
+
const innerType = elementType.slice(0, -2);
|
|
231
|
+
return `ARRAY[${element.map((item) => this.formatArrayDefaultElement(item, innerType)).join(", ")}]`;
|
|
232
|
+
}
|
|
233
|
+
const baseType = elementType.replace(/\([^)]*\)/g, "").trim().toLowerCase();
|
|
234
|
+
if (baseType === "json" || baseType === "jsonb") {
|
|
235
|
+
const encoded = JSON.stringify(element);
|
|
236
|
+
if (encoded === void 0) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
237
|
+
return `${this.db.sequelize.escape(encoded)}::${baseType}`;
|
|
238
|
+
}
|
|
239
|
+
if (INTEGER_ELEMENT_TYPES.has(baseType)) {
|
|
240
|
+
if (typeof element === "bigint") return String(element);
|
|
241
|
+
if (typeof element === "number") {
|
|
242
|
+
if (!Number.isSafeInteger(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
243
|
+
return String(element);
|
|
244
|
+
}
|
|
245
|
+
if (typeof element === "string" && /^[+-]?\d+$/.test(element.trim())) return element.trim();
|
|
246
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
247
|
+
}
|
|
248
|
+
if (NUMERIC_ELEMENT_TYPES.has(baseType)) {
|
|
249
|
+
if (typeof element === "bigint") return String(element);
|
|
250
|
+
if (typeof element === "number") {
|
|
251
|
+
if (!Number.isFinite(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
252
|
+
return String(element);
|
|
253
|
+
}
|
|
254
|
+
if (typeof element === "string" && /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(element.trim())) {
|
|
255
|
+
return element.trim();
|
|
256
|
+
}
|
|
257
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
258
|
+
}
|
|
259
|
+
if (BOOLEAN_ELEMENT_TYPES.has(baseType)) {
|
|
260
|
+
if (typeof element === "boolean") return element ? "TRUE" : "FALSE";
|
|
261
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
262
|
+
}
|
|
263
|
+
if (typeof element === "boolean") return element ? "TRUE" : "FALSE";
|
|
264
|
+
if (typeof element === "bigint") return String(element);
|
|
265
|
+
if (typeof element === "number") {
|
|
266
|
+
if (!Number.isFinite(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
267
|
+
return this.db.sequelize.escape(element);
|
|
268
|
+
}
|
|
269
|
+
if (typeof element === "string" || element instanceof Date) {
|
|
270
|
+
return this.db.sequelize.escape(element);
|
|
271
|
+
}
|
|
272
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
273
|
+
}
|
|
274
|
+
defaultSql(value, columnType) {
|
|
275
|
+
if (value === null) return "NULL";
|
|
276
|
+
const rawType = (columnType || "").trim();
|
|
277
|
+
const lowerType = rawType.toLowerCase();
|
|
278
|
+
if (lowerType.endsWith("[]")) {
|
|
279
|
+
if (!SAFE_ARRAY_TYPE_RE.test(rawType)) {
|
|
280
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
281
|
+
}
|
|
282
|
+
if (Array.isArray(value)) {
|
|
283
|
+
if (!value.length) return `ARRAY[]::${rawType}`;
|
|
284
|
+
const innerType = rawType.slice(0, -2);
|
|
285
|
+
return `ARRAY[${value.map((item) => this.formatArrayDefaultElement(item, innerType)).join(", ")}]::${rawType}`;
|
|
286
|
+
}
|
|
287
|
+
if (typeof value === "string") {
|
|
288
|
+
return `${this.db.sequelize.escape(value)}::${rawType}`;
|
|
289
|
+
}
|
|
290
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
291
|
+
}
|
|
292
|
+
if (lowerType === "json" || lowerType === "jsonb") {
|
|
293
|
+
if (typeof value === "string") return this.db.sequelize.escape(value);
|
|
294
|
+
if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value instanceof Date || typeof value === "object" && value !== null) {
|
|
295
|
+
const encoded = JSON.stringify(value);
|
|
296
|
+
if (encoded === void 0) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
297
|
+
return this.db.sequelize.escape(encoded);
|
|
298
|
+
}
|
|
299
|
+
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
300
|
+
}
|
|
301
|
+
if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
|
|
302
|
+
if (typeof value === "bigint") return String(value);
|
|
303
|
+
if (typeof value === "number") {
|
|
304
|
+
if (!Number.isFinite(value)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
305
|
+
return this.db.sequelize.escape(value);
|
|
306
|
+
}
|
|
307
|
+
if (typeof value === "string" || value instanceof Date) {
|
|
308
|
+
return this.db.sequelize.escape(value);
|
|
161
309
|
}
|
|
162
310
|
throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
|
|
163
311
|
}
|
|
@@ -347,21 +495,20 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
347
495
|
throw new import_validation_error.PostgresValidationError("Field name and type are required");
|
|
348
496
|
}
|
|
349
497
|
const columnName = field.field || field.name;
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
)} ${this.fieldType(collectionName, field)}`;
|
|
498
|
+
const sqlType = this.fieldType(collectionName, field);
|
|
499
|
+
let sql = `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(columnName)} ${sqlType}`;
|
|
353
500
|
if (field.autoIncrement && field.defaultValue !== void 0) {
|
|
354
501
|
throw new import_validation_error.PostgresValidationError("A generated field cannot also have a default value");
|
|
355
502
|
}
|
|
356
503
|
if (field.autoIncrement) sql += " GENERATED BY DEFAULT AS IDENTITY";
|
|
357
504
|
if (field.allowNull === false) sql += " NOT NULL";
|
|
358
|
-
if (field.defaultValue !== void 0) sql += ` DEFAULT ${this.defaultSql(field.defaultValue)}`;
|
|
505
|
+
if (field.defaultValue !== void 0) sql += ` DEFAULT ${this.defaultSql(field.defaultValue, sqlType)}`;
|
|
359
506
|
if (field.primaryKey) sql += " PRIMARY KEY";
|
|
360
507
|
await this.db.sequelize.query(sql, { transaction });
|
|
361
508
|
if (field.unique && !field.primaryKey) await this.setUnique(collectionName, columnName, true, transaction);
|
|
362
509
|
}
|
|
363
510
|
async updateField(collectionName, fieldName, options, transaction) {
|
|
364
|
-
var _a, _b, _c, _d;
|
|
511
|
+
var _a, _b, _c, _d, _e, _f;
|
|
365
512
|
if (!transaction) {
|
|
366
513
|
return this.db.sequelize.transaction(
|
|
367
514
|
(externalTransaction) => this.updateField(collectionName, fieldName, options, externalTransaction)
|
|
@@ -370,10 +517,11 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
370
517
|
const table = this.tableSql(collectionName);
|
|
371
518
|
const columnName = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(fieldName)) == null ? void 0 : _b.columnName()) || fieldName;
|
|
372
519
|
const column = this.quoteIdentifier(columnName);
|
|
373
|
-
|
|
520
|
+
let alteredType;
|
|
521
|
+
if (["type", "dataType", "length", "precision", "scale", "elementType"].some((key) => key in options)) {
|
|
374
522
|
const existing = ((_d = (_c = this.getCollection(collectionName)) == null ? void 0 : _c.getField(fieldName)) == null ? void 0 : _d.options) || {};
|
|
375
|
-
|
|
376
|
-
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${
|
|
523
|
+
alteredType = this.fieldType(collectionName, { ...existing, ...options, name: fieldName });
|
|
524
|
+
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${alteredType}`, {
|
|
377
525
|
transaction
|
|
378
526
|
});
|
|
379
527
|
}
|
|
@@ -386,7 +534,24 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
386
534
|
);
|
|
387
535
|
}
|
|
388
536
|
if (options.defaultValue !== void 0) {
|
|
389
|
-
|
|
537
|
+
let clause;
|
|
538
|
+
if (options.defaultValue === null) {
|
|
539
|
+
clause = "DROP DEFAULT";
|
|
540
|
+
} else {
|
|
541
|
+
let columnType = alteredType;
|
|
542
|
+
if (!columnType) {
|
|
543
|
+
const { schema, tableName } = this.tableInfo(collectionName);
|
|
544
|
+
columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
|
|
545
|
+
if (!columnType) {
|
|
546
|
+
const existing = ((_f = (_e = this.getCollection(collectionName)) == null ? void 0 : _e.getField(fieldName)) == null ? void 0 : _f.options) || {};
|
|
547
|
+
const merged = { ...existing, ...options, name: fieldName };
|
|
548
|
+
if (merged.type) {
|
|
549
|
+
columnType = this.fieldType(collectionName, merged);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
clause = `SET DEFAULT ${this.defaultSql(options.defaultValue, columnType)}`;
|
|
554
|
+
}
|
|
390
555
|
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} ${clause}`, { transaction });
|
|
391
556
|
}
|
|
392
557
|
if (options.unique !== void 0) {
|
|
@@ -697,5 +862,7 @@ class PostgresCollectionManager extends import_data_source_manager.SequelizeColl
|
|
|
697
862
|
}
|
|
698
863
|
// Annotate the CommonJS export names for ESM import in node:
|
|
699
864
|
0 && (module.exports = {
|
|
700
|
-
PostgresCollectionManager
|
|
865
|
+
PostgresCollectionManager,
|
|
866
|
+
applyPostgresArrayDataType,
|
|
867
|
+
isPostgresPhysicalArrayRawType
|
|
701
868
|
});
|
|
@@ -86,7 +86,7 @@ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource
|
|
|
86
86
|
try {
|
|
87
87
|
return await this.collectionManager.discoverTables();
|
|
88
88
|
} finally {
|
|
89
|
-
if (!this.isLoaded) await this.close();
|
|
89
|
+
if (!this.isLoaded && !this.reusedDatabase) await this.close();
|
|
90
90
|
}
|
|
91
91
|
};
|
|
92
92
|
introspector.getTableColumnsInfo = async (tableInfo) => {
|
|
@@ -164,25 +164,27 @@ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource
|
|
|
164
164
|
return tables.map((name) => ({ name }));
|
|
165
165
|
}
|
|
166
166
|
async loadTables(ctx, tables = [], options = {}) {
|
|
167
|
-
var _a, _b, _c, _d
|
|
167
|
+
var _a, _b, _c, _d;
|
|
168
168
|
const names = selectedTables(tables);
|
|
169
|
-
const { actionName, resourceName, params } = ctx.action || {};
|
|
169
|
+
const { actionName, resourceName, params } = (ctx == null ? void 0 : ctx.action) || {};
|
|
170
|
+
const values = (params == null ? void 0 : params.values) && typeof params.values === "object" && !Array.isArray(params.values) ? params.values : void 0;
|
|
170
171
|
const isSettingsAction = resourceName === "dataSources" && ["create", "update"].includes(actionName);
|
|
171
172
|
const isLoadTablesAction = resourceName === "dataSources" && actionName === "loadTables";
|
|
172
|
-
const preserveSelection = Boolean(
|
|
173
|
-
if (
|
|
174
|
-
delete
|
|
173
|
+
const preserveSelection = Boolean(values == null ? void 0 : values.__postgresPreserveSelection);
|
|
174
|
+
if (values && "__postgresPreserveSelection" in values) {
|
|
175
|
+
delete values.__postgresPreserveSelection;
|
|
175
176
|
}
|
|
176
|
-
if (isSettingsAction && Array.isArray(
|
|
177
|
-
|
|
178
|
-
|
|
177
|
+
if (isSettingsAction && values && Array.isArray(values.collections) && !preserveSelection) {
|
|
178
|
+
const currentOptions = values.options && typeof values.options === "object" && !Array.isArray(values.options) ? values.options : {};
|
|
179
|
+
values.options = {
|
|
180
|
+
...currentOptions,
|
|
179
181
|
addAllCollections: false,
|
|
180
182
|
selectedCollections: names
|
|
181
183
|
};
|
|
182
184
|
}
|
|
183
185
|
try {
|
|
184
186
|
let localData = options.localData;
|
|
185
|
-
if (!localData && isLoadTablesAction && ctx.db) {
|
|
187
|
+
if (!localData && isLoadTablesAction && (ctx == null ? void 0 : ctx.db)) {
|
|
186
188
|
const record = await ctx.db.getRepository("dataSources").findOne({
|
|
187
189
|
filterByTk: this.name
|
|
188
190
|
});
|
|
@@ -192,10 +194,10 @@ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource
|
|
|
192
194
|
}
|
|
193
195
|
const collections = await this.prepareTables(names, localData || {});
|
|
194
196
|
this.collectionManager.replaceCollections(collections);
|
|
195
|
-
if (isLoadTablesAction) {
|
|
197
|
+
if (isLoadTablesAction && (ctx == null ? void 0 : ctx.db)) {
|
|
196
198
|
const updatedSelection = await this.addSelectedTables(ctx, names, names);
|
|
197
199
|
if (!updatedSelection && names.length) {
|
|
198
|
-
const plugin = ((
|
|
200
|
+
const plugin = ((_b = (_a = ctx.app) == null ? void 0 : _a.pm) == null ? void 0 : _b.get(import_constants.NAMESPACE)) || ((_d = (_c = ctx.app) == null ? void 0 : _c.pm) == null ? void 0 : _d.get("data-source-postgres"));
|
|
199
201
|
if (plugin) {
|
|
200
202
|
await plugin.sendSyncMessage({
|
|
201
203
|
type: "tablesLoaded",
|
|
@@ -206,7 +208,7 @@ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource
|
|
|
206
208
|
}
|
|
207
209
|
}
|
|
208
210
|
} finally {
|
|
209
|
-
if (!this.isLoaded) await this.close();
|
|
211
|
+
if (!this.isLoaded && !this.reusedDatabase) await this.close();
|
|
210
212
|
}
|
|
211
213
|
}
|
|
212
214
|
async prepareTables(tables, localData = {}) {
|
|
@@ -249,6 +251,38 @@ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource
|
|
|
249
251
|
[inferred],
|
|
250
252
|
saved ? { ...localData, [inferred.name]: saved } : localData
|
|
251
253
|
);
|
|
254
|
+
const inferredByColumn = /* @__PURE__ */ new Map();
|
|
255
|
+
const inferredByName = /* @__PURE__ */ new Map();
|
|
256
|
+
for (const field of inferred.fields || []) {
|
|
257
|
+
const record = field;
|
|
258
|
+
const colKey = String(record.columnName || record.field || record.name || "");
|
|
259
|
+
if (colKey && !inferredByColumn.has(colKey)) {
|
|
260
|
+
inferredByColumn.set(colKey, record);
|
|
261
|
+
}
|
|
262
|
+
if (typeof record.name === "string" && !inferredByName.has(record.name)) {
|
|
263
|
+
inferredByName.set(record.name, record);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (const field of merged.fields || []) {
|
|
267
|
+
const fieldRecord = field;
|
|
268
|
+
const colKey = String(fieldRecord.columnName || fieldRecord.field || fieldRecord.name || "");
|
|
269
|
+
const inferredField = (colKey ? inferredByColumn.get(colKey) : void 0) || inferredByName.get(String(field.name || ""));
|
|
270
|
+
if (inferredField) {
|
|
271
|
+
if (inferredField.rawType !== void 0) {
|
|
272
|
+
fieldRecord.rawType = inferredField.rawType;
|
|
273
|
+
}
|
|
274
|
+
if (field.type === "array" || field.type === "set") {
|
|
275
|
+
if (inferredField.dataType === "array" || (0, import_postgres_collection_manager.isPostgresPhysicalArrayRawType)(inferredField.rawType)) {
|
|
276
|
+
fieldRecord.dataType = "array";
|
|
277
|
+
if ((typeof fieldRecord.elementType !== "string" || !fieldRecord.elementType.trim()) && typeof inferredField.elementType === "string") {
|
|
278
|
+
fieldRecord.elementType = inferredField.elementType;
|
|
279
|
+
}
|
|
280
|
+
} else {
|
|
281
|
+
fieldRecord.dataType = "json";
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
252
286
|
const identityNames = identityByTable.get(tableName);
|
|
253
287
|
if (identityNames == null ? void 0 : identityNames.size) {
|
|
254
288
|
for (const field of merged.fields || []) {
|
|
@@ -26,7 +26,8 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
26
26
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
27
|
var sql_validator_exports = {};
|
|
28
28
|
__export(sql_validator_exports, {
|
|
29
|
-
checkSQL: () => checkSQL
|
|
29
|
+
checkSQL: () => checkSQL,
|
|
30
|
+
normalizeSqlCollectionQuery: () => normalizeSqlCollectionQuery
|
|
30
31
|
});
|
|
31
32
|
module.exports = __toCommonJS(sql_validator_exports);
|
|
32
33
|
var import_validation_error = require("./validation-error");
|
|
@@ -78,84 +79,132 @@ function consumeDoubleQuotedIdentifier(sql, start) {
|
|
|
78
79
|
}
|
|
79
80
|
return { nextIndex: i, sanitized: `"${raw.replace(/[^A-Za-z0-9_]/g, " ")}"` };
|
|
80
81
|
}
|
|
81
|
-
function
|
|
82
|
+
function scanSqlTokens(sql, strict) {
|
|
82
83
|
const out = [];
|
|
84
|
+
const nonTrivia = [];
|
|
83
85
|
let i = 0;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
86
|
+
try {
|
|
87
|
+
while (i < sql.length) {
|
|
88
|
+
const ch = sql[i];
|
|
89
|
+
const next = sql[i + 1];
|
|
90
|
+
if (ch === "-" && next === "-") {
|
|
91
|
+
i += 2;
|
|
92
|
+
while (i < sql.length && sql[i] !== "\n") i += 1;
|
|
93
|
+
out.push(" ");
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (ch === "/" && next === "*") {
|
|
97
|
+
let depth = 1;
|
|
98
|
+
i += 2;
|
|
99
|
+
while (i < sql.length && depth > 0) {
|
|
100
|
+
if (sql[i] === "/" && sql[i + 1] === "*") {
|
|
101
|
+
depth += 1;
|
|
102
|
+
i += 2;
|
|
103
|
+
} else if (sql[i] === "*" && sql[i + 1] === "/") {
|
|
104
|
+
depth -= 1;
|
|
105
|
+
i += 2;
|
|
106
|
+
} else {
|
|
107
|
+
i += 1;
|
|
108
|
+
}
|
|
105
109
|
}
|
|
110
|
+
if (depth > 0) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
|
|
111
|
+
out.push(" ");
|
|
112
|
+
continue;
|
|
106
113
|
}
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
if ((ch === "u" || ch === "U") && next === "&" && (sql[i + 2] === "'" || sql[i + 2] === '"')) {
|
|
112
|
-
throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
|
|
113
|
-
}
|
|
114
|
-
if ((ch === "e" || ch === "E") && next === "'" && (i === 0 || !/[A-Za-z0-9\x80-\uffff_$]/.test(sql[i - 1]))) {
|
|
115
|
-
i = consumeQuotedLiteral(sql, i + 2, true);
|
|
116
|
-
out.push("''");
|
|
117
|
-
continue;
|
|
118
|
-
}
|
|
119
|
-
if (/[A-Za-z\x80-\uffff_]/.test(ch)) {
|
|
120
|
-
const start = i;
|
|
121
|
-
i += 1;
|
|
122
|
-
while (i < sql.length && /[A-Za-z0-9\x80-\uffff_$]/.test(sql[i])) i += 1;
|
|
123
|
-
out.push(sql.slice(start, i));
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
if (ch === "'") {
|
|
127
|
-
i = consumeQuotedLiteral(sql, i + 1, false);
|
|
128
|
-
out.push("''");
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
if (ch === '"') {
|
|
132
|
-
const parsed = consumeDoubleQuotedIdentifier(sql, i);
|
|
133
|
-
out.push(parsed.sanitized);
|
|
134
|
-
i = parsed.nextIndex;
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (ch === "$") {
|
|
138
|
-
const tail = sql.slice(i);
|
|
139
|
-
const paramMatch = tail.match(/^\$[0-9]+/);
|
|
140
|
-
if (paramMatch) {
|
|
141
|
-
out.push(paramMatch[0]);
|
|
142
|
-
i += paramMatch[0].length;
|
|
114
|
+
if (/\s/.test(ch)) {
|
|
115
|
+
out.push(ch);
|
|
116
|
+
i += 1;
|
|
143
117
|
continue;
|
|
144
118
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
119
|
+
if ((ch === "u" || ch === "U") && next === "&" && (sql[i + 2] === "'" || sql[i + 2] === '"')) {
|
|
120
|
+
if (strict) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
|
|
121
|
+
out.push(sql.slice(i, i + 2));
|
|
122
|
+
nonTrivia.push("code");
|
|
123
|
+
i += 2;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if ((ch === "e" || ch === "E") && next === "'" && (i === 0 || !/[A-Za-z0-9\x80-\uffff_$]/.test(sql[i - 1]))) {
|
|
127
|
+
i = consumeQuotedLiteral(sql, i + 2, true);
|
|
151
128
|
out.push("''");
|
|
129
|
+
nonTrivia.push("code");
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (/[A-Za-z\x80-\uffff_]/.test(ch)) {
|
|
133
|
+
const start = i;
|
|
134
|
+
i += 1;
|
|
135
|
+
while (i < sql.length && /[A-Za-z0-9\x80-\uffff_$]/.test(sql[i])) i += 1;
|
|
136
|
+
out.push(sql.slice(start, i));
|
|
137
|
+
nonTrivia.push("code");
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (ch === "'") {
|
|
141
|
+
i = consumeQuotedLiteral(sql, i + 1, false);
|
|
142
|
+
out.push("''");
|
|
143
|
+
nonTrivia.push("code");
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (ch === '"') {
|
|
147
|
+
const parsed = consumeDoubleQuotedIdentifier(sql, i);
|
|
148
|
+
out.push(parsed.sanitized);
|
|
149
|
+
nonTrivia.push("code");
|
|
150
|
+
i = parsed.nextIndex;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (ch === "$") {
|
|
154
|
+
const tail = sql.slice(i);
|
|
155
|
+
const paramMatch = tail.match(/^\$[0-9]+/);
|
|
156
|
+
if (paramMatch) {
|
|
157
|
+
out.push(paramMatch[0]);
|
|
158
|
+
nonTrivia.push("code");
|
|
159
|
+
i += paramMatch[0].length;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const tagMatch = tail.match(/^\$(?:[A-Za-z\x80-\uffff_][A-Za-z0-9\x80-\uffff_]*)?\$/);
|
|
163
|
+
if (tagMatch) {
|
|
164
|
+
const tag = tagMatch[0];
|
|
165
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
166
|
+
if (end === -1) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
|
|
167
|
+
i = end + tag.length;
|
|
168
|
+
out.push("''");
|
|
169
|
+
nonTrivia.push("code");
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (ch === ";") {
|
|
174
|
+
out.push(";");
|
|
175
|
+
nonTrivia.push(i);
|
|
176
|
+
i += 1;
|
|
152
177
|
continue;
|
|
153
178
|
}
|
|
179
|
+
out.push(ch);
|
|
180
|
+
nonTrivia.push("code");
|
|
181
|
+
i += 1;
|
|
154
182
|
}
|
|
155
|
-
|
|
156
|
-
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (strict) throw error;
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
const trailingSemicolonIndices = [];
|
|
188
|
+
for (let idx = nonTrivia.length - 1; idx >= 0; idx -= 1) {
|
|
189
|
+
const token = nonTrivia[idx];
|
|
190
|
+
if (typeof token !== "number") break;
|
|
191
|
+
trailingSemicolonIndices.push(token);
|
|
192
|
+
}
|
|
193
|
+
return { sanitized: out.join("").trim(), trailingSemicolonIndices };
|
|
194
|
+
}
|
|
195
|
+
function sanitizeSQL(sql) {
|
|
196
|
+
const scanned = scanSqlTokens(sql, true);
|
|
197
|
+
if (!scanned) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
|
|
198
|
+
return scanned.sanitized;
|
|
199
|
+
}
|
|
200
|
+
function normalizeSqlCollectionQuery(sql) {
|
|
201
|
+
const scanned = scanSqlTokens(sql, false);
|
|
202
|
+
if (!scanned) return sql.trim();
|
|
203
|
+
let working = sql;
|
|
204
|
+
for (const semiIndex of scanned.trailingSemicolonIndices) {
|
|
205
|
+
working = working.slice(0, semiIndex) + working.slice(semiIndex + 1);
|
|
157
206
|
}
|
|
158
|
-
return
|
|
207
|
+
return working.trim();
|
|
159
208
|
}
|
|
160
209
|
function checkSQL(sql) {
|
|
161
210
|
if (!sql || typeof sql !== "string") {
|
|
@@ -199,5 +248,6 @@ function checkSQL(sql) {
|
|
|
199
248
|
}
|
|
200
249
|
// Annotate the CommonJS export names for ESM import in node:
|
|
201
250
|
0 && (module.exports = {
|
|
202
|
-
checkSQL
|
|
251
|
+
checkSQL,
|
|
252
|
+
normalizeSqlCollectionQuery
|
|
203
253
|
});
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"displayName.zh-CN": "数据源:外部PostgreSQL",
|
|
5
5
|
"description": "Connect to external PostgreSQL databases as data sources",
|
|
6
6
|
"description.zh-CN": "连接外部PostgreSQL数据库作为数据源",
|
|
7
|
-
"version": "2.0.
|
|
7
|
+
"version": "2.0.1",
|
|
8
8
|
"license": "AGPL-3.0",
|
|
9
9
|
"main": "dist/server/index.js",
|
|
10
10
|
"nocobase": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"url": "git+https://github.com/OrgGem/nocobase-beta.git",
|
|
46
46
|
"directory": "packages/plugins/plugin-data-source-postgres"
|
|
47
47
|
},
|
|
48
|
-
"gitHead": "
|
|
48
|
+
"gitHead": "5b21f0f8498a767052d7ee569b54c3e5378ca04f",
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public",
|
|
51
51
|
"registry": "https://registry.npmjs.org/"
|