plugin-data-source-postgres 0.0.0-stage → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/constants.js +45 -0
- package/dist/externalVersion.js +29 -0
- package/dist/locale/en-US.json +141 -0
- package/dist/locale/zh-CN.json +141 -0
- package/dist/server/collections/adjacency-list-repository.js +340 -0
- package/dist/server/collections/index.js +45 -0
- package/dist/server/collections/sql-collection.js +84 -0
- package/dist/server/collections/sql-model.js +149 -0
- package/dist/server/collections/tree-collection.js +118 -0
- package/dist/server/hooks/field-hooks.js +412 -0
- package/dist/server/index.js +38 -0
- package/dist/server/plugin.js +1273 -0
- package/dist/server/postgres-collection-manager.js +868 -0
- package/dist/server/postgres-datasource.js +361 -0
- package/dist/server/utils/sql-validator.js +253 -0
- package/dist/server/utils/validation-error.js +59 -0
- package/package.json +51 -4
- package/server.js +1 -0
- package/src/client/AddCollectionAction.tsx +307 -0
- package/src/client/ConfigurationForm.tsx +203 -0
- package/src/client/PostgresCollectionTemplate.tsx +109 -0
- package/src/client/__tests__/client-v1.test.tsx +265 -0
- package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
- package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
- package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
- package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
- package/src/client/collection-templates/base-template-helper.ts +62 -0
- package/src/client/collection-templates/field-interfaces-config.ts +73 -0
- package/src/client/collection-templates/index.ts +19 -0
- package/src/client/index.tsx +69 -0
- package/src/client-v2/PostgresAddCollection.tsx +422 -0
- package/src/client-v2/PostgresConfigForm.tsx +178 -0
- package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
- package/src/client-v2/__tests__/plugin.test.tsx +372 -0
- package/src/client-v2/collection-options.ts +22 -0
- package/src/client-v2/index.tsx +10 -0
- package/src/client-v2/plugin.tsx +71 -0
- package/src/constants.ts +20 -0
- package/src/locale/en-US.json +141 -0
- package/src/locale/zh-CN.json +141 -0
- package/src/server/__tests__/field-hooks.test.ts +357 -0
- package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
- package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
- package/src/server/__tests__/sql-model.test.ts +159 -0
- package/src/server/__tests__/sql-validator.test.ts +126 -0
- package/src/server/collections/adjacency-list-repository.ts +378 -0
- package/src/server/collections/index.ts +19 -0
- package/src/server/collections/sql-collection.ts +66 -0
- package/src/server/collections/sql-model.ts +158 -0
- package/src/server/collections/tree-collection.ts +102 -0
- package/src/server/hooks/field-hooks.ts +548 -0
- package/src/server/index.ts +13 -0
- package/src/server/plugin.ts +1499 -0
- package/src/server/postgres-collection-manager.ts +1027 -0
- package/src/server/postgres-datasource.ts +410 -0
- package/src/server/utils/sql-validator.ts +258 -0
- package/src/server/utils/validation-error.ts +38 -0
|
@@ -0,0 +1,410 @@
|
|
|
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 { isPostgresPhysicalArrayRawType, 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 && !this.reusedDatabase) 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 values =
|
|
193
|
+
params?.values && typeof params.values === 'object' && !Array.isArray(params.values)
|
|
194
|
+
? (params.values as Record<string, unknown>)
|
|
195
|
+
: undefined;
|
|
196
|
+
const isSettingsAction = resourceName === 'dataSources' && ['create', 'update'].includes(actionName);
|
|
197
|
+
const isLoadTablesAction = resourceName === 'dataSources' && actionName === 'loadTables';
|
|
198
|
+
const preserveSelection = Boolean(values?.__postgresPreserveSelection);
|
|
199
|
+
if (values && '__postgresPreserveSelection' in values) {
|
|
200
|
+
delete values.__postgresPreserveSelection;
|
|
201
|
+
}
|
|
202
|
+
if (isSettingsAction && values && Array.isArray(values.collections) && !preserveSelection) {
|
|
203
|
+
const currentOptions =
|
|
204
|
+
values.options && typeof values.options === 'object' && !Array.isArray(values.options)
|
|
205
|
+
? (values.options as Record<string, unknown>)
|
|
206
|
+
: {};
|
|
207
|
+
values.options = {
|
|
208
|
+
...currentOptions,
|
|
209
|
+
addAllCollections: false,
|
|
210
|
+
selectedCollections: names,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
let localData = options.localData;
|
|
215
|
+
if (!localData && isLoadTablesAction && ctx?.db) {
|
|
216
|
+
const record = (await ctx.db.getRepository('dataSources').findOne({
|
|
217
|
+
filterByTk: this.name,
|
|
218
|
+
})) as { loadLocalData?: () => Promise<LoadedCollections> } | null;
|
|
219
|
+
if (record && typeof record.loadLocalData === 'function') {
|
|
220
|
+
localData = await record.loadLocalData();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const collections = await this.prepareTables(names, localData || {});
|
|
224
|
+
this.collectionManager.replaceCollections(collections);
|
|
225
|
+
if (isLoadTablesAction && ctx?.db) {
|
|
226
|
+
const updatedSelection = await this.addSelectedTables(ctx, names, names);
|
|
227
|
+
if (!updatedSelection && names.length) {
|
|
228
|
+
const plugin = ctx.app?.pm?.get(NAMESPACE) || ctx.app?.pm?.get('data-source-postgres');
|
|
229
|
+
if (plugin) {
|
|
230
|
+
await plugin.sendSyncMessage({
|
|
231
|
+
type: 'tablesLoaded',
|
|
232
|
+
dataSourceKey: this.name,
|
|
233
|
+
tableNames: names,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
} finally {
|
|
239
|
+
if (!this.isLoaded && !this.reusedDatabase) await this.close();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async prepareTables(tables: string[], localData: LoadedCollections = {}): Promise<CollectionOptions[]> {
|
|
244
|
+
const tableNames = selectedTables(tables);
|
|
245
|
+
if (!tableNames.length) return [];
|
|
246
|
+
const schema = this.collectionManager.db.options.schema || 'public';
|
|
247
|
+
|
|
248
|
+
const identityRows = await this.collectionManager.db.sequelize.query<{ tableName: string; name: string }>(
|
|
249
|
+
`SELECT table_name AS "tableName", column_name AS name FROM information_schema.columns
|
|
250
|
+
WHERE table_schema = :schema AND table_name IN (:tableNames) AND is_identity = 'YES'`,
|
|
251
|
+
{ replacements: { schema, tableNames }, type: QueryTypes.SELECT },
|
|
252
|
+
);
|
|
253
|
+
const identityByTable = new Map<string, Set<string>>();
|
|
254
|
+
for (const row of identityRows) {
|
|
255
|
+
let cols = identityByTable.get(row.tableName);
|
|
256
|
+
if (!cols) {
|
|
257
|
+
cols = new Set<string>();
|
|
258
|
+
identityByTable.set(row.tableName, cols);
|
|
259
|
+
}
|
|
260
|
+
cols.add(row.name);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const kindsByTable = await this.collectionManager.getTableKinds(tableNames);
|
|
264
|
+
const collections = new Array<CollectionOptions>(tableNames.length);
|
|
265
|
+
let nextIndex = 0;
|
|
266
|
+
|
|
267
|
+
const runWorker = async () => {
|
|
268
|
+
while (nextIndex < tableNames.length) {
|
|
269
|
+
const index = nextIndex;
|
|
270
|
+
nextIndex += 1;
|
|
271
|
+
const tableName = tableNames[index];
|
|
272
|
+
const kind = kindsByTable.get(tableName);
|
|
273
|
+
const isView = kind === 'v' || kind === 'm';
|
|
274
|
+
const saved = localData[tableName] || Object.values(localData).find((item) => item.tableName === tableName);
|
|
275
|
+
const inferred = await this.introspector.getCollection({
|
|
276
|
+
tableInfo: { tableName, schema },
|
|
277
|
+
localOptions: { ...(isView ? { view: true } : {}), ...(saved || {}) },
|
|
278
|
+
});
|
|
279
|
+
inferred.name = saved?.name || inferred.name;
|
|
280
|
+
inferred.tableName = tableName;
|
|
281
|
+
inferred.schema = schema;
|
|
282
|
+
const [merged] = this.mergeWithLoadedCollections(
|
|
283
|
+
[inferred],
|
|
284
|
+
saved ? { ...localData, [inferred.name]: saved } : localData,
|
|
285
|
+
);
|
|
286
|
+
const inferredByColumn = new Map<string, Record<string, unknown>>();
|
|
287
|
+
const inferredByName = new Map<string, Record<string, unknown>>();
|
|
288
|
+
for (const field of inferred.fields || []) {
|
|
289
|
+
const record = field as unknown as Record<string, unknown>;
|
|
290
|
+
const colKey = String(record.columnName || record.field || record.name || '');
|
|
291
|
+
if (colKey && !inferredByColumn.has(colKey)) {
|
|
292
|
+
inferredByColumn.set(colKey, record);
|
|
293
|
+
}
|
|
294
|
+
if (typeof record.name === 'string' && !inferredByName.has(record.name)) {
|
|
295
|
+
inferredByName.set(record.name, record);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
for (const field of merged.fields || []) {
|
|
299
|
+
const fieldRecord = field as unknown as Record<string, unknown>;
|
|
300
|
+
const colKey = String(fieldRecord.columnName || fieldRecord.field || fieldRecord.name || '');
|
|
301
|
+
const inferredField =
|
|
302
|
+
(colKey ? inferredByColumn.get(colKey) : undefined) || inferredByName.get(String(field.name || ''));
|
|
303
|
+
if (inferredField) {
|
|
304
|
+
if (inferredField.rawType !== undefined) {
|
|
305
|
+
fieldRecord.rawType = inferredField.rawType;
|
|
306
|
+
}
|
|
307
|
+
if (field.type === 'array' || field.type === 'set') {
|
|
308
|
+
if (inferredField.dataType === 'array' || isPostgresPhysicalArrayRawType(inferredField.rawType)) {
|
|
309
|
+
fieldRecord.dataType = 'array';
|
|
310
|
+
if (
|
|
311
|
+
(typeof fieldRecord.elementType !== 'string' || !fieldRecord.elementType.trim()) &&
|
|
312
|
+
typeof inferredField.elementType === 'string'
|
|
313
|
+
) {
|
|
314
|
+
fieldRecord.elementType = inferredField.elementType;
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
// Keep JSONB storage for legacy array fields backed by JSON/JSONB columns in PostgreSQL.
|
|
318
|
+
fieldRecord.dataType = 'json';
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const identityNames = identityByTable.get(tableName);
|
|
324
|
+
if (identityNames?.size) {
|
|
325
|
+
for (const field of merged.fields || []) {
|
|
326
|
+
if (identityNames.has(field.field || field.name)) field.autoIncrement = true;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const primaryKeys = (merged.fields || []).filter((field) => field.primaryKey).map((field) => field.name);
|
|
330
|
+
if (!saved?.filterTargetKey && primaryKeys.length) {
|
|
331
|
+
merged.filterTargetKey = primaryKeys.length === 1 ? primaryKeys[0] : primaryKeys;
|
|
332
|
+
}
|
|
333
|
+
merged.introspected = true;
|
|
334
|
+
merged.from = merged.from || 'dbsync';
|
|
335
|
+
if (isView) {
|
|
336
|
+
merged.view = true;
|
|
337
|
+
merged.viewName = tableName;
|
|
338
|
+
merged.template = 'view';
|
|
339
|
+
merged.writableView = false;
|
|
340
|
+
}
|
|
341
|
+
collections[index] = merged;
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
const concurrency = Math.min(5, tableNames.length);
|
|
346
|
+
await Promise.all(Array.from({ length: concurrency }, () => runWorker()));
|
|
347
|
+
return collections;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async addSelectedTables(ctx: Context, names: string[], refreshTables?: string[]): Promise<boolean> {
|
|
351
|
+
return this.updateSelectedTables(ctx, names, [], refreshTables);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async removeSelectedTables(ctx: Context, names: string[]): Promise<boolean> {
|
|
355
|
+
return this.updateSelectedTables(ctx, [], names);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private async updateSelectedTables(
|
|
359
|
+
ctx: Context,
|
|
360
|
+
additions: string[],
|
|
361
|
+
removals: string[],
|
|
362
|
+
refreshTables?: string[],
|
|
363
|
+
): Promise<boolean> {
|
|
364
|
+
if (!additions.length && !removals.length) return false;
|
|
365
|
+
const repository = ctx.db.getRepository('dataSources');
|
|
366
|
+
let updated: string[] | undefined;
|
|
367
|
+
await ctx.db.sequelize.transaction(async (transaction) => {
|
|
368
|
+
const source = await repository.findOne({ filterByTk: this.name, transaction, lock: transaction.LOCK.UPDATE });
|
|
369
|
+
if (!source) throw new PostgresValidationError('Data source {{name}} does not exist', { name: this.name });
|
|
370
|
+
const current = source.get('options') as PostgresOptions;
|
|
371
|
+
if (current.addAllCollections ?? current.autoDiscover !== false) return;
|
|
372
|
+
const existing =
|
|
373
|
+
current.selectedCollections ||
|
|
374
|
+
this.collectionManager.getCollections().map((collection) => {
|
|
375
|
+
const table = collection.model.getTableName();
|
|
376
|
+
return typeof table === 'string' ? table : table.tableName;
|
|
377
|
+
});
|
|
378
|
+
const removed = new Set(removals);
|
|
379
|
+
const selected = selectedTables([...existing, ...additions]).filter((name) => !removed.has(name));
|
|
380
|
+
if (
|
|
381
|
+
Array.isArray(current.selectedCollections) &&
|
|
382
|
+
selected.length === current.selectedCollections.length &&
|
|
383
|
+
selected.every((name, index) => name === current.selectedCollections[index])
|
|
384
|
+
)
|
|
385
|
+
return;
|
|
386
|
+
source.set('options', { ...current, addAllCollections: false, selectedCollections: selected });
|
|
387
|
+
await source.save({ transaction, hooks: false });
|
|
388
|
+
updated = selected;
|
|
389
|
+
});
|
|
390
|
+
if (!updated) return false;
|
|
391
|
+
if (ctx.app.dataSourceManager.get(this.name) === this) {
|
|
392
|
+
this.options = { ...this.options, addAllCollections: false, selectedCollections: updated };
|
|
393
|
+
}
|
|
394
|
+
const plugin = ctx.app.pm.get(NAMESPACE) || ctx.app.pm.get('data-source-postgres');
|
|
395
|
+
if (plugin) {
|
|
396
|
+
await plugin.sendSyncMessage({
|
|
397
|
+
type: 'selectionChanged',
|
|
398
|
+
dataSourceKey: this.name,
|
|
399
|
+
...(refreshTables?.length ? { refreshTables } : {}),
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async close(): Promise<void> {
|
|
406
|
+
if (this.isClosed) return;
|
|
407
|
+
this.isClosed = true;
|
|
408
|
+
await this.collectionManager.db.close();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
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 scanSqlTokens(sql: string, strict: boolean): { sanitized: string; trailingSemicolonIndices: number[] } | null {
|
|
66
|
+
const out: string[] = [];
|
|
67
|
+
const nonTrivia: Array<'code' | number> = [];
|
|
68
|
+
let i = 0;
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
while (i < sql.length) {
|
|
72
|
+
const ch = sql[i];
|
|
73
|
+
const next = sql[i + 1];
|
|
74
|
+
|
|
75
|
+
if (ch === '-' && next === '-') {
|
|
76
|
+
i += 2;
|
|
77
|
+
while (i < sql.length && sql[i] !== '\n') i += 1;
|
|
78
|
+
out.push(' ');
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (ch === '/' && next === '*') {
|
|
83
|
+
let depth = 1;
|
|
84
|
+
i += 2;
|
|
85
|
+
while (i < sql.length && depth > 0) {
|
|
86
|
+
if (sql[i] === '/' && sql[i + 1] === '*') {
|
|
87
|
+
depth += 1;
|
|
88
|
+
i += 2;
|
|
89
|
+
} else if (sql[i] === '*' && sql[i + 1] === '/') {
|
|
90
|
+
depth -= 1;
|
|
91
|
+
i += 2;
|
|
92
|
+
} else {
|
|
93
|
+
i += 1;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (depth > 0) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
|
|
97
|
+
out.push(' ');
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (/\s/.test(ch)) {
|
|
102
|
+
out.push(ch);
|
|
103
|
+
i += 1;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if ((ch === 'u' || ch === 'U') && next === '&' && (sql[i + 2] === "'" || sql[i + 2] === '"')) {
|
|
108
|
+
if (strict) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
|
|
109
|
+
out.push(sql.slice(i, i + 2));
|
|
110
|
+
nonTrivia.push('code');
|
|
111
|
+
i += 2;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if ((ch === 'e' || ch === 'E') && next === "'" && (i === 0 || !/[A-Za-z0-9\x80-\uffff_$]/.test(sql[i - 1]))) {
|
|
116
|
+
i = consumeQuotedLiteral(sql, i + 2, true);
|
|
117
|
+
out.push("''");
|
|
118
|
+
nonTrivia.push('code');
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (/[A-Za-z\x80-\uffff_]/.test(ch)) {
|
|
123
|
+
const start = i;
|
|
124
|
+
i += 1;
|
|
125
|
+
while (i < sql.length && /[A-Za-z0-9\x80-\uffff_$]/.test(sql[i])) i += 1;
|
|
126
|
+
out.push(sql.slice(start, i));
|
|
127
|
+
nonTrivia.push('code');
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (ch === "'") {
|
|
132
|
+
i = consumeQuotedLiteral(sql, i + 1, false);
|
|
133
|
+
out.push("''");
|
|
134
|
+
nonTrivia.push('code');
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (ch === '"') {
|
|
139
|
+
const parsed = consumeDoubleQuotedIdentifier(sql, i);
|
|
140
|
+
out.push(parsed.sanitized);
|
|
141
|
+
nonTrivia.push('code');
|
|
142
|
+
i = parsed.nextIndex;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (ch === '$') {
|
|
147
|
+
const tail = sql.slice(i);
|
|
148
|
+
const paramMatch = tail.match(/^\$[0-9]+/);
|
|
149
|
+
if (paramMatch) {
|
|
150
|
+
out.push(paramMatch[0]);
|
|
151
|
+
nonTrivia.push('code');
|
|
152
|
+
i += paramMatch[0].length;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const tagMatch = tail.match(/^\$(?:[A-Za-z\x80-\uffff_][A-Za-z0-9\x80-\uffff_]*)?\$/);
|
|
156
|
+
if (tagMatch) {
|
|
157
|
+
const tag = tagMatch[0];
|
|
158
|
+
const end = sql.indexOf(tag, i + tag.length);
|
|
159
|
+
if (end === -1) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
|
|
160
|
+
i = end + tag.length;
|
|
161
|
+
out.push("''");
|
|
162
|
+
nonTrivia.push('code');
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (ch === ';') {
|
|
168
|
+
out.push(';');
|
|
169
|
+
nonTrivia.push(i);
|
|
170
|
+
i += 1;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
out.push(ch);
|
|
175
|
+
nonTrivia.push('code');
|
|
176
|
+
i += 1;
|
|
177
|
+
}
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if (strict) throw error;
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const trailingSemicolonIndices: number[] = [];
|
|
184
|
+
for (let idx = nonTrivia.length - 1; idx >= 0; idx -= 1) {
|
|
185
|
+
const token = nonTrivia[idx];
|
|
186
|
+
if (typeof token !== 'number') break;
|
|
187
|
+
trailingSemicolonIndices.push(token);
|
|
188
|
+
}
|
|
189
|
+
return { sanitized: out.join('').trim(), trailingSemicolonIndices };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function sanitizeSQL(sql: string): string {
|
|
193
|
+
const scanned = scanSqlTokens(sql, true);
|
|
194
|
+
if (!scanned) throw new PostgresValidationError('Invalid or unsupported SQL syntax');
|
|
195
|
+
return scanned.sanitized;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Strip trailing statement semicolons after any comments/whitespace so subquery wrapping stays valid.
|
|
200
|
+
*/
|
|
201
|
+
export function normalizeSqlCollectionQuery(sql: string): string {
|
|
202
|
+
const scanned = scanSqlTokens(sql, false);
|
|
203
|
+
if (!scanned) return sql.trim();
|
|
204
|
+
let working = sql;
|
|
205
|
+
for (const semiIndex of scanned.trailingSemicolonIndices) {
|
|
206
|
+
working = working.slice(0, semiIndex) + working.slice(semiIndex + 1);
|
|
207
|
+
}
|
|
208
|
+
return working.trim();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Validate a SQL collection query so only single read-only SELECT/WITH statements run.
|
|
213
|
+
*/
|
|
214
|
+
export function checkSQL(sql: string): void {
|
|
215
|
+
if (!sql || typeof sql !== 'string') {
|
|
216
|
+
throw new PostgresValidationError('SQL query is required');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
let sanitized = sanitizeSQL(sql);
|
|
220
|
+
if (!sanitized) {
|
|
221
|
+
throw new PostgresValidationError('SQL query cannot be empty');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (sanitized.endsWith(';')) {
|
|
225
|
+
sanitized = sanitized.slice(0, -1).trim();
|
|
226
|
+
}
|
|
227
|
+
if (!sanitized) {
|
|
228
|
+
throw new PostgresValidationError('SQL query cannot be empty');
|
|
229
|
+
}
|
|
230
|
+
if (sanitized.includes(';')) {
|
|
231
|
+
throw new PostgresValidationError('Multiple SQL statements are not allowed');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (!/^(select|with)\b/i.test(sanitized)) {
|
|
235
|
+
throw new PostgresValidationError('Only SELECT statements or WITH clauses are supported');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (/^with\b/i.test(sanitized)) {
|
|
239
|
+
if (!/\bselect\b/i.test(sanitized)) {
|
|
240
|
+
throw new PostgresValidationError('Only SELECT statements or WITH clauses are supported');
|
|
241
|
+
}
|
|
242
|
+
const cteMatch = sanitized.match(CTE_DISALLOWED_KEYWORDS);
|
|
243
|
+
if (cteMatch) {
|
|
244
|
+
throw new PostgresValidationError('SQL statement contains dangerous keyword: {{keyword}}', {
|
|
245
|
+
keyword: cteMatch[0].toLowerCase(),
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
for (const pattern of DANGEROUS_PATTERNS) {
|
|
251
|
+
const match = sanitized.match(pattern);
|
|
252
|
+
if (match) {
|
|
253
|
+
throw new PostgresValidationError('SQL statement contains dangerous keyword: {{keyword}}', {
|
|
254
|
+
keyword: match[0].toLowerCase(),
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|