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,1027 @@
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 { CollectionOptions, SequelizeCollectionManager } from '@nocobase/data-source-manager';
11
+ import { cloneDeep } from 'lodash';
12
+ import { ColumnsDescription, QueryTypes, SyncOptions, Transaction } from 'sequelize';
13
+ import { createHash } from 'crypto';
14
+ import { PostgresValidationError } from './utils/validation-error';
15
+
16
+ interface FieldOptions {
17
+ name: string;
18
+ field?: string;
19
+ type?: string;
20
+ dataType?: string;
21
+ allowNull?: boolean;
22
+ defaultValue?: unknown;
23
+ unique?: boolean;
24
+ autoIncrement?: boolean;
25
+ primaryKey?: boolean;
26
+ length?: number | string;
27
+ precision?: number;
28
+ scale?: number;
29
+ elementType?: string;
30
+ [key: string]: unknown;
31
+ }
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
+
74
+ interface UniqueIndex {
75
+ indexName: string;
76
+ constraintName: string | null;
77
+ isValid?: boolean;
78
+ }
79
+
80
+ interface ForeignKeyOptions {
81
+ foreignKey: string;
82
+ targetKey: string;
83
+ target: string;
84
+ onDelete?: string;
85
+ onUpdate?: string;
86
+ defaultOnDelete?: string;
87
+ replaceActions?: boolean;
88
+ }
89
+
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
+
116
+ defineCollection(options: CollectionOptions) {
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);
134
+ }
135
+ return super.defineCollection(normalizedOptions as CollectionOptions);
136
+ }
137
+
138
+ replaceCollections(collections: CollectionOptions[]): void {
139
+ const snapshots: CollectionOptions[] = [];
140
+ const added: string[] = [];
141
+ try {
142
+ for (const collection of collections) {
143
+ const existing = this.getCollection(collection.name);
144
+ if (existing) {
145
+ snapshots.push(
146
+ cloneDeep({
147
+ ...existing.options,
148
+ fields: existing.getFields().map((field) => field.options),
149
+ }),
150
+ );
151
+ this.removeCollection(collection.name);
152
+ } else {
153
+ added.push(collection.name);
154
+ }
155
+ this.defineCollection(collection);
156
+ }
157
+ } catch (error) {
158
+ for (const name of added) {
159
+ if (this.hasCollection(name)) this.removeCollection(name);
160
+ }
161
+ for (const snapshot of snapshots.reverse()) {
162
+ if (this.hasCollection(snapshot.name)) this.removeCollection(snapshot.name);
163
+ try {
164
+ this.defineCollection(snapshot);
165
+ } catch {
166
+ // Preserve the original defineCollection error if restoring the snapshot also fails.
167
+ }
168
+ }
169
+ throw error;
170
+ }
171
+ }
172
+
173
+ private quoteIdentifier(value: string): string {
174
+ return `"${value.replace(/"/g, '""')}"`;
175
+ }
176
+
177
+ private tableInfo(collectionName: string): { schema: string; tableName: string } {
178
+ const collection = this.getCollection(collectionName);
179
+ const modelTable = collection?.model?.getTableName();
180
+ if (typeof modelTable === 'object' && modelTable) {
181
+ return { schema: modelTable.schema || this.db.options.schema || 'public', tableName: modelTable.tableName };
182
+ }
183
+ return {
184
+ schema: this.db.options.schema || 'public',
185
+ tableName: typeof modelTable === 'string' ? modelTable : collectionName,
186
+ };
187
+ }
188
+
189
+ private tableSql(collectionName: string): string {
190
+ const { schema, tableName } = this.tableInfo(collectionName);
191
+ return `${this.quoteIdentifier(schema)}.${this.quoteIdentifier(tableName)}`;
192
+ }
193
+
194
+ private fieldType(collectionName: string, options: FieldOptions): string {
195
+ const collection = this.getCollection(collectionName);
196
+ if (!collection) throw new PostgresValidationError('Collection {{name}} does not exist', { name: collectionName });
197
+ const buildOptions: FieldOptions = applyPostgresArrayDataType({ ...options });
198
+ const field = this.db.buildField(buildOptions, { collection, database: this.db });
199
+ if (field.isRelationField() || !field.dataType) {
200
+ throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
201
+ type: options.type || '',
202
+ });
203
+ }
204
+ const sequelizeField = field.toSequelize() as { type?: { toSql?: () => string; key?: string } };
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') {
209
+ throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
210
+ type: options.type || '',
211
+ });
212
+ }
213
+ const sqlType = normalizedType.toSql();
214
+ if (!sqlType || sqlType.toUpperCase() === 'VIRTUAL') {
215
+ throw new PostgresValidationError('Field type {{type}} does not represent a PostgreSQL column', {
216
+ type: options.type || '',
217
+ });
218
+ }
219
+ return sqlType;
220
+ }
221
+
222
+ private async getColumnDataType(
223
+ schema: string,
224
+ tableName: string,
225
+ columnName: string,
226
+ transaction?: Transaction,
227
+ ): Promise<string | undefined> {
228
+ const columns = await this.db.sequelize.query<{ dataType: string }>(
229
+ `SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) AS "dataType"
230
+ FROM pg_catalog.pg_attribute a
231
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
232
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
233
+ WHERE n.nspname = :schema AND c.relname = :tableName AND a.attname = :columnName
234
+ AND a.attnum > 0 AND NOT a.attisdropped`,
235
+ {
236
+ replacements: { schema, tableName, columnName },
237
+ type: QueryTypes.SELECT,
238
+ transaction,
239
+ },
240
+ );
241
+ return columns[0]?.dataType;
242
+ }
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
+
255
+ private async isColumnNotNull(
256
+ schema: string,
257
+ tableName: string,
258
+ columnName: string,
259
+ transaction?: Transaction,
260
+ ): Promise<boolean> {
261
+ const columns = await this.db.sequelize.query<{ notNull: boolean }>(
262
+ `SELECT a.attnotnull AS "notNull"
263
+ FROM pg_catalog.pg_attribute a
264
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
265
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
266
+ WHERE n.nspname = :schema AND c.relname = :tableName AND a.attname = :columnName
267
+ AND a.attnum > 0 AND NOT a.attisdropped`,
268
+ {
269
+ replacements: { schema, tableName, columnName },
270
+ type: QueryTypes.SELECT,
271
+ transaction,
272
+ },
273
+ );
274
+ return columns[0]?.notNull === true;
275
+ }
276
+
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);
376
+ }
377
+ throw new PostgresValidationError('Unsupported PostgreSQL default value');
378
+ }
379
+
380
+ async createTable(options: Record<string, unknown>, transaction?: Transaction): Promise<boolean> {
381
+ if (!transaction) {
382
+ return this.db.sequelize.transaction((externalTransaction) => this.createTable(options, externalTransaction));
383
+ }
384
+ const name = options.name;
385
+ if (typeof name !== 'string' || !name) {
386
+ throw new PostgresValidationError('Collection name is required');
387
+ }
388
+ const existing = this.getCollection(name);
389
+ const table = existing
390
+ ? this.tableInfo(name)
391
+ : {
392
+ schema: typeof options.schema === 'string' ? options.schema : this.db.options.schema || 'public',
393
+ tableName: typeof options.tableName === 'string' ? options.tableName : name,
394
+ };
395
+ if (await this.getRelationKind(table.schema, table.tableName, transaction)) {
396
+ return false;
397
+ }
398
+ const collection = existing || this.defineCollection({ ...options, name } as CollectionOptions);
399
+ try {
400
+ const syncOptions: SyncOptions & { transaction: Transaction } = { force: false, transaction };
401
+ await collection.model.sync(syncOptions);
402
+ } catch (error) {
403
+ if (!existing && this.getCollection(name) === collection) this.removeCollection(name);
404
+ throw error;
405
+ }
406
+ return true;
407
+ }
408
+
409
+ async dropTable(collectionName: string, cascade = false, transaction?: Transaction): Promise<void> {
410
+ if (!transaction) {
411
+ return this.db.sequelize.transaction((externalTransaction) =>
412
+ this.dropTable(collectionName, cascade, externalTransaction),
413
+ );
414
+ }
415
+ const kind = await this.getTableKind(collectionName, transaction);
416
+ if (!kind) return;
417
+ const object = kind === 'm' ? 'MATERIALIZED VIEW' : kind === 'v' ? 'VIEW' : 'TABLE';
418
+ await this.db.sequelize.query(
419
+ `DROP ${object} IF EXISTS ${this.tableSql(collectionName)} ${cascade ? 'CASCADE' : 'RESTRICT'}`,
420
+ {
421
+ transaction,
422
+ },
423
+ );
424
+ }
425
+
426
+ async getRelationKind(schema: string, tableName: string, transaction?: Transaction): Promise<string | undefined> {
427
+ const rows = await this.db.sequelize.query<{ kind: string }>(
428
+ `SELECT c.relkind AS kind FROM pg_catalog.pg_class c
429
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
430
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind IN ('r', 'p', 'v', 'm')`,
431
+ { replacements: { schema, tableName }, type: QueryTypes.SELECT, transaction },
432
+ );
433
+ return rows[0]?.kind;
434
+ }
435
+
436
+ async getTableKind(collectionName: string, transaction?: Transaction): Promise<string | undefined> {
437
+ const { schema, tableName } = this.tableInfo(collectionName);
438
+ return this.getRelationKind(schema, tableName, transaction);
439
+ }
440
+
441
+ async hasZeroUserColumns(schema: string, tableName: string): Promise<boolean> {
442
+ const rows = await this.db.sequelize.query<{ empty: boolean }>(
443
+ `SELECT NOT EXISTS (
444
+ SELECT 1 FROM pg_catalog.pg_attribute a
445
+ WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
446
+ ) AS empty
447
+ FROM pg_catalog.pg_class c
448
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
449
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind IN ('r', 'p', 'v', 'm')`,
450
+ { replacements: { schema, tableName }, type: QueryTypes.SELECT },
451
+ );
452
+ return rows[0]?.empty === true;
453
+ }
454
+
455
+ async describeMaterializedView(schema: string, tableName: string): Promise<ColumnsDescription | null> {
456
+ const rows = await this.db.sequelize.query<{
457
+ name: string;
458
+ type: string;
459
+ elementType: string | null;
460
+ allowNull: boolean;
461
+ comment: string | null;
462
+ }>(
463
+ `SELECT a.attname AS name,
464
+ CASE
465
+ WHEN t.typcategory = 'A' AND t.typelem <> 0 THEN 'ARRAY'
466
+ ELSE UPPER(pg_catalog.format_type(
467
+ a.atttypid,
468
+ CASE WHEN t.typname IN ('varchar', 'bpchar', 'numeric') THEN a.atttypmod ELSE -1 END
469
+ ))
470
+ END AS type,
471
+ CASE
472
+ WHEN t.typcategory = 'A' AND t.typelem <> 0 THEN pg_catalog.format_type(t.typelem, -1)
473
+ ELSE NULL
474
+ END AS "elementType",
475
+ NOT a.attnotnull AS "allowNull",
476
+ pg_catalog.col_description(c.oid, a.attnum) AS comment
477
+ FROM pg_catalog.pg_attribute a
478
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
479
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
480
+ JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
481
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind = 'm'
482
+ AND a.attnum > 0 AND NOT a.attisdropped
483
+ ORDER BY a.attnum`,
484
+ { replacements: { schema, tableName }, type: QueryTypes.SELECT },
485
+ );
486
+ if (!rows.length) return null;
487
+ const description: ColumnsDescription = {};
488
+ for (const row of rows) {
489
+ const col: ColumnsDescription[string] & { elementType?: string } = {
490
+ type: row.type,
491
+ allowNull: row.allowNull,
492
+ defaultValue: '',
493
+ primaryKey: false,
494
+ autoIncrement: false,
495
+ comment: row.comment,
496
+ };
497
+ if (row.elementType) col.elementType = row.elementType;
498
+ description[row.name] = col;
499
+ }
500
+ return description;
501
+ }
502
+
503
+ async getSingleColumnUniqueIndexes(
504
+ schema: string,
505
+ tableName: string,
506
+ ): Promise<Array<{ column_name: string; is_single_column: boolean }>> {
507
+ return this.db.sequelize.query<{ column_name: string; is_single_column: boolean }>(
508
+ `SELECT a.attname AS column_name, TRUE AS is_single_column
509
+ FROM pg_catalog.pg_index i
510
+ JOIN pg_catalog.pg_class tbl ON tbl.oid = i.indrelid
511
+ JOIN pg_catalog.pg_namespace n ON n.oid = tbl.relnamespace
512
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = tbl.oid AND a.attnum = i.indkey[0]
513
+ WHERE n.nspname = :schema AND tbl.relname = :tableName
514
+ AND i.indisunique AND NOT i.indisprimary AND i.indnkeyatts = 1 AND i.indpred IS NULL
515
+ AND i.indisvalid AND i.indislive AND a.attnum > 0`,
516
+ { replacements: { schema, tableName }, type: QueryTypes.SELECT },
517
+ );
518
+ }
519
+
520
+ async getTableKinds(tableNames: string[], transaction?: Transaction): Promise<Map<string, string>> {
521
+ const result = new Map<string, string>();
522
+ if (!tableNames.length) return result;
523
+ const schema = this.db.options.schema || 'public';
524
+ const rows = await this.db.sequelize.query<{ tableName: string; kind: string }>(
525
+ `SELECT c.relname AS "tableName", c.relkind AS kind
526
+ FROM pg_catalog.pg_class c
527
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
528
+ WHERE n.nspname = :schema AND c.relname IN (:tableNames) AND c.relkind IN ('r', 'p', 'v', 'm')`,
529
+ { replacements: { schema, tableNames }, type: QueryTypes.SELECT, transaction },
530
+ );
531
+ for (const row of rows) {
532
+ result.set(row.tableName, row.kind);
533
+ }
534
+ return result;
535
+ }
536
+
537
+ async discoverTables(): Promise<string[]> {
538
+ const rows = await this.db.sequelize.query<{ name: string }>(
539
+ `SELECT c.relname AS name
540
+ FROM pg_catalog.pg_class c
541
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
542
+ WHERE n.nspname = :schema AND c.relkind IN ('r', 'p', 'v', 'm')
543
+ AND (pg_catalog.has_table_privilege(c.oid, 'SELECT') OR pg_catalog.has_any_column_privilege(c.oid, 'SELECT'))
544
+ ORDER BY c.relname`,
545
+ { replacements: { schema: this.db.options.schema || 'public' }, type: QueryTypes.SELECT },
546
+ );
547
+ return rows.map((row) => row.name);
548
+ }
549
+
550
+ async discoverColumns(collectionName: string, transaction?: Transaction): Promise<Record<string, unknown>[]> {
551
+ const { schema, tableName } = this.tableInfo(collectionName);
552
+ return this.db.sequelize.query<Record<string, unknown>>(
553
+ `SELECT c.column_name, c.data_type, c.is_nullable, c.column_default,
554
+ c.character_maximum_length, c.numeric_precision, c.numeric_scale,
555
+ c.ordinal_position,
556
+ EXISTS (
557
+ SELECT 1 FROM information_schema.table_constraints tc
558
+ JOIN information_schema.key_column_usage ku
559
+ ON ku.constraint_catalog = tc.constraint_catalog
560
+ AND ku.constraint_schema = tc.constraint_schema
561
+ AND ku.constraint_name = tc.constraint_name
562
+ AND ku.table_name = tc.table_name
563
+ WHERE tc.constraint_type = 'PRIMARY KEY'
564
+ AND ku.table_schema = c.table_schema AND ku.table_name = c.table_name
565
+ AND ku.column_name = c.column_name
566
+ ) AS is_primary_key,
567
+ (c.is_identity = 'YES' OR COALESCE(c.column_default LIKE 'nextval(%', false)) AS is_auto_increment
568
+ FROM information_schema.columns c
569
+ WHERE c.table_schema = :schema AND c.table_name = :tableName
570
+ ORDER BY c.ordinal_position`,
571
+ { replacements: { schema, tableName }, type: QueryTypes.SELECT, transaction },
572
+ );
573
+ }
574
+
575
+ async addField(collectionName: string, field: FieldOptions, transaction?: Transaction): Promise<void> {
576
+ if (!transaction) {
577
+ return this.db.sequelize.transaction((externalTransaction) =>
578
+ this.addField(collectionName, field, externalTransaction),
579
+ );
580
+ }
581
+ if (!field.name || !field.type) {
582
+ throw new PostgresValidationError('Field name and type are required');
583
+ }
584
+ const columnName = field.field || field.name;
585
+ const sqlType = this.fieldType(collectionName, field);
586
+ let sql = `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(columnName)} ${sqlType}`;
587
+ if (field.autoIncrement && field.defaultValue !== undefined) {
588
+ throw new PostgresValidationError('A generated field cannot also have a default value');
589
+ }
590
+ if (field.autoIncrement) sql += ' GENERATED BY DEFAULT AS IDENTITY';
591
+ if (field.allowNull === false) sql += ' NOT NULL';
592
+ if (field.defaultValue !== undefined) sql += ` DEFAULT ${this.defaultSql(field.defaultValue, sqlType)}`;
593
+ if (field.primaryKey) sql += ' PRIMARY KEY';
594
+ await this.db.sequelize.query(sql, { transaction });
595
+ if (field.unique && !field.primaryKey) await this.setUnique(collectionName, columnName, true, transaction);
596
+ }
597
+
598
+ async updateField(
599
+ collectionName: string,
600
+ fieldName: string,
601
+ options: Omit<FieldOptions, 'name'>,
602
+ transaction?: Transaction,
603
+ ): Promise<void> {
604
+ if (!transaction) {
605
+ return this.db.sequelize.transaction((externalTransaction) =>
606
+ this.updateField(collectionName, fieldName, options, externalTransaction),
607
+ );
608
+ }
609
+ const table = this.tableSql(collectionName);
610
+ const columnName = this.getCollection(collectionName)?.getField(fieldName)?.columnName() || fieldName;
611
+ const column = this.quoteIdentifier(columnName);
612
+ let alteredType: string | undefined;
613
+ if (['type', 'dataType', 'length', 'precision', 'scale', 'elementType'].some((key) => key in options)) {
614
+ const existing = this.getCollection(collectionName)?.getField(fieldName)?.options || {};
615
+ alteredType = this.fieldType(collectionName, { ...existing, ...options, name: fieldName });
616
+ await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${alteredType}`, {
617
+ transaction,
618
+ });
619
+ }
620
+ if (options.allowNull !== undefined) {
621
+ await this.db.sequelize.query(
622
+ `ALTER TABLE ${table} ALTER COLUMN ${column} ${options.allowNull ? 'DROP' : 'SET'} NOT NULL`,
623
+ {
624
+ transaction,
625
+ },
626
+ );
627
+ }
628
+ if (options.defaultValue !== undefined) {
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
+ }
647
+ await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} ${clause}`, { transaction });
648
+ }
649
+ if (options.unique !== undefined) {
650
+ await this.setUnique(collectionName, columnName, options.unique, transaction);
651
+ }
652
+ }
653
+
654
+ async removeField(
655
+ collectionName: string,
656
+ fieldName: string,
657
+ cascade = false,
658
+ transaction?: Transaction,
659
+ ): Promise<void> {
660
+ const columnName = this.getCollection(collectionName)?.getField(fieldName)?.columnName() || fieldName;
661
+ await this.db.sequelize.query(
662
+ `ALTER TABLE ${this.tableSql(collectionName)} DROP COLUMN ${this.quoteIdentifier(columnName)} ${
663
+ cascade ? 'CASCADE' : 'RESTRICT'
664
+ }`,
665
+ { transaction },
666
+ );
667
+ }
668
+
669
+ async ensureForeignKey(collectionName: string, options: ForeignKeyOptions, transaction?: Transaction): Promise<void> {
670
+ if (!transaction) {
671
+ return this.db.sequelize.transaction((externalTransaction) =>
672
+ this.ensureForeignKey(collectionName, options, externalTransaction),
673
+ );
674
+ }
675
+ const actions: Record<string, string> = {
676
+ 'NO ACTION': 'a',
677
+ RESTRICT: 'r',
678
+ CASCADE: 'c',
679
+ 'SET NULL': 'n',
680
+ 'SET DEFAULT': 'd',
681
+ };
682
+ const actionNames: Record<string, string> = {
683
+ a: 'NO ACTION',
684
+ r: 'RESTRICT',
685
+ c: 'CASCADE',
686
+ n: 'SET NULL',
687
+ d: 'SET DEFAULT',
688
+ };
689
+ const defaultOnDelete = (options.defaultOnDelete || 'SET NULL').toUpperCase();
690
+ let onDelete = (options.onDelete || defaultOnDelete).toUpperCase();
691
+ let onUpdate = (options.onUpdate || 'CASCADE').toUpperCase();
692
+ if (!actions[onDelete] || !actions[onUpdate])
693
+ throw new PostgresValidationError('Invalid PostgreSQL foreign key action');
694
+ const source = this.tableInfo(collectionName);
695
+ const target = this.tableInfo(options.target);
696
+ const sourceColumn =
697
+ this.getCollection(collectionName)?.getField(options.foreignKey)?.columnName() || options.foreignKey;
698
+ const targetColumn =
699
+ this.getCollection(options.target)?.getField(options.targetKey)?.columnName() || options.targetKey;
700
+ const sourceKind = await this.getRelationKind(source.schema, source.tableName, transaction);
701
+ if (!sourceKind) {
702
+ throw new PostgresValidationError('Collection {{name}} does not exist', { name: collectionName });
703
+ }
704
+ if (sourceKind === 'v' || sourceKind === 'm') {
705
+ throw new PostgresValidationError('This collection is read-only');
706
+ }
707
+ const targetKind = await this.getRelationKind(target.schema, target.tableName, transaction);
708
+ if (!targetKind) {
709
+ throw new PostgresValidationError('Collection {{name}} does not exist', { name: options.target });
710
+ }
711
+ if (targetKind === 'v' || targetKind === 'm') {
712
+ throw new PostgresValidationError('This collection is read-only');
713
+ }
714
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
715
+ if (!targetDataType)
716
+ throw new PostgresValidationError('Target column {{collection}}.{{field}} does not exist', {
717
+ collection: options.target,
718
+ field: options.targetKey,
719
+ });
720
+ const sourceColumnType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
721
+ if (!sourceColumnType) {
722
+ await this.db.sequelize.query(
723
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(
724
+ sourceColumn,
725
+ )} ${targetDataType}`,
726
+ { transaction },
727
+ );
728
+ }
729
+ const constraints = await this.db.sequelize.query<{
730
+ constraintName: string;
731
+ targetSchema: string;
732
+ targetTable: string;
733
+ targetColumn: string;
734
+ deleteAction: string;
735
+ updateAction: string;
736
+ columnCount: number;
737
+ }>(
738
+ `SELECT con.conname AS "constraintName",
739
+ tn.nspname AS "targetSchema", t.relname AS "targetTable", ta.attname AS "targetColumn",
740
+ con.confdeltype AS "deleteAction", con.confupdtype AS "updateAction",
741
+ cardinality(con.conkey) AS "columnCount"
742
+ FROM pg_catalog.pg_constraint con
743
+ JOIN pg_catalog.pg_class s ON s.oid = con.conrelid
744
+ JOIN pg_catalog.pg_namespace sn ON sn.oid = s.relnamespace
745
+ JOIN pg_catalog.pg_attribute sa ON sa.attrelid = s.oid AND sa.attnum = ANY(con.conkey)
746
+ JOIN pg_catalog.pg_class t ON t.oid = con.confrelid
747
+ JOIN pg_catalog.pg_namespace tn ON tn.oid = t.relnamespace
748
+ JOIN pg_catalog.pg_attribute ta ON ta.attrelid = t.oid AND ta.attnum = con.confkey[array_position(con.conkey, sa.attnum)]
749
+ WHERE con.contype = 'f' AND sn.nspname = :schema AND s.relname = :tableName AND sa.attname = :columnName`,
750
+ {
751
+ replacements: { schema: source.schema, tableName: source.tableName, columnName: sourceColumn },
752
+ type: QueryTypes.SELECT,
753
+ transaction,
754
+ },
755
+ );
756
+ if (constraints.length) {
757
+ const sameTarget =
758
+ constraints.length === 1 &&
759
+ constraints[0].columnCount === 1 &&
760
+ constraints[0].targetSchema === target.schema &&
761
+ constraints[0].targetTable === target.tableName &&
762
+ constraints[0].targetColumn === targetColumn;
763
+ const actionsMatch =
764
+ (!options.onDelete || constraints[0].deleteAction === actions[onDelete]) &&
765
+ (!options.onUpdate || constraints[0].updateAction === actions[onUpdate]);
766
+ if (sameTarget && actionsMatch) {
767
+ return;
768
+ }
769
+ if (sameTarget && options.replaceActions && constraints[0].constraintName) {
770
+ onDelete = options.onDelete ? onDelete : actionNames[constraints[0].deleteAction] || onDelete;
771
+ onUpdate = options.onUpdate ? onUpdate : actionNames[constraints[0].updateAction] || onUpdate;
772
+ await this.db.sequelize.query(
773
+ `ALTER TABLE ${this.tableSql(collectionName)} DROP CONSTRAINT ${this.quoteIdentifier(
774
+ constraints[0].constraintName,
775
+ )}`,
776
+ { transaction },
777
+ );
778
+ } else {
779
+ throw new PostgresValidationError('Conflicting foreign key exists for {{collection}}.{{field}}', {
780
+ collection: collectionName,
781
+ field: sourceColumn,
782
+ });
783
+ }
784
+ }
785
+ const hash = createHash('sha256')
786
+ .update(
787
+ `${source.schema}\0${source.tableName}\0${sourceColumn}\0${target.schema}\0${target.tableName}\0${targetColumn}`,
788
+ )
789
+ .digest('hex')
790
+ .slice(0, 24);
791
+ await this.db.sequelize.query(
792
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD CONSTRAINT ${this.quoteIdentifier(`fk_${hash}`)}
793
+ FOREIGN KEY (${this.quoteIdentifier(sourceColumn)}) REFERENCES ${this.tableSql(
794
+ options.target,
795
+ )} (${this.quoteIdentifier(targetColumn)})
796
+ ON DELETE ${onDelete} ON UPDATE ${onUpdate}`,
797
+ { transaction },
798
+ );
799
+ }
800
+
801
+ async ensureForeignKeyArray(
802
+ collectionName: string,
803
+ options: { foreignKey: string; targetKey: string; target: string },
804
+ transaction?: Transaction,
805
+ ): Promise<void> {
806
+ if (!transaction) {
807
+ return this.db.sequelize.transaction((externalTransaction) =>
808
+ this.ensureForeignKeyArray(collectionName, options, externalTransaction),
809
+ );
810
+ }
811
+ const source = this.tableInfo(collectionName);
812
+ const target = this.tableInfo(options.target);
813
+ const sourceColumn =
814
+ this.getCollection(collectionName)?.getField(options.foreignKey)?.columnName() || options.foreignKey;
815
+ const targetColumn =
816
+ this.getCollection(options.target)?.getField(options.targetKey)?.columnName() || options.targetKey;
817
+ const sourceKind = await this.getRelationKind(source.schema, source.tableName, transaction);
818
+ if (!sourceKind) {
819
+ throw new PostgresValidationError('Collection {{name}} does not exist', { name: collectionName });
820
+ }
821
+ if (sourceKind === 'v' || sourceKind === 'm') {
822
+ throw new PostgresValidationError('This collection is read-only');
823
+ }
824
+ const targetKind = await this.getRelationKind(target.schema, target.tableName, transaction);
825
+ if (!targetKind) {
826
+ throw new PostgresValidationError('Collection {{name}} does not exist', { name: options.target });
827
+ }
828
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
829
+ if (!targetDataType) {
830
+ throw new PostgresValidationError('Target column {{collection}}.{{field}} does not exist', {
831
+ collection: options.target,
832
+ field: options.targetKey,
833
+ });
834
+ }
835
+ const existingType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
836
+ if (!existingType) {
837
+ await this.db.sequelize.query(
838
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(
839
+ sourceColumn,
840
+ )} ${targetDataType}[]`,
841
+ { transaction },
842
+ );
843
+ return;
844
+ }
845
+ const stripModifiers = (value: string) =>
846
+ value
847
+ .trim()
848
+ .toLowerCase()
849
+ .replace(/\([^)]*\)/g, '');
850
+ const normalizedExisting = stripModifiers(existingType);
851
+ const normalizedExpected = `${stripModifiers(targetDataType)}[]`;
852
+ if (normalizedExisting !== normalizedExpected && normalizedExisting !== 'json' && normalizedExisting !== 'jsonb') {
853
+ throw new PostgresValidationError(
854
+ 'Foreign key {{collection}}.{{field}} has incompatible PostgreSQL type {{type}}',
855
+ {
856
+ collection: collectionName,
857
+ field: sourceColumn,
858
+ type: existingType,
859
+ },
860
+ );
861
+ }
862
+ }
863
+
864
+ async ensureJoinTable(
865
+ collectionName: string,
866
+ options: {
867
+ through: string;
868
+ foreignKey: string;
869
+ otherKey: string;
870
+ sourceKey: string;
871
+ targetKey: string;
872
+ target: string;
873
+ onDelete?: string;
874
+ onUpdate?: string;
875
+ replaceActions?: boolean;
876
+ },
877
+ transaction?: Transaction,
878
+ ): Promise<void> {
879
+ if (!transaction) {
880
+ return this.db.sequelize.transaction((externalTransaction) =>
881
+ this.ensureJoinTable(collectionName, options, externalTransaction),
882
+ );
883
+ }
884
+ const source = this.tableInfo(collectionName);
885
+ const target = this.tableInfo(options.target);
886
+ const through = this.tableInfo(options.through);
887
+ if (
888
+ options.through === collectionName ||
889
+ options.through === options.target ||
890
+ (through.schema === source.schema && through.tableName === source.tableName) ||
891
+ (through.schema === target.schema && through.tableName === target.tableName)
892
+ ) {
893
+ throw new PostgresValidationError('Join table {{name}} cannot match source or target collection', {
894
+ name: options.through,
895
+ });
896
+ }
897
+ if (options.foreignKey === options.otherKey) {
898
+ throw new PostgresValidationError('Many-to-many foreign key and other key must be different');
899
+ }
900
+ const sourceColumn =
901
+ this.getCollection(collectionName)?.getField(options.sourceKey)?.columnName() || options.sourceKey;
902
+ const targetColumn =
903
+ this.getCollection(options.target)?.getField(options.targetKey)?.columnName() || options.targetKey;
904
+ const sourceDataType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
905
+ if (!sourceDataType) {
906
+ throw new PostgresValidationError('Target column {{collection}}.{{field}} does not exist', {
907
+ collection: collectionName,
908
+ field: options.sourceKey,
909
+ });
910
+ }
911
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
912
+ if (!targetDataType) {
913
+ throw new PostgresValidationError('Target column {{collection}}.{{field}} does not exist', {
914
+ collection: options.target,
915
+ field: options.targetKey,
916
+ });
917
+ }
918
+ const throughKind = await this.getRelationKind(through.schema, through.tableName, transaction);
919
+ if (throughKind === 'v' || throughKind === 'm') {
920
+ throw new PostgresValidationError('This collection is read-only');
921
+ }
922
+ const requestedDelete = options.onDelete?.toUpperCase();
923
+ const requestedUpdate = options.onUpdate?.toUpperCase();
924
+ const usesNullOrDefault = (action?: string) => action === 'SET NULL' || action === 'SET DEFAULT';
925
+ if (usesNullOrDefault(requestedDelete) || usesNullOrDefault(requestedUpdate)) {
926
+ if (
927
+ !throughKind ||
928
+ (await this.isColumnNotNull(through.schema, through.tableName, options.foreignKey, transaction)) ||
929
+ (await this.isColumnNotNull(through.schema, through.tableName, options.otherKey, transaction))
930
+ ) {
931
+ throw new PostgresValidationError('Invalid PostgreSQL foreign key action');
932
+ }
933
+ }
934
+ if (!throughKind) {
935
+ const throughSql = `${this.quoteIdentifier(through.schema)}.${this.quoteIdentifier(through.tableName)}`;
936
+ const fkSql = this.quoteIdentifier(options.foreignKey);
937
+ const okSql = this.quoteIdentifier(options.otherKey);
938
+ await this.db.sequelize.query(
939
+ `CREATE TABLE ${throughSql} (${fkSql} ${sourceDataType} NOT NULL, ${okSql} ${targetDataType} NOT NULL, PRIMARY KEY (${fkSql}, ${okSql}))`,
940
+ { transaction },
941
+ );
942
+ const indexHash = createHash('sha256')
943
+ .update(`${through.schema}\0${through.tableName}\0${options.otherKey}`)
944
+ .digest('hex')
945
+ .slice(0, 24);
946
+ await this.db.sequelize.query(
947
+ `CREATE INDEX ${this.quoteIdentifier(`idx_${indexHash}`)} ON ${throughSql} (${okSql})`,
948
+ { transaction },
949
+ );
950
+ }
951
+ await this.ensureForeignKey(
952
+ options.through,
953
+ {
954
+ foreignKey: options.foreignKey,
955
+ targetKey: options.sourceKey,
956
+ target: collectionName,
957
+ onDelete: options.onDelete,
958
+ onUpdate: options.onUpdate,
959
+ defaultOnDelete: 'CASCADE',
960
+ replaceActions: options.replaceActions,
961
+ },
962
+ transaction,
963
+ );
964
+ await this.ensureForeignKey(
965
+ options.through,
966
+ {
967
+ foreignKey: options.otherKey,
968
+ targetKey: options.targetKey,
969
+ target: options.target,
970
+ onDelete: options.onDelete,
971
+ onUpdate: options.onUpdate,
972
+ defaultOnDelete: 'CASCADE',
973
+ replaceActions: options.replaceActions,
974
+ },
975
+ transaction,
976
+ );
977
+ }
978
+
979
+ private async setUnique(
980
+ collectionName: string,
981
+ columnName: string,
982
+ unique: boolean,
983
+ transaction?: Transaction,
984
+ ): Promise<void> {
985
+ const { schema, tableName } = this.tableInfo(collectionName);
986
+ const indexes = await this.db.sequelize.query<UniqueIndex>(
987
+ `SELECT idx.relname AS "indexName", con.conname AS "constraintName", i.indisvalid AS "isValid"
988
+ FROM pg_catalog.pg_index i
989
+ JOIN pg_catalog.pg_class tbl ON tbl.oid = i.indrelid
990
+ JOIN pg_catalog.pg_namespace n ON n.oid = tbl.relnamespace
991
+ JOIN pg_catalog.pg_class idx ON idx.oid = i.indexrelid
992
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = tbl.oid AND a.attnum = i.indkey[0]
993
+ LEFT JOIN pg_catalog.pg_constraint con ON con.conindid = i.indexrelid AND con.contype = 'u'
994
+ WHERE n.nspname = :schema AND tbl.relname = :tableName AND a.attname = :columnName
995
+ AND i.indisunique AND NOT i.indisprimary AND i.indnkeyatts = 1 AND i.indpred IS NULL AND a.attnum > 0`,
996
+ { replacements: { schema, tableName, columnName }, type: QueryTypes.SELECT, transaction },
997
+ );
998
+ const dropEntry = async (index: UniqueIndex) => {
999
+ const sql = index.constraintName
1000
+ ? `ALTER TABLE ${this.tableSql(collectionName)} DROP CONSTRAINT ${this.quoteIdentifier(index.constraintName)}`
1001
+ : `DROP INDEX ${this.quoteIdentifier(schema)}.${this.quoteIdentifier(index.indexName)}`;
1002
+ await this.db.sequelize.query(sql, { transaction });
1003
+ };
1004
+ if (unique) {
1005
+ const validIndexes = indexes.filter((index) => index.isValid !== false);
1006
+ for (const invalidIndex of indexes.filter((index) => index.isValid === false)) {
1007
+ await dropEntry(invalidIndex);
1008
+ }
1009
+ if (validIndexes.length === 0) {
1010
+ const hash = createHash('sha256').update(`${schema}\0${tableName}\0${columnName}`).digest('hex').slice(0, 24);
1011
+ await this.db.sequelize.query(
1012
+ `CREATE UNIQUE INDEX ${this.quoteIdentifier(`idx_unique_${hash}`)} ON ${this.tableSql(
1013
+ collectionName,
1014
+ )} (${this.quoteIdentifier(columnName)})`,
1015
+ { transaction },
1016
+ );
1017
+ }
1018
+ } else {
1019
+ for (const index of indexes) {
1020
+ await dropEntry(index);
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ // Collections are introspected. DDL is performed only by explicit collection/field actions.
1026
+ async sync(): Promise<void> {}
1027
+ }