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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +9 -3
  2. package/client-v2.js +1 -0
  3. package/client.js +1 -0
  4. package/dist/client/index.js +10 -0
  5. package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
  6. package/dist/client-v2/index.js +10 -0
  7. package/dist/constants.js +45 -0
  8. package/dist/externalVersion.js +29 -0
  9. package/dist/locale/en-US.json +141 -0
  10. package/dist/locale/zh-CN.json +141 -0
  11. package/dist/server/collections/adjacency-list-repository.js +340 -0
  12. package/dist/server/collections/index.js +45 -0
  13. package/dist/server/collections/sql-collection.js +84 -0
  14. package/dist/server/collections/sql-model.js +149 -0
  15. package/dist/server/collections/tree-collection.js +118 -0
  16. package/dist/server/hooks/field-hooks.js +412 -0
  17. package/dist/server/index.js +38 -0
  18. package/dist/server/plugin.js +1273 -0
  19. package/dist/server/postgres-collection-manager.js +868 -0
  20. package/dist/server/postgres-datasource.js +361 -0
  21. package/dist/server/utils/sql-validator.js +253 -0
  22. package/dist/server/utils/validation-error.js +59 -0
  23. package/package.json +51 -4
  24. package/server.js +1 -0
  25. package/src/client/AddCollectionAction.tsx +307 -0
  26. package/src/client/ConfigurationForm.tsx +203 -0
  27. package/src/client/PostgresCollectionTemplate.tsx +109 -0
  28. package/src/client/__tests__/client-v1.test.tsx +265 -0
  29. package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
  30. package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
  31. package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
  32. package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
  33. package/src/client/collection-templates/base-template-helper.ts +62 -0
  34. package/src/client/collection-templates/field-interfaces-config.ts +73 -0
  35. package/src/client/collection-templates/index.ts +19 -0
  36. package/src/client/index.tsx +69 -0
  37. package/src/client-v2/PostgresAddCollection.tsx +422 -0
  38. package/src/client-v2/PostgresConfigForm.tsx +178 -0
  39. package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
  40. package/src/client-v2/__tests__/plugin.test.tsx +372 -0
  41. package/src/client-v2/collection-options.ts +22 -0
  42. package/src/client-v2/index.tsx +10 -0
  43. package/src/client-v2/plugin.tsx +71 -0
  44. package/src/constants.ts +20 -0
  45. package/src/locale/en-US.json +141 -0
  46. package/src/locale/zh-CN.json +141 -0
  47. package/src/server/__tests__/field-hooks.test.ts +357 -0
  48. package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
  49. package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
  50. package/src/server/__tests__/sql-model.test.ts +159 -0
  51. package/src/server/__tests__/sql-validator.test.ts +126 -0
  52. package/src/server/collections/adjacency-list-repository.ts +378 -0
  53. package/src/server/collections/index.ts +19 -0
  54. package/src/server/collections/sql-collection.ts +66 -0
  55. package/src/server/collections/sql-model.ts +158 -0
  56. package/src/server/collections/tree-collection.ts +102 -0
  57. package/src/server/hooks/field-hooks.ts +548 -0
  58. package/src/server/index.ts +13 -0
  59. package/src/server/plugin.ts +1499 -0
  60. package/src/server/postgres-collection-manager.ts +1027 -0
  61. package/src/server/postgres-datasource.ts +410 -0
  62. package/src/server/utils/sql-validator.ts +258 -0
  63. package/src/server/utils/validation-error.ts +38 -0
