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.
Files changed (63) hide show
  1. package/README.md +9 -3
  2. package/client-v2.js +1 -0
  3. package/client.js +1 -0
  4. package/dist/client/index.js +10 -0
  5. package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
  6. package/dist/client-v2/index.js +10 -0
  7. package/dist/constants.js +45 -0
  8. package/dist/externalVersion.js +29 -0
  9. package/dist/locale/en-US.json +141 -0
  10. package/dist/locale/zh-CN.json +141 -0
  11. package/dist/server/collections/adjacency-list-repository.js +340 -0
  12. package/dist/server/collections/index.js +45 -0
  13. package/dist/server/collections/sql-collection.js +84 -0
  14. package/dist/server/collections/sql-model.js +149 -0
  15. package/dist/server/collections/tree-collection.js +118 -0
  16. package/dist/server/hooks/field-hooks.js +412 -0
  17. package/dist/server/index.js +38 -0
  18. package/dist/server/plugin.js +1273 -0
  19. package/dist/server/postgres-collection-manager.js +868 -0
  20. package/dist/server/postgres-datasource.js +361 -0
  21. package/dist/server/utils/sql-validator.js +253 -0
  22. package/dist/server/utils/validation-error.js +59 -0
  23. package/package.json +51 -4
  24. package/server.js +1 -0
  25. package/src/client/AddCollectionAction.tsx +307 -0
  26. package/src/client/ConfigurationForm.tsx +203 -0
  27. package/src/client/PostgresCollectionTemplate.tsx +109 -0
  28. package/src/client/__tests__/client-v1.test.tsx +265 -0
  29. package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
  30. package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
  31. package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
  32. package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
  33. package/src/client/collection-templates/base-template-helper.ts +62 -0
  34. package/src/client/collection-templates/field-interfaces-config.ts +73 -0
  35. package/src/client/collection-templates/index.ts +19 -0
  36. package/src/client/index.tsx +69 -0
  37. package/src/client-v2/PostgresAddCollection.tsx +422 -0
  38. package/src/client-v2/PostgresConfigForm.tsx +178 -0
  39. package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
  40. package/src/client-v2/__tests__/plugin.test.tsx +372 -0
  41. package/src/client-v2/collection-options.ts +22 -0
  42. package/src/client-v2/index.tsx +10 -0
  43. package/src/client-v2/plugin.tsx +71 -0
  44. package/src/constants.ts +20 -0
  45. package/src/locale/en-US.json +141 -0
  46. package/src/locale/zh-CN.json +141 -0
  47. package/src/server/__tests__/field-hooks.test.ts +357 -0
  48. package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
  49. package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
  50. package/src/server/__tests__/sql-model.test.ts +159 -0
  51. package/src/server/__tests__/sql-validator.test.ts +126 -0
  52. package/src/server/collections/adjacency-list-repository.ts +378 -0
  53. package/src/server/collections/index.ts +19 -0
  54. package/src/server/collections/sql-collection.ts +66 -0
  55. package/src/server/collections/sql-model.ts +158 -0
  56. package/src/server/collections/tree-collection.ts +102 -0
  57. package/src/server/hooks/field-hooks.ts +548 -0
  58. package/src/server/index.ts +13 -0
  59. package/src/server/plugin.ts +1499 -0
  60. package/src/server/postgres-collection-manager.ts +1027 -0
  61. package/src/server/postgres-datasource.ts +410 -0
  62. package/src/server/utils/sql-validator.ts +258 -0
  63. package/src/server/utils/validation-error.ts +38 -0
