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,868 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var postgres_collection_manager_exports = {};
28
+ __export(postgres_collection_manager_exports, {
29
+ PostgresCollectionManager: () => PostgresCollectionManager,
30
+ applyPostgresArrayDataType: () => applyPostgresArrayDataType,
31
+ isPostgresPhysicalArrayRawType: () => isPostgresPhysicalArrayRawType
32
+ });
33
+ module.exports = __toCommonJS(postgres_collection_manager_exports);
34
+ var import_data_source_manager = require("@nocobase/data-source-manager");
35
+ var import_lodash = require("lodash");
36
+ var import_sequelize = require("sequelize");
37
+ var import_crypto = require("crypto");
38
+ var import_validation_error = require("./utils/validation-error");
39
+ const POSTGRES_BUILD_FIELD_NORMALIZED = Symbol("postgresBuildFieldNormalized");
40
+ function isPostgresPhysicalArrayRawType(rawType) {
41
+ if (typeof rawType !== "string") return false;
42
+ const trimmed = rawType.trim();
43
+ return trimmed.toUpperCase() === "ARRAY" || trimmed.endsWith("[]");
44
+ }
45
+ function applyPostgresArrayDataType(field) {
46
+ const type = field.type;
47
+ if (type !== "array" && type !== "set") {
48
+ return field;
49
+ }
50
+ const hasRawType = typeof field.rawType === "string" && field.rawType.trim().length > 0;
51
+ if (hasRawType && !isPostgresPhysicalArrayRawType(field.rawType)) {
52
+ if (field.dataType === void 0 || field.dataType === null || field.dataType === "") {
53
+ Object.assign(field, { dataType: "json" });
54
+ }
55
+ return field;
56
+ }
57
+ const elementType = field.elementType;
58
+ if (typeof elementType === "string" && elementType.trim().length > 0 && (field.dataType === void 0 || field.dataType === null || field.dataType === "")) {
59
+ Object.assign(field, { dataType: "array" });
60
+ }
61
+ return field;
62
+ }
63
+ const SAFE_ARRAY_TYPE_RE = /^[a-zA-Z_][a-zA-Z0-9_]*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\s+[a-zA-Z_][a-zA-Z0-9_]*)*(?:\(\d+(?:\s*,\s*\d+)?\))?(?:\[\])+$/;
64
+ const INTEGER_ELEMENT_TYPES = /* @__PURE__ */ new Set(["smallint", "integer", "int", "int2", "int4", "bigint", "int8"]);
65
+ const NUMERIC_ELEMENT_TYPES = /* @__PURE__ */ new Set(["real", "float", "float4", "float8", "double precision", "numeric", "decimal"]);
66
+ const BOOLEAN_ELEMENT_TYPES = /* @__PURE__ */ new Set(["boolean", "bool"]);
67
+ class PostgresCollectionManager extends import_data_source_manager.SequelizeCollectionManager {
68
+ constructor(options) {
69
+ super(options);
70
+ this.installArrayFieldNormalizer();
71
+ }
72
+ installArrayFieldNormalizer() {
73
+ const dbRecord = this.db;
74
+ const originalBuildField = dbRecord == null ? void 0 : dbRecord.buildField;
75
+ if (typeof originalBuildField !== "function" || originalBuildField[POSTGRES_BUILD_FIELD_NORMALIZED]) {
76
+ return;
77
+ }
78
+ const wrappedBuildField = function(fieldOptions, context) {
79
+ if (fieldOptions && typeof fieldOptions === "object") {
80
+ applyPostgresArrayDataType(fieldOptions);
81
+ }
82
+ return originalBuildField.call(this, fieldOptions, context);
83
+ };
84
+ wrappedBuildField[POSTGRES_BUILD_FIELD_NORMALIZED] = true;
85
+ dbRecord.buildField = wrappedBuildField;
86
+ }
87
+ defineCollection(options) {
88
+ const normalizedOptions = Array.isArray(options.fields) ? {
89
+ ...options,
90
+ fields: options.fields.map(
91
+ (field) => field && typeof field === "object" ? applyPostgresArrayDataType({ ...field }) : field
92
+ )
93
+ } : options;
94
+ if (normalizedOptions.tree) {
95
+ const { tree, ...rest } = normalizedOptions;
96
+ return super.defineCollection({
97
+ ...rest,
98
+ postgresTree: tree,
99
+ template: normalizedOptions.template || "tree"
100
+ });
101
+ }
102
+ return super.defineCollection(normalizedOptions);
103
+ }
104
+ replaceCollections(collections) {
105
+ const snapshots = [];
106
+ const added = [];
107
+ try {
108
+ for (const collection of collections) {
109
+ const existing = this.getCollection(collection.name);
110
+ if (existing) {
111
+ snapshots.push(
112
+ (0, import_lodash.cloneDeep)({
113
+ ...existing.options,
114
+ fields: existing.getFields().map((field) => field.options)
115
+ })
116
+ );
117
+ this.removeCollection(collection.name);
118
+ } else {
119
+ added.push(collection.name);
120
+ }
121
+ this.defineCollection(collection);
122
+ }
123
+ } catch (error) {
124
+ for (const name of added) {
125
+ if (this.hasCollection(name)) this.removeCollection(name);
126
+ }
127
+ for (const snapshot of snapshots.reverse()) {
128
+ if (this.hasCollection(snapshot.name)) this.removeCollection(snapshot.name);
129
+ try {
130
+ this.defineCollection(snapshot);
131
+ } catch {
132
+ }
133
+ }
134
+ throw error;
135
+ }
136
+ }
137
+ quoteIdentifier(value) {
138
+ return `"${value.replace(/"/g, '""')}"`;
139
+ }
140
+ tableInfo(collectionName) {
141
+ var _a;
142
+ const collection = this.getCollection(collectionName);
143
+ const modelTable = (_a = collection == null ? void 0 : collection.model) == null ? void 0 : _a.getTableName();
144
+ if (typeof modelTable === "object" && modelTable) {
145
+ return { schema: modelTable.schema || this.db.options.schema || "public", tableName: modelTable.tableName };
146
+ }
147
+ return {
148
+ schema: this.db.options.schema || "public",
149
+ tableName: typeof modelTable === "string" ? modelTable : collectionName
150
+ };
151
+ }
152
+ tableSql(collectionName) {
153
+ const { schema, tableName } = this.tableInfo(collectionName);
154
+ return `${this.quoteIdentifier(schema)}.${this.quoteIdentifier(tableName)}`;
155
+ }
156
+ fieldType(collectionName, options) {
157
+ var _a, _b;
158
+ const collection = this.getCollection(collectionName);
159
+ if (!collection) throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: collectionName });
160
+ const buildOptions = applyPostgresArrayDataType({ ...options });
161
+ const field = this.db.buildField(buildOptions, { collection, database: this.db });
162
+ if (field.isRelationField() || !field.dataType) {
163
+ throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
164
+ type: options.type || ""
165
+ });
166
+ }
167
+ const sequelizeField = field.toSequelize();
168
+ const normalizedType = ((_b = (_a = this.db.sequelize).normalizeDataType) == null ? void 0 : _b.call(_a, sequelizeField.type)) ?? sequelizeField.type;
169
+ if (!normalizedType || normalizedType.key === "VIRTUAL" || typeof normalizedType.toSql !== "function") {
170
+ throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
171
+ type: options.type || ""
172
+ });
173
+ }
174
+ const sqlType = normalizedType.toSql();
175
+ if (!sqlType || sqlType.toUpperCase() === "VIRTUAL") {
176
+ throw new import_validation_error.PostgresValidationError("Field type {{type}} does not represent a PostgreSQL column", {
177
+ type: options.type || ""
178
+ });
179
+ }
180
+ return sqlType;
181
+ }
182
+ async getColumnDataType(schema, tableName, columnName, transaction) {
183
+ var _a;
184
+ const columns = await this.db.sequelize.query(
185
+ `SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) AS "dataType"
186
+ FROM pg_catalog.pg_attribute a
187
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
188
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
189
+ WHERE n.nspname = :schema AND c.relname = :tableName AND a.attname = :columnName
190
+ AND a.attnum > 0 AND NOT a.attisdropped`,
191
+ {
192
+ replacements: { schema, tableName, columnName },
193
+ type: import_sequelize.QueryTypes.SELECT,
194
+ transaction
195
+ }
196
+ );
197
+ return (_a = columns[0]) == null ? void 0 : _a.dataType;
198
+ }
199
+ async isPhysicalArrayColumn(collectionName, columnName, transaction) {
200
+ const { schema, tableName } = this.tableInfo(collectionName);
201
+ const columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
202
+ if (columnType === void 0) return void 0;
203
+ return isPostgresPhysicalArrayRawType(columnType);
204
+ }
205
+ async isColumnNotNull(schema, tableName, columnName, transaction) {
206
+ var _a;
207
+ const columns = await this.db.sequelize.query(
208
+ `SELECT a.attnotnull AS "notNull"
209
+ FROM pg_catalog.pg_attribute a
210
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
211
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
212
+ WHERE n.nspname = :schema AND c.relname = :tableName AND a.attname = :columnName
213
+ AND a.attnum > 0 AND NOT a.attisdropped`,
214
+ {
215
+ replacements: { schema, tableName, columnName },
216
+ type: import_sequelize.QueryTypes.SELECT,
217
+ transaction
218
+ }
219
+ );
220
+ return ((_a = columns[0]) == null ? void 0 : _a.notNull) === true;
221
+ }
222
+ formatArrayDefaultElement(element, elementType) {
223
+ if (element === null) return "NULL";
224
+ if (element === void 0 || typeof element === "function" || typeof element === "symbol") {
225
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
226
+ }
227
+ if (elementType.endsWith("[]")) {
228
+ if (!Array.isArray(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
229
+ if (!element.length) return `ARRAY[]::${elementType}`;
230
+ const innerType = elementType.slice(0, -2);
231
+ return `ARRAY[${element.map((item) => this.formatArrayDefaultElement(item, innerType)).join(", ")}]`;
232
+ }
233
+ const baseType = elementType.replace(/\([^)]*\)/g, "").trim().toLowerCase();
234
+ if (baseType === "json" || baseType === "jsonb") {
235
+ const encoded = JSON.stringify(element);
236
+ if (encoded === void 0) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
237
+ return `${this.db.sequelize.escape(encoded)}::${baseType}`;
238
+ }
239
+ if (INTEGER_ELEMENT_TYPES.has(baseType)) {
240
+ if (typeof element === "bigint") return String(element);
241
+ if (typeof element === "number") {
242
+ if (!Number.isSafeInteger(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
243
+ return String(element);
244
+ }
245
+ if (typeof element === "string" && /^[+-]?\d+$/.test(element.trim())) return element.trim();
246
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
247
+ }
248
+ if (NUMERIC_ELEMENT_TYPES.has(baseType)) {
249
+ if (typeof element === "bigint") return String(element);
250
+ if (typeof element === "number") {
251
+ if (!Number.isFinite(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
252
+ return String(element);
253
+ }
254
+ if (typeof element === "string" && /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(element.trim())) {
255
+ return element.trim();
256
+ }
257
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
258
+ }
259
+ if (BOOLEAN_ELEMENT_TYPES.has(baseType)) {
260
+ if (typeof element === "boolean") return element ? "TRUE" : "FALSE";
261
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
262
+ }
263
+ if (typeof element === "boolean") return element ? "TRUE" : "FALSE";
264
+ if (typeof element === "bigint") return String(element);
265
+ if (typeof element === "number") {
266
+ if (!Number.isFinite(element)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
267
+ return this.db.sequelize.escape(element);
268
+ }
269
+ if (typeof element === "string" || element instanceof Date) {
270
+ return this.db.sequelize.escape(element);
271
+ }
272
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
273
+ }
274
+ defaultSql(value, columnType) {
275
+ if (value === null) return "NULL";
276
+ const rawType = (columnType || "").trim();
277
+ const lowerType = rawType.toLowerCase();
278
+ if (lowerType.endsWith("[]")) {
279
+ if (!SAFE_ARRAY_TYPE_RE.test(rawType)) {
280
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
281
+ }
282
+ if (Array.isArray(value)) {
283
+ if (!value.length) return `ARRAY[]::${rawType}`;
284
+ const innerType = rawType.slice(0, -2);
285
+ return `ARRAY[${value.map((item) => this.formatArrayDefaultElement(item, innerType)).join(", ")}]::${rawType}`;
286
+ }
287
+ if (typeof value === "string") {
288
+ return `${this.db.sequelize.escape(value)}::${rawType}`;
289
+ }
290
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
291
+ }
292
+ if (lowerType === "json" || lowerType === "jsonb") {
293
+ if (typeof value === "string") return this.db.sequelize.escape(value);
294
+ if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value instanceof Date || typeof value === "object" && value !== null) {
295
+ const encoded = JSON.stringify(value);
296
+ if (encoded === void 0) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
297
+ return this.db.sequelize.escape(encoded);
298
+ }
299
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
300
+ }
301
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
302
+ if (typeof value === "bigint") return String(value);
303
+ if (typeof value === "number") {
304
+ if (!Number.isFinite(value)) throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
305
+ return this.db.sequelize.escape(value);
306
+ }
307
+ if (typeof value === "string" || value instanceof Date) {
308
+ return this.db.sequelize.escape(value);
309
+ }
310
+ throw new import_validation_error.PostgresValidationError("Unsupported PostgreSQL default value");
311
+ }
312
+ async createTable(options, transaction) {
313
+ if (!transaction) {
314
+ return this.db.sequelize.transaction((externalTransaction) => this.createTable(options, externalTransaction));
315
+ }
316
+ const name = options.name;
317
+ if (typeof name !== "string" || !name) {
318
+ throw new import_validation_error.PostgresValidationError("Collection name is required");
319
+ }
320
+ const existing = this.getCollection(name);
321
+ const table = existing ? this.tableInfo(name) : {
322
+ schema: typeof options.schema === "string" ? options.schema : this.db.options.schema || "public",
323
+ tableName: typeof options.tableName === "string" ? options.tableName : name
324
+ };
325
+ if (await this.getRelationKind(table.schema, table.tableName, transaction)) {
326
+ return false;
327
+ }
328
+ const collection = existing || this.defineCollection({ ...options, name });
329
+ try {
330
+ const syncOptions = { force: false, transaction };
331
+ await collection.model.sync(syncOptions);
332
+ } catch (error) {
333
+ if (!existing && this.getCollection(name) === collection) this.removeCollection(name);
334
+ throw error;
335
+ }
336
+ return true;
337
+ }
338
+ async dropTable(collectionName, cascade = false, transaction) {
339
+ if (!transaction) {
340
+ return this.db.sequelize.transaction(
341
+ (externalTransaction) => this.dropTable(collectionName, cascade, externalTransaction)
342
+ );
343
+ }
344
+ const kind = await this.getTableKind(collectionName, transaction);
345
+ if (!kind) return;
346
+ const object = kind === "m" ? "MATERIALIZED VIEW" : kind === "v" ? "VIEW" : "TABLE";
347
+ await this.db.sequelize.query(
348
+ `DROP ${object} IF EXISTS ${this.tableSql(collectionName)} ${cascade ? "CASCADE" : "RESTRICT"}`,
349
+ {
350
+ transaction
351
+ }
352
+ );
353
+ }
354
+ async getRelationKind(schema, tableName, transaction) {
355
+ var _a;
356
+ const rows = await this.db.sequelize.query(
357
+ `SELECT c.relkind AS kind FROM pg_catalog.pg_class c
358
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
359
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind IN ('r', 'p', 'v', 'm')`,
360
+ { replacements: { schema, tableName }, type: import_sequelize.QueryTypes.SELECT, transaction }
361
+ );
362
+ return (_a = rows[0]) == null ? void 0 : _a.kind;
363
+ }
364
+ async getTableKind(collectionName, transaction) {
365
+ const { schema, tableName } = this.tableInfo(collectionName);
366
+ return this.getRelationKind(schema, tableName, transaction);
367
+ }
368
+ async hasZeroUserColumns(schema, tableName) {
369
+ var _a;
370
+ const rows = await this.db.sequelize.query(
371
+ `SELECT NOT EXISTS (
372
+ SELECT 1 FROM pg_catalog.pg_attribute a
373
+ WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
374
+ ) AS empty
375
+ FROM pg_catalog.pg_class c
376
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
377
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind IN ('r', 'p', 'v', 'm')`,
378
+ { replacements: { schema, tableName }, type: import_sequelize.QueryTypes.SELECT }
379
+ );
380
+ return ((_a = rows[0]) == null ? void 0 : _a.empty) === true;
381
+ }
382
+ async describeMaterializedView(schema, tableName) {
383
+ const rows = await this.db.sequelize.query(
384
+ `SELECT a.attname AS name,
385
+ CASE
386
+ WHEN t.typcategory = 'A' AND t.typelem <> 0 THEN 'ARRAY'
387
+ ELSE UPPER(pg_catalog.format_type(
388
+ a.atttypid,
389
+ CASE WHEN t.typname IN ('varchar', 'bpchar', 'numeric') THEN a.atttypmod ELSE -1 END
390
+ ))
391
+ END AS type,
392
+ CASE
393
+ WHEN t.typcategory = 'A' AND t.typelem <> 0 THEN pg_catalog.format_type(t.typelem, -1)
394
+ ELSE NULL
395
+ END AS "elementType",
396
+ NOT a.attnotnull AS "allowNull",
397
+ pg_catalog.col_description(c.oid, a.attnum) AS comment
398
+ FROM pg_catalog.pg_attribute a
399
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
400
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
401
+ JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
402
+ WHERE n.nspname = :schema AND c.relname = :tableName AND c.relkind = 'm'
403
+ AND a.attnum > 0 AND NOT a.attisdropped
404
+ ORDER BY a.attnum`,
405
+ { replacements: { schema, tableName }, type: import_sequelize.QueryTypes.SELECT }
406
+ );
407
+ if (!rows.length) return null;
408
+ const description = {};
409
+ for (const row of rows) {
410
+ const col = {
411
+ type: row.type,
412
+ allowNull: row.allowNull,
413
+ defaultValue: "",
414
+ primaryKey: false,
415
+ autoIncrement: false,
416
+ comment: row.comment
417
+ };
418
+ if (row.elementType) col.elementType = row.elementType;
419
+ description[row.name] = col;
420
+ }
421
+ return description;
422
+ }
423
+ async getSingleColumnUniqueIndexes(schema, tableName) {
424
+ return this.db.sequelize.query(
425
+ `SELECT a.attname AS column_name, TRUE AS is_single_column
426
+ FROM pg_catalog.pg_index i
427
+ JOIN pg_catalog.pg_class tbl ON tbl.oid = i.indrelid
428
+ JOIN pg_catalog.pg_namespace n ON n.oid = tbl.relnamespace
429
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = tbl.oid AND a.attnum = i.indkey[0]
430
+ WHERE n.nspname = :schema AND tbl.relname = :tableName
431
+ AND i.indisunique AND NOT i.indisprimary AND i.indnkeyatts = 1 AND i.indpred IS NULL
432
+ AND i.indisvalid AND i.indislive AND a.attnum > 0`,
433
+ { replacements: { schema, tableName }, type: import_sequelize.QueryTypes.SELECT }
434
+ );
435
+ }
436
+ async getTableKinds(tableNames, transaction) {
437
+ const result = /* @__PURE__ */ new Map();
438
+ if (!tableNames.length) return result;
439
+ const schema = this.db.options.schema || "public";
440
+ const rows = await this.db.sequelize.query(
441
+ `SELECT c.relname AS "tableName", c.relkind AS kind
442
+ FROM pg_catalog.pg_class c
443
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
444
+ WHERE n.nspname = :schema AND c.relname IN (:tableNames) AND c.relkind IN ('r', 'p', 'v', 'm')`,
445
+ { replacements: { schema, tableNames }, type: import_sequelize.QueryTypes.SELECT, transaction }
446
+ );
447
+ for (const row of rows) {
448
+ result.set(row.tableName, row.kind);
449
+ }
450
+ return result;
451
+ }
452
+ async discoverTables() {
453
+ const rows = await this.db.sequelize.query(
454
+ `SELECT c.relname AS name
455
+ FROM pg_catalog.pg_class c
456
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
457
+ WHERE n.nspname = :schema AND c.relkind IN ('r', 'p', 'v', 'm')
458
+ AND (pg_catalog.has_table_privilege(c.oid, 'SELECT') OR pg_catalog.has_any_column_privilege(c.oid, 'SELECT'))
459
+ ORDER BY c.relname`,
460
+ { replacements: { schema: this.db.options.schema || "public" }, type: import_sequelize.QueryTypes.SELECT }
461
+ );
462
+ return rows.map((row) => row.name);
463
+ }
464
+ async discoverColumns(collectionName, transaction) {
465
+ const { schema, tableName } = this.tableInfo(collectionName);
466
+ return this.db.sequelize.query(
467
+ `SELECT c.column_name, c.data_type, c.is_nullable, c.column_default,
468
+ c.character_maximum_length, c.numeric_precision, c.numeric_scale,
469
+ c.ordinal_position,
470
+ EXISTS (
471
+ SELECT 1 FROM information_schema.table_constraints tc
472
+ JOIN information_schema.key_column_usage ku
473
+ ON ku.constraint_catalog = tc.constraint_catalog
474
+ AND ku.constraint_schema = tc.constraint_schema
475
+ AND ku.constraint_name = tc.constraint_name
476
+ AND ku.table_name = tc.table_name
477
+ WHERE tc.constraint_type = 'PRIMARY KEY'
478
+ AND ku.table_schema = c.table_schema AND ku.table_name = c.table_name
479
+ AND ku.column_name = c.column_name
480
+ ) AS is_primary_key,
481
+ (c.is_identity = 'YES' OR COALESCE(c.column_default LIKE 'nextval(%', false)) AS is_auto_increment
482
+ FROM information_schema.columns c
483
+ WHERE c.table_schema = :schema AND c.table_name = :tableName
484
+ ORDER BY c.ordinal_position`,
485
+ { replacements: { schema, tableName }, type: import_sequelize.QueryTypes.SELECT, transaction }
486
+ );
487
+ }
488
+ async addField(collectionName, field, transaction) {
489
+ if (!transaction) {
490
+ return this.db.sequelize.transaction(
491
+ (externalTransaction) => this.addField(collectionName, field, externalTransaction)
492
+ );
493
+ }
494
+ if (!field.name || !field.type) {
495
+ throw new import_validation_error.PostgresValidationError("Field name and type are required");
496
+ }
497
+ const columnName = field.field || field.name;
498
+ const sqlType = this.fieldType(collectionName, field);
499
+ let sql = `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(columnName)} ${sqlType}`;
500
+ if (field.autoIncrement && field.defaultValue !== void 0) {
501
+ throw new import_validation_error.PostgresValidationError("A generated field cannot also have a default value");
502
+ }
503
+ if (field.autoIncrement) sql += " GENERATED BY DEFAULT AS IDENTITY";
504
+ if (field.allowNull === false) sql += " NOT NULL";
505
+ if (field.defaultValue !== void 0) sql += ` DEFAULT ${this.defaultSql(field.defaultValue, sqlType)}`;
506
+ if (field.primaryKey) sql += " PRIMARY KEY";
507
+ await this.db.sequelize.query(sql, { transaction });
508
+ if (field.unique && !field.primaryKey) await this.setUnique(collectionName, columnName, true, transaction);
509
+ }
510
+ async updateField(collectionName, fieldName, options, transaction) {
511
+ var _a, _b, _c, _d, _e, _f;
512
+ if (!transaction) {
513
+ return this.db.sequelize.transaction(
514
+ (externalTransaction) => this.updateField(collectionName, fieldName, options, externalTransaction)
515
+ );
516
+ }
517
+ const table = this.tableSql(collectionName);
518
+ const columnName = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(fieldName)) == null ? void 0 : _b.columnName()) || fieldName;
519
+ const column = this.quoteIdentifier(columnName);
520
+ let alteredType;
521
+ if (["type", "dataType", "length", "precision", "scale", "elementType"].some((key) => key in options)) {
522
+ const existing = ((_d = (_c = this.getCollection(collectionName)) == null ? void 0 : _c.getField(fieldName)) == null ? void 0 : _d.options) || {};
523
+ alteredType = this.fieldType(collectionName, { ...existing, ...options, name: fieldName });
524
+ await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} TYPE ${alteredType}`, {
525
+ transaction
526
+ });
527
+ }
528
+ if (options.allowNull !== void 0) {
529
+ await this.db.sequelize.query(
530
+ `ALTER TABLE ${table} ALTER COLUMN ${column} ${options.allowNull ? "DROP" : "SET"} NOT NULL`,
531
+ {
532
+ transaction
533
+ }
534
+ );
535
+ }
536
+ if (options.defaultValue !== void 0) {
537
+ let clause;
538
+ if (options.defaultValue === null) {
539
+ clause = "DROP DEFAULT";
540
+ } else {
541
+ let columnType = alteredType;
542
+ if (!columnType) {
543
+ const { schema, tableName } = this.tableInfo(collectionName);
544
+ columnType = await this.getColumnDataType(schema, tableName, columnName, transaction);
545
+ if (!columnType) {
546
+ const existing = ((_f = (_e = this.getCollection(collectionName)) == null ? void 0 : _e.getField(fieldName)) == null ? void 0 : _f.options) || {};
547
+ const merged = { ...existing, ...options, name: fieldName };
548
+ if (merged.type) {
549
+ columnType = this.fieldType(collectionName, merged);
550
+ }
551
+ }
552
+ }
553
+ clause = `SET DEFAULT ${this.defaultSql(options.defaultValue, columnType)}`;
554
+ }
555
+ await this.db.sequelize.query(`ALTER TABLE ${table} ALTER COLUMN ${column} ${clause}`, { transaction });
556
+ }
557
+ if (options.unique !== void 0) {
558
+ await this.setUnique(collectionName, columnName, options.unique, transaction);
559
+ }
560
+ }
561
+ async removeField(collectionName, fieldName, cascade = false, transaction) {
562
+ var _a, _b;
563
+ const columnName = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(fieldName)) == null ? void 0 : _b.columnName()) || fieldName;
564
+ await this.db.sequelize.query(
565
+ `ALTER TABLE ${this.tableSql(collectionName)} DROP COLUMN ${this.quoteIdentifier(columnName)} ${cascade ? "CASCADE" : "RESTRICT"}`,
566
+ { transaction }
567
+ );
568
+ }
569
+ async ensureForeignKey(collectionName, options, transaction) {
570
+ var _a, _b, _c, _d;
571
+ if (!transaction) {
572
+ return this.db.sequelize.transaction(
573
+ (externalTransaction) => this.ensureForeignKey(collectionName, options, externalTransaction)
574
+ );
575
+ }
576
+ const actions = {
577
+ "NO ACTION": "a",
578
+ RESTRICT: "r",
579
+ CASCADE: "c",
580
+ "SET NULL": "n",
581
+ "SET DEFAULT": "d"
582
+ };
583
+ const actionNames = {
584
+ a: "NO ACTION",
585
+ r: "RESTRICT",
586
+ c: "CASCADE",
587
+ n: "SET NULL",
588
+ d: "SET DEFAULT"
589
+ };
590
+ const defaultOnDelete = (options.defaultOnDelete || "SET NULL").toUpperCase();
591
+ let onDelete = (options.onDelete || defaultOnDelete).toUpperCase();
592
+ let onUpdate = (options.onUpdate || "CASCADE").toUpperCase();
593
+ if (!actions[onDelete] || !actions[onUpdate])
594
+ throw new import_validation_error.PostgresValidationError("Invalid PostgreSQL foreign key action");
595
+ const source = this.tableInfo(collectionName);
596
+ const target = this.tableInfo(options.target);
597
+ const sourceColumn = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(options.foreignKey)) == null ? void 0 : _b.columnName()) || options.foreignKey;
598
+ const targetColumn = ((_d = (_c = this.getCollection(options.target)) == null ? void 0 : _c.getField(options.targetKey)) == null ? void 0 : _d.columnName()) || options.targetKey;
599
+ const sourceKind = await this.getRelationKind(source.schema, source.tableName, transaction);
600
+ if (!sourceKind) {
601
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: collectionName });
602
+ }
603
+ if (sourceKind === "v" || sourceKind === "m") {
604
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
605
+ }
606
+ const targetKind = await this.getRelationKind(target.schema, target.tableName, transaction);
607
+ if (!targetKind) {
608
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: options.target });
609
+ }
610
+ if (targetKind === "v" || targetKind === "m") {
611
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
612
+ }
613
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
614
+ if (!targetDataType)
615
+ throw new import_validation_error.PostgresValidationError("Target column {{collection}}.{{field}} does not exist", {
616
+ collection: options.target,
617
+ field: options.targetKey
618
+ });
619
+ const sourceColumnType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
620
+ if (!sourceColumnType) {
621
+ await this.db.sequelize.query(
622
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(
623
+ sourceColumn
624
+ )} ${targetDataType}`,
625
+ { transaction }
626
+ );
627
+ }
628
+ const constraints = await this.db.sequelize.query(
629
+ `SELECT con.conname AS "constraintName",
630
+ tn.nspname AS "targetSchema", t.relname AS "targetTable", ta.attname AS "targetColumn",
631
+ con.confdeltype AS "deleteAction", con.confupdtype AS "updateAction",
632
+ cardinality(con.conkey) AS "columnCount"
633
+ FROM pg_catalog.pg_constraint con
634
+ JOIN pg_catalog.pg_class s ON s.oid = con.conrelid
635
+ JOIN pg_catalog.pg_namespace sn ON sn.oid = s.relnamespace
636
+ JOIN pg_catalog.pg_attribute sa ON sa.attrelid = s.oid AND sa.attnum = ANY(con.conkey)
637
+ JOIN pg_catalog.pg_class t ON t.oid = con.confrelid
638
+ JOIN pg_catalog.pg_namespace tn ON tn.oid = t.relnamespace
639
+ JOIN pg_catalog.pg_attribute ta ON ta.attrelid = t.oid AND ta.attnum = con.confkey[array_position(con.conkey, sa.attnum)]
640
+ WHERE con.contype = 'f' AND sn.nspname = :schema AND s.relname = :tableName AND sa.attname = :columnName`,
641
+ {
642
+ replacements: { schema: source.schema, tableName: source.tableName, columnName: sourceColumn },
643
+ type: import_sequelize.QueryTypes.SELECT,
644
+ transaction
645
+ }
646
+ );
647
+ if (constraints.length) {
648
+ const sameTarget = constraints.length === 1 && constraints[0].columnCount === 1 && constraints[0].targetSchema === target.schema && constraints[0].targetTable === target.tableName && constraints[0].targetColumn === targetColumn;
649
+ const actionsMatch = (!options.onDelete || constraints[0].deleteAction === actions[onDelete]) && (!options.onUpdate || constraints[0].updateAction === actions[onUpdate]);
650
+ if (sameTarget && actionsMatch) {
651
+ return;
652
+ }
653
+ if (sameTarget && options.replaceActions && constraints[0].constraintName) {
654
+ onDelete = options.onDelete ? onDelete : actionNames[constraints[0].deleteAction] || onDelete;
655
+ onUpdate = options.onUpdate ? onUpdate : actionNames[constraints[0].updateAction] || onUpdate;
656
+ await this.db.sequelize.query(
657
+ `ALTER TABLE ${this.tableSql(collectionName)} DROP CONSTRAINT ${this.quoteIdentifier(
658
+ constraints[0].constraintName
659
+ )}`,
660
+ { transaction }
661
+ );
662
+ } else {
663
+ throw new import_validation_error.PostgresValidationError("Conflicting foreign key exists for {{collection}}.{{field}}", {
664
+ collection: collectionName,
665
+ field: sourceColumn
666
+ });
667
+ }
668
+ }
669
+ const hash = (0, import_crypto.createHash)("sha256").update(
670
+ `${source.schema}\0${source.tableName}\0${sourceColumn}\0${target.schema}\0${target.tableName}\0${targetColumn}`
671
+ ).digest("hex").slice(0, 24);
672
+ await this.db.sequelize.query(
673
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD CONSTRAINT ${this.quoteIdentifier(`fk_${hash}`)}
674
+ FOREIGN KEY (${this.quoteIdentifier(sourceColumn)}) REFERENCES ${this.tableSql(
675
+ options.target
676
+ )} (${this.quoteIdentifier(targetColumn)})
677
+ ON DELETE ${onDelete} ON UPDATE ${onUpdate}`,
678
+ { transaction }
679
+ );
680
+ }
681
+ async ensureForeignKeyArray(collectionName, options, transaction) {
682
+ var _a, _b, _c, _d;
683
+ if (!transaction) {
684
+ return this.db.sequelize.transaction(
685
+ (externalTransaction) => this.ensureForeignKeyArray(collectionName, options, externalTransaction)
686
+ );
687
+ }
688
+ const source = this.tableInfo(collectionName);
689
+ const target = this.tableInfo(options.target);
690
+ const sourceColumn = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(options.foreignKey)) == null ? void 0 : _b.columnName()) || options.foreignKey;
691
+ const targetColumn = ((_d = (_c = this.getCollection(options.target)) == null ? void 0 : _c.getField(options.targetKey)) == null ? void 0 : _d.columnName()) || options.targetKey;
692
+ const sourceKind = await this.getRelationKind(source.schema, source.tableName, transaction);
693
+ if (!sourceKind) {
694
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: collectionName });
695
+ }
696
+ if (sourceKind === "v" || sourceKind === "m") {
697
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
698
+ }
699
+ const targetKind = await this.getRelationKind(target.schema, target.tableName, transaction);
700
+ if (!targetKind) {
701
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: options.target });
702
+ }
703
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
704
+ if (!targetDataType) {
705
+ throw new import_validation_error.PostgresValidationError("Target column {{collection}}.{{field}} does not exist", {
706
+ collection: options.target,
707
+ field: options.targetKey
708
+ });
709
+ }
710
+ const existingType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
711
+ if (!existingType) {
712
+ await this.db.sequelize.query(
713
+ `ALTER TABLE ${this.tableSql(collectionName)} ADD COLUMN ${this.quoteIdentifier(
714
+ sourceColumn
715
+ )} ${targetDataType}[]`,
716
+ { transaction }
717
+ );
718
+ return;
719
+ }
720
+ const stripModifiers = (value) => value.trim().toLowerCase().replace(/\([^)]*\)/g, "");
721
+ const normalizedExisting = stripModifiers(existingType);
722
+ const normalizedExpected = `${stripModifiers(targetDataType)}[]`;
723
+ if (normalizedExisting !== normalizedExpected && normalizedExisting !== "json" && normalizedExisting !== "jsonb") {
724
+ throw new import_validation_error.PostgresValidationError(
725
+ "Foreign key {{collection}}.{{field}} has incompatible PostgreSQL type {{type}}",
726
+ {
727
+ collection: collectionName,
728
+ field: sourceColumn,
729
+ type: existingType
730
+ }
731
+ );
732
+ }
733
+ }
734
+ async ensureJoinTable(collectionName, options, transaction) {
735
+ var _a, _b, _c, _d, _e, _f;
736
+ if (!transaction) {
737
+ return this.db.sequelize.transaction(
738
+ (externalTransaction) => this.ensureJoinTable(collectionName, options, externalTransaction)
739
+ );
740
+ }
741
+ const source = this.tableInfo(collectionName);
742
+ const target = this.tableInfo(options.target);
743
+ const through = this.tableInfo(options.through);
744
+ if (options.through === collectionName || options.through === options.target || through.schema === source.schema && through.tableName === source.tableName || through.schema === target.schema && through.tableName === target.tableName) {
745
+ throw new import_validation_error.PostgresValidationError("Join table {{name}} cannot match source or target collection", {
746
+ name: options.through
747
+ });
748
+ }
749
+ if (options.foreignKey === options.otherKey) {
750
+ throw new import_validation_error.PostgresValidationError("Many-to-many foreign key and other key must be different");
751
+ }
752
+ const sourceColumn = ((_b = (_a = this.getCollection(collectionName)) == null ? void 0 : _a.getField(options.sourceKey)) == null ? void 0 : _b.columnName()) || options.sourceKey;
753
+ const targetColumn = ((_d = (_c = this.getCollection(options.target)) == null ? void 0 : _c.getField(options.targetKey)) == null ? void 0 : _d.columnName()) || options.targetKey;
754
+ const sourceDataType = await this.getColumnDataType(source.schema, source.tableName, sourceColumn, transaction);
755
+ if (!sourceDataType) {
756
+ throw new import_validation_error.PostgresValidationError("Target column {{collection}}.{{field}} does not exist", {
757
+ collection: collectionName,
758
+ field: options.sourceKey
759
+ });
760
+ }
761
+ const targetDataType = await this.getColumnDataType(target.schema, target.tableName, targetColumn, transaction);
762
+ if (!targetDataType) {
763
+ throw new import_validation_error.PostgresValidationError("Target column {{collection}}.{{field}} does not exist", {
764
+ collection: options.target,
765
+ field: options.targetKey
766
+ });
767
+ }
768
+ const throughKind = await this.getRelationKind(through.schema, through.tableName, transaction);
769
+ if (throughKind === "v" || throughKind === "m") {
770
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
771
+ }
772
+ const requestedDelete = (_e = options.onDelete) == null ? void 0 : _e.toUpperCase();
773
+ const requestedUpdate = (_f = options.onUpdate) == null ? void 0 : _f.toUpperCase();
774
+ const usesNullOrDefault = (action) => action === "SET NULL" || action === "SET DEFAULT";
775
+ if (usesNullOrDefault(requestedDelete) || usesNullOrDefault(requestedUpdate)) {
776
+ if (!throughKind || await this.isColumnNotNull(through.schema, through.tableName, options.foreignKey, transaction) || await this.isColumnNotNull(through.schema, through.tableName, options.otherKey, transaction)) {
777
+ throw new import_validation_error.PostgresValidationError("Invalid PostgreSQL foreign key action");
778
+ }
779
+ }
780
+ if (!throughKind) {
781
+ const throughSql = `${this.quoteIdentifier(through.schema)}.${this.quoteIdentifier(through.tableName)}`;
782
+ const fkSql = this.quoteIdentifier(options.foreignKey);
783
+ const okSql = this.quoteIdentifier(options.otherKey);
784
+ await this.db.sequelize.query(
785
+ `CREATE TABLE ${throughSql} (${fkSql} ${sourceDataType} NOT NULL, ${okSql} ${targetDataType} NOT NULL, PRIMARY KEY (${fkSql}, ${okSql}))`,
786
+ { transaction }
787
+ );
788
+ const indexHash = (0, import_crypto.createHash)("sha256").update(`${through.schema}\0${through.tableName}\0${options.otherKey}`).digest("hex").slice(0, 24);
789
+ await this.db.sequelize.query(
790
+ `CREATE INDEX ${this.quoteIdentifier(`idx_${indexHash}`)} ON ${throughSql} (${okSql})`,
791
+ { transaction }
792
+ );
793
+ }
794
+ await this.ensureForeignKey(
795
+ options.through,
796
+ {
797
+ foreignKey: options.foreignKey,
798
+ targetKey: options.sourceKey,
799
+ target: collectionName,
800
+ onDelete: options.onDelete,
801
+ onUpdate: options.onUpdate,
802
+ defaultOnDelete: "CASCADE",
803
+ replaceActions: options.replaceActions
804
+ },
805
+ transaction
806
+ );
807
+ await this.ensureForeignKey(
808
+ options.through,
809
+ {
810
+ foreignKey: options.otherKey,
811
+ targetKey: options.targetKey,
812
+ target: options.target,
813
+ onDelete: options.onDelete,
814
+ onUpdate: options.onUpdate,
815
+ defaultOnDelete: "CASCADE",
816
+ replaceActions: options.replaceActions
817
+ },
818
+ transaction
819
+ );
820
+ }
821
+ async setUnique(collectionName, columnName, unique, transaction) {
822
+ const { schema, tableName } = this.tableInfo(collectionName);
823
+ const indexes = await this.db.sequelize.query(
824
+ `SELECT idx.relname AS "indexName", con.conname AS "constraintName", i.indisvalid AS "isValid"
825
+ FROM pg_catalog.pg_index i
826
+ JOIN pg_catalog.pg_class tbl ON tbl.oid = i.indrelid
827
+ JOIN pg_catalog.pg_namespace n ON n.oid = tbl.relnamespace
828
+ JOIN pg_catalog.pg_class idx ON idx.oid = i.indexrelid
829
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = tbl.oid AND a.attnum = i.indkey[0]
830
+ LEFT JOIN pg_catalog.pg_constraint con ON con.conindid = i.indexrelid AND con.contype = 'u'
831
+ WHERE n.nspname = :schema AND tbl.relname = :tableName AND a.attname = :columnName
832
+ AND i.indisunique AND NOT i.indisprimary AND i.indnkeyatts = 1 AND i.indpred IS NULL AND a.attnum > 0`,
833
+ { replacements: { schema, tableName, columnName }, type: import_sequelize.QueryTypes.SELECT, transaction }
834
+ );
835
+ const dropEntry = async (index) => {
836
+ const sql = index.constraintName ? `ALTER TABLE ${this.tableSql(collectionName)} DROP CONSTRAINT ${this.quoteIdentifier(index.constraintName)}` : `DROP INDEX ${this.quoteIdentifier(schema)}.${this.quoteIdentifier(index.indexName)}`;
837
+ await this.db.sequelize.query(sql, { transaction });
838
+ };
839
+ if (unique) {
840
+ const validIndexes = indexes.filter((index) => index.isValid !== false);
841
+ for (const invalidIndex of indexes.filter((index) => index.isValid === false)) {
842
+ await dropEntry(invalidIndex);
843
+ }
844
+ if (validIndexes.length === 0) {
845
+ const hash = (0, import_crypto.createHash)("sha256").update(`${schema}\0${tableName}\0${columnName}`).digest("hex").slice(0, 24);
846
+ await this.db.sequelize.query(
847
+ `CREATE UNIQUE INDEX ${this.quoteIdentifier(`idx_unique_${hash}`)} ON ${this.tableSql(
848
+ collectionName
849
+ )} (${this.quoteIdentifier(columnName)})`,
850
+ { transaction }
851
+ );
852
+ }
853
+ } else {
854
+ for (const index of indexes) {
855
+ await dropEntry(index);
856
+ }
857
+ }
858
+ }
859
+ // Collections are introspected. DDL is performed only by explicit collection/field actions.
860
+ async sync() {
861
+ }
862
+ }
863
+ // Annotate the CommonJS export names for ESM import in node:
864
+ 0 && (module.exports = {
865
+ PostgresCollectionManager,
866
+ applyPostgresArrayDataType,
867
+ isPostgresPhysicalArrayRawType
868
+ });