plugin-data-source-postgres 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +28 -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 +147 -0
  15. package/dist/server/collections/tree-collection.js +118 -0
  16. package/dist/server/hooks/field-hooks.js +392 -0
  17. package/dist/server/index.js +38 -0
  18. package/dist/server/plugin.js +690 -0
  19. package/dist/server/postgres-collection-manager.js +701 -0
  20. package/dist/server/postgres-datasource.js +327 -0
  21. package/dist/server/utils/sql-validator.js +203 -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 +1538 -0
  50. package/src/server/__tests__/sql-model.test.ts +115 -0
  51. package/src/server/__tests__/sql-validator.test.ts +119 -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 +514 -0
  58. package/src/server/index.ts +13 -0
  59. package/src/server/plugin.ts +764 -0
  60. package/src/server/postgres-collection-manager.ts +827 -0
  61. package/src/server/postgres-datasource.ts +365 -0
  62. package/src/server/utils/sql-validator.ts +203 -0
  63. package/src/server/utils/validation-error.ts +38 -0
@@ -0,0 +1,365 @@
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
+ import type { Context } from '@nocobase/actions';
11
+ import { Database, DatabaseOptions } from '@nocobase/database';
12
+ import {
13
+ CollectionOptions,
14
+ DatabaseIntrospector,
15
+ LoadedCollections,
16
+ LoadTablesOptions,
17
+ SequelizeDataSource,
18
+ } from '@nocobase/data-source-manager';
19
+ import { QueryTypes } from 'sequelize';
20
+ import { NAMESPACE } from '../constants';
21
+ import { PostgresCollectionManager } from './postgres-collection-manager';
22
+ import { PostgresValidationError } from './utils/validation-error';
23
+
24
+ interface PostgresOptions {
25
+ host?: string;
26
+ port?: string | number;
27
+ database?: string;
28
+ username?: string;
29
+ password?: string;
30
+ schema?: string;
31
+ ssl?: boolean;
32
+ sslCa?: string;
33
+ autoDiscover?: boolean;
34
+ addAllCollections?: boolean;
35
+ selectedCollections?: string[];
36
+ databaseInstance?: Database;
37
+ collectionManager?: { database?: Database };
38
+ logger?: DatabaseOptions['logger'];
39
+ pool?: DatabaseOptions['pool'];
40
+ }
41
+
42
+ function databaseOptions(options: PostgresOptions): DatabaseOptions {
43
+ const parsedPort = Number(options.port || 5432);
44
+ if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
45
+ throw new PostgresValidationError('Invalid PostgreSQL port');
46
+ }
47
+ return {
48
+ dialect: 'postgres',
49
+ host: options.host,
50
+ port: parsedPort,
51
+ database: options.database,
52
+ username: options.username,
53
+ password: options.password,
54
+ schema: options.schema || 'public',
55
+ logger: options.logger,
56
+ logging: false,
57
+ dialectOptions: {
58
+ connectionTimeoutMillis: 10000,
59
+ ssl: options.ssl ? { rejectUnauthorized: true, ...(options.sslCa ? { ca: options.sslCa } : {}) } : false,
60
+ },
61
+ pool: { max: 10, min: 0, idle: 30000, acquire: 10000, ...(options.pool || {}) },
62
+ };
63
+ }
64
+
65
+ function selectedTables(names: unknown): string[] {
66
+ return Array.isArray(names)
67
+ ? [...new Set(names.filter((name): name is string => typeof name === 'string' && name.length > 0))]
68
+ : [];
69
+ }
70
+
71
+ export class PostgresDataSource extends SequelizeDataSource {
72
+ declare collectionManager: PostgresCollectionManager;
73
+ private isLoaded = false;
74
+ private isClosed = false;
75
+ private reusedDatabase: boolean;
76
+
77
+ constructor(options: PostgresOptions) {
78
+ super(options);
79
+ this.reusedDatabase =
80
+ options.databaseInstance instanceof Database || options.collectionManager?.database instanceof Database;
81
+ }
82
+
83
+ createCollectionManager(options: PostgresOptions = {}): PostgresCollectionManager {
84
+ const existing = options.databaseInstance || options.collectionManager?.database;
85
+ const database = existing instanceof Database ? existing : new Database(databaseOptions(options));
86
+ return new PostgresCollectionManager({
87
+ ...options.collectionManager,
88
+ database,
89
+ collectionsFilter: (collection) =>
90
+ collection.options.introspected || collection.options.dataCategory !== 'system',
91
+ });
92
+ }
93
+
94
+ createDatabaseIntrospector(db: Database): DatabaseIntrospector {
95
+ const introspector = super.createDatabaseIntrospector(db);
96
+ const baseGetColumns = introspector.getTableColumnsInfo.bind(introspector);
97
+ // The manager calls getTables directly for a temporary source when saving settings.
98
+ introspector.getTables = async () => {
99
+ try {
100
+ return await this.collectionManager.discoverTables();
101
+ } finally {
102
+ if (!this.isLoaded) await this.close();
103
+ }
104
+ };
105
+ introspector.getTableColumnsInfo = async (tableInfo: { tableName: string; schema?: string }) => {
106
+ const schema = tableInfo.schema || db.options.schema || 'public';
107
+ try {
108
+ return await baseGetColumns(tableInfo);
109
+ } catch (error) {
110
+ if (!(error instanceof Error) || !error.message.startsWith('No description found for ')) {
111
+ throw error;
112
+ }
113
+ const columns = await this.collectionManager.describeMaterializedView(schema, tableInfo.tableName);
114
+ if (columns) return columns;
115
+ if (await this.collectionManager.hasZeroUserColumns(schema, tableInfo.tableName)) return {};
116
+ throw error;
117
+ }
118
+ };
119
+ introspector.getTableConstraints = async (tableInfo: { tableName: string; schema?: string }) => {
120
+ const schema = tableInfo.schema || db.options.schema || 'public';
121
+ return this.collectionManager.getSingleColumnUniqueIndexes(schema, tableInfo.tableName);
122
+ };
123
+ return introspector;
124
+ }
125
+
126
+ static async testConnection(options: PostgresOptions = {}): Promise<boolean> {
127
+ const database = new Database(databaseOptions(options));
128
+ try {
129
+ await database.sequelize.authenticate();
130
+ return true;
131
+ } finally {
132
+ await database.close();
133
+ }
134
+ }
135
+
136
+ async load(options: { localData?: LoadedCollections } = {}): Promise<void> {
137
+ const localData = options.localData || {};
138
+ this.isLoaded = true;
139
+ try {
140
+ await this.collectionManager.db.sequelize.authenticate();
141
+ const settings = this.options as PostgresOptions;
142
+ const loadAll = settings.addAllCollections ?? settings.autoDiscover !== false;
143
+ const available = await this.introspector.getTables();
144
+ const sqlCollections = Object.values(localData)
145
+ .filter((collection) => typeof collection.sql === 'string' && collection.sql.trim())
146
+ .map((collection) => ({
147
+ ...collection,
148
+ tableName: typeof collection.tableName === 'string' ? collection.tableName : collection.name,
149
+ fields: collection.fields || [],
150
+ introspected: true,
151
+ }));
152
+ const sqlNames = new Set(sqlCollections.map((collection) => collection.name));
153
+ const requested = loadAll
154
+ ? available
155
+ : Array.isArray(settings.selectedCollections)
156
+ ? selectedTables(settings.selectedCollections)
157
+ : Object.values(localData).map((collection) =>
158
+ typeof collection.tableName === 'string' ? collection.tableName : collection.name,
159
+ );
160
+ const existing = new Set(available);
161
+ const names = requested.filter((name) => {
162
+ if (sqlNames.has(name)) return false;
163
+ if (existing.has(name)) return true;
164
+ this.logger?.warn?.(`PostgreSQL table "${name}" is unavailable`);
165
+ return false;
166
+ });
167
+ const collections = await this.prepareTables(names, localData);
168
+ collections.push(...sqlCollections);
169
+ this.collectionManager.replaceCollections(collections);
170
+
171
+ const expected = new Set(collections.map((collection) => collection.name));
172
+ for (const collection of this.collectionManager.getCollections()) {
173
+ if (!expected.has(collection.name)) {
174
+ this.collectionManager.removeCollection(collection.name);
175
+ }
176
+ }
177
+ } catch (error) {
178
+ this.isLoaded = false;
179
+ if (!this.reusedDatabase) await this.close();
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ async readTables(): Promise<Array<{ name: string }>> {
185
+ const tables = await this.introspector.getTables();
186
+ return tables.map((name) => ({ name }));
187
+ }
188
+
189
+ async loadTables(ctx: Context, tables: string[] = [], options: LoadTablesOptions = {}): Promise<void> {
190
+ const names = selectedTables(tables);
191
+ const { actionName, resourceName, params } = ctx.action || {};
192
+ const isSettingsAction = resourceName === 'dataSources' && ['create', 'update'].includes(actionName);
193
+ const isLoadTablesAction = resourceName === 'dataSources' && actionName === 'loadTables';
194
+ const preserveSelection = Boolean(params.values?.__postgresPreserveSelection);
195
+ if (params.values && '__postgresPreserveSelection' in params.values) {
196
+ delete params.values.__postgresPreserveSelection;
197
+ }
198
+ if (isSettingsAction && Array.isArray(params.values?.collections) && !preserveSelection) {
199
+ params.values.options = {
200
+ ...params.values.options,
201
+ addAllCollections: false,
202
+ selectedCollections: names,
203
+ };
204
+ }
205
+ try {
206
+ let localData = options.localData;
207
+ if (!localData && isLoadTablesAction && ctx.db) {
208
+ const record = (await ctx.db.getRepository('dataSources').findOne({
209
+ filterByTk: this.name,
210
+ })) as { loadLocalData?: () => Promise<LoadedCollections> } | null;
211
+ if (record && typeof record.loadLocalData === 'function') {
212
+ localData = await record.loadLocalData();
213
+ }
214
+ }
215
+ const collections = await this.prepareTables(names, localData || {});
216
+ this.collectionManager.replaceCollections(collections);
217
+ if (isLoadTablesAction) {
218
+ const updatedSelection = await this.addSelectedTables(ctx, names, names);
219
+ if (!updatedSelection && names.length) {
220
+ const plugin = ctx.app?.pm?.get(NAMESPACE) || ctx.app?.pm?.get('data-source-postgres');
221
+ if (plugin) {
222
+ await plugin.sendSyncMessage({
223
+ type: 'tablesLoaded',
224
+ dataSourceKey: this.name,
225
+ tableNames: names,
226
+ });
227
+ }
228
+ }
229
+ }
230
+ } finally {
231
+ if (!this.isLoaded) await this.close();
232
+ }
233
+ }
234
+
235
+ async prepareTables(tables: string[], localData: LoadedCollections = {}): Promise<CollectionOptions[]> {
236
+ const tableNames = selectedTables(tables);
237
+ if (!tableNames.length) return [];
238
+ const schema = this.collectionManager.db.options.schema || 'public';
239
+
240
+ const identityRows = await this.collectionManager.db.sequelize.query<{ tableName: string; name: string }>(
241
+ `SELECT table_name AS "tableName", column_name AS name FROM information_schema.columns
242
+ WHERE table_schema = :schema AND table_name IN (:tableNames) AND is_identity = 'YES'`,
243
+ { replacements: { schema, tableNames }, type: QueryTypes.SELECT },
244
+ );
245
+ const identityByTable = new Map<string, Set<string>>();
246
+ for (const row of identityRows) {
247
+ let cols = identityByTable.get(row.tableName);
248
+ if (!cols) {
249
+ cols = new Set<string>();
250
+ identityByTable.set(row.tableName, cols);
251
+ }
252
+ cols.add(row.name);
253
+ }
254
+
255
+ const kindsByTable = await this.collectionManager.getTableKinds(tableNames);
256
+ const collections = new Array<CollectionOptions>(tableNames.length);
257
+ let nextIndex = 0;
258
+
259
+ const runWorker = async () => {
260
+ while (nextIndex < tableNames.length) {
261
+ const index = nextIndex;
262
+ nextIndex += 1;
263
+ const tableName = tableNames[index];
264
+ const kind = kindsByTable.get(tableName);
265
+ const isView = kind === 'v' || kind === 'm';
266
+ const saved = localData[tableName] || Object.values(localData).find((item) => item.tableName === tableName);
267
+ const inferred = await this.introspector.getCollection({
268
+ tableInfo: { tableName, schema },
269
+ localOptions: { ...(isView ? { view: true } : {}), ...(saved || {}) },
270
+ });
271
+ inferred.name = saved?.name || inferred.name;
272
+ inferred.tableName = tableName;
273
+ inferred.schema = schema;
274
+ const [merged] = this.mergeWithLoadedCollections(
275
+ [inferred],
276
+ saved ? { ...localData, [inferred.name]: saved } : localData,
277
+ );
278
+ const identityNames = identityByTable.get(tableName);
279
+ if (identityNames?.size) {
280
+ for (const field of merged.fields || []) {
281
+ if (identityNames.has(field.field || field.name)) field.autoIncrement = true;
282
+ }
283
+ }
284
+ const primaryKeys = (merged.fields || []).filter((field) => field.primaryKey).map((field) => field.name);
285
+ if (!saved?.filterTargetKey && primaryKeys.length) {
286
+ merged.filterTargetKey = primaryKeys.length === 1 ? primaryKeys[0] : primaryKeys;
287
+ }
288
+ merged.introspected = true;
289
+ merged.from = merged.from || 'dbsync';
290
+ if (isView) {
291
+ merged.view = true;
292
+ merged.viewName = tableName;
293
+ merged.template = 'view';
294
+ merged.writableView = false;
295
+ }
296
+ collections[index] = merged;
297
+ }
298
+ };
299
+
300
+ const concurrency = Math.min(5, tableNames.length);
301
+ await Promise.all(Array.from({ length: concurrency }, () => runWorker()));
302
+ return collections;
303
+ }
304
+
305
+ async addSelectedTables(ctx: Context, names: string[], refreshTables?: string[]): Promise<boolean> {
306
+ return this.updateSelectedTables(ctx, names, [], refreshTables);
307
+ }
308
+
309
+ async removeSelectedTables(ctx: Context, names: string[]): Promise<boolean> {
310
+ return this.updateSelectedTables(ctx, [], names);
311
+ }
312
+
313
+ private async updateSelectedTables(
314
+ ctx: Context,
315
+ additions: string[],
316
+ removals: string[],
317
+ refreshTables?: string[],
318
+ ): Promise<boolean> {
319
+ if (!additions.length && !removals.length) return false;
320
+ const repository = ctx.db.getRepository('dataSources');
321
+ let updated: string[] | undefined;
322
+ await ctx.db.sequelize.transaction(async (transaction) => {
323
+ const source = await repository.findOne({ filterByTk: this.name, transaction, lock: transaction.LOCK.UPDATE });
324
+ if (!source) throw new PostgresValidationError('Data source {{name}} does not exist', { name: this.name });
325
+ const current = source.get('options') as PostgresOptions;
326
+ if (current.addAllCollections ?? current.autoDiscover !== false) return;
327
+ const existing =
328
+ current.selectedCollections ||
329
+ this.collectionManager.getCollections().map((collection) => {
330
+ const table = collection.model.getTableName();
331
+ return typeof table === 'string' ? table : table.tableName;
332
+ });
333
+ const removed = new Set(removals);
334
+ const selected = selectedTables([...existing, ...additions]).filter((name) => !removed.has(name));
335
+ if (
336
+ Array.isArray(current.selectedCollections) &&
337
+ selected.length === current.selectedCollections.length &&
338
+ selected.every((name, index) => name === current.selectedCollections[index])
339
+ )
340
+ return;
341
+ source.set('options', { ...current, addAllCollections: false, selectedCollections: selected });
342
+ await source.save({ transaction, hooks: false });
343
+ updated = selected;
344
+ });
345
+ if (!updated) return false;
346
+ if (ctx.app.dataSourceManager.get(this.name) === this) {
347
+ this.options = { ...this.options, addAllCollections: false, selectedCollections: updated };
348
+ }
349
+ const plugin = ctx.app.pm.get(NAMESPACE) || ctx.app.pm.get('data-source-postgres');
350
+ if (plugin) {
351
+ await plugin.sendSyncMessage({
352
+ type: 'selectionChanged',
353
+ dataSourceKey: this.name,
354
+ ...(refreshTables?.length ? { refreshTables } : {}),
355
+ });
356
+ }
357
+ return true;
358
+ }
359
+
360
+ async close(): Promise<void> {
361
+ if (this.isClosed) return;
362
+ this.isClosed = true;
363
+ await this.collectionManager.db.close();
364
+ }
365
+ }
@@ -0,0 +1,203 @@
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
+ import { PostgresValidationError } from './validation-error';
11
+
12
+ const DANGEROUS_PATTERNS = [
13
+ /\bpg_\w*/i,
14
+ /\binformation_schema\b/i,
15
+ /\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,
16
+ ];
17
+
18
+ const CTE_DISALLOWED_KEYWORDS =
19
+ /\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;
20
+
21
+ function consumeQuotedLiteral(sql: string, start: number, allowBackslashEscape: boolean): number {
22
+ let i = start;
23
+ while (i < sql.length) {
24
+ if (allowBackslashEscape && sql[i] === '\\') {
25
+ if (i + 1 >= sql.length) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
26
+ i += 2;
27
+ continue;
28
+ }
29
+ if (sql[i] === "'") {
30
+ if (sql[i + 1] === "'") {
31
+ i += 2;
32
+ continue;
33
+ }
34
+ return i + 1;
35
+ }
36
+ i += 1;
37
+ }
38
+ throw new PostgresValidationError('Invalid or unsupported SQL syntax');
39
+ }
40
+
41
+ function consumeDoubleQuotedIdentifier(sql: string, start: number): { nextIndex: number; sanitized: string } {
42
+ let raw = '';
43
+ let i = start + 1;
44
+ let closed = false;
45
+ while (i < sql.length) {
46
+ if (sql[i] === '"') {
47
+ if (sql[i + 1] === '"') {
48
+ raw += '"';
49
+ i += 2;
50
+ continue;
51
+ }
52
+ i += 1;
53
+ closed = true;
54
+ break;
55
+ }
56
+ raw += sql[i];
57
+ i += 1;
58
+ }
59
+ if (!closed || raw.length === 0) {
60
+ throw new PostgresValidationError('Invalid or unsupported SQL syntax');
61
+ }
62
+ return { nextIndex: i, sanitized: `"${raw.replace(/[^A-Za-z0-9_]/g, ' ')}"` };
63
+ }
64
+
65
+ function sanitizeSQL(sql: string): string {
66
+ const out: string[] = [];
67
+ let i = 0;
68
+
69
+ while (i < sql.length) {
70
+ const ch = sql[i];
71
+ const next = sql[i + 1];
72
+
73
+ if (ch === '-' && next === '-') {
74
+ i += 2;
75
+ while (i < sql.length && sql[i] !== '\n') i += 1;
76
+ out.push(' ');
77
+ continue;
78
+ }
79
+
80
+ if (ch === '/' && next === '*') {
81
+ let depth = 1;
82
+ i += 2;
83
+ while (i < sql.length && depth > 0) {
84
+ if (sql[i] === '/' && sql[i + 1] === '*') {
85
+ depth += 1;
86
+ i += 2;
87
+ } else if (sql[i] === '*' && sql[i + 1] === '/') {
88
+ depth -= 1;
89
+ i += 2;
90
+ } else {
91
+ i += 1;
92
+ }
93
+ }
94
+ if (depth > 0) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
95
+ out.push(' ');
96
+ continue;
97
+ }
98
+
99
+ if ((ch === 'u' || ch === 'U') && next === '&' && (sql[i + 2] === "'" || sql[i + 2] === '"')) {
100
+ throw new PostgresValidationError('Invalid or unsupported SQL syntax');
101
+ }
102
+
103
+ if ((ch === 'e' || ch === 'E') && next === "'" && (i === 0 || !/[A-Za-z0-9\x80-\uffff_$]/.test(sql[i - 1]))) {
104
+ i = consumeQuotedLiteral(sql, i + 2, true);
105
+ out.push("''");
106
+ continue;
107
+ }
108
+
109
+ if (/[A-Za-z\x80-\uffff_]/.test(ch)) {
110
+ const start = i;
111
+ i += 1;
112
+ while (i < sql.length && /[A-Za-z0-9\x80-\uffff_$]/.test(sql[i])) i += 1;
113
+ out.push(sql.slice(start, i));
114
+ continue;
115
+ }
116
+
117
+ if (ch === "'") {
118
+ i = consumeQuotedLiteral(sql, i + 1, false);
119
+ out.push("''");
120
+ continue;
121
+ }
122
+
123
+ if (ch === '"') {
124
+ const parsed = consumeDoubleQuotedIdentifier(sql, i);
125
+ out.push(parsed.sanitized);
126
+ i = parsed.nextIndex;
127
+ continue;
128
+ }
129
+
130
+ if (ch === '$') {
131
+ const tail = sql.slice(i);
132
+ const paramMatch = tail.match(/^\$[0-9]+/);
133
+ if (paramMatch) {
134
+ out.push(paramMatch[0]);
135
+ i += paramMatch[0].length;
136
+ continue;
137
+ }
138
+ const tagMatch = tail.match(/^\$(?:[A-Za-z\x80-\uffff_][A-Za-z0-9\x80-\uffff_]*)?\$/);
139
+ if (tagMatch) {
140
+ const tag = tagMatch[0];
141
+ const end = sql.indexOf(tag, i + tag.length);
142
+ if (end === -1) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
143
+ i = end + tag.length;
144
+ out.push("''");
145
+ continue;
146
+ }
147
+ }
148
+
149
+ out.push(ch);
150
+ i += 1;
151
+ }
152
+
153
+ return out.join('').trim();
154
+ }
155
+
156
+ /**
157
+ * Validate a SQL collection query so only single read-only SELECT/WITH statements run.
158
+ */
159
+ export function checkSQL(sql: string): void {
160
+ if (!sql || typeof sql !== 'string') {
161
+ throw new PostgresValidationError('SQL query is required');
162
+ }
163
+
164
+ let sanitized = sanitizeSQL(sql);
165
+ if (!sanitized) {
166
+ throw new PostgresValidationError('SQL query cannot be empty');
167
+ }
168
+
169
+ if (sanitized.endsWith(';')) {
170
+ sanitized = sanitized.slice(0, -1).trim();
171
+ }
172
+ if (!sanitized) {
173
+ throw new PostgresValidationError('SQL query cannot be empty');
174
+ }
175
+ if (sanitized.includes(';')) {
176
+ throw new PostgresValidationError('Multiple SQL statements are not allowed');
177
+ }
178
+
179
+ if (!/^(select|with)\b/i.test(sanitized)) {
180
+ throw new PostgresValidationError('Only SELECT statements or WITH clauses are supported');
181
+ }
182
+
183
+ if (/^with\b/i.test(sanitized)) {
184
+ if (!/\bselect\b/i.test(sanitized)) {
185
+ throw new PostgresValidationError('Only SELECT statements or WITH clauses are supported');
186
+ }
187
+ const cteMatch = sanitized.match(CTE_DISALLOWED_KEYWORDS);
188
+ if (cteMatch) {
189
+ throw new PostgresValidationError('SQL statement contains dangerous keyword: {{keyword}}', {
190
+ keyword: cteMatch[0].toLowerCase(),
191
+ });
192
+ }
193
+ }
194
+
195
+ for (const pattern of DANGEROUS_PATTERNS) {
196
+ const match = sanitized.match(pattern);
197
+ if (match) {
198
+ throw new PostgresValidationError('SQL statement contains dangerous keyword: {{keyword}}', {
199
+ keyword: match[0].toLowerCase(),
200
+ });
201
+ }
202
+ }
203
+ }
@@ -0,0 +1,38 @@
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
+ import { NAMESPACE } from '../../constants';
11
+
12
+ type TranslationValues = Record<string, string | number>;
13
+ type TranslationContext = { [key: string]: unknown };
14
+
15
+ export class PostgresValidationError extends Error {
16
+ readonly status: number;
17
+ readonly statusCode: number;
18
+
19
+ constructor(
20
+ public readonly key: string,
21
+ public readonly values: TranslationValues = {},
22
+ status = 400,
23
+ ) {
24
+ super(key.replace(/{{\s*(\w+)\s*}}/g, (_match, name: string) => String(values[name] ?? '')));
25
+ this.name = 'PostgresValidationError';
26
+ this.status = status;
27
+ this.statusCode = status;
28
+ }
29
+ }
30
+
31
+ export function translateError(ctx: TranslationContext, error: PostgresValidationError): string {
32
+ if (typeof ctx.t !== 'function') return error.message;
33
+ return ctx.t(error.key, { ns: NAMESPACE, ...error.values });
34
+ }
35
+
36
+ export function translate(ctx: TranslationContext, key: string, values: TranslationValues = {}): string {
37
+ return translateError(ctx, new PostgresValidationError(key, values));
38
+ }