plugin-data-source-postgres 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/externalVersion.js +1 -0
- package/dist/server/collections/sql-collection.js +2 -2
- package/dist/server/collections/sql-model.js +4 -2
- package/dist/server/hooks/field-hooks.js +20 -0
- package/dist/server/plugin.js +603 -20
- package/dist/server/postgres-collection-manager.js +192 -25
- package/dist/server/postgres-datasource.js +47 -13
- package/dist/server/utils/sql-validator.js +119 -69
- package/package.json +2 -2
- package/src/server/__tests__/postgres-datasource.unit.test.ts +885 -0
- package/src/server/__tests__/sql-model.test.ts +47 -3
- package/src/server/__tests__/sql-validator.test.ts +8 -1
- package/src/server/collections/sql-collection.ts +2 -2
- package/src/server/collections/sql-model.ts +2 -2
- package/src/server/hooks/field-hooks.ts +36 -2
- package/src/server/plugin.ts +752 -17
- package/src/server/postgres-collection-manager.ts +228 -28
- package/src/server/postgres-datasource.ts +57 -12
- package/src/server/utils/sql-validator.ts +123 -68
|
@@ -17,6 +17,7 @@ interface FieldOptions {
|
|
|
17
17
|
name: string;
|
|
18
18
|
field?: string;
|
|
19
19
|
type?: string;
|
|
20
|
+
dataType?: string;
|
|
20
21
|
allowNull?: boolean;
|
|
21
22
|
defaultValue?: unknown;
|
|
22
23
|
unique?: boolean;
|
|
@@ -26,8 +27,50 @@ interface FieldOptions {
|
|
|
26
27
|
precision?: number;
|
|
27
28
|
scale?: number;
|
|
28
29
|
elementType?: string;
|
|
30
|
+
[key: string]: unknown;
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
const POSTGRES_BUILD_FIELD_NORMALIZED = Symbol('postgresBuildFieldNormalized');
|
|
34
|
+
|
|
35
|
+
export function isPostgresPhysicalArrayRawType(rawType: unknown): boolean {
|
|
36
|
+
if (typeof rawType !== 'string') return false;
|
|
37
|
+
const trimmed = rawType.trim();
|
|
38
|
+
return trimmed.toUpperCase() === 'ARRAY' || trimmed.endsWith('[]');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function applyPostgresArrayDataType<T extends Record<string, unknown>>(field: T): T {
|
|
42
|
+
const type = field.type;
|
|
43
|
+
if (type !== 'array' && type !== 'set') {
|
|
44
|
+
return field;
|
|
45
|
+
}
|
|
46
|
+
const hasRawType = typeof field.rawType === 'string' && field.rawType.trim().length > 0;
|
|
47
|
+
if (hasRawType && !isPostgresPhysicalArrayRawType(field.rawType)) {
|
|
48
|
+
if (field.dataType === undefined || field.dataType === null || field.dataType === '') {
|
|
49
|
+
Object.assign(field, { dataType: 'json' });
|
|
50
|
+
}
|
|
51
|
+
return field;
|
|
52
|
+
}
|
|
53
|
+
const elementType = field.elementType;
|
|
54
|
+
if (
|
|
55
|
+
typeof elementType === 'string' &&
|
|
56
|
+
elementType.trim().length > 0 &&
|
|
57
|
+
(field.dataType === undefined || field.dataType === null || field.dataType === '')
|
|
58
|
+
) {
|
|
59
|
+
Object.assign(field, { dataType: 'array' });
|
|
60
|
+
}
|
|
61
|
+
return field;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type SequelizeWithNormalize = {
|
|
65
|
+
normalizeDataType?: (type: unknown) => { toSql?: () => string; key?: string };
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const SAFE_ARRAY_TYPE_RE =
|
|
69
|
+
/^[a-zA-Z_][a-zA-Z0-9_]*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\[\])+$/;
|
|
70
|
+
const INTEGER_ELEMENT_TYPES = new Set(['smallint', 'integer', 'int', 'int2', 'int4', 'bigint', 'int8']);
|
|
71
|
+
const NUMERIC_ELEMENT_TYPES = new Set(['real', 'float', 'float4', 'float8', 'double precision', 'numeric', 'decimal']);
|
|
72
|
+
const BOOLEAN_ELEMENT_TYPES = new Set(['boolean', 'bool']);
|
|
73
|
+
|
|
31
74
|
interface UniqueIndex {
|
|
32
75
|
indexName: string;
|
|
33
76
|
constraintName: string | null;
|
|
@@ -45,12 +88,51 @@ interface ForeignKeyOptions {
|
|
|
45
88
|
}
|
|
46
89
|
|
|
47
90
|
export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
91
|
+
constructor(options?: ConstructorParameters<typeof SequelizeCollectionManager>[0]) {
|
|
92
|
+
super(options);
|
|
93
|
+
this.installArrayFieldNormalizer();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private installArrayFieldNormalizer(): void {
|
|
97
|
+
const dbRecord = this.db as unknown as {
|
|
98
|
+
buildField?: ((options: Record<string, unknown>, context: unknown) => unknown) & {
|
|
99
|
+
[POSTGRES_BUILD_FIELD_NORMALIZED]?: boolean;
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
const originalBuildField = dbRecord?.buildField;
|
|
103
|
+
if (typeof originalBuildField !== 'function' || originalBuildField[POSTGRES_BUILD_FIELD_NORMALIZED]) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const wrappedBuildField = function (this: unknown, fieldOptions: Record<string, unknown>, context: unknown) {
|
|
107
|
+
if (fieldOptions && typeof fieldOptions === 'object') {
|
|
108
|
+
applyPostgresArrayDataType(fieldOptions);
|
|
109
|
+
}
|
|
110
|
+
return originalBuildField.call(this, fieldOptions, context);
|
|
111
|
+
} as typeof originalBuildField;
|
|
112
|
+
wrappedBuildField[POSTGRES_BUILD_FIELD_NORMALIZED] = true;
|
|
113
|
+
dbRecord.buildField = wrappedBuildField;
|
|
114
|
+
}
|
|
115
|
+
|
|
48
116
|
defineCollection(options: CollectionOptions) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
117
|
+
const normalizedOptions = Array.isArray(options.fields)
|
|
118
|
+
? {
|
|
119
|
+
...options,
|
|
120
|
+
fields: options.fields.map((field) =>
|
|
121
|
+
field && typeof field === 'object'
|
|
122
|
+
? applyPostgresArrayDataType({ ...(field as Record<string, unknown>) })
|
|
123
|
+
: field,
|
|
124
|
+
),
|
|
125
|
+
}
|
|
126
|
+
: options;
|
|
127
|
+
if (normalizedOptions.tree) {
|
|
128
|
+
const { tree, ...rest } = normalizedOptions;
|
|
129
|
+
return super.defineCollection({
|
|
130
|
+
...rest,
|
|
131
|
+
postgresTree: tree,
|
|
132
|
+
template: normalizedOptions.template || 'tree',
|
|
133
|
+
} as CollectionOptions);
|
|
52
134
|
}
|
|
53
|
-
return super.defineCollection(
|
|
135
|
+
return super.defineCollection(normalizedOptions as CollectionOptions);
|
|
54
136
|
}
|
|
55
137
|
|
|
56
138
|
replaceCollections(collections: CollectionOptions[]): void {
|
|
@@ -112,23 +194,23 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
112
194
|
private fieldType(collectionName: string, options: FieldOptions): string {
|
|
113
195
|
const collection = this.getCollection(collectionName);
|
|
114
196
|
if (!collection) throw new PostgresValidationError('Collection {{name}} does not exist', { name: collectionName });
|
|
115
|
-
const
|
|
197
|
+
const buildOptions: FieldOptions = applyPostgresArrayDataType({ ...options });
|
|
198
|
+
const field = this.db.buildField(buildOptions, { collection, database: this.db });
|
|
116
199
|
if (field.isRelationField() || !field.dataType) {
|
|
117
200
|
throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
|
|
118
201
|
type: options.type || '',
|
|
119
202
|
});
|
|
120
203
|
}
|
|
121
204
|
const sequelizeField = field.toSequelize() as { type?: { toSql?: () => string; key?: string } };
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
sequelizeField.type
|
|
125
|
-
|
|
126
|
-
) {
|
|
205
|
+
const normalizedType =
|
|
206
|
+
(this.db.sequelize as unknown as SequelizeWithNormalize).normalizeDataType?.(sequelizeField.type) ??
|
|
207
|
+
sequelizeField.type;
|
|
208
|
+
if (!normalizedType || normalizedType.key === 'VIRTUAL' || typeof normalizedType.toSql !== 'function') {
|
|
127
209
|
throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
|
|
128
210
|
type: options.type || '',
|
|
129
211
|
});
|
|
130
212
|
}
|
|
131
|
-
const sqlType =
|
|
213
|
+
const sqlType = normalizedType.toSql();
|
|
132
214
|
if (!sqlType || sqlType.toUpperCase() === 'VIRTUAL') {
|
|
133
215
|
throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
|
|
134
216
|
type: options.type || '',
|
|
@@ -159,6 +241,17 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
159
241
|
return columns[0]?.dataType;
|
|
160
242
|
}
|
|
161
243
|
|
|
244
|
+
async isPhysicalArrayColumn(
|
|
245
|
+
collectionName: string,
|
|
246
|
+
columnName: string,
|
|
247
|
+
transaction?: Transaction,
|
|
248
|
+
): Promise<boolean | undefined> {
|
|
249
|
+
const { schema, tableName } = this.tableInfo(collectionName);
|
|
250
|
+
const columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
|
|
251
|
+
if (columnType === undefined) return undefined;
|
|
252
|
+
return isPostgresPhysicalArrayRawType(columnType);
|
|
253
|
+
}
|
|
254
|
+
|
|
162
255
|
private async isColumnNotNull(
|
|
163
256
|
schema: string,
|
|
164
257
|
tableName: string,
|
|
@@ -181,14 +274,105 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
181
274
|
return columns[0]?.notNull === true;
|
|
182
275
|
}
|
|
183
276
|
|
|
184
|
-
private
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (
|
|
190
|
-
|
|
191
|
-
|
|
277
|
+
private formatArrayDefaultElement(element: unknown, elementType: string): string {
|
|
278
|
+
if (element === null) return 'NULL';
|
|
279
|
+
if (element === undefined || typeof element === 'function' || typeof element === 'symbol') {
|
|
280
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
281
|
+
}
|
|
282
|
+
if (elementType.endsWith('[]')) {
|
|
283
|
+
if (!Array.isArray(element)) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
284
|
+
if (!element.length) return `ARRAY[]::${elementType}`;
|
|
285
|
+
const innerType = elementType.slice(0, -2);
|
|
286
|
+
return `ARRAY[${element.map((item) => this.formatArrayDefaultElement(item, innerType)).join(', ')}]`;
|
|
287
|
+
}
|
|
288
|
+
const baseType = elementType
|
|
289
|
+
.replace(/\([^)]*\)/g, '')
|
|
290
|
+
.trim()
|
|
291
|
+
.toLowerCase();
|
|
292
|
+
if (baseType === 'json' || baseType === 'jsonb') {
|
|
293
|
+
const encoded = JSON.stringify(element);
|
|
294
|
+
if (encoded === undefined) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
295
|
+
return `${this.db.sequelize.escape(encoded)}::${baseType}`;
|
|
296
|
+
}
|
|
297
|
+
if (INTEGER_ELEMENT_TYPES.has(baseType)) {
|
|
298
|
+
if (typeof element === 'bigint') return String(element);
|
|
299
|
+
if (typeof element === 'number') {
|
|
300
|
+
if (!Number.isSafeInteger(element)) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
301
|
+
return String(element);
|
|
302
|
+
}
|
|
303
|
+
if (typeof element === 'string' && /^[+-]?\d+$/.test(element.trim())) return element.trim();
|
|
304
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
305
|
+
}
|
|
306
|
+
if (NUMERIC_ELEMENT_TYPES.has(baseType)) {
|
|
307
|
+
if (typeof element === 'bigint') return String(element);
|
|
308
|
+
if (typeof element === 'number') {
|
|
309
|
+
if (!Number.isFinite(element)) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
310
|
+
return String(element);
|
|
311
|
+
}
|
|
312
|
+
if (typeof element === 'string' && /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(element.trim())) {
|
|
313
|
+
return element.trim();
|
|
314
|
+
}
|
|
315
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
316
|
+
}
|
|
317
|
+
if (BOOLEAN_ELEMENT_TYPES.has(baseType)) {
|
|
318
|
+
if (typeof element === 'boolean') return element ? 'TRUE' : 'FALSE';
|
|
319
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
320
|
+
}
|
|
321
|
+
if (typeof element === 'boolean') return element ? 'TRUE' : 'FALSE';
|
|
322
|
+
if (typeof element === 'bigint') return String(element);
|
|
323
|
+
if (typeof element === 'number') {
|
|
324
|
+
if (!Number.isFinite(element)) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
325
|
+
return this.db.sequelize.escape(element);
|
|
326
|
+
}
|
|
327
|
+
if (typeof element === 'string' || element instanceof Date) {
|
|
328
|
+
return this.db.sequelize.escape(element);
|
|
329
|
+
}
|
|
330
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private defaultSql(value: unknown, columnType?: string): string {
|
|
334
|
+
if (value === null) return 'NULL';
|
|
335
|
+
const rawType = (columnType || '').trim();
|
|
336
|
+
const lowerType = rawType.toLowerCase();
|
|
337
|
+
|
|
338
|
+
if (lowerType.endsWith('[]')) {
|
|
339
|
+
if (!SAFE_ARRAY_TYPE_RE.test(rawType)) {
|
|
340
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
341
|
+
}
|
|
342
|
+
if (Array.isArray(value)) {
|
|
343
|
+
if (!value.length) return `ARRAY[]::${rawType}`;
|
|
344
|
+
const innerType = rawType.slice(0, -2);
|
|
345
|
+
return `ARRAY[${value.map((item) => this.formatArrayDefaultElement(item, innerType)).join(', ')}]::${rawType}`;
|
|
346
|
+
}
|
|
347
|
+
if (typeof value === 'string') {
|
|
348
|
+
return `${this.db.sequelize.escape(value)}::${rawType}`;
|
|
349
|
+
}
|
|
350
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (lowerType === 'json' || lowerType === 'jsonb') {
|
|
354
|
+
if (typeof value === 'string') return this.db.sequelize.escape(value);
|
|
355
|
+
if (
|
|
356
|
+
typeof value === 'boolean' ||
|
|
357
|
+
(typeof value === 'number' && Number.isFinite(value)) ||
|
|
358
|
+
value instanceof Date ||
|
|
359
|
+
(typeof value === 'object' && value !== null)
|
|
360
|
+
) {
|
|
361
|
+
const encoded = JSON.stringify(value);
|
|
362
|
+
if (encoded === undefined) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
363
|
+
return this.db.sequelize.escape(encoded);
|
|
364
|
+
}
|
|
365
|
+
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';
|
|
369
|
+
if (typeof value === 'bigint') return String(value);
|
|
370
|
+
if (typeof value === 'number') {
|
|
371
|
+
if (!Number.isFinite(value)) throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
372
|
+
return this.db.sequelize.escape(value);
|
|
373
|
+
}
|
|
374
|
+
if (typeof value === 'string' || value instanceof Date) {
|
|
375
|
+
return this.db.sequelize.escape(value);
|
|
192
376
|
}
|
|
193
377
|
throw new PostgresValidationError('Unsupported PostgreSQL default value');
|
|
194
378
|
}
|
|
@@ -398,15 +582,14 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
398
582
|
throw new PostgresValidationError('Field name and type are required');
|
|
399
583
|
}
|
|
400
584
|
const columnName = field.field || field.name;
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
)} ${this.fieldType(collectionName, field)}`;
|
|
585
|
+
const sqlType = this.fieldType(collectionName, field);
|
|
586
|
+
let sql = `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(columnName)} ${sqlType}`;
|
|
404
587
|
if (field.autoIncrement && field.defaultValue !== undefined) {
|
|
405
588
|
throw new PostgresValidationError('A generated field cannot also have a default value');
|
|
406
589
|
}
|
|
407
590
|
if (field.autoIncrement) sql += ' GENERATED BY DEFAULT AS IDENTITY';
|
|
408
591
|
if (field.allowNull === false) sql += ' NOT NULL';
|
|
409
|
-
if (field.defaultValue !== undefined) sql += ` DEFAULT ${this.defaultSql(field.defaultValue)}`;
|
|
592
|
+
if (field.defaultValue !== undefined) sql += ` DEFAULT ${this.defaultSql(field.defaultValue, sqlType)}`;
|
|
410
593
|
if (field.primaryKey) sql += ' PRIMARY KEY';
|
|
411
594
|
await this.db.sequelize.query(sql, { transaction });
|
|
412
595
|
if (field.unique && !field.primaryKey) await this.setUnique(collectionName, columnName, true, transaction);
|
|
@@ -426,10 +609,11 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
426
609
|
const table = this.tableSql(collectionName);
|
|
427
610
|
const columnName = this.getCollection(collectionName)?.getField(fieldName)?.columnName() || fieldName;
|
|
428
611
|
const column = this.quoteIdentifier(columnName);
|
|
429
|
-
|
|
612
|
+
let alteredType: string | undefined;
|
|
613
|
+
if (['type', 'dataType', 'length', 'precision', 'scale', 'elementType'].some((key) => key in options)) {
|
|
430
614
|
const existing = this.getCollection(collectionName)?.getField(fieldName)?.options || {};
|
|
431
|
-
|
|
432
|
-
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${
|
|
615
|
+
alteredType = this.fieldType(collectionName, { ...existing, ...options, name: fieldName });
|
|
616
|
+
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${alteredType}`, {
|
|
433
617
|
transaction,
|
|
434
618
|
});
|
|
435
619
|
}
|
|
@@ -442,8 +626,24 @@ export class PostgresCollectionManager extends SequelizeCollectionManager {
|
|
|
442
626
|
);
|
|
443
627
|
}
|
|
444
628
|
if (options.defaultValue !== undefined) {
|
|
445
|
-
|
|
446
|
-
|
|
629
|
+
let clause: string;
|
|
630
|
+
if (options.defaultValue === null) {
|
|
631
|
+
clause = 'DROP DEFAULT';
|
|
632
|
+
} else {
|
|
633
|
+
let columnType = alteredType;
|
|
634
|
+
if (!columnType) {
|
|
635
|
+
const { schema, tableName } = this.tableInfo(collectionName);
|
|
636
|
+
columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
|
|
637
|
+
if (!columnType) {
|
|
638
|
+
const existing = this.getCollection(collectionName)?.getField(fieldName)?.options || {};
|
|
639
|
+
const merged = { ...existing, ...options, name: fieldName };
|
|
640
|
+
if (merged.type) {
|
|
641
|
+
columnType = this.fieldType(collectionName, merged);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
clause = `SET DEFAULT ${this.defaultSql(options.defaultValue, columnType)}`;
|
|
646
|
+
}
|
|
447
647
|
await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} ${clause}`, { transaction });
|
|
448
648
|
}
|
|
449
649
|
if (options.unique !== undefined) {
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
} from '@nocobase/data-source-manager';
|
|
19
19
|
import { QueryTypes } from 'sequelize';
|
|
20
20
|
import { NAMESPACE } from '../constants';
|
|
21
|
-
import { PostgresCollectionManager } from './postgres-collection-manager';
|
|
21
|
+
import { isPostgresPhysicalArrayRawType, PostgresCollectionManager } from './postgres-collection-manager';
|
|
22
22
|
import { PostgresValidationError } from './utils/validation-error';
|
|
23
23
|
|
|
24
24
|
interface PostgresOptions {
|
|
@@ -99,7 +99,7 @@ export class PostgresDataSource extends SequelizeDataSource {
|
|
|
99
99
|
try {
|
|
100
100
|
return await this.collectionManager.discoverTables();
|
|
101
101
|
} finally {
|
|
102
|
-
if (!this.isLoaded) await this.close();
|
|
102
|
+
if (!this.isLoaded && !this.reusedDatabase) await this.close();
|
|
103
103
|
}
|
|
104
104
|
};
|
|
105
105
|
introspector.getTableColumnsInfo = async (tableInfo: { tableName: string; schema?: string }) => {
|
|
@@ -188,23 +188,31 @@ export class PostgresDataSource extends SequelizeDataSource {
|
|
|
188
188
|
|
|
189
189
|
async loadTables(ctx: Context, tables: string[] = [], options: LoadTablesOptions = {}): Promise<void> {
|
|
190
190
|
const names = selectedTables(tables);
|
|
191
|
-
const { actionName, resourceName, params } = ctx
|
|
191
|
+
const { actionName, resourceName, params } = ctx?.action || {};
|
|
192
|
+
const values =
|
|
193
|
+
params?.values && typeof params.values === 'object' && !Array.isArray(params.values)
|
|
194
|
+
? (params.values as Record<string, unknown>)
|
|
195
|
+
: undefined;
|
|
192
196
|
const isSettingsAction = resourceName === 'dataSources' && ['create', 'update'].includes(actionName);
|
|
193
197
|
const isLoadTablesAction = resourceName === 'dataSources' && actionName === 'loadTables';
|
|
194
|
-
const preserveSelection = Boolean(
|
|
195
|
-
if (
|
|
196
|
-
delete
|
|
198
|
+
const preserveSelection = Boolean(values?.__postgresPreserveSelection);
|
|
199
|
+
if (values && '__postgresPreserveSelection' in values) {
|
|
200
|
+
delete values.__postgresPreserveSelection;
|
|
197
201
|
}
|
|
198
|
-
if (isSettingsAction && Array.isArray(
|
|
199
|
-
|
|
200
|
-
|
|
202
|
+
if (isSettingsAction && values && Array.isArray(values.collections) && !preserveSelection) {
|
|
203
|
+
const currentOptions =
|
|
204
|
+
values.options && typeof values.options === 'object' && !Array.isArray(values.options)
|
|
205
|
+
? (values.options as Record<string, unknown>)
|
|
206
|
+
: {};
|
|
207
|
+
values.options = {
|
|
208
|
+
...currentOptions,
|
|
201
209
|
addAllCollections: false,
|
|
202
210
|
selectedCollections: names,
|
|
203
211
|
};
|
|
204
212
|
}
|
|
205
213
|
try {
|
|
206
214
|
let localData = options.localData;
|
|
207
|
-
if (!localData && isLoadTablesAction && ctx
|
|
215
|
+
if (!localData && isLoadTablesAction && ctx?.db) {
|
|
208
216
|
const record = (await ctx.db.getRepository('dataSources').findOne({
|
|
209
217
|
filterByTk: this.name,
|
|
210
218
|
})) as { loadLocalData?: () => Promise<LoadedCollections> } | null;
|
|
@@ -214,7 +222,7 @@ export class PostgresDataSource extends SequelizeDataSource {
|
|
|
214
222
|
}
|
|
215
223
|
const collections = await this.prepareTables(names, localData || {});
|
|
216
224
|
this.collectionManager.replaceCollections(collections);
|
|
217
|
-
if (isLoadTablesAction) {
|
|
225
|
+
if (isLoadTablesAction && ctx?.db) {
|
|
218
226
|
const updatedSelection = await this.addSelectedTables(ctx, names, names);
|
|
219
227
|
if (!updatedSelection && names.length) {
|
|
220
228
|
const plugin = ctx.app?.pm?.get(NAMESPACE) || ctx.app?.pm?.get('data-source-postgres');
|
|
@@ -228,7 +236,7 @@ export class PostgresDataSource extends SequelizeDataSource {
|
|
|
228
236
|
}
|
|
229
237
|
}
|
|
230
238
|
} finally {
|
|
231
|
-
if (!this.isLoaded) await this.close();
|
|
239
|
+
if (!this.isLoaded && !this.reusedDatabase) await this.close();
|
|
232
240
|
}
|
|
233
241
|
}
|
|
234
242
|
|
|
@@ -275,6 +283,43 @@ export class PostgresDataSource extends SequelizeDataSource {
|
|
|
275
283
|
[inferred],
|
|
276
284
|
saved ? { ...localData, [inferred.name]: saved } : localData,
|
|
277
285
|
);
|
|
286
|
+
const inferredByColumn = new Map<string, Record<string, unknown>>();
|
|
287
|
+
const inferredByName = new Map<string, Record<string, unknown>>();
|
|
288
|
+
for (const field of inferred.fields || []) {
|
|
289
|
+
const record = field as unknown as Record<string, unknown>;
|
|
290
|
+
const colKey = String(record.columnName || record.field || record.name || '');
|
|
291
|
+
if (colKey && !inferredByColumn.has(colKey)) {
|
|
292
|
+
inferredByColumn.set(colKey, record);
|
|
293
|
+
}
|
|
294
|
+
if (typeof record.name === 'string' && !inferredByName.has(record.name)) {
|
|
295
|
+
inferredByName.set(record.name, record);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
for (const field of merged.fields || []) {
|
|
299
|
+
const fieldRecord = field as unknown as Record<string, unknown>;
|
|
300
|
+
const colKey = String(fieldRecord.columnName || fieldRecord.field || fieldRecord.name || '');
|
|
301
|
+
const inferredField =
|
|
302
|
+
(colKey ? inferredByColumn.get(colKey) : undefined) || inferredByName.get(String(field.name || ''));
|
|
303
|
+
if (inferredField) {
|
|
304
|
+
if (inferredField.rawType !== undefined) {
|
|
305
|
+
fieldRecord.rawType = inferredField.rawType;
|
|
306
|
+
}
|
|
307
|
+
if (field.type === 'array' || field.type === 'set') {
|
|
308
|
+
if (inferredField.dataType === 'array' || isPostgresPhysicalArrayRawType(inferredField.rawType)) {
|
|
309
|
+
fieldRecord.dataType = 'array';
|
|
310
|
+
if (
|
|
311
|
+
(typeof fieldRecord.elementType !== 'string' || !fieldRecord.elementType.trim()) &&
|
|
312
|
+
typeof inferredField.elementType === 'string'
|
|
313
|
+
) {
|
|
314
|
+
fieldRecord.elementType = inferredField.elementType;
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
// Keep JSONB storage for legacy array fields backed by JSON/JSONB columns in PostgreSQL.
|
|
318
|
+
fieldRecord.dataType = 'json';
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
278
323
|
const identityNames = identityByTable.get(tableName);
|
|
279
324
|
if (identityNames?.size) {
|
|
280
325
|
for (const field of merged.fields || []) {
|