plugin-data-source-postgres 2.0.0 → 2.1.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 (34) hide show
  1. package/README.md +1 -1
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/index.js +1 -1
  4. package/dist/constants.js +3 -0
  5. package/dist/externalVersion.js +10 -8
  6. package/dist/locale/en-US.json +8 -1
  7. package/dist/locale/zh-CN.json +8 -1
  8. package/dist/server/collections/sql-collection.js +2 -2
  9. package/dist/server/collections/sql-model.js +4 -2
  10. package/dist/server/hooks/field-hooks.js +20 -0
  11. package/dist/server/plugin.js +727 -23
  12. package/dist/server/postgres-collection-manager.js +192 -25
  13. package/dist/server/postgres-datasource.js +47 -13
  14. package/dist/server/utils/sql-validator.js +119 -69
  15. package/package.json +2 -2
  16. package/src/client/ConfigurationForm.tsx +312 -133
  17. package/src/client/__tests__/client-v1.test.tsx +80 -0
  18. package/src/client-v2/PostgresConfigForm.tsx +133 -6
  19. package/src/client-v2/__tests__/plugin.test.tsx +69 -0
  20. package/src/client-v2/plugin.tsx +2 -2
  21. package/src/constants.ts +15 -0
  22. package/src/locale/en-US.json +8 -1
  23. package/src/locale/zh-CN.json +8 -1
  24. package/src/server/__tests__/postgres-datasource.unit.test.ts +1038 -0
  25. package/src/server/__tests__/sql-model.test.ts +47 -3
  26. package/src/server/__tests__/sql-validator.test.ts +8 -1
  27. package/src/server/collections/sql-collection.ts +2 -2
  28. package/src/server/collections/sql-model.ts +2 -2
  29. package/src/server/hooks/field-hooks.ts +36 -2
  30. package/src/server/plugin.ts +912 -18
  31. package/src/server/postgres-collection-manager.ts +228 -28
  32. package/src/server/postgres-datasource.ts +57 -12
  33. package/src/server/utils/sql-validator.ts +123 -68
  34. package/dist/client-v2/985.34da95acdf7743ab.js +0 -10
@@ -11,9 +11,16 @@ import type { Context, Next } from '@nocobase/actions';
11
11
  import type { DataSource, LoadedCollections } from '@nocobase/data-source-manager';
12
12
  import type { Collection, Model } from '@nocobase/database';
13
13
  import { Plugin } from '@nocobase/server';
14
+ import { isValidFilter } from '@nocobase/utils';
14
15
  import { cloneDeep, isEqual, omit, pick } from 'lodash';
15
16
  import type { Transaction } from 'sequelize';
16
- import { DATA_SOURCE_TYPE } from '../constants';
17
+ import {
18
+ DATA_SOURCE_TYPE,
19
+ DEFAULT_PORT,
20
+ DEFAULT_SCHEMA,
21
+ LIST_SAVED_CONNECTIONS_ACTION,
22
+ type SavedPostgresConnection,
23
+ } from '../constants';
17
24
  import { PostgresSQLCollection } from './collections/sql-collection';
18
25
  import { PostgresTreeCollection } from './collections/tree-collection';