@@ -0,0 +1,1499 @@
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 { isValidFilter } from '@nocobase/utils';
15
+ import { cloneDeep, isEqual, omit, pick } from 'lodash';
16
+ import type { Transaction } from 'sequelize';
17
+ import { DATA_SOURCE_TYPE } from '../constants';
18
+ import { PostgresSQLCollection } from './collections/sql-collection';
19
+ import { PostgresTreeCollection } from './collections/tree-collection';
20
+ import {
21
+ buildArrayForeignKeyField,
22
+ fieldReferencesColumn,
23
+ getRelationLockTables,
24
+ removesPhysicalColumn,
25
+ syncFieldAction,
26
+ } from './hooks/field-hooks';
27
+ import { applyPostgresArrayDataType } from './postgres-collection-manager';
28
+ import { PostgresDataSource } from './postgres-datasource';
29
+ import { checkSQL } from './utils/sql-validator';
30
+ import { PostgresValidationError, translate, translateError } from './utils/validation-error';
31
+
32
+ const FIELD_ACTIONS = new Set(['create', 'update', 'apply', 'destroy']);
33
+ const WRITE_ACTIONS = new Set([
34
+ 'create',
35
+ 'firstOrCreate',
36
+ 'updateOrCreate',
37
+ 'update',
38
+ 'destroy',
39
+ 'destroyMany',
40
+ 'updateMany',
41
+ 'add',
42
+ 'remove',
43
+ 'set',
44
+ 'toggle',
45
+ 'move',
46
+ 'importXlsx',
47
+ ]);
48
+
49
+ type FieldValues = {
50
+ name?: string;
51
+ type?: string;
52
+ field?: string;
53
+ interface?: string;
54
+ allowNull?: boolean;
55
+ defaultValue?: unknown;
56
+ unique?: boolean;
57
+ settings?: FieldValues;
58
+ [key: string]: unknown;
59
+ };
60
+
61
+ const PRESET_FIELDS: Record<string, FieldValues> = {
62
+ id: { name: 'id', type: 'bigInt', interface: 'id', primaryKey: true, autoIncrement: true, allowNull: false },
63
+ createdAt: { name: 'createdAt', type: 'date', interface: 'createdAt', field: 'createdAt' },
64
+ updatedAt: { name: 'updatedAt', type: 'date', interface: 'updatedAt', field: 'updatedAt' },
65
+ };
66
+
67
+ function isRecord(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
69
+ }
70
+
71
+ const UNRESOLVED_TEMPLATE_RE = /\{\{[\s\S]*\}\}/;
72
+ const NEGATED_ARRAY_OPERATORS = new Set([
73
+ '$ne',
74
+ '$notIn',
75
+ '$notIncludes',
76
+ '$notStartsWith',
77
+ '$notEndWith',
78
+ '$empty',
79
+ '$noneOf',
80
+ ]);
81
+ const KNOWN_FILTER_OPERATORS = new Set([
82
+ '$eq',
83
+ '$ne',
84
+ '$in',
85
+ '$notIn',
86
+ '$includes',
87
+ '$notIncludes',
88
+ '$startsWith',
89
+ '$notStartsWith',
90
+ '$endWith',
91
+ '$notEndWith',
92
+ '$empty',
93
+ '$notEmpty',
94
+ '$isFalsy',
95
+ '$isTruly',
96
+ '$gt',
97
+ '$gte',
98
+ '$lt',
99
+ '$lte',
100
+ '$match',
101
+ '$notMatch',
102
+ '$anyOf',
103
+ '$noneOf',
104
+ '$exists',
105
+ '$notExists',
106
+ ]);
107
+ const LOGICAL_OPERATORS = new Set(['$and', '$or', '$not']);
108
+
109
+ function containsUnresolvedTemplate(value: unknown): boolean {
110
+ if (typeof value === 'string') return UNRESOLVED_TEMPLATE_RE.test(value);
111
+ if (Array.isArray(value)) return value.some((item) => containsUnresolvedTemplate(item));
112
+ if (isRecord(value)) return Object.values(value).some((item) => containsUnresolvedTemplate(item));
113
+ return false;
114
+ }
115
+
116
+ function compareOrdered(actual: unknown, operand: unknown): number | null {
117
+ if (
118
+ typeof actual === 'number' &&
119
+ typeof operand === 'number' &&
120
+ Number.isFinite(actual) &&
121
+ Number.isFinite(operand)
122
+ ) {
123
+ return actual === operand ? 0 : actual < operand ? -1 : 1;
124
+ }
125
+ if (typeof actual === 'string' && typeof operand === 'string') {
126
+ return actual === operand ? 0 : actual < operand ? -1 : 1;
127
+ }
128
+ if (actual instanceof Date && operand instanceof Date) {
129
+ const left = actual.getTime();
130
+ const right = operand.getTime();
131
+ if (!Number.isFinite(left) || !Number.isFinite(right)) return null;
132
+ return left === right ? 0 : left < right ? -1 : 1;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function isCaseInsensitiveEqualityDialect(dialect: string): boolean {
138
+ return dialect === 'mysql' || dialect === 'mariadb';
139
+ }
140
+
141
+ function valuesEqual(left: unknown, right: unknown, metadataDialect: string): boolean {
142
+ if (isCaseInsensitiveEqualityDialect(metadataDialect) && typeof left === 'string' && typeof right === 'string') {
143
+ return left.toLowerCase() === right.toLowerCase();
144
+ }
145
+ return isEqual(left, right);
146
+ }
147
+
148
+ function coerceLikeActual(actual: unknown, metadataDialect: string): string | null {
149
+ if (typeof actual === 'string') return actual;
150
+ if (
151
+ (metadataDialect === 'postgres' ||
152
+ metadataDialect === 'mysql' ||
153
+ metadataDialect === 'mariadb' ||
154
+ metadataDialect === 'sqlite') &&
155
+ (typeof actual === 'number' || typeof actual === 'boolean')
156
+ ) {
157
+ return String(actual);
158
+ }
159
+ return null;
160
+ }
161
+
162
+ function foldLikeCase(text: string, metadataDialect: string): string {
163
+ // Match core SQL LIKE/ILIKE case semantics per metadata DB dialect (ASCII-only folding for SQLite LIKE).
164
+ return metadataDialect === 'sqlite' ? text.replace(/[A-Z]/g, (ch) => ch.toLowerCase()) : text.toLowerCase();
165
+ }
166
+
167
+ function escapeRegExpChar(ch: string): string {
168
+ return /[\\^$.*+?()[\]{}|]/.test(ch) ? `\\${ch}` : ch;
169
+ }
170
+
171
+ function buildCoreLikePattern(
172
+ operand: string,
173
+ metadataDialect: string,
174
+ mode: 'includes' | 'startsWith' | 'endsWith',
175
+ ): string {
176
+ const escaped = operand.replace(/[_%]/g, '\\$&');
177
+ if (mode === 'startsWith') return `${escaped}%`;
178
+ if (mode === 'endsWith') return `%${escaped}`;
179
+ return `%${escaped}%`;
180
+ }
181
+
182
+ function compileSqlLikePattern(patternFolded: string, metadataDialect: string): RegExp | null {
183
+ // Sequelize emits `LIKE '...'` on SQLite without `ESCAPE '\'`, so `\` is literal while `_` and `%` stay wildcards.
184
+ // PostgreSQL ILIKE and MySQL/MariaDB LIKE use `\` as their default escape character.
185
+ const escapeChar = metadataDialect === 'sqlite' ? null : '\\';
186
+ const chars = Array.from(patternFolded);
187
+ let source = '^';
188
+ let prevWildcardMany = false;
189
+
190
+ for (let idx = 0; idx < chars.length; idx += 1) {
191
+ const ch = chars[idx];
192
+ if (escapeChar !== null && ch === escapeChar) {
193
+ if (idx + 1 >= chars.length) {
194
+ if (metadataDialect === 'postgres') return null;
195
+ source += '\\\\';
196
+ prevWildcardMany = false;
197
+ continue;
198
+ }
199
+ idx += 1;
200
+ source += escapeRegExpChar(chars[idx]);
201
+ prevWildcardMany = false;
202
+ continue;
203
+ }
204
+ if (ch === '%') {
205
+ if (!prevWildcardMany) {
206
+ source += '.*';
207
+ prevWildcardMany = true;
208
+ }
209
+ continue;
210
+ }
211
+ prevWildcardMany = false;
212
+ source += ch === '_' ? '.' : escapeRegExpChar(ch);
213
+ }
214
+
215
+ source += '$';
216
+ return new RegExp(source, 'su');
217
+ }
218
+
219
+ function matchLikeValue(
220
+ actualFolded: string,
221
+ rawOperand: string,
222
+ metadataDialect: string,
223
+ mode: 'includes' | 'startsWith' | 'endsWith',
224
+ ): boolean {
225
+ if (metadataDialect === 'mssql') {
226
+ const foldedOperand = foldLikeCase(rawOperand, metadataDialect);
227
+ if (mode === 'startsWith') return actualFolded.startsWith(foldedOperand);
228
+ if (mode === 'endsWith') return actualFolded.endsWith(foldedOperand);
229
+ return actualFolded.includes(foldedOperand);
230
+ }
231
+ const patternFolded = foldLikeCase(buildCoreLikePattern(rawOperand, metadataDialect, mode), metadataDialect);
232
+ const compiled = compileSqlLikePattern(patternFolded, metadataDialect);
233
+ return compiled !== null && compiled.test(actualFolded);
234
+ }
235
+
236
+ function evaluateLikeOperator(
237
+ actual: unknown,
238
+ operand: unknown,
239
+ metadataDialect: string,
240
+ mode: 'includes' | 'startsWith' | 'endsWith',
241
+ negated: boolean,
242
+ ): boolean {
243
+ if (mode === 'includes' && operand === null) {
244
+ return negated ? actual !== null && actual !== undefined : actual === null || actual === undefined;
245
+ }
246
+ const actualText = coerceLikeActual(actual, metadataDialect);
247
+ if (actualText === null) return false;
248
+ const actualFolded = foldLikeCase(actualText, metadataDialect);
249
+ if (typeof operand === 'string') {
250
+ const matched = matchLikeValue(actualFolded, operand, metadataDialect, mode);
251
+ return negated ? !matched : matched;
252
+ }
253
+ if (Array.isArray(operand) && operand.every((item): item is string => typeof item === 'string')) {
254
+ if (negated) {
255
+ return operand.every((item) => !matchLikeValue(actualFolded, item, metadataDialect, mode));
256
+ }
257
+ return operand.some((item) => matchLikeValue(actualFolded, item, metadataDialect, mode));
258
+ }
259
+ return false;
260
+ }
261
+
262
+ function evaluateSingleOperator(
263
+ actual: unknown,
264
+ operator: string,
265
+ operand: unknown,
266
+ metadataDialect = 'postgres',
267
+ ): boolean {
268
+ if (!KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand)) return false;
269
+ switch (operator) {
270
+ case '$eq':
271
+ if (operand === undefined) return true;
272
+ if (operand === null) return actual === null || actual === undefined;
273
+ if (Array.isArray(operand) && !Array.isArray(actual)) {
274
+ return (
275
+ actual !== null &&
276
+ actual !== undefined &&
277
+ operand.some((item) => item !== null && item !== undefined && valuesEqual(actual, item, metadataDialect))
278
+ );
279
+ }
280
+ return valuesEqual(actual, operand, metadataDialect);
281
+ case '$ne':
282
+ if (operand === null) return actual !== null && actual !== undefined;
283
+ if (Array.isArray(operand) && !Array.isArray(actual)) {
284
+ if (operand.length === 0) return true;
285
+ if (actual === null || actual === undefined) return false;
286
+ if (operand.some((item) => item === null || item === undefined)) return false;
287
+ return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
288
+ }
289
+ return !Array.isArray(actual) && (actual === null || actual === undefined)
290
+ ? true
291
+ : !valuesEqual(actual, operand, metadataDialect);
292
+ case '$in': {
293
+ if (operand === null || operand === undefined) return false;
294
+ const list = Array.isArray(operand) ? operand : [operand];
295
+ return (
296
+ actual !== null &&
297
+ actual !== undefined &&
298
+ list.some((item) => item !== null && item !== undefined && valuesEqual(actual, item, metadataDialect))
299
+ );
300
+ }
301
+ case '$notIn':
302
+ if (!Array.isArray(operand)) return false;
303
+ if (actual === null || actual === undefined || operand.length === 0) return true;
304
+ if (operand.some((item) => item === null || item === undefined)) return false;
305
+ return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
306
+ case '$exists': {
307
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
308
+ const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== undefined;
309
+ return operand === false ? !exists : exists;
310
+ }
311
+ case '$notExists': {
312
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
313
+ const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== undefined;
314
+ return operand === false ? exists : !exists;
315
+ }
316
+ case '$includes':
317
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'includes', false);
318
+ case '$notIncludes':
319
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'includes', true);
320
+ case '$startsWith':
321
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'startsWith', false);
322
+ case '$notStartsWith':
323
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'startsWith', true);
324
+ case '$endWith':
325
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'endsWith', false);
326
+ case '$notEndWith':
327
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'endsWith', true);
328
+ case '$empty': {
329
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
330
+ const empty =
331
+ actual === null || actual === undefined || actual === '' || (Array.isArray(actual) && !actual.length);
332
+ return operand === false ? !empty : empty;
333
+ }
334
+ case '$notEmpty': {
335
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
336
+ const empty =
337
+ actual === null || actual === undefined || actual === '' || (Array.isArray(actual) && !actual.length);
338
+ return operand === false ? empty : !empty;
339
+ }
340
+ case '$isFalsy':
341
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
342
+ return operand === false ? Boolean(actual) : !actual;
343
+ case '$isTruly':
344
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
345
+ return operand === false ? !actual : Boolean(actual);
346
+ case '$gt': {
347
+ const cmp = compareOrdered(actual, operand);
348
+ return cmp !== null && cmp > 0;
349
+ }
350
+ case '$gte': {
351
+ const cmp = compareOrdered(actual, operand);
352
+ return cmp !== null && cmp >= 0;
353
+ }
354
+ case '$lt': {
355
+ const cmp = compareOrdered(actual, operand);
356
+ return cmp !== null && cmp < 0;
357
+ }
358
+ case '$lte': {
359
+ const cmp = compareOrdered(actual, operand);
360
+ return cmp !== null && cmp <= 0;
361
+ }
362
+ case '$anyOf':
363
+ return (
364
+ Array.isArray(actual) &&
365
+ Array.isArray(operand) &&
366
+ actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)))
367
+ );
368
+ case '$noneOf':
369
+ return (
370
+ Array.isArray(actual) &&
371
+ Array.isArray(operand) &&
372
+ !actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)))
373
+ );
374
+ case '$match':
375
+ return (
376
+ Array.isArray(actual) &&
377
+ isRecord(operand) &&
378
+ actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect))
379
+ );
380
+ case '$notMatch':
381
+ return (
382
+ Array.isArray(actual) &&
383
+ isRecord(operand) &&
384
+ !actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect))
385
+ );
386
+ default:
387
+ return false;
388
+ }
389
+ }
390
+
391
+ const ARRAY_LEVEL_OPERATORS = new Set([
392
+ '$match',
393
+ '$notMatch',
394
+ '$anyOf',
395
+ '$noneOf',
396
+ '$empty',
397
+ '$notEmpty',
398
+ '$exists',
399
+ '$notExists',
400
+ ]);
401
+ const CONTAINER_ARRAY_KEYS = new Set(['fields', 'indexes']);
402
+ const MAX_PINNED_FILTER_CONTEXTS = 10_000;
403
+
404
+ function evaluateOperatorGroup(
405
+ target: { values: unknown[]; traversedArray: boolean },
406
+ entries: Array<[string, unknown]>,
407
+ metadataDialect: string,
408
+ ): boolean {
409
+ if (!entries.length) return true;
410
+ if (
411
+ entries.some(([operator, operand]) => !KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand))
412
+ ) {
413
+ return false;
414
+ }
415
+ if (target.traversedArray && entries.every(([operator]) => NEGATED_ARRAY_OPERATORS.has(operator))) {
416
+ return target.values.every((value) =>
417
+ entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect)),
418
+ );
419
+ }
420
+ return target.values.some((value) =>
421
+ entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect)),
422
+ );
423
+ }
424
+
425
+ function collectPositiveArrayPrefixes(filter: unknown, out: string[][], prefix: string[] = []): void {
426
+ if (!isRecord(filter)) return;
427
+ for (const [rawKey, condition] of Object.entries(filter)) {
428
+ if (rawKey === '$and' || rawKey === '$or') {
429
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
430
+ if (items) {
431
+ for (const item of items) collectPositiveArrayPrefixes(item, out, prefix);
432
+ }
433
+ continue;
434
+ }
435
+ if (rawKey === '$not' || rawKey.startsWith('$')) continue;
436
+
437
+ const parts = rawKey.split('.');
438
+ const lastPart = parts[parts.length - 1];
439
+ const hasTrailingOp = parts.length > 1 && lastPart.startsWith('$');
440
+ const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
441
+ if (fieldParts.some((part) => !part || part.startsWith('$'))) continue;
442
+
443
+ const fullParts = [...prefix, ...fieldParts];
444
+ let arrayLevelOnly = false;
445
+ if (hasTrailingOp) {
446
+ arrayLevelOnly = ARRAY_LEVEL_OPERATORS.has(lastPart);
447
+ } else if (isRecord(condition)) {
448
+ const keys = Object.keys(condition);
449
+ if (keys.length && keys.every((key) => KNOWN_FILTER_OPERATORS.has(key))) {
450
+ arrayLevelOnly = keys.every((key) => ARRAY_LEVEL_OPERATORS.has(key));
451
+ } else if (keys.length && keys.every((key) => !key.startsWith('$') || LOGICAL_OPERATORS.has(key))) {
452
+ for (let len = 1; len <= fullParts.length; len += 1) {
453
+ out.push(fullParts.slice(0, len));
454
+ }
455
+ collectPositiveArrayPrefixes(condition, out, fullParts);
456
+ continue;
457
+ }
458
+ }
459
+
460
+ const maxLen = arrayLevelOnly ? fullParts.length - 1 : fullParts.length;
461
+ for (let len = 1; len <= maxLen; len += 1) {
462
+ out.push(fullParts.slice(0, len));
463
+ }
464
+ }
465
+ }
466
+
467
+ function readPathWithPins(
468
+ record: Record<string, unknown>,
469
+ parts: string[],
470
+ pins: ReadonlyMap<string, unknown>,
471
+ ignoreLeafPin = false,
472
+ ): { values: unknown[]; traversedArray: boolean } {
473
+ let current: unknown[] = [record];
474
+ let traversedArray = false;
475
+ for (let idx = 0; idx < parts.length; idx += 1) {
476
+ const part = parts[idx];
477
+ const pathSoFar = parts.slice(0, idx + 1).join('.');
478
+ if (!(ignoreLeafPin && idx === parts.length - 1) && pins.has(pathSoFar)) {
479
+ current = [pins.get(pathSoFar)];
480
+ continue;
481
+ }
482
+ const next: unknown[] = [];
483
+ for (const item of current) {
484
+ if (Array.isArray(item)) {
485
+ traversedArray = true;
486
+ for (const entry of item) {
487
+ if (isRecord(entry)) {
488
+ if (part in entry) next.push(entry[part]);
489
+ else if (isRecord(entry.options) && part in entry.options) next.push(entry.options[part]);
490
+ }
491
+ }
492
+ } else if (isRecord(item)) {
493
+ if (part in item) {
494
+ next.push(item[part]);
495
+ } else if (isRecord(item.options) && part in item.options) {
496
+ next.push(item.options[part]);
497
+ } else {
498
+ next.push(undefined);
499
+ }
500
+ }
501
+ }
502
+ current = next;
503
+ }
504
+ return { values: current.length ? current : [undefined], traversedArray };
505
+ }
506
+
507
+ function expandPinsForPrefixes(
508
+ record: Record<string, unknown>,
509
+ inheritedPins: ReadonlyMap<string, unknown>,
510
+ candidatePrefixes: string[][],
511
+ ): Array<Map<string, unknown>> | null {
512
+ const uniquePrefixes = new Map<string, string[]>();
513
+ for (const parts of candidatePrefixes) {
514
+ const key = parts.join('.');
515
+ if (!inheritedPins.has(key) && !uniquePrefixes.has(key)) {
516
+ uniquePrefixes.set(key, parts);
517
+ }
518
+ }
519
+ const sortedPrefixes = [...uniquePrefixes.entries()].sort((a, b) => a[1].length - b[1].length);
520
+ let contexts: Array<Map<string, unknown>> = [new Map(inheritedPins)];
521
+
522
+ for (const [key, parts] of sortedPrefixes) {
523
+ const leafKey = parts[parts.length - 1];
524
+ const nextContexts: Array<Map<string, unknown>> = [];
525
+ for (const ctxPins of contexts) {
526
+ const rawTarget = readPathWithPins(record, parts, ctxPins, true);
527
+ if (rawTarget.values.length === 1 && Array.isArray(rawTarget.values[0])) {
528
+ const arr = rawTarget.values[0];
529
+ if (CONTAINER_ARRAY_KEYS.has(leafKey) || arr.some((entry) => isRecord(entry))) {
530
+ if (arr.length === 0) {
531
+ const forked = new Map(ctxPins);
532
+ forked.set(key, undefined);
533
+ nextContexts.push(forked);
534
+ } else {
535
+ for (const entry of arr) {
536
+ const forked = new Map(ctxPins);
537
+ forked.set(key, entry);
538
+ nextContexts.push(forked);
539
+ if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
540
+ }
541
+ }
542
+ continue;
543
+ }
544
+ }
545
+ nextContexts.push(ctxPins);
546
+ if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
547
+ }
548
+ contexts = nextContexts;
549
+ }
550
+ return contexts;
551
+ }
552
+
553
+ function extractSubPins(pins: ReadonlyMap<string, unknown>, prefix: string): Map<string, unknown> {
554
+ const prefixDot = `${prefix}.`;
555
+ const subPins = new Map<string, unknown>();
556
+ for (const [key, value] of pins.entries()) {
557
+ if (key.startsWith(prefixDot)) {
558
+ subPins.set(key.slice(prefixDot.length), value);
559
+ }
560
+ }
561
+ return subPins;
562
+ }
563
+
564
+ function evaluateEntriesWithPins(
565
+ record: Record<string, unknown>,
566
+ pins: ReadonlyMap<string, unknown>,
567
+ filter: unknown,
568
+ metadataDialect: string,
569
+ ): boolean {
570
+ if (!isRecord(filter)) return false;
571
+ for (const [rawKey, condition] of Object.entries(filter)) {
572
+ if (rawKey === '$and') {
573
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
574
+ if (!items || !items.every((item) => evaluateEntriesWithPins(record, pins, item, metadataDialect))) return false;
575
+ continue;
576
+ }
577
+ if (rawKey === '$or') {
578
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
579
+ if (!items || !items.some((item) => matchesScope(record, pins, item, metadataDialect))) return false;
580
+ continue;
581
+ }
582
+ if (rawKey === '$not') {
583
+ if (!isRecord(condition) || matchesScope(record, pins, condition, metadataDialect)) return false;
584
+ continue;
585
+ }
586
+ if (rawKey.startsWith('$')) return false;
587
+
588
+ const parts = rawKey.split('.');
589
+ const lastPart = parts[parts.length - 1];
590
+ const hasTrailingOp = parts.length > 1 && lastPart.startsWith('$');
591
+ const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
592
+ if (fieldParts.some((part) => !part || part.startsWith('$'))) return false;
593
+
594
+ if (hasTrailingOp) {
595
+ const target = readPathWithPins(record, fieldParts, pins, ARRAY_LEVEL_OPERATORS.has(lastPart));
596
+ if (!evaluateOperatorGroup(target, [[lastPart, condition]], metadataDialect)) return false;
597
+ continue;
598
+ }
599
+
600
+ if (isRecord(condition)) {
601
+ const entries = Object.entries(condition);
602
+ if (!entries.length) continue;
603
+ if (entries.every(([key]) => KNOWN_FILTER_OPERATORS.has(key))) {
604
+ const arrayLevelEntries = entries.filter(([key]) => ARRAY_LEVEL_OPERATORS.has(key));
605
+ const elementEntries = entries.filter(([key]) => !ARRAY_LEVEL_OPERATORS.has(key));
606
+ if (arrayLevelEntries.length) {
607
+ const arrayTarget = readPathWithPins(record, fieldParts, pins, true);
608
+ if (!evaluateOperatorGroup(arrayTarget, arrayLevelEntries, metadataDialect)) return false;
609
+ }
610
+ if (elementEntries.length) {
611
+ const elemTarget = readPathWithPins(record, fieldParts, pins, false);
612
+ if (!evaluateOperatorGroup(elemTarget, elementEntries, metadataDialect)) return false;
613
+ }
614
+ continue;
615
+ }
616
+ if (!entries.every(([key]) => !key.startsWith('$') || LOGICAL_OPERATORS.has(key))) return false;
617
+
618
+ const fieldPathKey = fieldParts.join('.');
619
+ const subPins = extractSubPins(pins, fieldPathKey);
620
+ if (pins.has(fieldPathKey)) {
621
+ const pinnedVal = pins.get(fieldPathKey);
622
+ if (!isRecord(pinnedVal) || !matchesScope(pinnedVal, subPins, condition, metadataDialect)) return false;
623
+ continue;
624
+ }
625
+ const target = readPathWithPins(record, fieldParts, pins, false);
626
+ const nestedMatched = target.values.some((value) => {
627
+ if (Array.isArray(value)) {
628
+ return value.some((entry) => isRecord(entry) && matchesScope(entry, subPins, condition, metadataDialect));
629
+ }
630
+ return isRecord(value) && matchesScope(value, subPins, condition, metadataDialect);
631
+ });
632
+ if (!nestedMatched) return false;
633
+ continue;
634
+ }
635
+
636
+ const target = readPathWithPins(record, fieldParts, pins, false);
637
+ if (!evaluateOperatorGroup(target, [['$eq', condition]], metadataDialect)) return false;
638
+ }
639
+ return true;
640
+ }
641
+
642
+ function matchesScope(
643
+ record: Record<string, unknown>,
644
+ inheritedPins: ReadonlyMap<string, unknown>,
645
+ filter: unknown,
646
+ metadataDialect: string,
647
+ ): boolean {
648
+ if (!isRecord(filter)) return false;
649
+ const prefixes: string[][] = [];
650
+ collectPositiveArrayPrefixes(filter, prefixes);
651
+ const expanded = expandPinsForPrefixes(record, inheritedPins, prefixes);
652
+ if (!expanded) return false;
653
+ return expanded.some((pins) => evaluateEntriesWithPins(record, pins, filter, metadataDialect));
654
+ }
655
+
656
+ function matchesCollectionFilter(
657
+ record: Record<string, unknown>,
658
+ filter: unknown,
659
+ metadataDialect = 'postgres',
660
+ ): boolean {
661
+ return matchesScope(record, new Map(), filter, metadataDialect);
662
+ }
663
+
664
+ function extractSql(values: Record<string, unknown> | undefined): unknown {
665
+ if (!values) return undefined;
666
+ if (values.sql !== undefined) return values.sql;
667
+ return isRecord(values.options) ? values.options.sql : undefined;
668
+ }
669
+
670
+ function names(value: unknown): string[] {
671
+ const values = Array.isArray(value) ? value : [value];
672
+ if (!values.length || values.some((item) => typeof item !== 'string' || !item)) {
673
+ throw new PostgresValidationError('A collection name is required');
674
+ }
675
+ return [...new Set(values as string[])];
676
+ }
677
+
678
+ function prepareFields(values: Record<string, unknown>): void {
679
+ if (!Array.isArray(values.fields)) return;
680
+ const hasStringPresets = values.fields.some((field) => typeof field === 'string');
681
+ if (hasStringPresets || (values.template === 'general' && values.fields.length === 0)) {
682
+ const selectedPresets = new Set(values.fields.filter((field): field is string => typeof field === 'string'));
683
+ values.autoGenId = selectedPresets.has('id');
684
+ values.createdAt = selectedPresets.has('createdAt');
685
+ values.updatedAt = selectedPresets.has('updatedAt');
686
+ values.timestamps = Boolean(values.createdAt || values.updatedAt);
687
+ } else if (values.createdAt === false && values.updatedAt === false && values.timestamps === undefined) {
688
+ values.timestamps = false;
689
+ }
690
+ const mapped: FieldValues[] = values.fields.map((field: FieldValues | string) => {
691
+ if (typeof field !== 'string') {
692
+ if (isRecord(field.settings)) {
693
+ if (field.elementType === undefined && typeof field.settings.elementType === 'string') {
694
+ field.elementType = field.settings.elementType;
695
+ }
696
+ if (field.dataType === undefined && typeof field.settings.dataType === 'string') {
697
+ field.dataType = field.settings.dataType;
698
+ }
699
+ }
700
+ return applyPostgresArrayDataType(field);
701
+ }
702
+ const preset = PRESET_FIELDS[field];
703
+ if (!preset) throw new PostgresValidationError('Unknown preset field {{name}}', { name: field });
704
+ return cloneDeep(preset);
705
+ });
706
+ const isSql = extractSql(values) !== undefined || values.template === 'sql';
707
+ if (!isSql) {
708
+ if (values.createdAt === true && !mapped.some((field) => field.name === 'createdAt')) {
709
+ mapped.push(cloneDeep(PRESET_FIELDS.createdAt));
710
+ }
711
+ if (values.updatedAt === true && !mapped.some((field) => field.name === 'updatedAt')) {
712
+ mapped.push(cloneDeep(PRESET_FIELDS.updatedAt));
713
+ }
714
+ }
715
+ values.fields = mapped;
716
+ }
717
+
718
+ async function localizeValidationErrors(ctx: Context, next: Next) {
719
+ try {
720
+ await next();
721
+ } catch (error) {
722
+ if (error instanceof PostgresValidationError) error.message = translateError(ctx, error);
723
+ const params = ctx.action?.params || {};
724
+ const postgresConnection =
725
+ ctx.action?.resourceName === 'dataSources' &&
726
+ (params.values?.type === DATA_SOURCE_TYPE ||
727
+ ctx.app?.dataSourceManager?.get(params.filterByTk) instanceof PostgresDataSource);
728
+ if (
729
+ postgresConnection &&
730
+ error instanceof Error &&
731
+ error.message === 'Test connection failed: Invalid PostgreSQL port'
732
+ ) {
733
+ error.message = translate(ctx, 'Test connection failed: {{reason}}', {
734
+ reason: translate(ctx, 'Invalid PostgreSQL port'),
735
+ });
736
+ const httpError = error as Error & { status?: number; statusCode?: number };
737
+ httpError.status = 400;
738
+ httpError.statusCode = 400;
739
+ }
740
+ throw error;
741
+ }
742
+ }
743
+
744
+ type PostgresSyncMessage = {
745
+ type?: string;
746
+ dataSourceKey?: string;
747
+ collectionName?: string;
748
+ collectionNames?: string[];
749
+ tableNames?: string[];
750
+ refreshTables?: string[];
751
+ fieldName?: string;
752
+ };
753
+
754
+ export class PluginDataSourcePostgresServer extends Plugin {
755
+ private selectionSyncs = new Map<string, Promise<void>>();
756
+ private activeSources = new Map<string, PostgresDataSource>();
757
+
758
+ private async closeDataSource(dataSourceKey: string, expectedSource?: PostgresDataSource) {
759
+ const current = this.app.dataSourceManager.get(dataSourceKey);
760
+ const tracked = this.activeSources.get(dataSourceKey);
761
+ const source = expectedSource || (current instanceof PostgresDataSource ? current : tracked);
762
+ if (!source) return;
763
+ if (tracked === source) {
764
+ this.activeSources.delete(dataSourceKey);
765
+ }
766
+ if (current === source) {
767
+ this.app.dataSourceManager.dataSources.delete(dataSourceKey);
768
+ }
769
+ const replacement = this.app.dataSourceManager.get(dataSourceKey);
770
+ if (
771
+ replacement instanceof PostgresDataSource &&
772
+ replacement !== source &&
773
+ replacement.collectionManager.db === source.collectionManager.db
774
+ ) {
775
+ return;
776
+ }
777
+ try {
778
+ await source.close();
779
+ } catch (error) {
780
+ this.app.log?.warn?.(`Failed to close PostgreSQL data source "${dataSourceKey}"`, { cause: error });
781
+ }
782
+ }
783
+
784
+ private async enqueueSelectionSync(key: string, task: () => Promise<void>) {
785
+ const previous = this.selectionSyncs.get(key) || Promise.resolve();
786
+ const current = previous.catch(() => undefined).then(task);
787
+ this.selectionSyncs.set(key, current);
788
+ try {
789
+ await current;
790
+ } finally {
791
+ if (this.selectionSyncs.get(key) === current) this.selectionSyncs.delete(key);
792
+ }
793
+ }
794
+
795
+ async handleSyncMessage(message: PostgresSyncMessage) {
796
+ if (!message?.dataSourceKey) return;
797
+ const key = message.dataSourceKey;
798
+ if (message.type === 'dataSourceRemoved') {
799
+ const existingRecord = await this.app.db?.getRepository?.('dataSources')?.findOne?.({ filterByTk: key });
800
+ if (existingRecord) return;
801
+ await this.closeDataSource(key);
802
+ return;
803
+ }
804
+ if (message.type === 'selectionChanged') {
805
+ const refreshTables = Array.isArray(message.refreshTables)
806
+ ? message.refreshTables.filter((name): name is string => typeof name === 'string' && name.length > 0)
807
+ : [];
808
+ await this.enqueueSelectionSync(key, () => this.reconcileSelection(key, refreshTables));
809
+ return;
810
+ }
811
+
812
+ if (message.type === 'tablesLoaded' && Array.isArray(message.tableNames)) {
813
+ const tableNames = message.tableNames;
814
+ await this.enqueueSelectionSync(key, () => this.syncLoadedTables(key, tableNames));
815
+ return;
816
+ }
817
+
818
+ const source = this.app.dataSourceManager.get(key);
819
+ if (!(source instanceof PostgresDataSource)) return;
820
+
821
+ if (message.type === 'collectionCreated' && message.collectionName) {
822
+ await this.syncCreatedCollection(source, key, message.collectionName);
823
+ return;
824
+ }
825
+
826
+ if (message.type === 'collectionRemoved' && Array.isArray(message.collectionNames)) {
827
+ for (const name of message.collectionNames) {
828
+ if (typeof name === 'string' && source.collectionManager.hasCollection(name)) {
829
+ source.collectionManager.removeCollection(name);
830
+ }
831
+ }
832
+ return;
833
+ }
834
+
835
+ if (message.type === 'fieldRemoved' && message.collectionName && message.fieldName) {
836
+ const collection = source.collectionManager.getCollection(message.collectionName);
837
+ if (collection?.getField(message.fieldName)) {
838
+ collection.removeField(message.fieldName);
839
+ }
840
+ }
841
+ }
842
+
843
+ private async syncLoadedTables(dataSourceKey: string, tableNames: string[]) {
844
+ const source = this.app.dataSourceManager.get(dataSourceKey);
845
+ if (!(source instanceof PostgresDataSource)) return;
846
+ const requested = [
847
+ ...new Set(tableNames.filter((name): name is string => typeof name === 'string' && name.length > 0)),
848
+ ];
849
+ if (!requested.length) return;
850
+ const record = (await this.app.db.getRepository('dataSources').findOne({ filterByTk: dataSourceKey })) as
851
+ | (Model & { loadLocalData?: () => Promise<LoadedCollections> })
852
+ | null;
853
+ if (!record) return;
854
+ const storedOptions = typeof record.get === 'function' ? record.get('options') || {} : {};
855
+ const selectedFilter =
856
+ storedOptions.addAllCollections === false && Array.isArray(storedOptions.selectedCollections)
857
+ ? new Set(storedOptions.selectedCollections.filter((name: unknown): name is string => typeof name === 'string'))
858
+ : undefined;
859
+ const allowed = selectedFilter ? requested.filter((name) => selectedFilter.has(name)) : requested;
860
+ if (!allowed.length) return;
861
+ const localData = typeof record.loadLocalData === 'function' ? await record.loadLocalData() : {};
862
+ const available = new Set(await source.introspector.getTables());
863
+ const targets = allowed.filter((name) => available.has(name));
864
+ if (!targets.length) return;
865
+ const collections = await source.prepareTables(targets, localData);
866
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
867
+ source.collectionManager.replaceCollections(collections);
868
+ }
869
+
870
+ private async syncCreatedCollection(source: PostgresDataSource, dataSourceKey: string, collectionName: string) {
871
+ const collectionRecord = await this.app.db.getRepository('dataSourcesCollections').findOne({
872
+ filter: { dataSourceKey, name: collectionName },
873
+ });
874
+ if (!collectionRecord) return;
875
+ const fieldRecords = await this.app.db.getRepository('dataSourcesFields').find({
876
+ filter: { dataSourceKey, collectionName },
877
+ });
878
+ const collectionOptions = {
879
+ ...collectionRecord.toJSON(),
880
+ fields: fieldRecords.map((field) => field.toJSON()),
881
+ };
882
+ if (typeof collectionOptions.sql === 'string' && collectionOptions.sql.trim()) {
883
+ const existing = source.collectionManager.getCollection(collectionName);
884
+ if (existing) {
885
+ existing.updateOptions(collectionOptions);
886
+ } else {
887
+ source.collectionManager.defineCollection({
888
+ ...collectionOptions,
889
+ tableName: typeof collectionOptions.tableName === 'string' ? collectionOptions.tableName : collectionName,
890
+ introspected: true,
891
+ });
892
+ }
893
+ return;
894
+ }
895
+ const tableName = typeof collectionOptions.tableName === 'string' ? collectionOptions.tableName : collectionName;
896
+ const [prepared] = await source.prepareTables([tableName], { [collectionName]: collectionOptions });
897
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source || !prepared) return;
898
+ const existing = source.collectionManager.getCollection(collectionName);
899
+ if (existing) {
900
+ existing.updateOptions(prepared);
901
+ } else {
902
+ source.collectionManager.defineCollection(prepared);
903
+ }
904
+ }
905
+
906
+ private async reconcileSelection(dataSourceKey: string, refreshTables: string[] = []) {
907
+ const source = this.app.dataSourceManager.get(dataSourceKey);
908
+ if (!(source instanceof PostgresDataSource)) return;
909
+ const record = await this.app.db.getRepository('dataSources').findOne({ filterByTk: dataSourceKey });
910
+ if (!record) return;
911
+ const storedOptions = record.get('options') || {};
912
+ if (storedOptions.addAllCollections !== false || !Array.isArray(storedOptions.selectedCollections)) return;
913
+ const resolvedOptions = this.app.environment.renderJsonTemplate(storedOptions);
914
+ const activeOptions = pick(source.options, Object.keys(resolvedOptions));
915
+ const selectAll = source.options.addAllCollections ?? source.options.autoDiscover !== false;
916
+ if (
917
+ selectAll ||
918
+ !isEqual(
919
+ omit(activeOptions, ['selectedCollections', 'addAllCollections']),
920
+ omit(resolvedOptions, ['selectedCollections', 'addAllCollections']),
921
+ )
922
+ )
923
+ return;
924
+
925
+ const selected = new Set<string>(
926
+ storedOptions.selectedCollections.filter((name: unknown): name is string => typeof name === 'string'),
927
+ );
928
+ const available = new Set(await source.introspector.getTables());
929
+ const localData = await record.loadLocalData();
930
+ const existing = source.collectionManager.getCollections();
931
+ const physicalName = (collection: Collection) => {
932
+ const table = collection.model.getTableName();
933
+ return typeof table === 'string' ? table : table.tableName;
934
+ };
935
+ const missing = [...selected].filter(
936
+ (name) => available.has(name) && !existing.some((item) => physicalName(item) === name),
937
+ );
938
+ const refreshed = refreshTables.filter((name) => selected.has(name) && available.has(name));
939
+ const targets = [...new Set([...missing, ...refreshed])];
940
+ const collections = await source.prepareTables(targets, localData);
941
+ if (this.app.dataSourceManager.get(dataSourceKey) !== source) return;
942
+ source.collectionManager.replaceCollections(collections);
943
+ for (const collection of existing) {
944
+ if (!collection.options.sql && !selected.has(physicalName(collection))) {
945
+ source.collectionManager.removeCollection(collection.name);
946
+ }
947
+ }
948
+ source.options = { ...source.options, addAllCollections: false, selectedCollections: [...selected] };
949
+ }
950
+
951
+ async beforeLoad() {
952
+ this.app.dataSourceManager.registerDataSourceType(DATA_SOURCE_TYPE, PostgresDataSource);
953
+ this.app.dataSourceManager.beforeAddDataSource((dataSource: DataSource) => {
954
+ if (!(dataSource instanceof PostgresDataSource)) return;
955
+ const { db } = dataSource.collectionManager;
956
+ db.collectionFactory.registerCollectionType(PostgresSQLCollection, {
957
+ condition: (options) => Boolean(options.sql),
958
+ async onSync() {},
959
+ async onDump() {},
960
+ });
961
+ db.collectionFactory.registerCollectionType(PostgresTreeCollection, {
962
+ condition: (options) => Boolean(options.postgresTree || options.template === 'tree'),
963
+ });
964
+ dataSource.resourceManager.use(localizeValidationErrors, {
965
+ tag: 'postgres-validation-errors',
966
+ after: ['auth'],
967
+ before: ['acl'],
968
+ });
969
+ dataSource.resourceManager.use(
970
+ async (ctx, next) => {
971
+ if (WRITE_ACTIONS.has(ctx.action?.actionName)) {
972
+ const resourceName = ctx.action?.resourceName;
973
+ const [sourceName, associationName] = typeof resourceName === 'string' ? resourceName.split('.') : [];
974
+ const sourceCollection = sourceName ? dataSource.collectionManager.getCollection(sourceName) : undefined;
975
+ const targetCollection =
976
+ sourceCollection && associationName && resourceName
977
+ ? dataSource.collectionManager.getCollection(resourceName)
978
+ : undefined;
979
+ const throughName = associationName && sourceCollection?.getField(associationName)?.options?.through;
980
+ const throughCollection =
981
+ typeof throughName === 'string' ? dataSource.collectionManager.getCollection(throughName) : undefined;
982
+ const isReadOnly = (collection?: Collection | null) =>
983
+ Boolean(collection?.options?.view || collection?.options?.sql);
984
+ if (isReadOnly(sourceCollection) || isReadOnly(targetCollection) || isReadOnly(throughCollection)) {
985
+ ctx.throw(403, translate(ctx, 'This collection is read-only'));
986
+ }
987
+ }
988
+ await next();
989
+ },
990
+ { tag: 'postgres-read-only-collections', after: ['acl'] },
991
+ );
992
+ });
993
+ this.app.dataSourceManager.afterAddDataSource((dataSource: DataSource) => {
994
+ if (dataSource instanceof PostgresDataSource) {
995
+ this.activeSources.set(dataSource.name, dataSource);
996
+ }
997
+ });
998
+ }
999
+
1000
+ async load() {
1001
+ this.app.db?.on?.(
1002
+ 'dataSources.afterDestroy',
1003
+ async (
1004
+ model: Model,
1005
+ options?: { transaction?: Transaction & { afterCommit?: (fn: () => Promise<void> | void) => void } },
1006
+ ) => {
1007
+ if (model.get('type') !== DATA_SOURCE_TYPE) return;
1008
+ const key = String(model.get('key') || '');
1009
+ if (!key) return;
1010
+ const current = this.app.dataSourceManager.get(key);
1011
+ const target = current instanceof PostgresDataSource ? current : this.activeSources.get(key);
1012
+ if (target && this.activeSources.get(key) === target) {
1013
+ this.activeSources.delete(key);
1014
+ }
1015
+ const close = () => (target ? this.closeDataSource(key, target) : Promise.resolve());
1016
+ if (options?.transaction && typeof options.transaction.afterCommit === 'function') {
1017
+ options.transaction.afterCommit(close);
1018
+ } else {
1019
+ await close();
1020
+ }
1021
+ await this.sendSyncMessage(
1022
+ { type: 'dataSourceRemoved', dataSourceKey: key },
1023
+ options?.transaction ? { transaction: options.transaction } : undefined,
1024
+ );
1025
+ },
1026
+ );
1027
+ this.app.resourceManager.registerPreActionHandler('dataSources:readTables', async (ctx, next) => {
1028
+ const { dataSourceKey, dbOptions } = ctx.action.params.values || {};
1029
+ if (dbOptions?.type !== DATA_SOURCE_TYPE) {
1030
+ await next();
1031
+ return;
1032
+ }
1033
+
1034
+ const manager = this.app.dataSourceManager;
1035
+ const renderedOptions = this.app.environment?.renderJsonTemplate
1036
+ ? this.app.environment.renderJsonTemplate(dbOptions)
1037
+ : dbOptions;
1038
+ const probe = manager.factory.create(DATA_SOURCE_TYPE, {
1039
+ name: dataSourceKey,
1040
+ ...renderedOptions,
1041
+ pool: { max: 1, min: 0, acquire: 10000, idle: 1000 },
1042
+ }) as PostgresDataSource;
1043
+ const owned = ![...manager.dataSources.values()].includes(probe);
1044
+ let requestFailed = false;
1045
+ let requestError: unknown;
1046
+ try {
1047
+ ctx.body = await probe.readTables();
1048
+ } catch (error) {
1049
+ requestFailed = true;
1050
+ requestError = error;
1051
+ } finally {
1052
+ if (owned) {
1053
+ try {
1054
+ await probe.close();
1055
+ } catch (error) {
1056
+ if (requestFailed) {
1057
+ this.app.log?.warn?.('[PostgreSQL] Failed to close temporary table-list connection');
1058
+ } else {
1059
+ requestFailed = true;
1060
+ requestError = error;
1061
+ }
1062
+ }
1063
+ }
1064
+ }
1065
+ if (requestFailed) throw requestError;
1066
+ });
1067
+
1068
+ this.app.resourceManager.use(localizeValidationErrors, {
1069
+ tag: 'postgres-validation-errors',
1070
+ after: ['auth'],
1071
+ before: ['acl'],
1072
+ });
1073
+ this.app.resourceManager.use(
1074
+ async (ctx: Context, next: Next) => {
1075
+ const { resourceName, actionName, params } = ctx.action || {};
1076
+ if (resourceName === 'dataSources.collections') {
1077
+ const dataSourceKey = ctx.action?.sourceId || params?.associatedIndex;
1078
+ const dataSource = dataSourceKey ? this.app.dataSourceManager.get(dataSourceKey) : undefined;
1079
+ if (dataSource instanceof PostgresDataSource) {
1080
+ if (actionName === 'create' || actionName === 'destroy') {
1081
+ await this.mutateCollection(ctx, dataSource, next);
1082
+ return;
1083
+ }
1084
+ if (actionName === 'update') {
1085
+ const sql = extractSql(params.values as Record<string, unknown> | undefined);
1086
+ if (sql !== undefined) {
1087
+ const existing = dataSource.collectionManager.getCollection(params.filterByTk);
1088
+ if (!existing?.options?.sql) {
1089
+ ctx.throw(400, translate(ctx, 'Only SQL collections can update SQL queries'));
1090
+ }
1091
+ checkSQL(typeof sql === 'string' ? sql : '');
1092
+ }
1093
+ await next();
1094
+ const targetName = typeof params.filterByTk === 'string' ? params.filterByTk : '';
1095
+ if (targetName) {
1096
+ await this.sendSyncMessage({
1097
+ type: 'collectionCreated',
1098
+ dataSourceKey: dataSource.name,
1099
+ collectionName: targetName,
1100
+ });
1101
+ }
1102
+ return;
1103
+ }
1104
+ }
1105
+ }
1106
+
1107
+ if (resourceName === 'dataSourcesCollections.fields' && FIELD_ACTIONS.has(actionName)) {
1108
+ const index = String(params.associatedIndex || '');
1109
+ const separator = index.indexOf('.');
1110
+ const indexDataSourceKey = separator !== -1 ? index.slice(0, separator) : '';
1111
+ const indexCollectionName = separator !== -1 ? index.slice(separator + 1) : '';
1112
+ const rawBody = (ctx.request as { body?: unknown } | undefined)?.body;
1113
+ const input = (params.values || (isRecord(rawBody) ? rawBody : {})) as FieldValues;
1114
+ const dataSourceKey =
1115
+ actionName === 'apply' && typeof input.dataSourceKey === 'string' && input.dataSourceKey
1116
+ ? input.dataSourceKey
1117
+ : indexDataSourceKey;
1118
+ const collectionName =
1119
+ actionName === 'apply' && typeof input.collectionName === 'string' && input.collectionName
1120
+ ? input.collectionName
1121
+ : indexCollectionName;
1122
+ const dataSource = dataSourceKey && collectionName && this.app.dataSourceManager.get(dataSourceKey);
1123
+ if (dataSource instanceof PostgresDataSource) {
1124
+ await this.mutateField(ctx, dataSource, collectionName, input, next);
1125
+ return;
1126
+ }
1127
+ }
1128
+ await next();
1129
+ },
1130
+ { tag: 'postgres-schema-actions', after: ['acl'] },
1131
+ );
1132
+ }
1133
+
1134
+ private async resolveCollectionsToDestroy(ctx: Context, source: PostgresDataSource): Promise<string[]> {
1135
+ const params = ctx.action?.params || {};
1136
+ const permission = (
1137
+ ctx as {
1138
+ permission?: {
1139
+ parsedParams?: { filter?: unknown };
1140
+ can?: { params?: { filter?: unknown } };
1141
+ };
1142
+ }
1143
+ ).permission;
1144
+ const rawFilter = params.filter;
1145
+ const scopeFilter = permission?.parsedParams?.filter ?? permission?.can?.params?.filter;
1146
+ const hasRawFilter = isValidFilter(rawFilter);
1147
+ const hasScopeFilter = isValidFilter(scopeFilter);
1148
+ const effectiveFilter =
1149
+ hasRawFilter && hasScopeFilter && !isEqual(rawFilter, scopeFilter)
1150
+ ? { $and: [rawFilter, scopeFilter] }
1151
+ : hasRawFilter
1152
+ ? rawFilter
1153
+ : hasScopeFilter
1154
+ ? scopeFilter
1155
+ : undefined;
1156
+
1157
+ const hasFilterByTk = params.filterByTk !== undefined && params.filterByTk !== null;
1158
+ let requestedNames: string[] | undefined;
1159
+ if (hasFilterByTk) {
1160
+ if (Array.isArray(params.filterByTk) && params.filterByTk.length === 0) {
1161
+ return [];
1162
+ }
1163
+ requestedNames = names(params.filterByTk);
1164
+ } else if (!effectiveFilter) {
1165
+ throw new PostgresValidationError('A collection name is required');
1166
+ }
1167
+
1168
+ const manager = source.collectionManager;
1169
+ if (!effectiveFilter) {
1170
+ for (const name of requestedNames ?? []) {
1171
+ if (!manager.getCollection(name)) {
1172
+ ctx.throw(404, translate(ctx, 'Collection {{name}} does not exist', { name }));
1173
+ }
1174
+ }
1175
+ return requestedNames ?? [];
1176
+ }
1177
+
1178
+ const db = this.app.db || ctx.db;
1179
+ const metadataDialect = db?.sequelize?.getDialect?.() ?? 'postgres';
1180
+ const collectionsRepo = db?.getRepository?.('dataSourcesCollections') as
1181
+ | { find?: (options: Record<string, unknown>) => Promise<Model[]> }
1182
+ | undefined;
1183
+
1184
+ if (collectionsRepo && typeof collectionsRepo.find === 'function') {
1185
+ const baseFilter: Record<string, unknown> = {
1186
+ dataSourceKey: source.name,
1187
+ ...(requestedNames ? { name: { $in: requestedNames } } : {}),
1188
+ };
1189
+ const persistedAll = await collectionsRepo.find({ filter: baseFilter, context: ctx });
1190
+ const persistedNames = new Set(persistedAll.map((row) => String(row.get('name'))));
1191
+ const persistedMatched = await collectionsRepo.find({
1192
+ filter: { $and: [baseFilter, effectiveFilter] },
1193
+ context: ctx,
1194
+ });
1195
+ const matchedSet = new Set(persistedMatched.map((row) => String(row.get('name'))));
1196
+
1197
+ for (const collection of manager.getCollections()) {
1198
+ if (persistedNames.has(collection.name)) continue;
1199
+ if (requestedNames && !requestedNames.includes(collection.name)) continue;
1200
+ const record: Record<string, unknown> = {
1201
+ ...collection.options,
1202
+ name: collection.name,
1203
+ dataSourceKey: source.name,
1204
+ dataSources: { key: source.name, type: DATA_SOURCE_TYPE },
1205
+ options: collection.options,
1206
+ fields: collection.getFields().map((field) => field.options),
1207
+ };
1208
+ if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
1209
+ matchedSet.add(collection.name);
1210
+ }
1211
+ }
1212
+
1213
+ return requestedNames ? requestedNames.filter((name) => matchedSet.has(name)) : [...matchedSet];
1214
+ }
1215
+
1216
+ const matchedRuntime = new Set<string>();
1217
+ for (const collection of manager.getCollections()) {
1218
+ if (requestedNames && !requestedNames.includes(collection.name)) continue;
1219
+ const record: Record<string, unknown> = {
1220
+ ...collection.options,
1221
+ name: collection.name,
1222
+ dataSourceKey: source.name,
1223
+ dataSources: { key: source.name, type: DATA_SOURCE_TYPE },
1224
+ options: collection.options,
1225
+ fields: collection.getFields().map((field) => field.options),
1226
+ };
1227
+ if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
1228
+ matchedRuntime.add(collection.name);
1229
+ }
1230
+ }
1231
+ return requestedNames ? requestedNames.filter((name) => matchedRuntime.has(name)) : [...matchedRuntime];
1232
+ }
1233
+
1234
+ private async mutateCollection(ctx: Context, source: PostgresDataSource, next: Next) {
1235
+ const manager = source.collectionManager;
1236
+ const { actionName, params } = ctx.action;
1237
+ const values = (params.values || {}) as Record<string, unknown>;
1238
+ if (actionName === 'create') {
1239
+ const [name] = names(values.name);
1240
+ prepareFields(values);
1241
+ if (manager.hasCollection(name)) ctx.throw(409, translate(ctx, 'Collection {{name}} already exists', { name }));
1242
+ const sql = extractSql(values);
1243
+ if (sql !== undefined || values.template === 'sql') {
1244
+ checkSQL(typeof sql === 'string' ? sql : '');
1245
+ await next();
1246
+ await this.sendSyncMessage({ type: 'collectionCreated', dataSourceKey: source.name, collectionName: name });
1247
+ return;
1248
+ }
1249
+ if (values.view || values.template === 'view') {
1250
+ ctx.throw(400, translate(ctx, 'Use Load tables to import an existing view'));
1251
+ }
1252
+
1253
+ let createdCollection: Collection | undefined;
1254
+ await manager.db.sequelize.transaction(async (transaction) => {
1255
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
1256
+ replacements: { table: `${manager.db.options.schema || 'public'}.${String(values.tableName || name)}` },
1257
+ transaction,
1258
+ });
1259
+ if (manager.hasCollection(name)) ctx.throw(409, translate(ctx, 'Collection {{name}} already exists', { name }));
1260
+ if (!(await manager.createTable(values, transaction)))
1261
+ ctx.throw(409, translate(ctx, 'Table {{name}} already exists', { name }));
1262
+ createdCollection = manager.getCollection(name);
1263
+ });
1264
+
1265
+ try {
1266
+ await next();
1267
+ } catch (error) {
1268
+ try {
1269
+ await manager.dropTable(name, false);
1270
+ } catch (cleanupError) {
1271
+ this.app.log?.warn?.(`Failed to roll back PostgreSQL table "${name}" after metadata error`, {
1272
+ cause: cleanupError,
1273
+ });
1274
+ }
1275
+ if (createdCollection && manager.getCollection(name) === createdCollection) manager.removeCollection(name);
1276
+ throw error;
1277
+ }
1278
+ await source.addSelectedTables(ctx, [String(values.tableName || name)]);
1279
+ await this.sendSyncMessage({ type: 'collectionCreated', dataSourceKey: source.name, collectionName: name });
1280
+ return;
1281
+ }
1282
+
1283
+ const collectionNames = await this.resolveCollectionsToDestroy(ctx, source);
1284
+ if (collectionNames.length === 0) {
1285
+ ctx.body = true;
1286
+ return;
1287
+ }
1288
+
1289
+ const snapshots = collectionNames.flatMap((name) => {
1290
+ const collection = manager.getCollection(name);
1291
+ if (!collection) return [];
1292
+ return [
1293
+ {
1294
+ name,
1295
+ physicalName: String(collection.options.tableName || name),
1296
+ isSql: Boolean(collection.options.sql),
1297
+ options: cloneDeep({
1298
+ ...collection.options,
1299
+ tableName: String(collection.options.tableName || name),
1300
+ fields: collection.getFields().map((field) => field.options),
1301
+ }),
1302
+ },
1303
+ ];
1304
+ });
1305
+ const cascade = params.cascade === true || params.cascade === 'true';
1306
+ const hadFilterByTk = Object.prototype.hasOwnProperty.call(params, 'filterByTk');
1307
+ const hadFilter = Object.prototype.hasOwnProperty.call(params, 'filter');
1308
+ const originalFilterByTk = params.filterByTk;
1309
+ const originalFilter = params.filter;
1310
+ try {
1311
+ await manager.db.sequelize.transaction(async (transaction) => {
1312
+ for (const snapshot of [...snapshots].sort((left, right) =>
1313
+ left.physicalName.localeCompare(right.physicalName),
1314
+ )) {
1315
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
1316
+ replacements: { table: `${manager.db.options.schema || 'public'}.${snapshot.physicalName}` },
1317
+ transaction,
1318
+ });
1319
+ if (!snapshot.isSql) await manager.dropTable(snapshot.name, cascade, transaction);
1320
+ }
1321
+ params.filterByTk = collectionNames;
1322
+ delete params.filter;
1323
+ await next();
1324
+ });
1325
+ } catch (error) {
1326
+ if (hadFilterByTk) params.filterByTk = originalFilterByTk;
1327
+ else delete params.filterByTk;
1328
+ if (hadFilter) params.filter = originalFilter;
1329
+ else delete params.filter;
1330
+ for (const snapshot of snapshots) {
1331
+ if (!manager.hasCollection(snapshot.name)) manager.defineCollection(snapshot.options);
1332
+ }
1333
+ throw error;
1334
+ }
1335
+ const fieldsRepo = (this.app.db || ctx.db)?.getRepository?.('dataSourcesFields') as
1336
+ | { destroy?: (options: Record<string, unknown>) => Promise<unknown> }
1337
+ | undefined;
1338
+ if (fieldsRepo && typeof fieldsRepo.destroy === 'function') {
1339
+ try {
1340
+ await fieldsRepo.destroy({
1341
+ filter: { dataSourceKey: source.name, collectionName: { $in: collectionNames } },
1342
+ individualHooks: false,
1343
+ hooks: false,
1344
+ });
1345
+ } catch (cleanupError) {
1346
+ this.app.log?.warn?.(`Failed to clean up orphaned field metadata for PostgreSQL data source "${source.name}"`, {
1347
+ cause: cleanupError,
1348
+ });
1349
+ }
1350
+ }
1351
+ for (const snapshot of snapshots) {
1352
+ if (manager.hasCollection(snapshot.name)) manager.removeCollection(snapshot.name);
1353
+ }
1354
+ await source.removeSelectedTables(
1355
+ ctx,
1356
+ snapshots.map((snapshot) => snapshot.physicalName),
1357
+ );
1358
+ await this.sendSyncMessage({
1359
+ type: 'collectionRemoved',
1360
+ dataSourceKey: source.name,
1361
+ collectionNames,
1362
+ });
1363
+ }
1364
+
1365
+ private async mutateField(
1366
+ ctx: Context,
1367
+ source: PostgresDataSource,
1368
+ collectionName: string,
1369
+ input: FieldValues,
1370
+ next: Next,
1371
+ ) {
1372
+ const manager = source.collectionManager;
1373
+ const collection = manager.getCollection(collectionName);
1374
+ if (!collection) ctx.throw(404, translate(ctx, 'Collection {{name}} does not exist', { name: collectionName }));
1375
+ const action = ctx.action.actionName;
1376
+ const { params } = ctx.action;
1377
+ const fieldName = params.filterByTk;
1378
+ if (Array.isArray(fieldName)) ctx.throw(400, translate(ctx, 'Delete one field at a time'));
1379
+ if (collection.options.sql) {
1380
+ await next();
1381
+ if (action === 'destroy' && typeof fieldName === 'string') {
1382
+ if (collection.getField(fieldName)) collection.removeField(fieldName);
1383
+ await this.sendSyncMessage({
1384
+ type: 'fieldRemoved',
1385
+ dataSourceKey: source.name,
1386
+ collectionName,
1387
+ fieldName,
1388
+ });
1389
+ }
1390
+ return;
1391
+ }
1392
+ if (collection.options.view) {
1393
+ const targetName = fieldName || input.name;
1394
+ if (action === 'create' || action === 'destroy' || !targetName || !collection.getField(targetName)) {
1395
+ ctx.throw(403, translate(ctx, 'This collection is read-only'));
1396
+ }
1397
+ await next();
1398
+ return;
1399
+ }
1400
+ if (action === 'destroy' && typeof fieldName === 'string' && removesPhysicalColumn(collection, fieldName)) {
1401
+ const columnName = collection.getField(fieldName)?.columnName() || fieldName;
1402
+ const references = await ctx.db.getRepository('dataSourcesFields').find({
1403
+ filter: { dataSourceKey: source.name },
1404
+ });
1405
+ if (
1406
+ references.some((field) =>
1407
+ fieldReferencesColumn(field.toJSON(), field.get('collectionName'), collectionName, [fieldName, columnName]),
1408
+ )
1409
+ ) {
1410
+ ctx.throw(400, translate(ctx, 'Field {{name}} is referenced by another field', { name: fieldName }));
1411
+ }
1412
+ }
1413
+ const snapshot = cloneDeep({ ...collection.options, fields: collection.getFields().map((field) => field.options) });
1414
+ const lockTables = getRelationLockTables(
1415
+ manager,
1416
+ collectionName,
1417
+ input,
1418
+ typeof fieldName === 'string' ? fieldName : undefined,
1419
+ );
1420
+ let metadataActionStarted = false;
1421
+ try {
1422
+ await manager.db.sequelize.transaction(async (transaction) => {
1423
+ for (const table of lockTables) {
1424
+ await manager.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:table, 0))', {
1425
+ replacements: { table },
1426
+ transaction,
1427
+ });
1428
+ }
1429
+ await syncFieldAction(manager, action, collectionName, fieldName, input, transaction);
1430
+ if (input.dataType === 'array' && isRecord(params.values)) {
1431
+ if (
1432
+ params.values.dataType === undefined ||
1433
+ params.values.dataType === null ||
1434
+ params.values.dataType === ''
1435
+ ) {
1436
+ params.values.dataType = 'array';
1437
+ }
1438
+ if (params.values.elementType === undefined && typeof input.elementType === 'string') {
1439
+ params.values.elementType = input.elementType;
1440
+ }
1441
+ }
1442
+ metadataActionStarted = true;
1443
+ await next();
1444
+ });
1445
+ } catch (error) {
1446
+ const current = manager.getCollection(collectionName);
1447
+ if (metadataActionStarted && current) {
1448
+ current.resetFields();
1449
+ current.updateOptions(snapshot);
1450
+ }
1451
+ throw error;
1452
+ }
1453
+ if (action === 'destroy' && typeof fieldName === 'string') {
1454
+ if (manager.getCollection(collectionName)?.getField(fieldName)) {
1455
+ manager.getCollection(collectionName).removeField(fieldName);
1456
+ }
1457
+ await this.sendSyncMessage({
1458
+ type: 'fieldRemoved',
1459
+ dataSourceKey: source.name,
1460
+ collectionName,
1461
+ fieldName,
1462
+ });
1463
+ return;
1464
+ }
1465
+ const savedName = typeof fieldName === 'string' && fieldName ? fieldName : input.name;
1466
+ const savedRelation = savedName
1467
+ ? manager.getCollection(collectionName)?.getField(savedName)?.options || input
1468
+ : input;
1469
+ const companion = buildArrayForeignKeyField(manager, collectionName, savedRelation);
1470
+ if (companion && typeof companion.name === 'string') {
1471
+ manager.getCollection(collectionName)?.setField(companion.name, companion);
1472
+ const fieldsRepo = (this.app.db || ctx.db)?.getRepository?.('dataSourcesFields') as
1473
+ | {
1474
+ findOne?: (options: Record<string, unknown>) => Promise<unknown>;
1475
+ create?: (options: Record<string, unknown>) => Promise<unknown>;
1476
+ }
1477
+ | undefined;
1478
+ if (fieldsRepo && typeof fieldsRepo.findOne === 'function' && typeof fieldsRepo.create === 'function') {
1479
+ try {
1480
+ const existingRecord = await fieldsRepo.findOne({
1481
+ filter: { dataSourceKey: source.name, collectionName, name: companion.name },
1482
+ });
1483
+ if (!existingRecord) {
1484
+ await fieldsRepo.create({
1485
+ values: { ...companion, collectionName, dataSourceKey: source.name },
1486
+ });
1487
+ }
1488
+ } catch (companionError) {
1489
+ this.app.log?.warn?.(
1490
+ `Failed to persist companion array field "${collectionName}.${companion.name}" for PostgreSQL data source "${source.name}"`,
1491
+ { cause: companionError },
1492
+ );
1493
+ }
1494
+ }
1495
+ }
1496
+ }
1497
+ }
1498
+
1499
+ export default PluginDataSourcePostgresServer;