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

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