@@ -0,0 +1,361 @@
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 postgres_datasource_exports = {};
28
+ __export(postgres_datasource_exports, {
29
+ PostgresDataSource: () => PostgresDataSource
30
+ });
31
+ module.exports = __toCommonJS(postgres_datasource_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_data_source_manager = require("@nocobase/data-source-manager");
34
+ var import_sequelize = require("sequelize");
35
+ var import_constants = require("../constants");
36
+ var import_postgres_collection_manager = require("./postgres-collection-manager");
37
+ var import_validation_error = require("./utils/validation-error");
38
+ function databaseOptions(options) {
39
+ const parsedPort = Number(options.port || 5432);
40
+ if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
41
+ throw new import_validation_error.PostgresValidationError("Invalid PostgreSQL port");
42
+ }
43
+ return {
44
+ dialect: "postgres",
45
+ host: options.host,
46
+ port: parsedPort,
47
+ database: options.database,
48
+ username: options.username,
49
+ password: options.password,
50
+ schema: options.schema || "public",
51
+ logger: options.logger,
52
+ logging: false,
53
+ dialectOptions: {
54
+ connectionTimeoutMillis: 1e4,
55
+ ssl: options.ssl ? { rejectUnauthorized: true, ...options.sslCa ? { ca: options.sslCa } : {} } : false
56
+ },
57
+ pool: { max: 10, min: 0, idle: 3e4, acquire: 1e4, ...options.pool || {} }
58
+ };
59
+ }
60
+ function selectedTables(names) {
61
+ return Array.isArray(names) ? [...new Set(names.filter((name) => typeof name === "string" && name.length > 0))] : [];
62
+ }
63
+ class PostgresDataSource extends import_data_source_manager.SequelizeDataSource {
64
+ isLoaded = false;
65
+ isClosed = false;
66
+ reusedDatabase;
67
+ constructor(options) {
68
+ var _a;
69
+ super(options);
70
+ this.reusedDatabase = options.databaseInstance instanceof import_database.Database || ((_a = options.collectionManager) == null ? void 0 : _a.database) instanceof import_database.Database;
71
+ }
72
+ createCollectionManager(options = {}) {
73
+ var _a;
74
+ const existing = options.databaseInstance || ((_a = options.collectionManager) == null ? void 0 : _a.database);
75
+ const database = existing instanceof import_database.Database ? existing : new import_database.Database(databaseOptions(options));
76
+ return new import_postgres_collection_manager.PostgresCollectionManager({
77
+ ...options.collectionManager,
78
+ database,
79
+ collectionsFilter: (collection) => collection.options.introspected || collection.options.dataCategory !== "system"
80
+ });
81
+ }
82
+ createDatabaseIntrospector(db) {
83
+ const introspector = super.createDatabaseIntrospector(db);
84
+ const baseGetColumns = introspector.getTableColumnsInfo.bind(introspector);
85
+ introspector.getTables = async () => {
86
+ try {
87
+ return await this.collectionManager.discoverTables();
88
+ } finally {
89
+ if (!this.isLoaded && !this.reusedDatabase) await this.close();
90
+ }
91
+ };
92
+ introspector.getTableColumnsInfo = async (tableInfo) => {
93
+ const schema = tableInfo.schema || db.options.schema || "public";
94
+ try {
95
+ return await baseGetColumns(tableInfo);
96
+ } catch (error) {
97
+ if (!(error instanceof Error) || !error.message.startsWith("No description found for ")) {
98
+ throw error;
99
+ }
100
+ const columns = await this.collectionManager.describeMaterializedView(schema, tableInfo.tableName);
101
+ if (columns) return columns;
102
+ if (await this.collectionManager.hasZeroUserColumns(schema, tableInfo.tableName)) return {};
103
+ throw error;
104
+ }
105
+ };
106
+ introspector.getTableConstraints = async (tableInfo) => {
107
+ const schema = tableInfo.schema || db.options.schema || "public";
108
+ return this.collectionManager.getSingleColumnUniqueIndexes(schema, tableInfo.tableName);
109
+ };
110
+ return introspector;
111
+ }
112
+ static async testConnection(options = {}) {
113
+ const database = new import_database.Database(databaseOptions(options));
114
+ try {
115
+ await database.sequelize.authenticate();
116
+ return true;
117
+ } finally {
118
+ await database.close();
119
+ }
120
+ }
121
+ async load(options = {}) {
122
+ const localData = options.localData || {};
123
+ this.isLoaded = true;
124
+ try {
125
+ await this.collectionManager.db.sequelize.authenticate();
126
+ const settings = this.options;
127
+ const loadAll = settings.addAllCollections ?? settings.autoDiscover !== false;
128
+ const available = await this.introspector.getTables();
129
+ const sqlCollections = Object.values(localData).filter((collection) => typeof collection.sql === "string" && collection.sql.trim()).map((collection) => ({
130
+ ...collection,
131
+ tableName: typeof collection.tableName === "string" ? collection.tableName : collection.name,
132
+ fields: collection.fields || [],
133
+ introspected: true
134
+ }));
135
+ const sqlNames = new Set(sqlCollections.map((collection) => collection.name));
136
+ const requested = loadAll ? available : Array.isArray(settings.selectedCollections) ? selectedTables(settings.selectedCollections) : Object.values(localData).map(
137
+ (collection) => typeof collection.tableName === "string" ? collection.tableName : collection.name
138
+ );
139
+ const existing = new Set(available);
140
+ const names = requested.filter((name) => {
141
+ var _a, _b;
142
+ if (sqlNames.has(name)) return false;
143
+ if (existing.has(name)) return true;
144
+ (_b = (_a = this.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `PostgreSQL table "${name}" is unavailable`);
145
+ return false;
146
+ });
147
+ const collections = await this.prepareTables(names, localData);
148
+ collections.push(...sqlCollections);
149
+ this.collectionManager.replaceCollections(collections);
150
+ const expected = new Set(collections.map((collection) => collection.name));
151
+ for (const collection of this.collectionManager.getCollections()) {
152
+ if (!expected.has(collection.name)) {
153
+ this.collectionManager.removeCollection(collection.name);
154
+ }
155
+ }
156
+ } catch (error) {
157
+ this.isLoaded = false;
158
+ if (!this.reusedDatabase) await this.close();
159
+ throw error;
160
+ }
161
+ }
162
+ async readTables() {
163
+ const tables = await this.introspector.getTables();
164
+ return tables.map((name) => ({ name }));
165
+ }
166
+ async loadTables(ctx, tables = [], options = {}) {
167
+ var _a, _b, _c, _d;
168
+ const names = selectedTables(tables);
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;
171
+ const isSettingsAction = resourceName === "dataSources" && ["create", "update"].includes(actionName);
172
+ const isLoadTablesAction = resourceName === "dataSources" && actionName === "loadTables";
173
+ const preserveSelection = Boolean(values == null ? void 0 : values.__postgresPreserveSelection);
174
+ if (values && "__postgresPreserveSelection" in values) {
175
+ delete values.__postgresPreserveSelection;
176
+ }
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,
181
+ addAllCollections: false,
182
+ selectedCollections: names
183
+ };
184
+ }
185
+ try {
186
+ let localData = options.localData;
187
+ if (!localData && isLoadTablesAction && (ctx == null ? void 0 : ctx.db)) {
188
+ const record = await ctx.db.getRepository("dataSources").findOne({
189
+ filterByTk: this.name
190
+ });
191
+ if (record && typeof record.loadLocalData === "function") {
192
+ localData = await record.loadLocalData();
193
+ }
194
+ }
195
+ const collections = await this.prepareTables(names, localData || {});
196
+ this.collectionManager.replaceCollections(collections);
197
+ if (isLoadTablesAction && (ctx == null ? void 0 : ctx.db)) {
198
+ const updatedSelection = await this.addSelectedTables(ctx, names, names);
199
+ if (!updatedSelection && names.length) {
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"));
201
+ if (plugin) {
202
+ await plugin.sendSyncMessage({
203
+ type: "tablesLoaded",
204
+ dataSourceKey: this.name,
205
+ tableNames: names
206
+ });
207
+ }
208
+ }
209
+ }
210
+ } finally {
211
+ if (!this.isLoaded && !this.reusedDatabase) await this.close();
212
+ }
213
+ }
214
+ async prepareTables(tables, localData = {}) {
215
+ const tableNames = selectedTables(tables);
216
+ if (!tableNames.length) return [];
217
+ const schema = this.collectionManager.db.options.schema || "public";
218
+ const identityRows = await this.collectionManager.db.sequelize.query(
219
+ `SELECT table_name AS "tableName", column_name AS name FROM information_schema.columns
220
+ WHERE table_schema = :schema AND table_name IN (:tableNames) AND is_identity = 'YES'`,
221
+ { replacements: { schema, tableNames }, type: import_sequelize.QueryTypes.SELECT }
222
+ );
223
+ const identityByTable = /* @__PURE__ */ new Map();
224
+ for (const row of identityRows) {
225
+ let cols = identityByTable.get(row.tableName);
226
+ if (!cols) {
227
+ cols = /* @__PURE__ */ new Set();
228
+ identityByTable.set(row.tableName, cols);
229
+ }
230
+ cols.add(row.name);
231
+ }
232
+ const kindsByTable = await this.collectionManager.getTableKinds(tableNames);
233
+ const collections = new Array(tableNames.length);
234
+ let nextIndex = 0;
235
+ const runWorker = async () => {
236
+ while (nextIndex < tableNames.length) {
237
+ const index = nextIndex;
238
+ nextIndex += 1;
239
+ const tableName = tableNames[index];
240
+ const kind = kindsByTable.get(tableName);
241
+ const isView = kind === "v" || kind === "m";
242
+ const saved = localData[tableName] || Object.values(localData).find((item) => item.tableName === tableName);
243
+ const inferred = await this.introspector.getCollection({
244
+ tableInfo: { tableName, schema },
245
+ localOptions: { ...isView ? { view: true } : {}, ...saved || {} }
246
+ });
247
+ inferred.name = (saved == null ? void 0 : saved.name) || inferred.name;
248
+ inferred.tableName = tableName;
249
+ inferred.schema = schema;
250
+ const [merged] = this.mergeWithLoadedCollections(
251
+ [inferred],
252
+ saved ? { ...localData, [inferred.name]: saved } : localData
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
+ }
286
+ const identityNames = identityByTable.get(tableName);
287
+ if (identityNames == null ? void 0 : identityNames.size) {
288
+ for (const field of merged.fields || []) {
289
+ if (identityNames.has(field.field || field.name)) field.autoIncrement = true;
290
+ }
291
+ }
292
+ const primaryKeys = (merged.fields || []).filter((field) => field.primaryKey).map((field) => field.name);
293
+ if (!(saved == null ? void 0 : saved.filterTargetKey) && primaryKeys.length) {
294
+ merged.filterTargetKey = primaryKeys.length === 1 ? primaryKeys[0] : primaryKeys;
295
+ }
296
+ merged.introspected = true;
297
+ merged.from = merged.from || "dbsync";
298
+ if (isView) {
299
+ merged.view = true;
300
+ merged.viewName = tableName;
301
+ merged.template = "view";
302
+ merged.writableView = false;
303
+ }
304
+ collections[index] = merged;
305
+ }
306
+ };
307
+ const concurrency = Math.min(5, tableNames.length);
308
+ await Promise.all(Array.from({ length: concurrency }, () => runWorker()));
309
+ return collections;
310
+ }
311
+ async addSelectedTables(ctx, names, refreshTables) {
312
+ return this.updateSelectedTables(ctx, names, [], refreshTables);
313
+ }
314
+ async removeSelectedTables(ctx, names) {
315
+ return this.updateSelectedTables(ctx, [], names);
316
+ }
317
+ async updateSelectedTables(ctx, additions, removals, refreshTables) {
318
+ if (!additions.length && !removals.length) return false;
319
+ const repository = ctx.db.getRepository("dataSources");
320
+ let updated;
321
+ await ctx.db.sequelize.transaction(async (transaction) => {
322
+ const source = await repository.findOne({ filterByTk: this.name, transaction, lock: transaction.LOCK.UPDATE });
323
+ if (!source) throw new import_validation_error.PostgresValidationError("Data source {{name}} does not exist", { name: this.name });
324
+ const current = source.get("options");
325
+ if (current.addAllCollections ?? current.autoDiscover !== false) return;
326
+ const existing = current.selectedCollections || this.collectionManager.getCollections().map((collection) => {
327
+ const table = collection.model.getTableName();
328
+ return typeof table === "string" ? table : table.tableName;
329
+ });
330
+ const removed = new Set(removals);
331
+ const selected = selectedTables([...existing, ...additions]).filter((name) => !removed.has(name));
332
+ if (Array.isArray(current.selectedCollections) && selected.length === current.selectedCollections.length && selected.every((name, index) => name === current.selectedCollections[index]))
333
+ return;
334
+ source.set("options", { ...current, addAllCollections: false, selectedCollections: selected });
335
+ await source.save({ transaction, hooks: false });
336
+ updated = selected;
337
+ });
338
+ if (!updated) return false;
339
+ if (ctx.app.dataSourceManager.get(this.name) === this) {
340
+ this.options = { ...this.options, addAllCollections: false, selectedCollections: updated };
341
+ }
342
+ const plugin = ctx.app.pm.get(import_constants.NAMESPACE) || ctx.app.pm.get("data-source-postgres");
343
+ if (plugin) {
344
+ await plugin.sendSyncMessage({
345
+ type: "selectionChanged",
346
+ dataSourceKey: this.name,
347
+ ...(refreshTables == null ? void 0 : refreshTables.length) ? { refreshTables } : {}
348
+ });
349
+ }
350
+ return true;
351
+ }
352
+ async close() {
353
+ if (this.isClosed) return;
354
+ this.isClosed = true;
355
+ await this.collectionManager.db.close();
356
+ }
357
+ }
358
+ // Annotate the CommonJS export names for ESM import in node:
359
+ 0 && (module.exports = {
360
+ PostgresDataSource
361
+ });
@@ -0,0 +1,253 @@
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 sql_validator_exports = {};
28
+ __export(sql_validator_exports, {
29
+ checkSQL: () => checkSQL,
30
+ normalizeSqlCollectionQuery: () => normalizeSqlCollectionQuery
31
+ });
32
+ module.exports = __toCommonJS(sql_validator_exports);
33
+ var import_validation_error = require("./validation-error");
34
+ const DANGEROUS_PATTERNS = [
35
+ /\bpg_\w*/i,
36
+ /\binformation_schema\b/i,
37
+ /\b(?:current_setting|set_config|generate_series|lo_import|lo_export|dblink\w*|query_to_xml\w*|table_to_xml\w*|cursor_to_xml\w*|xmlparse|copy|uescape)\b/i
38
+ ];
39
+ const CTE_DISALLOWED_KEYWORDS = /\b(?:insert|update|delete|merge|create|alter|drop|truncate|grant|revoke|copy|call|do|execute|prepare|deallocate|lock|vacuum|analyze|cluster|reindex|refresh)\b/i;
40
+ function consumeQuotedLiteral(sql, start, allowBackslashEscape) {
41
+ let i = start;
42
+ while (i < sql.length) {
43
+ if (allowBackslashEscape && sql[i] === "\\") {
44
+ if (i + 1 >= sql.length) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
45
+ i += 2;
46
+ continue;
47
+ }
48
+ if (sql[i] === "'") {
49
+ if (sql[i + 1] === "'") {
50
+ i += 2;
51
+ continue;
52
+ }
53
+ return i + 1;
54
+ }
55
+ i += 1;
56
+ }
57
+ throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
58
+ }
59
+ function consumeDoubleQuotedIdentifier(sql, start) {
60
+ let raw = "";
61
+ let i = start + 1;
62
+ let closed = false;
63
+ while (i < sql.length) {
64
+ if (sql[i] === '"') {
65
+ if (sql[i + 1] === '"') {
66
+ raw += '"';
67
+ i += 2;
68
+ continue;
69
+ }
70
+ i += 1;
71
+ closed = true;
72
+ break;
73
+ }
74
+ raw += sql[i];
75
+ i += 1;
76
+ }
77
+ if (!closed || raw.length === 0) {
78
+ throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
79
+ }
80
+ return { nextIndex: i, sanitized: `"${raw.replace(/[^A-Za-z0-9_]/g, " ")}"` };
81
+ }
82
+ function scanSqlTokens(sql, strict) {
83
+ const out = [];
84
+ const nonTrivia = [];
85
+ let i = 0;
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
+ }
109
+ }
110
+ if (depth > 0) throw new import_validation_error.PostgresValidationError("Invalid or unsupported SQL syntax");
111
+ out.push(" ");
112
+ continue;
113
+ }
114
+ if (/\s/.test(ch)) {
115
+ out.push(ch);
116
+ i += 1;
117
+ continue;
118
+ }
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);
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;
177
+ continue;
178
+ }
179
+ out.push(ch);
180
+ nonTrivia.push("code");
181
+ i += 1;
182
+ }
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);
206
+ }
207
+ return working.trim();
208
+ }
209
+ function checkSQL(sql) {
210
+ if (!sql || typeof sql !== "string") {
211
+ throw new import_validation_error.PostgresValidationError("SQL query is required");
212
+ }
213
+ let sanitized = sanitizeSQL(sql);
214
+ if (!sanitized) {
215
+ throw new import_validation_error.PostgresValidationError("SQL query cannot be empty");
216
+ }
217
+ if (sanitized.endsWith(";")) {
218
+ sanitized = sanitized.slice(0, -1).trim();
219
+ }
220
+ if (!sanitized) {
221
+ throw new import_validation_error.PostgresValidationError("SQL query cannot be empty");
222
+ }
223
+ if (sanitized.includes(";")) {
224
+ throw new import_validation_error.PostgresValidationError("Multiple SQL statements are not allowed");
225
+ }
226
+ if (!/^(select|with)\b/i.test(sanitized)) {
227
+ throw new import_validation_error.PostgresValidationError("Only SELECT statements or WITH clauses are supported");
228
+ }
229
+ if (/^with\b/i.test(sanitized)) {
230
+ if (!/\bselect\b/i.test(sanitized)) {
231
+ throw new import_validation_error.PostgresValidationError("Only SELECT statements or WITH clauses are supported");
232
+ }
233
+ const cteMatch = sanitized.match(CTE_DISALLOWED_KEYWORDS);
234
+ if (cteMatch) {
235
+ throw new import_validation_error.PostgresValidationError("SQL statement contains dangerous keyword: {{keyword}}", {
236
+ keyword: cteMatch[0].toLowerCase()
237
+ });
238
+ }
239
+ }
240
+ for (const pattern of DANGEROUS_PATTERNS) {
241
+ const match = sanitized.match(pattern);
242
+ if (match) {
243
+ throw new import_validation_error.PostgresValidationError("SQL statement contains dangerous keyword: {{keyword}}", {
244
+ keyword: match[0].toLowerCase()
245
+ });
246
+ }
247
+ }
248
+ }
249
+ // Annotate the CommonJS export names for ESM import in node:
250
+ 0 && (module.exports = {
251
+ checkSQL,
252
+ normalizeSqlCollectionQuery
253
+ });
@@ -0,0 +1,59 @@
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 validation_error_exports = {};
28
+ __export(validation_error_exports, {
29
+ PostgresValidationError: () => PostgresValidationError,
30
+ translate: () => translate,
31
+ translateError: () => translateError
32
+ });
33
+ module.exports = __toCommonJS(validation_error_exports);
34
+ var import_constants = require("../../constants");
35
+ class PostgresValidationError extends Error {
36
+ constructor(key, values = {}, status = 400) {
37
+ super(key.replace(/{{\s*(\w+)\s*}}/g, (_match, name) => String(values[name] ?? "")));
38
+ this.key = key;
39
+ this.values = values;
40
+ this.name = "PostgresValidationError";
41
+ this.status = status;
42
+ this.statusCode = status;
43
+ }
44
+ status;
45
+ statusCode;
46
+ }
47
+ function translateError(ctx, error) {
48
+ if (typeof ctx.t !== "function") return error.message;
49
+ return ctx.t(error.key, { ns: import_constants.NAMESPACE, ...error.values });
50
+ }
51
+ function translate(ctx, key, values = {}) {
52
+ return translateError(ctx, new PostgresValidationError(key, values));
53
+ }
54
+ // Annotate the CommonJS export names for ESM import in node:
55
+ 0 && (module.exports = {
56
+ PostgresValidationError,
57
+ translate,
58
+ translateError
59
+ });