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,764 @@
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, Next } from '@nocobase/actions';
11
+ import type { DataSource, LoadedCollections } from '@nocobase/data-source-manager';
12
+ import type { Collection, Model } from '@nocobase/database';
13
+ import { Plugin } from '@nocobase/server';
14
+ import { cloneDeep, isEqual, omit, pick } from 'lodash';
15
+ import type { Transaction } from 'sequelize';
16
+ import { DATA_SOURCE_TYPE } from '../constants';
17
+ import { PostgresSQLCollection } from './collections/sql-collection';
18
+ import { PostgresTreeCollection } from './collections/tree-collection';
19
+ import {
20
+ buildArrayForeignKeyField,
21
+ fieldReferencesColumn,
22
+ getRelationLockTables,
23
+ removesPhysicalColumn,
24
+ syncFieldAction,
25
+ } from './hooks/field-hooks';
26
+ import { PostgresDataSource } from './postgres-datasource';
27
+ import { checkSQL } from './utils/sql-validator';
28
+ import { PostgresValidationError, translate, translateError } from './utils/validation-error';
29
+
30
+ const FIELD_ACTIONS = new Set(['create', 'update', 'apply', 'destroy']);
31
+ const WRITE_ACTIONS = new Set([
32
+ 'create',
33
+ 'firstOrCreate',
34
+ 'updateOrCreate',
35
+ 'update',
36
+ 'destroy',
37
+ 'destroyMany',
38
+ 'updateMany',
39
+ 'add',
40
+ 'remove',
41
+ 'set',
42
+ 'toggle',
43
+ 'move',
44
+ 'importXlsx',
45
+ ]);
46
+
47
+ type FieldValues = {
48
+ name?: string;
49
+ type?: string;
50
+ field?: string;
51
+ interface?: string;
52
+ allowNull?: boolean;
53
+ defaultValue?: unknown;
54
+ unique?: boolean;
55
+ settings?: FieldValues;
56
+ [key: string]: unknown;
57
+ };
58
+
59
+ const PRESET_FIELDS: Record<string, FieldValues> = {
60
+ id: { name: 'id', type: 'bigInt', interface: 'id', primaryKey: true, autoIncrement: true, allowNull: false },
61
+ createdAt: { name: 'createdAt', type: 'date', interface: 'createdAt', field: 'createdAt' },
62
+ updatedAt: { name: 'updatedAt', type: 'date', interface: 'updatedAt', field: 'updatedAt' },
63
+ };
64
+
65
+ function isRecord(value: unknown): value is Record<string, unknown> {
66
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
67
+ }
68
+
69
+ function extractSql(values: Record<string, unknown> | undefined): unknown {
70
+ if (!values) return undefined;
71
+ if (values.sql !== undefined) return values.sql;
72
+ return isRecord(values.options) ? values.options.sql : undefined;
73
+ }
74
+
75
+ function names(value: unknown): string[] {
76
+ const values = Array.isArray(value) ? value : [value];
77
+ if (!values.length || values.some((item) => typeof item !== 'string' || !item)) {
78
+ throw new PostgresValidationError('A collection name is required');
79
+ }
80
+ return [...new Set(values as string[])];
81
+ }
82
+
83
+ function prepareFields(values: Record<string, unknown>): void {
84
+ if (!Array.isArray(values.fields)) return;
85
+ const hasStringPresets = values.fields.some((field) => typeof field === 'string');
86
+ if (hasStringPresets || (values.template === 'general' && values.fields.length === 0)) {
87
+ const selectedPresets = new Set(values.fields.filter((field): field is string => typeof field === 'string'));
88
+ values.autoGenId = selectedPresets.has('id');
89
+ values.createdAt = selectedPresets.has('createdAt');
90
+ values.updatedAt = selectedPresets.has('updatedAt');
91
+ values.timestamps = Boolean(values.createdAt || values.updatedAt);
92
+ } else if (values.createdAt === false && values.updatedAt === false && values.timestamps === undefined) {
93
+ values.timestamps = false;
94
+ }
95
+ const mapped: FieldValues[] = values.fields.map((field: FieldValues | string) => {
96
+ if (typeof field !== 'string') return field;
97
+ const preset = PRESET_FIELDS[field];
98
+ if (!preset) throw new PostgresValidationError('Unknown preset field {{name}}', { name: field });
99
+ return cloneDeep(preset);
100
+ });
101
+ const isSql = extractSql(values) !== undefined || values.template === 'sql';
102
+ if (!isSql) {
103
+ if (values.createdAt === true && !mapped.some((field) => field.name === 'createdAt')) {
104
+ mapped.push(cloneDeep(PRESET_FIELDS.createdAt));
105
+ }
106
+ if (values.updatedAt === true && !mapped.some((field) => field.name === 'updatedAt')) {
107
+ mapped.push(cloneDeep(PRESET_FIELDS.updatedAt));
108
+ }
109
+ }
110
+ values.fields = mapped;
111
+ }
112
+
113
+ async function localizeValidationErrors(ctx: Context, next: Next) {
114
+ try {
115
+ await next();
116
+ } catch (error) {
117
+ if (error instanceof PostgresValidationError) error.message = translateError(ctx, error);
118
+ const params = ctx.action?.params || {};
119
+ const postgresConnection =
120
+ ctx.action?.resourceName === 'dataSources' &&
121
+ (params.values?.type === DATA_SOURCE_TYPE ||
122
+ ctx.app?.dataSourceManager?.get(params.filterByTk) instanceof PostgresDataSource);
123
+ if (
124
+ postgresConnection &&
125
+ error instanceof Error &&
126
+ error.message === 'Test connection failed: Invalid PostgreSQL port'
127
+ ) {
128
+ error.message = translate(ctx, 'Test connection failed: {{reason}}', {
129
+ reason: translate(ctx, 'Invalid PostgreSQL port'),
130
+ });
131
+ const httpError = error as Error & { status?: number; statusCode?: number };
132
+ httpError.status = 400;
133
+ httpError.statusCode = 400;
134
+ }
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ type PostgresSyncMessage = {
140
+ type?: string;
141
+ dataSourceKey?: string;
142
+ collectionName?: string;
143
+ collectionNames?: string[];
144
+ tableNames?: string[];
145
+ refreshTables?: string[];
146
+ fieldName?: string;
147
+ };
148
+
149
+ export class PluginDataSourcePostgresServer extends Plugin {
150
+ private selectionSyncs = new Map<string, Promise<void>>();
151
+ private activeSources = new Map<string, PostgresDataSource>();
152
+
153
+ private async closeDataSource(dataSourceKey: string, expectedSource?: PostgresDataSource) {
154
+ const current = this.app.dataSourceManager.get(dataSourceKey);
155
+ const tracked = this.activeSources.get(dataSourceKey);
156
+ const source = expectedSource || (current instanceof PostgresDataSource ? current : tracked);
157
+ if (!source) return;
158
+ if (tracked === source) {
159
+ this.activeSources.delete(dataSourceKey);
160
+ }
161
+ if (current === source) {
162
+ this.app.dataSourceManager.dataSources.delete(dataSourceKey);
163
+ }
164
+ const replacement = this.app.dataSourceManager.get(dataSourceKey);
165
+ if (
166
+ replacement instanceof PostgresDataSource &&
167
+ replacement !== source &&
168
+ replacement.collectionManager.db === source.collectionManager.db
169
+ ) {
170
+ return;
171
+ }
172
+ try {
173
+ await source.close();
174
+ } catch (error) {
175
+ this.app.log?.warn?.(`Failed to close PostgreSQL data source "${dataSourceKey}"`, { cause: error });
176
+ }
177
+ }
178
+
179
+ private async enqueueSelectionSync(key: string, task: () => Promise<void>) {
180
+ const previous = this.selectionSyncs.get(key) || Promise.resolve();
181
+ const current = previous.catch(() => undefined).then(task);
182
+ this.selectionSyncs.set(key, current);
183
+ try {
184
+ await current;
185
+ } finally {
186
+ if (this.selectionSyncs.get(key) === current) this.selectionSyncs.delete(key);
187
+ }
188
+ }
189
+
190
+ async handleSyncMessage(message: PostgresSyncMessage) {
191
+ if (!message?.dataSourceKey) return;
192
+ const key = message.dataSourceKey;
193
+ if (message.type === 'dataSourceRemoved') {
194
+ const existingRecord = await this.app.db?.getRepository?.('dataSources')?.findOne?.({ filterByTk: key });
195
+ if (existingRecord) return;
196
+ await this.closeDataSource(key);
197
+ return;
198
+ }
199
+ if (message.type === 'selectionChanged') {
200
+ const refreshTables = Array.isArray(message.refreshTables)
201
+ ? message.refreshTables.filter((name): name is string => typeof name === 'string' && name.length > 0)
202
+ : [];
203
+ await this.enqueueSelectionSync(key, () => this.reconcileSelection(key, refreshTables));
204
+ return;
205
+ }
206
+
207
+ if (message.type === 'tablesLoaded' && Array.isArray(message.tableNames)) {
208
+ const tableNames = message.tableNames;
209
+ await this.enqueueSelectionSync(key, () => this.syncLoadedTables(key, tableNames));
210
+ return;
211
+ }
212
+
213
+ const source = this.app.dataSourceManager.get(key);
214
+ if (!(source instanceof PostgresDataSource)) return;
215
+
216
+ if (message.type === 'collectionCreated' && message.collectionName) {
217
+ await this.syncCreatedCollection(source, key, message.collectionName);
218
+ return;
219
+ }
220
+
221
+ if (message.type === 'collectionRemoved' && Array.isArray(message.collectionNames)) {
222
+ for (const name of message.collectionNames) {
223
+ if (typeof name === 'string' && source.collectionManager.hasCollection(name)) {
224
+ source.collectionManager.removeCollection(name);
225
+ }
226
+ }
227
+ return;
228
+ }
229
+
230
+ if (message.type === 'fieldRemoved' && message.collectionName && message.fieldName) {
231
+ const collection = source.collectionManager.getCollection(message.collectionName);
232
+ if (collection?.getField(message.fieldName)) {
233
+ collection.removeField(message.fieldName);
234
+ }
235
+ }
236
+ }
237
+
238
+ private async syncLoadedTables(dataSourceKey: string, tableNames: string[]) {
239
+ const source = this.app.dataSourceManager.get(dataSourceKey);
240
+ if (!(source instanceof PostgresDataSource)) return;
241
+ const requested = [
242
+ ...new Set(tableNames.filter((name): name is string => typeof name === 'string' && name.length > 0)),
243
+ ];
244
+ if (!requested.length) return;
245
+ const record = (await this.app.db.getRepository('dataSources').findOne({ filterByTk: dataSourceKey })) as
246
+ | (Model & { loadLocalData?: () => Promise<LoadedCollections> })
247
+ | null;
248
+ if (!record) return;
249
+ const storedOptions = typeof record.get === 'function' ? record.get('options') || {} : {};
250
+ const selectedFilter =
251
+ storedOptions.addAllCollections === false && Array.isArray(storedOptions.selectedCollections)
252
+ ? new Set(storedOptions.selectedCollections.filter((name: unknown): name is string => typeof name === 'string'))
253
+ : undefined;
254
+ const allowed = selectedFilter ? requested.filter((name) => selectedFilter.has(name)) : requested;
255
+ if (!allowed.length) return;
256
+ const localData = typeof record.loadLocalData === 'function' ? await record.loadLocalData() : {};
257
+ const available = new Set(await source.introspector.getTables());
258
+ const targets = allowed.filter((name) => available.has(name));
259
+ if (!targets.length) return;
260
+ const collections = await source.prepareTables(targets, localData);
261
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
262
+ source.collectionManager.replaceCollections(collections);
263
+ }
264
+
265
+ private async syncCreatedCollection(source: PostgresDataSource, dataSourceKey: string, collectionName: string) {
266
+ const collectionRecord = await this.app.db.getRepository('dataSourcesCollections').findOne({
267
+ filter: { dataSourceKey, name: collectionName },
268
+ });
269
+ if (!collectionRecord) return;
270
+ const fieldRecords = await this.app.db.getRepository('dataSourcesFields').find({
271
+ filter: { dataSourceKey, collectionName },
272
+ });
273
+ const collectionOptions = {
274
+ ...collectionRecord.toJSON(),
275
+ fields: fieldRecords.map((field) => field.toJSON()),
276
+ };
277
+ if (typeof collectionOptions.sql === 'string' && collectionOptions.sql.trim()) {
278
+ const existing = source.collectionManager.getCollection(collectionName);
279
+ if (existing) {
280
+ existing.updateOptions(collectionOptions);
281
+ } else {
282
+ source.collectionManager.defineCollection({
283
+ ...collectionOptions,
284
+ tableName: typeof collectionOptions.tableName === 'string' ? collectionOptions.tableName : collectionName,
285
+ introspected: true,
286
+ });
287
+ }
288
+ return;
289
+ }
290
+ const tableName = typeof collectionOptions.tableName === 'string' ? collectionOptions.tableName : collectionName;
291
+ const [prepared] = await source.prepareTables([tableName], { [collectionName]: collectionOptions });
292
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source || !prepared) return;
293
+ const existing = source.collectionManager.getCollection(collectionName);
294
+ if (existing) {
295
+ existing.updateOptions(prepared);
296
+ } else {
297
+ source.collectionManager.defineCollection(prepared);
298
+ }
299
+ }
300
+
301
+ private async reconcileSelection(dataSourceKey: string, refreshTables: string[] = []) {
302
+ const source = this.app.dataSourceManager.get(dataSourceKey);
303
+ if (!(source instanceof PostgresDataSource)) return;
304
+ const record = await this.app.db.getRepository('dataSources').findOne({ filterByTk: dataSourceKey });
305
+ if (!record) return;
306
+ const storedOptions = record.get('options') || {};
307
+ if (storedOptions.addAllCollections !== false || !Array.isArray(storedOptions.selectedCollections)) return;
308
+ const resolvedOptions = this.app.environment.renderJsonTemplate(storedOptions);
309
+ const activeOptions = pick(source.options, Object.keys(resolvedOptions));
310
+ const selectAll = source.options.addAllCollections ?? source.options.autoDiscover !== false;
311
+ if (
312
+ selectAll ||
313
+ !isEqual(
314
+ omit(activeOptions, ['selectedCollections', 'addAllCollections']),
315
+ omit(resolvedOptions, ['selectedCollections', 'addAllCollections']),
316
+ )
317
+ )
318
+ return;
319
+
320
+ const selected = new Set<string>(
321
+ storedOptions.selectedCollections.filter((name: unknown): name is string => typeof name === 'string'),
322
+ );
323
+ const available = new Set(await source.introspector.getTables());
324
+ const localData = await record.loadLocalData();
325
+ const existing = source.collectionManager.getCollections();
326
+ const physicalName = (collection: Collection) => {
327
+ const table = collection.model.getTableName();
328
+ return typeof table === 'string' ? table : table.tableName;
329
+ };
330
+ const missing = [...selected].filter(
331
+ (name) => available.has(name) && !existing.some((item) => physicalName(item) === name),
332
+ );
333
+ const refreshed = refreshTables.filter((name) => selected.has(name) && available.has(name));
334
+ const targets = [...new Set([...missing, ...refreshed])];
335
+ const collections = await source.prepareTables(targets, localData);
336
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
337
+ source.collectionManager.replaceCollections(collections);
338
+ for (const collection of existing) {
339
+ if (!collection.options.sql && !selected.has(physicalName(collection))) {
340
+ source.collectionManager.removeCollection(collection.name);
341
+ }
342
+ }
343
+ source.options = { ...source.options, addAllCollections: false, selectedCollections: [...selected] };
344
+ }
345
+
346
+ async beforeLoad() {
347
+ this.app.dataSourceManager.registerDataSourceType(DATA_SOURCE_TYPE, PostgresDataSource);
348
+ this.app.dataSourceManager.beforeAddDataSource((dataSource: DataSource) => {
349
+ if (!(dataSource instanceof PostgresDataSource)) return;
350
+ const { db } = dataSource.collectionManager;
351
+ db.collectionFactory.registerCollectionType(PostgresSQLCollection, {
352
+ condition: (options) => Boolean(options.sql),
353
+ async onSync() {},
354
+ async onDump() {},
355
+ });
356
+ db.collectionFactory.registerCollectionType(PostgresTreeCollection, {
357
+ condition: (options) => Boolean(options.postgresTree || options.template === 'tree'),
358
+ });
359
+ dataSource.resourceManager.use(localizeValidationErrors, {
360
+ tag: 'postgres-validation-errors',
361
+ after: ['auth'],
362
+ before: ['acl'],
363
+ });
364
+ dataSource.resourceManager.use(
365
+ async (ctx, next) => {
366
+ if (WRITE_ACTIONS.has(ctx.action?.actionName)) {
367
+ const resourceName = ctx.action?.resourceName;
368
+ const [sourceName, associationName] = typeof resourceName === 'string' ? resourceName.split('.') : [];
369
+ const sourceCollection = sourceName ? dataSource.collectionManager.getCollection(sourceName) : undefined;
370
+ const targetCollection =
371
+ sourceCollection && associationName && resourceName
372
+ ? dataSource.collectionManager.getCollection(resourceName)
373
+ : undefined;
374
+ const throughName = associationName && sourceCollection?.getField(associationName)?.options?.through;
375
+ const throughCollection =
376
+ typeof throughName === 'string' ? dataSource.collectionManager.getCollection(throughName) : undefined;
377
+ const isReadOnly = (collection?: Collection | null) =>
378
+ Boolean(collection?.options?.view || collection?.options?.sql);
379
+ if (isReadOnly(sourceCollection) || isReadOnly(targetCollection) || isReadOnly(throughCollection)) {
380
+ ctx.throw(403, translate(ctx, 'This collection is read-only'));
381
+ }
382
+ }
383
+ await next();
384
+ },
385
+ { tag: 'postgres-read-only-collections', after: ['acl'] },
386
+ );
387
+ });
388
+ this.app.dataSourceManager.afterAddDataSource((dataSource: DataSource) => {
389
+ if (dataSource instanceof PostgresDataSource) {
390
+ this.activeSources.set(dataSource.name, dataSource);
391
+ }
392
+ });
393
+ }
394
+
395
+ async load() {
396
+ this.app.db?.on?.(
397
+ 'dataSources.afterDestroy',
398
+ async (
399
+ model: Model,
400
+ options?: { transaction?: Transaction & { afterCommit?: (fn: () => Promise<void> | void) => void } },
401
+ ) => {
402
+ if (model.get('type') !== DATA_SOURCE_TYPE) return;
403
+ const key = String(model.get('key') || '');
404
+ if (!key) return;
405
+ const current = this.app.dataSourceManager.get(key);
406
+ const target = current instanceof PostgresDataSource ? current : this.activeSources.get(key);
407
+ if (target && this.activeSources.get(key) === target) {
408
+ this.activeSources.delete(key);
409
+ }
410
+ const close = () => (target ? this.closeDataSource(key, target) : Promise.resolve());
411
+ if (options?.transaction && typeof options.transaction.afterCommit === 'function') {
412
+ options.transaction.afterCommit(close);
413
+ } else {
414
+ await close();
415
+ }
416
+ await this.sendSyncMessage(
417
+ { type: 'dataSourceRemoved', dataSourceKey: key },
418
+ options?.transaction ? { transaction: options.transaction } : undefined,
419
+ );
420
+ },
421
+ );
422
+ this.app.resourceManager.registerPreActionHandler('dataSources:readTables', async (ctx, next) => {
423
+ const { dataSourceKey, dbOptions } = ctx.action.params.values || {};
424
+ if (dbOptions?.type !== DATA_SOURCE_TYPE) {
425
+ await next();
426
+ return;
427
+ }
428
+
429
+ const manager = this.app.dataSourceManager;
430
+ const renderedOptions = this.app.environment?.renderJsonTemplate
431
+ ? this.app.environment.renderJsonTemplate(dbOptions)
432
+ : dbOptions;
433
+ const probe = manager.factory.create(DATA_SOURCE_TYPE, {
434
+ name: dataSourceKey,
435
+ ...renderedOptions,
436
+ pool: { max: 1, min: 0, acquire: 10000, idle: 1000 },
437
+ }) as PostgresDataSource;
438
+ const owned = ![...manager.dataSources.values()].includes(probe);
439
+ let requestFailed = false;
440
+ let requestError: unknown;
441
+ try {
442
+ ctx.body = await probe.readTables();
443
+ } catch (error) {
444
+ requestFailed = true;
445
+ requestError = error;
446
+ } finally {
447
+ if (owned) {
448
+ try {
449
+ await probe.close();
450
+ } catch (error) {
451
+ if (requestFailed) {
452
+ this.app.log?.warn?.('[PostgreSQL] Failed to close temporary table-list connection');
453
+ } else {
454
+ requestFailed = true;
455
+ requestError = error;
456
+ }
457
+ }
458
+ }
459
+ }
460
+ if (requestFailed) throw requestError;
461
+ });
462
+
463
+ this.app.resourceManager.use(localizeValidationErrors, {
464
+ tag: 'postgres-validation-errors',
465
+ after: ['auth'],
466
+ before: ['acl'],
467
+ });
468
+ this.app.resourceManager.use(
469
+ async (ctx: Context, next: Next) => {
470
+ const { resourceName, actionName, params } = ctx.action || {};
471
+ if (resourceName === 'dataSources.collections') {
472
+ const dataSource = this.app.dataSourceManager.get(params.associatedIndex);
473
+ if (dataSource instanceof PostgresDataSource) {
474
+ if (actionName === 'create' || actionName === 'destroy') {
475
+ await this.mutateCollection(ctx, dataSource, next);
476
+ return;
477
+ }
478
+ if (actionName === 'update') {
479
+ const sql = extractSql(params.values as Record<string, unknown> | undefined);
480
+ if (sql !== undefined) {
481
+ const existing = dataSource.collectionManager.getCollection(params.filterByTk);
482
+ if (!existing?.options?.sql) {
483
+ ctx.throw(400, translate(ctx, 'Only SQL collections can update SQL queries'));
484
+ }
485
+ checkSQL(typeof sql === 'string' ? sql : '');
486
+ }
487
+ await next();
488
+ const targetName = typeof params.filterByTk === 'string' ? params.filterByTk : '';
489
+ if (targetName) {
490
+ await this.sendSyncMessage({
491
+ type: 'collectionCreated',
492
+ dataSourceKey: dataSource.name,
493
+ collectionName: targetName,
494
+ });
495
+ }
496
+ return;
497
+ }
498
+ }
499
+ }
500
+
501
+ if (resourceName === 'dataSourcesCollections.fields' && FIELD_ACTIONS.has(actionName)) {
502
+ const index = String(params.associatedIndex || '');
503
+ const separator = index.indexOf('.');
504
+ const indexDataSourceKey = separator !== -1 ? index.slice(0, separator) : '';
505
+ const indexCollectionName = separator !== -1 ? index.slice(separator + 1) : '';
506
+ const rawBody = (ctx.request as { body?: unknown } | undefined)?.body;
507
+ const input = (params.values || (isRecord(rawBody) ? rawBody : {})) as FieldValues;
508
+ const dataSourceKey =
509
+ actionName === 'apply' && typeof input.dataSourceKey === 'string' && input.dataSourceKey
510
+ ? input.dataSourceKey
511
+ : indexDataSourceKey;
512
+ const collectionName =
513
+ actionName === 'apply' && typeof input.collectionName === 'string' && input.collectionName
514
+ ? input.collectionName
515
+ : indexCollectionName;
516
+ const dataSource = dataSourceKey && collectionName && this.app.dataSourceManager.get(dataSourceKey);
517
+ if (dataSource instanceof PostgresDataSource) {
518
+ await this.mutateField(ctx, dataSource, collectionName, input, next);
519
+ return;
520
+ }
521
+ }
522
+ await next();
523
+ },
524
+ { tag: 'postgres-schema-actions', after: ['acl'] },
525
+ );
526
+ }
527
+
528
+ private async mutateCollection(ctx: Context, source: PostgresDataSource, next: Next) {
529
+ const manager = source.collectionManager;
530
+ const { actionName, params } = ctx.action;
531
+ const values = (params.values || {}) as Record<string, unknown>;
532
+ if (actionName === 'create') {
533
+ const [name] = names(values.name);
534
+ prepareFields(values);
535
+ if (manager.hasCollection(name)) ctx.throw(409, translate(ctx, 'Collection {{name}} already exists', { name }));
536
+ const sql = extractSql(values);
537
+ if (sql !== undefined || values.template === 'sql') {
538
+ checkSQL(typeof sql === 'string' ? sql : '');
539
+ await next();
540
+ await this.sendSyncMessage({ type: 'collectionCreated', dataSourceKey: source.name, collectionName: name });
541
+ return;
542
+ }
543
+ if (values.view || values.template === 'view') {
544
+ ctx.throw(400, translate(ctx, 'Use Load tables to import an existing view'));
545
+ }
546
+
547
+ let createdCollection: Collection | undefined;
548
+ await manager.db.sequelize.transaction(async (transaction) => {
549
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
550
+ replacements: { table: `${manager.db.options.schema || 'public'}.${String(values.tableName || name)}` },
551
+ transaction,
552
+ });
553
+ if (manager.hasCollection(name)) ctx.throw(409, translate(ctx, 'Collection {{name}} already exists', { name }));
554
+ if (!(await manager.createTable(values, transaction)))
555
+ ctx.throw(409, translate(ctx, 'Table {{name}} already exists', { name }));
556
+ createdCollection = manager.getCollection(name);
557
+ });
558
+
559
+ try {
560
+ await next();
561
+ } catch (error) {
562
+ try {
563
+ await manager.dropTable(name, false);
564
+ } catch (cleanupError) {
565
+ this.app.log?.warn?.(`Failed to roll back PostgreSQL table "${name}" after metadata error`, {
566
+ cause: cleanupError,
567
+ });
568
+ }
569
+ if (createdCollection && manager.getCollection(name) === createdCollection) manager.removeCollection(name);
570
+ throw error;
571
+ }
572
+ await source.addSelectedTables(ctx, [String(values.tableName || name)]);
573
+ await this.sendSyncMessage({ type: 'collectionCreated', dataSourceKey: source.name, collectionName: name });
574
+ return;
575
+ }
576
+
577
+ const collectionNames = names(params.filterByTk);
578
+ const snapshots = collectionNames.map((name) => {
579
+ const collection = manager.getCollection(name);
580
+ if (!collection) ctx.throw(404, translate(ctx, 'Collection {{name}} does not exist', { name }));
581
+ return {
582
+ name,
583
+ physicalName: String(collection.options.tableName || name),
584
+ isSql: Boolean(collection.options.sql),
585
+ options: cloneDeep({
586
+ ...collection.options,
587
+ tableName: String(collection.options.tableName || name),
588
+ fields: collection.getFields().map((field) => field.options),
589
+ }),
590
+ };
591
+ });
592
+ const cascade = params.cascade === true || params.cascade === 'true';
593
+ try {
594
+ await manager.db.sequelize.transaction(async (transaction) => {
595
+ for (const snapshot of [...snapshots].sort((left, right) =>
596
+ left.physicalName.localeCompare(right.physicalName),
597
+ )) {
598
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
599
+ replacements: { table: `${manager.db.options.schema || 'public'}.${snapshot.physicalName}` },
600
+ transaction,
601
+ });
602
+ if (!snapshot.isSql) await manager.dropTable(snapshot.name, cascade, transaction);
603
+ }
604
+ await next();
605
+ });
606
+ } catch (error) {
607
+ for (const snapshot of snapshots) {
608
+ if (!manager.hasCollection(snapshot.name)) manager.defineCollection(snapshot.options);
609
+ }
610
+ throw error;
611
+ }
612
+ const fieldsRepo = this.app.db?.getRepository?.('dataSourcesFields') as
613
+ | { destroy?: (options: Record<string, unknown>) => Promise<unknown> }
614
+ | undefined;
615
+ if (fieldsRepo && typeof fieldsRepo.destroy === 'function') {
616
+ try {
617
+ await fieldsRepo.destroy({
618
+ filter: { dataSourceKey: source.name, collectionName: { $in: collectionNames } },
619
+ individualHooks: false,
620
+ hooks: false,
621
+ });
622
+ } catch (cleanupError) {
623
+ this.app.log?.warn?.(`Failed to clean up orphaned field metadata for PostgreSQL data source "${source.name}"`, {
624
+ cause: cleanupError,
625
+ });
626
+ }
627
+ }
628
+ for (const snapshot of snapshots) {
629
+ if (manager.hasCollection(snapshot.name)) manager.removeCollection(snapshot.name);
630
+ }
631
+ await source.removeSelectedTables(
632
+ ctx,
633
+ snapshots.map((snapshot) => snapshot.physicalName),
634
+ );
635
+ await this.sendSyncMessage({
636
+ type: 'collectionRemoved',
637
+ dataSourceKey: source.name,
638
+ collectionNames: snapshots.map((snapshot) => snapshot.name),
639
+ });
640
+ }
641
+
642
+ private async mutateField(
643
+ ctx: Context,
644
+ source: PostgresDataSource,
645
+ collectionName: string,
646
+ input: FieldValues,
647
+ next: Next,
648
+ ) {
649
+ const manager = source.collectionManager;
650
+ const collection = manager.getCollection(collectionName);
651
+ if (!collection) ctx.throw(404, translate(ctx, 'Collection {{name}} does not exist', { name: collectionName }));
652
+ const action = ctx.action.actionName;
653
+ const { params } = ctx.action;
654
+ const fieldName = params.filterByTk;
655
+ if (Array.isArray(fieldName)) ctx.throw(400, translate(ctx, 'Delete one field at a time'));
656
+ if (collection.options.sql) {
657
+ await next();
658
+ if (action === 'destroy' && typeof fieldName === 'string') {
659
+ if (collection.getField(fieldName)) collection.removeField(fieldName);
660
+ await this.sendSyncMessage({
661
+ type: 'fieldRemoved',
662
+ dataSourceKey: source.name,
663
+ collectionName,
664
+ fieldName,
665
+ });
666
+ }
667
+ return;
668
+ }
669
+ if (collection.options.view) {
670
+ const targetName = fieldName || input.name;
671
+ if (action === 'create' || action === 'destroy' || !targetName || !collection.getField(targetName)) {
672
+ ctx.throw(403, translate(ctx, 'This collection is read-only'));
673
+ }
674
+ await next();
675
+ return;
676
+ }
677
+ if (action === 'destroy' && typeof fieldName === 'string' && removesPhysicalColumn(collection, fieldName)) {
678
+ const columnName = collection.getField(fieldName)?.columnName() || fieldName;
679
+ const references = await ctx.db.getRepository('dataSourcesFields').find({
680
+ filter: { dataSourceKey: source.name },
681
+ });
682
+ if (
683
+ references.some((field) =>
684
+ fieldReferencesColumn(field.toJSON(), field.get('collectionName'), collectionName, [fieldName, columnName]),
685
+ )
686
+ ) {
687
+ ctx.throw(400, translate(ctx, 'Field {{name}} is referenced by another field', { name: fieldName }));
688
+ }
689
+ }
690
+ const snapshot = cloneDeep({ ...collection.options, fields: collection.getFields().map((field) => field.options) });
691
+ const lockTables = getRelationLockTables(
692
+ manager,
693
+ collectionName,
694
+ input,
695
+ typeof fieldName === 'string' ? fieldName : undefined,
696
+ );
697
+ let metadataActionStarted = false;
698
+ try {
699
+ await manager.db.sequelize.transaction(async (transaction) => {
700
+ for (const table of lockTables) {
701
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
702
+ replacements: { table },
703
+ transaction,
704
+ });
705
+ }
706
+ await syncFieldAction(manager, action, collectionName, fieldName, input, transaction);
707
+ metadataActionStarted = true;
708
+ await next();
709
+ });
710
+ } catch (error) {
711
+ const current = manager.getCollection(collectionName);
712
+ if (metadataActionStarted && current) {
713
+ current.resetFields();
714
+ current.updateOptions(snapshot);
715
+ }
716
+ throw error;
717
+ }
718
+ if (action === 'destroy' && typeof fieldName === 'string') {
719
+ if (manager.getCollection(collectionName)?.getField(fieldName)) {
720
+ manager.getCollection(collectionName).removeField(fieldName);
721
+ }
722
+ await this.sendSyncMessage({
723
+ type: 'fieldRemoved',
724
+ dataSourceKey: source.name,
725
+ collectionName,
726
+ fieldName,
727
+ });
728
+ return;
729
+ }
730
+ const savedName = typeof fieldName === 'string' && fieldName ? fieldName : input.name;
731
+ const savedRelation = savedName
732
+ ? manager.getCollection(collectionName)?.getField(savedName)?.options || input
733
+ : input;
734
+ const companion = buildArrayForeignKeyField(manager, collectionName, savedRelation);
735
+ if (companion && typeof companion.name === 'string') {
736
+ manager.getCollection(collectionName)?.setField(companion.name, companion);
737
+ const fieldsRepo = (this.app.db || ctx.db)?.getRepository?.('dataSourcesFields') as
738
+ | {
739
+ findOne?: (options: Record<string, unknown>) => Promise<unknown>;
740
+ create?: (options: Record<string, unknown>) => Promise<unknown>;
741
+ }
742
+ | undefined;
743
+ if (fieldsRepo && typeof fieldsRepo.findOne === 'function' && typeof fieldsRepo.create === 'function') {
744
+ try {
745
+ const existingRecord = await fieldsRepo.findOne({
746
+ filter: { dataSourceKey: source.name, collectionName, name: companion.name },
747
+ });
748
+ if (!existingRecord) {
749
+ await fieldsRepo.create({
750
+ values: { ...companion, collectionName, dataSourceKey: source.name },
751
+ });
752
+ }
753
+ } catch (companionError) {
754
+ this.app.log?.warn?.(
755
+ `Failed to persist companion array field "${collectionName}.${companion.name}" for PostgreSQL data source "${source.name}"`,
756
+ { cause: companionError },
757
+ );
758
+ }
759
+ }
760
+ }
761
+ }
762
+ }
763
+
764
+ export default PluginDataSourcePostgresServer;