19
26
  import {
@@ -23,6 +30,7 @@ import {
23
30
  removesPhysicalColumn,
24
31
  syncFieldAction,
25
32
  } from './hooks/field-hooks';
33
+ import { applyPostgresArrayDataType } from './postgres-collection-manager';
26
34
  import { PostgresDataSource } from './postgres-datasource';
27
35
  import { checkSQL } from './utils/sql-validator';
28
36
  import { PostgresValidationError, translate, translateError } from './utils/validation-error';
@@ -66,6 +74,599 @@ function isRecord(value: unknown): value is Record<string, unknown> {
66
74
  return typeof value === 'object' && value !== null && !Array.isArray(value);
67
75
  }
68
76
 
77
+ const UNRESOLVED_TEMPLATE_RE = /\{\{[\s\S]*\}\}/;
78
+ const NEGATED_ARRAY_OPERATORS = new Set([
79
+ '$ne',
80
+ '$notIn',
81
+ '$notIncludes',
82
+ '$notStartsWith',
83
+ '$notEndWith',
84
+ '$empty',
85
+ '$noneOf',
86
+ ]);
87
+ const KNOWN_FILTER_OPERATORS = new Set([
88
+ '$eq',
89
+ '$ne',
90
+ '$in',
91
+ '$notIn',
92
+ '$includes',
93
+ '$notIncludes',
94
+ '$startsWith',
95
+ '$notStartsWith',
96
+ '$endWith',
97
+ '$notEndWith',
98
+ '$empty',
99
+ '$notEmpty',
100
+ '$isFalsy',
101
+ '$isTruly',
102
+ '$gt',
103
+ '$gte',
104
+ '$lt',
105
+ '$lte',
106
+ '$match',
107
+ '$notMatch',
108
+ '$anyOf',
109
+ '$noneOf',
110
+ '$exists',
111
+ '$notExists',
112
+ ]);
113
+ const LOGICAL_OPERATORS = new Set(['$and', '$or', '$not']);
114
+
115
+ function containsUnresolvedTemplate(value: unknown): boolean {
116
+ if (typeof value === 'string') return UNRESOLVED_TEMPLATE_RE.test(value);
117
+ if (Array.isArray(value)) return value.some((item) => containsUnresolvedTemplate(item));
118
+ if (isRecord(value)) return Object.values(value).some((item) => containsUnresolvedTemplate(item));
119
+ return false;
120
+ }
121
+
122
+ function compareOrdered(actual: unknown, operand: unknown): number | null {
123
+ if (
124
+ typeof actual === 'number' &&
125
+ typeof operand === 'number' &&
126
+ Number.isFinite(actual) &&
127
+ Number.isFinite(operand)
128
+ ) {
129
+ return actual === operand ? 0 : actual < operand ? -1 : 1;
130
+ }
131
+ if (typeof actual === 'string' && typeof operand === 'string') {
132
+ return actual === operand ? 0 : actual < operand ? -1 : 1;
133
+ }
134
+ if (actual instanceof Date && operand instanceof Date) {
135
+ const left = actual.getTime();
136
+ const right = operand.getTime();
137
+ if (!Number.isFinite(left) || !Number.isFinite(right)) return null;
138
+ return left === right ? 0 : left < right ? -1 : 1;
139
+ }
140
+ return null;
141
+ }
142
+
143
+ function isCaseInsensitiveEqualityDialect(dialect: string): boolean {
144
+ return dialect === 'mysql' || dialect === 'mariadb';
145
+ }
146
+
147
+ function valuesEqual(left: unknown, right: unknown, metadataDialect: string): boolean {
148
+ if (isCaseInsensitiveEqualityDialect(metadataDialect) && typeof left === 'string' && typeof right === 'string') {
149
+ return left.toLowerCase() === right.toLowerCase();
150
+ }
151
+ return isEqual(left, right);
152
+ }
153
+
154
+ function coerceLikeActual(actual: unknown, metadataDialect: string): string | null {
155
+ if (typeof actual === 'string') return actual;
156
+ if (
157
+ (metadataDialect === 'postgres' ||
158
+ metadataDialect === 'mysql' ||
159
+ metadataDialect === 'mariadb' ||
160
+ metadataDialect === 'sqlite') &&
161
+ (typeof actual === 'number' || typeof actual === 'boolean')
162
+ ) {
163
+ return String(actual);
164
+ }
165
+ return null;
166
+ }
167
+
168
+ function foldLikeCase(text: string, metadataDialect: string): string {
169
+ // Match core SQL LIKE/ILIKE case semantics per metadata DB dialect (ASCII-only folding for SQLite LIKE).
170
+ return metadataDialect === 'sqlite' ? text.replace(/[A-Z]/g, (ch) => ch.toLowerCase()) : text.toLowerCase();
171
+ }
172
+
173
+ function escapeRegExpChar(ch: string): string {
174
+ return /[\\^$.*+?()[\]{}|]/.test(ch) ? `\\${ch}` : ch;
175
+ }
176
+
177
+ function buildCoreLikePattern(
178
+ operand: string,
179
+ metadataDialect: string,
180
+ mode: 'includes' | 'startsWith' | 'endsWith',
181
+ ): string {
182
+ const escaped = operand.replace(/[_%]/g, '\\$&');
183
+ if (mode === 'startsWith') return `${escaped}%`;
184
+ if (mode === 'endsWith') return `%${escaped}`;
185
+ return `%${escaped}%`;
186
+ }
187
+
188
+ function compileSqlLikePattern(patternFolded: string, metadataDialect: string): RegExp | null {
189
+ // Sequelize emits `LIKE '...'` on SQLite without `ESCAPE '\'`, so `\` is literal while `_` and `%` stay wildcards.
190
+ // PostgreSQL ILIKE and MySQL/MariaDB LIKE use `\` as their default escape character.
191
+ const escapeChar = metadataDialect === 'sqlite' ? null : '\\';
192
+ const chars = Array.from(patternFolded);
193
+ let source = '^';
194
+ let prevWildcardMany = false;
195
+
196
+ for (let idx = 0; idx < chars.length; idx += 1) {
197
+ const ch = chars[idx];
198
+ if (escapeChar !== null && ch === escapeChar) {
199
+ if (idx + 1 >= chars.length) {
200
+ if (metadataDialect === 'postgres') return null;
201
+ source += '\\\\';
202
+ prevWildcardMany = false;
203
+ continue;
204
+ }
205
+ idx += 1;
206
+ source += escapeRegExpChar(chars[idx]);
207
+ prevWildcardMany = false;
208
+ continue;
209
+ }
210
+ if (ch === '%') {
211
+ if (!prevWildcardMany) {
212
+ source += '.*';
213
+ prevWildcardMany = true;
214
+ }
215
+ continue;
216
+ }
217
+ prevWildcardMany = false;
218
+ source += ch === '_' ? '.' : escapeRegExpChar(ch);
219
+ }
220
+
221
+ source += '$';
222
+ return new RegExp(source, 'su');
223
+ }
224
+
225
+ function matchLikeValue(
226
+ actualFolded: string,
227
+ rawOperand: string,
228
+ metadataDialect: string,
229
+ mode: 'includes' | 'startsWith' | 'endsWith',
230
+ ): boolean {
231
+ if (metadataDialect === 'mssql') {
232
+ const foldedOperand = foldLikeCase(rawOperand, metadataDialect);
233
+ if (mode === 'startsWith') return actualFolded.startsWith(foldedOperand);
234
+ if (mode === 'endsWith') return actualFolded.endsWith(foldedOperand);
235
+ return actualFolded.includes(foldedOperand);
236
+ }
237
+ const patternFolded = foldLikeCase(buildCoreLikePattern(rawOperand, metadataDialect, mode), metadataDialect);
238
+ const compiled = compileSqlLikePattern(patternFolded, metadataDialect);
239
+ return compiled !== null && compiled.test(actualFolded);
240
+ }
241
+
242
+ function evaluateLikeOperator(
243
+ actual: unknown,
244
+ operand: unknown,
245
+ metadataDialect: string,
246
+ mode: 'includes' | 'startsWith' | 'endsWith',
247
+ negated: boolean,
248
+ ): boolean {
249
+ if (mode === 'includes' && operand === null) {
250
+ return negated ? actual !== null && actual !== undefined : actual === null || actual === undefined;
251
+ }
252
+ const actualText = coerceLikeActual(actual, metadataDialect);
253
+ if (actualText === null) return false;
254
+ const actualFolded = foldLikeCase(actualText, metadataDialect);
255
+ if (typeof operand === 'string') {
256
+ const matched = matchLikeValue(actualFolded, operand, metadataDialect, mode);
257
+ return negated ? !matched : matched;
258
+ }
259
+ if (Array.isArray(operand) && operand.every((item): item is string => typeof item === 'string')) {
260
+ if (negated) {
261
+ return operand.every((item) => !matchLikeValue(actualFolded, item, metadataDialect, mode));
262
+ }
263
+ return operand.some((item) => matchLikeValue(actualFolded, item, metadataDialect, mode));
264
+ }
265
+ return false;
266
+ }
267
+
268
+ function evaluateSingleOperator(
269
+ actual: unknown,
270
+ operator: string,
271
+ operand: unknown,
272
+ metadataDialect = 'postgres',
273
+ ): boolean {
274
+ if (!KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand)) return false;
275
+ switch (operator) {
276
+ case '$eq':
277
+ if (operand === undefined) return true;
278
+ if (operand === null) return actual === null || actual === undefined;
279
+ if (Array.isArray(operand) && !Array.isArray(actual)) {
280
+ return (
281
+ actual !== null &&
282
+ actual !== undefined &&
283
+ operand.some((item) => item !== null && item !== undefined && valuesEqual(actual, item, metadataDialect))
284
+ );
285
+ }
286
+ return valuesEqual(actual, operand, metadataDialect);
287
+ case '$ne':
288
+ if (operand === null) return actual !== null && actual !== undefined;
289
+ if (Array.isArray(operand) && !Array.isArray(actual)) {
290
+ if (operand.length === 0) return true;
291
+ if (actual === null || actual === undefined) return false;
292
+ if (operand.some((item) => item === null || item === undefined)) return false;
293
+ return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
294
+ }
295
+ return !Array.isArray(actual) && (actual === null || actual === undefined)
296
+ ? true
297
+ : !valuesEqual(actual, operand, metadataDialect);
298
+ case '$in': {
299
+ if (operand === null || operand === undefined) return false;
300
+ const list = Array.isArray(operand) ? operand : [operand];
301
+ return (
302
+ actual !== null &&
303
+ actual !== undefined &&
304
+ list.some((item) => item !== null && item !== undefined && valuesEqual(actual, item, metadataDialect))
305
+ );
306
+ }
307
+ case '$notIn':
308
+ if (!Array.isArray(operand)) return false;
309
+ if (actual === null || actual === undefined || operand.length === 0) return true;
310
+ if (operand.some((item) => item === null || item === undefined)) return false;
311
+ return !operand.some((item) => valuesEqual(actual, item, metadataDialect));
312
+ case '$exists': {
313
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
314
+ const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== undefined;
315
+ return operand === false ? !exists : exists;
316
+ }
317
+ case '$notExists': {
318
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
319
+ const exists = Array.isArray(actual) ? actual.length > 0 : actual !== null && actual !== undefined;
320
+ return operand === false ? exists : !exists;
321
+ }
322
+ case '$includes':
323
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'includes', false);
324
+ case '$notIncludes':
325
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'includes', true);
326
+ case '$startsWith':
327
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'startsWith', false);
328
+ case '$notStartsWith':
329
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'startsWith', true);
330
+ case '$endWith':
331
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'endsWith', false);
332
+ case '$notEndWith':
333
+ return evaluateLikeOperator(actual, operand, metadataDialect, 'endsWith', true);
334
+ case '$empty': {
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 '$notEmpty': {
341
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
342
+ const empty =
343
+ actual === null || actual === undefined || actual === '' || (Array.isArray(actual) && !actual.length);
344
+ return operand === false ? empty : !empty;
345
+ }
346
+ case '$isFalsy':
347
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
348
+ return operand === false ? Boolean(actual) : !actual;
349
+ case '$isTruly':
350
+ if (operand !== undefined && typeof operand !== 'boolean') return false;
351
+ return operand === false ? !actual : Boolean(actual);
352
+ case '$gt': {
353
+ const cmp = compareOrdered(actual, operand);
354
+ return cmp !== null && cmp > 0;
355
+ }
356
+ case '$gte': {
357
+ const cmp = compareOrdered(actual, operand);
358
+ return cmp !== null && cmp >= 0;
359
+ }
360
+ case '$lt': {
361
+ const cmp = compareOrdered(actual, operand);
362
+ return cmp !== null && cmp < 0;
363
+ }
364
+ case '$lte': {
365
+ const cmp = compareOrdered(actual, operand);
366
+ return cmp !== null && cmp <= 0;
367
+ }
368
+ case '$anyOf':
369
+ return (
370
+ Array.isArray(actual) &&
371
+ Array.isArray(operand) &&
372
+ actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)))
373
+ );
374
+ case '$noneOf':
375
+ return (
376
+ Array.isArray(actual) &&
377
+ Array.isArray(operand) &&
378
+ !actual.some((item) => operand.some((target) => valuesEqual(item, target, metadataDialect)))
379
+ );
380
+ case '$match':
381
+ return (
382
+ Array.isArray(actual) &&
383
+ isRecord(operand) &&
384
+ actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect))
385
+ );
386
+ case '$notMatch':
387
+ return (
388
+ Array.isArray(actual) &&
389
+ isRecord(operand) &&
390
+ !actual.some((item) => isRecord(item) && matchesCollectionFilter(item, operand, metadataDialect))
391
+ );
392
+ default:
393
+ return false;
394
+ }
395
+ }
396
+
397
+ const ARRAY_LEVEL_OPERATORS = new Set([
398
+ '$match',
399
+ '$notMatch',
400
+ '$anyOf',
401
+ '$noneOf',
402
+ '$empty',
403
+ '$notEmpty',
404
+ '$exists',
405
+ '$notExists',
406
+ ]);
407
+ const CONTAINER_ARRAY_KEYS = new Set(['fields', 'indexes']);
408
+ const MAX_PINNED_FILTER_CONTEXTS = 10_000;
409
+
410
+ function evaluateOperatorGroup(
411
+ target: { values: unknown[]; traversedArray: boolean },
412
+ entries: Array<[string, unknown]>,
413
+ metadataDialect: string,
414
+ ): boolean {
415
+ if (!entries.length) return true;
416
+ if (
417
+ entries.some(([operator, operand]) => !KNOWN_FILTER_OPERATORS.has(operator) || containsUnresolvedTemplate(operand))
418
+ ) {
419
+ return false;
420
+ }
421
+ if (target.traversedArray && entries.every(([operator]) => NEGATED_ARRAY_OPERATORS.has(operator))) {
422
+ return target.values.every((value) =>
423
+ entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect)),
424
+ );
425
+ }
426
+ return target.values.some((value) =>
427
+ entries.every(([operator, operand]) => evaluateSingleOperator(value, operator, operand, metadataDialect)),
428
+ );
429
+ }
430
+
431
+ function collectPositiveArrayPrefixes(filter: unknown, out: string[][], prefix: string[] = []): void {
432
+ if (!isRecord(filter)) return;
433
+ for (const [rawKey, condition] of Object.entries(filter)) {
434
+ if (rawKey === '$and' || rawKey === '$or') {
435
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
436
+ if (items) {
437
+ for (const item of items) collectPositiveArrayPrefixes(item, out, prefix);
438
+ }
439
+ continue;
440
+ }
441
+ if (rawKey === '$not' || rawKey.startsWith('$')) continue;
442
+
443
+ const parts = rawKey.split('.');
444
+ const lastPart = parts[parts.length - 1];
445
+ const hasTrailingOp = parts.length > 1 && lastPart.startsWith('$');
446
+ const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
447
+ if (fieldParts.some((part) => !part || part.startsWith('$'))) continue;
448
+
449
+ const fullParts = [...prefix, ...fieldParts];
450
+ let arrayLevelOnly = false;
451
+ if (hasTrailingOp) {
452
+ arrayLevelOnly = ARRAY_LEVEL_OPERATORS.has(lastPart);
453
+ } else if (isRecord(condition)) {
454
+ const keys = Object.keys(condition);
455
+ if (keys.length && keys.every((key) => KNOWN_FILTER_OPERATORS.has(key))) {
456
+ arrayLevelOnly = keys.every((key) => ARRAY_LEVEL_OPERATORS.has(key));
457
+ } else if (keys.length && keys.every((key) => !key.startsWith('$') || LOGICAL_OPERATORS.has(key))) {
458
+ for (let len = 1; len <= fullParts.length; len += 1) {
459
+ out.push(fullParts.slice(0, len));
460
+ }
461
+ collectPositiveArrayPrefixes(condition, out, fullParts);
462
+ continue;
463
+ }
464
+ }
465
+
466
+ const maxLen = arrayLevelOnly ? fullParts.length - 1 : fullParts.length;
467
+ for (let len = 1; len <= maxLen; len += 1) {
468
+ out.push(fullParts.slice(0, len));
469
+ }
470
+ }
471
+ }
472
+
473
+ function readPathWithPins(
474
+ record: Record<string, unknown>,
475
+ parts: string[],
476
+ pins: ReadonlyMap<string, unknown>,
477
+ ignoreLeafPin = false,
478
+ ): { values: unknown[]; traversedArray: boolean } {
479
+ let current: unknown[] = [record];
480
+ let traversedArray = false;
481
+ for (let idx = 0; idx < parts.length; idx += 1) {
482
+ const part = parts[idx];
483
+ const pathSoFar = parts.slice(0, idx + 1).join('.');
484
+ if (!(ignoreLeafPin && idx === parts.length - 1) && pins.has(pathSoFar)) {
485
+ current = [pins.get(pathSoFar)];
486
+ continue;
487
+ }
488
+ const next: unknown[] = [];
489
+ for (const item of current) {
490
+ if (Array.isArray(item)) {
491
+ traversedArray = true;
492
+ for (const entry of item) {
493
+ if (isRecord(entry)) {
494
+ if (part in entry) next.push(entry[part]);
495
+ else if (isRecord(entry.options) && part in entry.options) next.push(entry.options[part]);
496
+ }
497
+ }
498
+ } else if (isRecord(item)) {
499
+ if (part in item) {
500
+ next.push(item[part]);
501
+ } else if (isRecord(item.options) && part in item.options) {
502
+ next.push(item.options[part]);
503
+ } else {
504
+ next.push(undefined);
505
+ }
506
+ }
507
+ }
508
+ current = next;
509
+ }
510
+ return { values: current.length ? current : [undefined], traversedArray };
511
+ }
512
+
513
+ function expandPinsForPrefixes(
514
+ record: Record<string, unknown>,
515
+ inheritedPins: ReadonlyMap<string, unknown>,
516
+ candidatePrefixes: string[][],
517
+ ): Array<Map<string, unknown>> | null {
518
+ const uniquePrefixes = new Map<string, string[]>();
519
+ for (const parts of candidatePrefixes) {
520
+ const key = parts.join('.');
521
+ if (!inheritedPins.has(key) && !uniquePrefixes.has(key)) {
522
+ uniquePrefixes.set(key, parts);
523
+ }
524
+ }
525
+ const sortedPrefixes = [...uniquePrefixes.entries()].sort((a, b) => a[1].length - b[1].length);
526
+ let contexts: Array<Map<string, unknown>> = [new Map(inheritedPins)];
527
+
528
+ for (const [key, parts] of sortedPrefixes) {
529
+ const leafKey = parts[parts.length - 1];
530
+ const nextContexts: Array<Map<string, unknown>> = [];
531
+ for (const ctxPins of contexts) {
532
+ const rawTarget = readPathWithPins(record, parts, ctxPins, true);
533
+ if (rawTarget.values.length === 1 && Array.isArray(rawTarget.values[0])) {
534
+ const arr = rawTarget.values[0];
535
+ if (CONTAINER_ARRAY_KEYS.has(leafKey) || arr.some((entry) => isRecord(entry))) {
536
+ if (arr.length === 0) {
537
+ const forked = new Map(ctxPins);
538
+ forked.set(key, undefined);
539
+ nextContexts.push(forked);
540
+ } else {
541
+ for (const entry of arr) {
542
+ const forked = new Map(ctxPins);
543
+ forked.set(key, entry);
544
+ nextContexts.push(forked);
545
+ if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
546
+ }
547
+ }
548
+ continue;
549
+ }
550
+ }
551
+ nextContexts.push(ctxPins);
552
+ if (nextContexts.length > MAX_PINNED_FILTER_CONTEXTS) return null;
553
+ }
554
+ contexts = nextContexts;
555
+ }
556
+ return contexts;
557
+ }
558
+
559
+ function extractSubPins(pins: ReadonlyMap<string, unknown>, prefix: string): Map<string, unknown> {
560
+ const prefixDot = `${prefix}.`;
561
+ const subPins = new Map<string, unknown>();
562
+ for (const [key, value] of pins.entries()) {
563
+ if (key.startsWith(prefixDot)) {
564
+ subPins.set(key.slice(prefixDot.length), value);
565
+ }
566
+ }
567
+ return subPins;
568
+ }
569
+
570
+ function evaluateEntriesWithPins(
571
+ record: Record<string, unknown>,
572
+ pins: ReadonlyMap<string, unknown>,
573
+ filter: unknown,
574
+ metadataDialect: string,
575
+ ): boolean {
576
+ if (!isRecord(filter)) return false;
577
+ for (const [rawKey, condition] of Object.entries(filter)) {
578
+ if (rawKey === '$and') {
579
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
580
+ if (!items || !items.every((item) => evaluateEntriesWithPins(record, pins, item, metadataDialect))) return false;
581
+ continue;
582
+ }
583
+ if (rawKey === '$or') {
584
+ const items = Array.isArray(condition) ? condition : isRecord(condition) ? Object.values(condition) : null;
585
+ if (!items || !items.some((item) => matchesScope(record, pins, item, metadataDialect))) return false;
586
+ continue;
587
+ }
588
+ if (rawKey === '$not') {
589
+ if (!isRecord(condition) || matchesScope(record, pins, condition, metadataDialect)) return false;
590
+ continue;
591
+ }
592
+ if (rawKey.startsWith('$')) return false;
593
+
594
+ const parts = rawKey.split('.');
595
+ const lastPart = parts[parts.length - 1];
596
+ const hasTrailingOp = parts.length > 1 && lastPart.startsWith('$');
597
+ const fieldParts = hasTrailingOp ? parts.slice(0, -1) : parts;
598
+ if (fieldParts.some((part) => !part || part.startsWith('$'))) return false;
599
+
600
+ if (hasTrailingOp) {
601
+ const target = readPathWithPins(record, fieldParts, pins, ARRAY_LEVEL_OPERATORS.has(lastPart));
602
+ if (!evaluateOperatorGroup(target, [[lastPart, condition]], metadataDialect)) return false;
603
+ continue;
604
+ }
605
+
606
+ if (isRecord(condition)) {
607
+ const entries = Object.entries(condition);
608
+ if (!entries.length) continue;
609
+ if (entries.every(([key]) => KNOWN_FILTER_OPERATORS.has(key))) {
610
+ const arrayLevelEntries = entries.filter(([key]) => ARRAY_LEVEL_OPERATORS.has(key));
611
+ const elementEntries = entries.filter(([key]) => !ARRAY_LEVEL_OPERATORS.has(key));
612
+ if (arrayLevelEntries.length) {
613
+ const arrayTarget = readPathWithPins(record, fieldParts, pins, true);
614
+ if (!evaluateOperatorGroup(arrayTarget, arrayLevelEntries, metadataDialect)) return false;
615
+ }
616
+ if (elementEntries.length) {
617
+ const elemTarget = readPathWithPins(record, fieldParts, pins, false);
618
+ if (!evaluateOperatorGroup(elemTarget, elementEntries, metadataDialect)) return false;
619
+ }
620
+ continue;
621
+ }
622
+ if (!entries.every(([key]) => !key.startsWith('$') || LOGICAL_OPERATORS.has(key))) return false;
623
+
624
+ const fieldPathKey = fieldParts.join('.');
625
+ const subPins = extractSubPins(pins, fieldPathKey);
626
+ if (pins.has(fieldPathKey)) {
627
+ const pinnedVal = pins.get(fieldPathKey);
628
+ if (!isRecord(pinnedVal) || !matchesScope(pinnedVal, subPins, condition, metadataDialect)) return false;
629
+ continue;
630
+ }
631
+ const target = readPathWithPins(record, fieldParts, pins, false);
632
+ const nestedMatched = target.values.some((value) => {
633
+ if (Array.isArray(value)) {
634
+ return value.some((entry) => isRecord(entry) && matchesScope(entry, subPins, condition, metadataDialect));
635
+ }
636
+ return isRecord(value) && matchesScope(value, subPins, condition, metadataDialect);
637
+ });
638
+ if (!nestedMatched) return false;
639
+ continue;
640
+ }
641
+
642
+ const target = readPathWithPins(record, fieldParts, pins, false);
643
+ if (!evaluateOperatorGroup(target, [['$eq', condition]], metadataDialect)) return false;
644
+ }
645
+ return true;
646
+ }
647
+
648
+ function matchesScope(
649
+ record: Record<string, unknown>,
650
+ inheritedPins: ReadonlyMap<string, unknown>,
651
+ filter: unknown,
652
+ metadataDialect: string,
653
+ ): boolean {
654
+ if (!isRecord(filter)) return false;
655
+ const prefixes: string[][] = [];
656
+ collectPositiveArrayPrefixes(filter, prefixes);
657
+ const expanded = expandPinsForPrefixes(record, inheritedPins, prefixes);
658
+ if (!expanded) return false;
659
+ return expanded.some((pins) => evaluateEntriesWithPins(record, pins, filter, metadataDialect));
660
+ }
661
+
662
+ function matchesCollectionFilter(
663
+ record: Record<string, unknown>,
664
+ filter: unknown,
665
+ metadataDialect = 'postgres',
666
+ ): boolean {
667
+ return matchesScope(record, new Map(), filter, metadataDialect);
668
+ }
669
+
69
670
  function extractSql(values: Record<string, unknown> | undefined): unknown {
70
671
  if (!values) return undefined;
71
672
  if (values.sql !== undefined) return values.sql;
@@ -93,7 +694,17 @@ function prepareFields(values: Record<string, unknown>): void {
93
694
  values.timestamps = false;
94
695
  }
95
696
  const mapped: FieldValues[] = values.fields.map((field: FieldValues | string) => {
96
- if (typeof field !== 'string') return field;
697
+ if (typeof field !== 'string') {
698
+ if (isRecord(field.settings)) {
699
+ if (field.elementType === undefined && typeof field.settings.elementType === 'string') {
700
+ field.elementType = field.settings.elementType;
701
+ }
702
+ if (field.dataType === undefined && typeof field.settings.dataType === 'string') {
703
+ field.dataType = field.settings.dataType;
704
+ }
705
+ }
706
+ return applyPostgresArrayDataType(field);
707
+ }
97
708
  const preset = PRESET_FIELDS[field];
98
709
  if (!preset) throw new PostgresValidationError('Unknown preset field {{name}}', { name: field });
99
710
  return cloneDeep(preset);
@@ -110,6 +721,93 @@ function prepareFields(values: Record<string, unknown>): void {
110
721
  values.fields = mapped;
111
722
  }
112
723
 
724
+ function toSavedPostgresConnection(record: Model): SavedPostgresConnection | null {
725
+ const key = String(record.get('key') || '').trim();
726
+ const options = record.get('options');
727
+ if (!key || !isRecord(options)) return null;
728
+ const host = typeof options.host === 'string' ? options.host.trim() : '';
729
+ const username = typeof options.username === 'string' ? options.username.trim() : '';
730
+ if (!host || !username) return null;
731
+ const rawPort = Number(options.port);
732
+ const port = Number.isInteger(rawPort) && rawPort >= 1 && rawPort <= 65535 ? rawPort : DEFAULT_PORT;
733
+ const database = typeof options.database === 'string' ? options.database.trim() : '';
734
+ const schema = typeof options.schema === 'string' && options.schema.trim() ? options.schema.trim() : DEFAULT_SCHEMA;
735
+ const displayName = String(record.get('displayName') || key);
736
+ return {
737
+ key,
738
+ displayName,
739
+ host,
740
+ port,
741
+ database,
742
+ schema,
743
+ username,
744
+ ssl: Boolean(options.ssl),
745
+ hasPassword: typeof options.password === 'string' && options.password.length > 0,
746
+ hasSslCa: typeof options.sslCa === 'string' && options.sslCa.trim().length > 0,
747
+ };
748
+ }
749
+
750
+ async function resolveSavedConnectionOptions(ctx: Context, targetOptions: Record<string, unknown>): Promise<void> {
751
+ const rawSourceKey = targetOptions.sourceConnectionKey;
752
+ if ('sourceConnectionKey' in targetOptions) {
753
+ delete targetOptions.sourceConnectionKey;
754
+ }
755
+ const sourceKey = typeof rawSourceKey === 'string' ? rawSourceKey.trim() : '';
756
+ if (!sourceKey) return;
757
+
758
+ const repo = ctx.db?.getRepository?.('dataSources');
759
+ const sourceRecord = (await repo?.findOne?.({
760
+ filter: { key: sourceKey, type: DATA_SOURCE_TYPE },
761
+ })) as Model | null | undefined;
762
+ if (!sourceRecord) {
763
+ throw new PostgresValidationError('Saved PostgreSQL connection {{name}} does not exist', { name: sourceKey });
764
+ }
765
+ const sourceOptions = sourceRecord.get('options');
766
+ if (!isRecord(sourceOptions)) return;
767
+
768
+ if (!targetOptions.host && typeof sourceOptions.host === 'string') {
769
+ targetOptions.host = sourceOptions.host;
770
+ }
771
+ if (
772
+ (targetOptions.port === undefined || targetOptions.port === null || targetOptions.port === '') &&
773
+ sourceOptions.port !== undefined
774
+ ) {
775
+ targetOptions.port = sourceOptions.port;
776
+ }
777
+ if (!targetOptions.database && typeof sourceOptions.database === 'string') {
778
+ targetOptions.database = sourceOptions.database;
779
+ }
780
+ if (!targetOptions.schema && typeof sourceOptions.schema === 'string') {
781
+ targetOptions.schema = sourceOptions.schema;
782
+ }
783
+ if (!targetOptions.username && typeof sourceOptions.username === 'string') {
784
+ targetOptions.username = sourceOptions.username;
785
+ }
786
+ if (targetOptions.ssl === undefined && sourceOptions.ssl !== undefined) {
787
+ targetOptions.ssl = Boolean(sourceOptions.ssl);
788
+ }
789
+
790
+ // Only inherit secret credentials when endpoint host, port, and username match the saved connection.
791
+ const sameHost = String(targetOptions.host || '').trim() === String(sourceOptions.host || '').trim();
792
+ const samePort = Number(targetOptions.port ?? DEFAULT_PORT) === Number(sourceOptions.port ?? DEFAULT_PORT);
793
+ const sameUsername = String(targetOptions.username || '').trim() === String(sourceOptions.username || '').trim();
794
+ if (sameHost && samePort && sameUsername) {
795
+ const hasCustomPassword = typeof targetOptions.password === 'string' && targetOptions.password.length > 0;
796
+ if (!hasCustomPassword && typeof sourceOptions.password === 'string' && sourceOptions.password.length > 0) {
797
+ targetOptions.password = sourceOptions.password;
798
+ }
799
+ const hasCustomSslCa = typeof targetOptions.sslCa === 'string' && targetOptions.sslCa.trim().length > 0;
800
+ if (
801
+ !hasCustomSslCa &&
802
+ targetOptions.ssl !== false &&
803
+ typeof sourceOptions.sslCa === 'string' &&
804
+ sourceOptions.sslCa.trim().length > 0
805
+ ) {
806
+ targetOptions.sslCa = sourceOptions.sslCa;
807
+ }
808
+ }
809
+ }
810
+
113
811
  async function localizeValidationErrors(ctx: Context, next: Next) {
114
812
  try {
115
813
  await next();
@@ -419,6 +1117,32 @@ export class PluginDataSourcePostgresServer extends Plugin {
419
1117
  );
420
1118
  },
421
1119
  );
1120
+ const listSavedConnectionsHandler = async (ctx: Context, next: Next) => {
1121
+ const records = (await ctx.db.getRepository('dataSources').find({
1122
+ filter: { type: DATA_SOURCE_TYPE },
1123
+ sort: ['createdAt'],
1124
+ })) as Model[];
1125
+ ctx.body = records
1126
+ .map((record) => toSavedPostgresConnection(record))
1127
+ .filter((item): item is SavedPostgresConnection => item !== null);
1128
+ await next();
1129
+ };
1130
+ const hasDefinedDataSources = Boolean(this.app.resourceManager.isDefined?.('dataSources'));
1131
+ if (hasDefinedDataSources) {
1132
+ const dataSourcesResource = this.app.resourceManager.getResource?.('dataSources') as
1133
+ | {
1134
+ actions?: Map<string, unknown>;
1135
+ addAction?: (name: string, handler: (ctx: Context, next: Next) => Promise<void>) => void;
1136
+ }
1137
+ | undefined;
1138
+ if (dataSourcesResource && !dataSourcesResource.actions?.has('listPostgresConnections')) {
1139
+ dataSourcesResource.addAction?.('listPostgresConnections', listSavedConnectionsHandler);
1140
+ }
1141
+ } else {
1142
+ this.app.resourceManager.registerActionHandlers?.({
1143
+ [LIST_SAVED_CONNECTIONS_ACTION]: listSavedConnectionsHandler,
1144
+ });
1145
+ }
422
1146
  this.app.resourceManager.registerPreActionHandler('dataSources:readTables', async (ctx, next) => {
423
1147
  const { dataSourceKey, dbOptions } = ctx.action.params.values || {};
424
1148
  if (dbOptions?.type !== DATA_SOURCE_TYPE) {
@@ -426,6 +1150,10 @@ export class PluginDataSourcePostgresServer extends Plugin {
426
1150
  return;
427
1151
  }
428
1152
 
1153
+ if (isRecord(dbOptions)) {
1154
+ await resolveSavedConnectionOptions(ctx, dbOptions);
1155
+ }
1156
+
429
1157
  const manager = this.app.dataSourceManager;
430
1158
  const renderedOptions = this.app.environment?.renderJsonTemplate
431
1159
  ? this.app.environment.renderJsonTemplate(dbOptions)
@@ -469,7 +1197,8 @@ export class PluginDataSourcePostgresServer extends Plugin {
469
1197
  async (ctx: Context, next: Next) => {
470
1198
  const { resourceName, actionName, params } = ctx.action || {};
471
1199
  if (resourceName === 'dataSources.collections') {
472
- const dataSource = this.app.dataSourceManager.get(params.associatedIndex);
1200
+ const dataSourceKey = ctx.action?.sourceId || params?.associatedIndex;
1201
+ const dataSource = dataSourceKey ? this.app.dataSourceManager.get(dataSourceKey) : undefined;
473
1202
  if (dataSource instanceof PostgresDataSource) {
474
1203
  if (actionName === 'create' || actionName === 'destroy') {
475
1204
  await this.mutateCollection(ctx, dataSource, next);
@@ -523,6 +1252,142 @@ export class PluginDataSourcePostgresServer extends Plugin {
523
1252
  },
524
1253
  { tag: 'postgres-schema-actions', after: ['acl'] },
525
1254
  );
1255
+ this.app.resourceManager.use(
1256
+ async (ctx: Context, next: Next) => {
1257
+ const { resourceName, actionName, params } = ctx.action || {};
1258
+ if (resourceName === 'dataSources') {
1259
+ const values = isRecord(params?.values) ? params.values : undefined;
1260
+ if (
1261
+ actionName === 'readTables' &&
1262
+ isRecord(values?.dbOptions) &&
1263
+ values.dbOptions.type === DATA_SOURCE_TYPE
1264
+ ) {
1265
+ await resolveSavedConnectionOptions(ctx, values.dbOptions);
1266
+ } else if (
1267
+ (actionName === 'testConnection' || actionName === 'create') &&
1268
+ values?.type === DATA_SOURCE_TYPE &&
1269
+ isRecord(values.options)
1270
+ ) {
1271
+ await resolveSavedConnectionOptions(ctx, values.options);
1272
+ } else if (actionName === 'update' && isRecord(values?.options) && 'sourceConnectionKey' in values.options) {
1273
+ let isPostgresTarget =
1274
+ values.type === DATA_SOURCE_TYPE ||
1275
+ this.app.dataSourceManager.get(params?.filterByTk) instanceof PostgresDataSource;
1276
+ if (!isPostgresTarget && params?.filterByTk) {
1277
+ const target = (await ctx.db
1278
+ ?.getRepository?.('dataSources')
1279
+ ?.findOne?.({ filterByTk: params.filterByTk })) as Model | null | undefined;
1280
+ isPostgresTarget = target?.get?.('type') === DATA_SOURCE_TYPE;
1281
+ }
1282
+ if (isPostgresTarget) {
1283
+ await resolveSavedConnectionOptions(ctx, values.options);
1284
+ }
1285
+ }
1286
+ }
1287
+ await next();
1288
+ },
1289
+ { tag: 'postgres-saved-connection', after: ['acl'], before: ['default'] },
1290
+ );
1291
+ }
1292
+
1293
+ private async resolveCollectionsToDestroy(ctx: Context, source: PostgresDataSource): Promise<string[]> {
1294
+ const params = ctx.action?.params || {};
1295
+ const permission = (
1296
+ ctx as {
1297
+ permission?: {
1298
+ parsedParams?: { filter?: unknown };
1299
+ can?: { params?: { filter?: unknown } };
1300
+ };
1301
+ }
1302
+ ).permission;
1303
+ const rawFilter = params.filter;
1304
+ const scopeFilter = permission?.parsedParams?.filter ?? permission?.can?.params?.filter;
1305
+ const hasRawFilter = isValidFilter(rawFilter);
1306
+ const hasScopeFilter = isValidFilter(scopeFilter);
1307
+ const effectiveFilter =
1308
+ hasRawFilter && hasScopeFilter && !isEqual(rawFilter, scopeFilter)
1309
+ ? { $and: [rawFilter, scopeFilter] }
1310
+ : hasRawFilter
1311
+ ? rawFilter
1312
+ : hasScopeFilter
1313
+ ? scopeFilter
1314
+ : undefined;
1315
+
1316
+ const hasFilterByTk = params.filterByTk !== undefined && params.filterByTk !== null;
1317
+ let requestedNames: string[] | undefined;
1318
+ if (hasFilterByTk) {
1319
+ if (Array.isArray(params.filterByTk) && params.filterByTk.length === 0) {
1320
+ return [];
1321
+ }
1322
+ requestedNames = names(params.filterByTk);
1323
+ } else if (!effectiveFilter) {
1324
+ throw new PostgresValidationError('A collection name is required');
1325
+ }
1326
+
1327
+ const manager = source.collectionManager;
1328
+ if (!effectiveFilter) {
1329
+ for (const name of requestedNames ?? []) {
1330
+ if (!manager.getCollection(name)) {
1331
+ ctx.throw(404, translate(ctx, 'Collection {{name}} does not exist', { name }));
1332
+ }
1333
+ }
1334
+ return requestedNames ?? [];
1335
+ }
1336
+
1337
+ const db = this.app.db || ctx.db;
1338
+ const metadataDialect = db?.sequelize?.getDialect?.() ?? 'postgres';
1339
+ const collectionsRepo = db?.getRepository?.('dataSourcesCollections') as
1340
+ | { find?: (options: Record<string, unknown>) => Promise<Model[]> }
1341
+ | undefined;
1342
+
1343
+ if (collectionsRepo && typeof collectionsRepo.find === 'function') {
1344
+ const baseFilter: Record<string, unknown> = {
1345
+ dataSourceKey: source.name,
1346
+ ...(requestedNames ? { name: { $in: requestedNames } } : {}),
1347
+ };
1348
+ const persistedAll = await collectionsRepo.find({ filter: baseFilter, context: ctx });
1349
+ const persistedNames = new Set(persistedAll.map((row) => String(row.get('name'))));
1350
+ const persistedMatched = await collectionsRepo.find({
1351
+ filter: { $and: [baseFilter, effectiveFilter] },
1352
+ context: ctx,
1353
+ });
1354
+ const matchedSet = new Set(persistedMatched.map((row) => String(row.get('name'))));
1355
+
1356
+ for (const collection of manager.getCollections()) {
1357
+ if (persistedNames.has(collection.name)) continue;
1358
+ if (requestedNames && !requestedNames.includes(collection.name)) continue;
1359
+ const record: Record<string, unknown> = {
1360
+ ...collection.options,
1361
+ name: collection.name,
1362
+ dataSourceKey: source.name,
1363
+ dataSources: { key: source.name, type: DATA_SOURCE_TYPE },
1364
+ options: collection.options,
1365
+ fields: collection.getFields().map((field) => field.options),
1366
+ };
1367
+ if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
1368
+ matchedSet.add(collection.name);
1369
+ }
1370
+ }
1371
+
1372
+ return requestedNames ? requestedNames.filter((name) => matchedSet.has(name)) : [...matchedSet];
1373
+ }
1374
+
1375
+ const matchedRuntime = new Set<string>();
1376
+ for (const collection of manager.getCollections()) {
1377
+ if (requestedNames && !requestedNames.includes(collection.name)) continue;
1378
+ const record: Record<string, unknown> = {
1379
+ ...collection.options,
1380
+ name: collection.name,
1381
+ dataSourceKey: source.name,
1382
+ dataSources: { key: source.name, type: DATA_SOURCE_TYPE },
1383
+ options: collection.options,
1384
+ fields: collection.getFields().map((field) => field.options),
1385
+ };
1386
+ if (matchesCollectionFilter(record, effectiveFilter, metadataDialect)) {
1387
+ matchedRuntime.add(collection.name);
1388
+ }
1389
+ }
1390
+ return requestedNames ? requestedNames.filter((name) => matchedRuntime.has(name)) : [...matchedRuntime];
526
1391
  }
527
1392
 
528
1393
  private async mutateCollection(ctx: Context, source: PostgresDataSource, next: Next) {
@@ -574,22 +1439,33 @@ export class PluginDataSourcePostgresServer extends Plugin {
574
1439
  return;
575
1440
  }
576
1441
 
577
- const collectionNames = names(params.filterByTk);
578
- const snapshots = collectionNames.map((name) => {
1442
+ const collectionNames = await this.resolveCollectionsToDestroy(ctx, source);
1443
+ if (collectionNames.length === 0) {
1444
+ ctx.body = true;
1445
+ return;
1446
+ }
1447
+
1448
+ const snapshots = collectionNames.flatMap((name) => {
579
1449
  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
- };
1450
+ if (!collection) return [];
1451
+ return [
1452
+ {
1453
+ name,
1454
+ physicalName: String(collection.options.tableName || name),
1455
+ isSql: Boolean(collection.options.sql),
1456
+ options: cloneDeep({
1457
+ ...collection.options,
1458
+ tableName: String(collection.options.tableName || name),
1459
+ fields: collection.getFields().map((field) => field.options),
1460
+ }),
1461
+ },
1462
+ ];
591
1463
  });
592
1464
  const cascade = params.cascade === true || params.cascade === 'true';
1465
+ const hadFilterByTk = Object.prototype.hasOwnProperty.call(params, 'filterByTk');
1466
+ const hadFilter = Object.prototype.hasOwnProperty.call(params, 'filter');
1467
+ const originalFilterByTk = params.filterByTk;
1468
+ const originalFilter = params.filter;
593
1469
  try {
594
1470
  await manager.db.sequelize.transaction(async (transaction) => {
595
1471
  for (const snapshot of [...snapshots].sort((left, right) =>
@@ -601,15 +1477,21 @@ export class PluginDataSourcePostgresServer extends Plugin {
601
1477
  });
602
1478
  if (!snapshot.isSql) await manager.dropTable(snapshot.name, cascade, transaction);
603
1479
  }
1480
+ params.filterByTk = collectionNames;
1481
+ delete params.filter;
604
1482
  await next();
605
1483
  });
606
1484
  } catch (error) {
1485
+ if (hadFilterByTk) params.filterByTk = originalFilterByTk;
1486
+ else delete params.filterByTk;
1487
+ if (hadFilter) params.filter = originalFilter;
1488
+ else delete params.filter;
607
1489
  for (const snapshot of snapshots) {
608
1490
  if (!manager.hasCollection(snapshot.name)) manager.defineCollection(snapshot.options);
609
1491
  }
610
1492
  throw error;
611
1493
  }
612
- const fieldsRepo = this.app.db?.getRepository?.('dataSourcesFields') as
1494
+ const fieldsRepo = (this.app.db || ctx.db)?.getRepository?.('dataSourcesFields') as
613
1495
  | { destroy?: (options: Record<string, unknown>) => Promise<unknown> }
614
1496
  | undefined;
615
1497
  if (fieldsRepo && typeof fieldsRepo.destroy === 'function') {
@@ -635,7 +1517,7 @@ export class PluginDataSourcePostgresServer extends Plugin {
635
1517
  await this.sendSyncMessage({
636
1518
  type: 'collectionRemoved',
637
1519
  dataSourceKey: source.name,
638
- collectionNames: snapshots.map((snapshot) => snapshot.name),
1520
+ collectionNames,
639
1521
  });
640
1522
  }
641
1523
 
@@ -704,6 +1586,18 @@ export class PluginDataSourcePostgresServer extends Plugin {
704
1586
  });
705
1587
  }
706
1588
  await syncFieldAction(manager, action, collectionName, fieldName, input, transaction);
1589
+ if (input.dataType === 'array' && isRecord(params.values)) {
1590
+ if (
1591
+ params.values.dataType === undefined ||
1592
+ params.values.dataType === null ||
1593
+ params.values.dataType === ''
1594
+ ) {
1595
+ params.values.dataType = 'array';
1596
+ }
1597
+ if (params.values.elementType === undefined && typeof input.elementType === 'string') {
1598
+ params.values.elementType = input.elementType;
1599
+ }
1600
+ }
707
1601
  metadataActionStarted = true;
708
1602
  await next();
709
1603
  });