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,149 @@
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 sql_model_exports = {};
28
+ __export(sql_model_exports, {
29
+ SQLModel: () => SQLModel
30
+ });
31
+ module.exports = __toCommonJS(sql_model_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_lodash = require("lodash");
34
+ var import_sequelize = require("sequelize");
35
+ var import_validation_error = require("../utils/validation-error");
36
+ function selectQuery(_tableName, options, model) {
37
+ var _a;
38
+ const queryOptions = options || {};
39
+ if ((0, import_lodash.isEmpty)(queryOptions)) return `${model.sql}
40
+ ;`;
41
+ let attributes = (_a = queryOptions.attributes) == null ? void 0 : _a.slice();
42
+ if (attributes) {
43
+ const fields = Array.from(model.collection.fields.keys());
44
+ attributes = attributes.filter(
45
+ (attribute) => attribute === "*" || typeof attribute !== "string" || fields.includes(attribute)
46
+ );
47
+ }
48
+ const escaped = this.escapeAttributes(attributes, { model });
49
+ const selected = escaped && escaped.length > 0 ? escaped : ["*"];
50
+ const clauses = [];
51
+ if (Object.prototype.hasOwnProperty.call(queryOptions, "where")) {
52
+ const where = this.getWhereConditions(queryOptions.where, model.name, model, queryOptions);
53
+ if (where) clauses.push(` WHERE ${where}`);
54
+ }
55
+ if (queryOptions.group) {
56
+ const groups = Array.isArray(queryOptions.group) ? queryOptions.group : [queryOptions.group];
57
+ clauses.push(
58
+ ` GROUP BY ${groups.map((value) => this.aliasGrouping(value, model, model.name, queryOptions)).join(", ")}`
59
+ );
60
+ }
61
+ if (queryOptions.order) {
62
+ const orders = this.getQueryOrders(queryOptions, model, false).mainQueryOrder;
63
+ if (orders.length) clauses.push(` ORDER BY ${orders.join(", ")}`);
64
+ }
65
+ const limit = this.addLimitAndOffset(queryOptions, model);
66
+ if (limit) clauses.push(limit);
67
+ return `SELECT ${selected.join(", ")} FROM (${model.sql}
68
+ ) ${this.getAliasToken()} ${this.quoteIdentifier(
69
+ model.name
70
+ )}${clauses.join("")};`;
71
+ }
72
+ class SQLModel extends import_database.Model {
73
+ static sql;
74
+ static get queryInterface() {
75
+ const queryInterface = this.sequelize.getQueryInterface();
76
+ const nativeGenerator = queryInterface.queryGenerator;
77
+ const generator = new Proxy(nativeGenerator, {
78
+ get(target, key, receiver) {
79
+ return key === "selectQuery" ? selectQuery : Reflect.get(target, key, receiver);
80
+ }
81
+ });
82
+ return new Proxy(queryInterface, {
83
+ get: (target, key, receiver) => {
84
+ if (key === "queryGenerator") return generator;
85
+ if (key !== "select" && key !== "rawSelect") return Reflect.get(target, key, receiver);
86
+ return async (...args) => {
87
+ const optionsIndex = key === "select" ? 2 : 1;
88
+ const options = args[optionsIndex] || {};
89
+ const schema = this.database.options.schema || "public";
90
+ const quotedSchema = nativeGenerator.quoteIdentifier(schema);
91
+ if (options.transaction) {
92
+ const transaction = options.transaction;
93
+ const [settings] = await this.sequelize.query(
94
+ `SELECT current_setting('transaction_read_only') AS "readOnly", current_setting('search_path') AS "searchPath", current_setting('standard_conforming_strings') AS scs`,
95
+ { type: import_sequelize.QueryTypes.SELECT, transaction }
96
+ );
97
+ if (settings.readOnly !== "on")
98
+ throw new import_validation_error.PostgresValidationError("SQL collection queries require a read-only transaction");
99
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', 'on', true)`, { transaction });
100
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
101
+ replacements: { path: quotedSchema },
102
+ transaction
103
+ });
104
+ let result;
105
+ try {
106
+ result = await Reflect.apply(Reflect.get(target, key), receiver, args);
107
+ } catch (error) {
108
+ try {
109
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
110
+ replacements: { path: settings.searchPath },
111
+ transaction
112
+ });
113
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', :scs, true)`, {
114
+ replacements: { scs: settings.scs },
115
+ transaction
116
+ });
117
+ } catch {
118
+ }
119
+ throw error;
120
+ }
121
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
122
+ replacements: { path: settings.searchPath },
123
+ transaction
124
+ });
125
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', :scs, true)`, {
126
+ replacements: { scs: settings.scs },
127
+ transaction
128
+ });
129
+ return result;
130
+ }
131
+ return this.sequelize.transaction(async (transaction) => {
132
+ await this.sequelize.query("SET TRANSACTION READ ONLY", { transaction });
133
+ await this.sequelize.query("SET LOCAL standard_conforming_strings = on", { transaction });
134
+ await this.sequelize.query(`SET LOCAL search_path TO ${quotedSchema}`, { transaction });
135
+ args[optionsIndex] = { ...options, transaction };
136
+ return Reflect.apply(Reflect.get(target, key), receiver, args);
137
+ });
138
+ };
139
+ }
140
+ });
141
+ }
142
+ static async sync() {
143
+ return this;
144
+ }
145
+ }
146
+ // Annotate the CommonJS export names for ESM import in node:
147
+ 0 && (module.exports = {
148
+ SQLModel
149
+ });
@@ -0,0 +1,118 @@
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 tree_collection_exports = {};
28
+ __export(tree_collection_exports, {
29
+ PostgresTreeCollection: () => PostgresTreeCollection
30
+ });
31
+ module.exports = __toCommonJS(tree_collection_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_sequelize = require("sequelize");
34
+ var import_adjacency_list_repository = require("./adjacency-list-repository");
35
+ var import_validation_error = require("../utils/validation-error");
36
+ function quoteIdentifier(value) {
37
+ return `"${value.replace(/"/g, '""')}"`;
38
+ }
39
+ function normalizeTree(options) {
40
+ const result = { ...options, postgresTree: options.postgresTree || options.tree || true };
41
+ delete result.tree;
42
+ return result;
43
+ }
44
+ class PostgresTreeCollection extends import_database.Collection {
45
+ constructor(options, context) {
46
+ super(normalizeTree(options), context);
47
+ this.model.addHook("beforeSave", async (node, hookOptions) => {
48
+ var _a, _b, _c;
49
+ if (!node.isNewRecord && !node.changed(this.treeForeignKey)) return;
50
+ const primaryKey = this.model.primaryKeyAttribute;
51
+ const nodeKey = node.get(primaryKey);
52
+ const parent = node.get(this.treeForeignKey);
53
+ if (parent === null || parent === void 0) return;
54
+ if (!hookOptions.transaction) throw new import_validation_error.PostgresValidationError("Tree parent changes require a transaction");
55
+ if (nodeKey !== null && nodeKey !== void 0 && String(parent) === String(nodeKey)) {
56
+ throw new import_validation_error.PostgresValidationError("Cycle detected in tree collection {{name}}", { name: this.name });
57
+ }
58
+ const modelTable = this.model.getTableName();
59
+ const schema = typeof modelTable === "object" && modelTable ? modelTable.schema || this.db.options.schema || "public" : this.db.options.schema || "public";
60
+ const tableName = typeof modelTable === "object" && modelTable ? modelTable.tableName : String(modelTable || this.name);
61
+ await this.db.sequelize.query("SELECT pg_advisory_xact_lock(hashtextextended(:tree, 0))", {
62
+ replacements: { tree: `${schema}.${tableName}` },
63
+ transaction: hookOptions.transaction
64
+ });
65
+ const pk = quoteIdentifier(((_a = this.getField(primaryKey)) == null ? void 0 : _a.columnName()) || primaryKey);
66
+ const fk = quoteIdentifier(((_b = this.getField(this.treeForeignKey)) == null ? void 0 : _b.columnName()) || this.treeForeignKey);
67
+ const tableSql = `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}`;
68
+ const hasNodeKey = nodeKey !== null && nodeKey !== void 0;
69
+ const rows = await this.db.sequelize.query(
70
+ `WITH RECURSIVE ancestors AS (
71
+ SELECT t.${pk} AS id, t.${fk} AS "parentId", ARRAY[t.${pk}] AS path, FALSE AS is_cycle
72
+ FROM ${tableSql} t
73
+ WHERE t.${pk} = :parent
74
+ UNION ALL
75
+ SELECT p.${pk} AS id, p.${fk} AS "parentId", ancestors.path || p.${pk}, p.${pk} = ANY(ancestors.path) AS is_cycle
76
+ FROM ${tableSql} p
77
+ JOIN ancestors ON p.${pk} = ancestors."parentId"
78
+ WHERE NOT ancestors.is_cycle
79
+ )
80
+ SELECT COALESCE(BOOL_OR(is_cycle${hasNodeKey ? " OR id = :nodeKey" : ""}), FALSE) AS "hasCycle"
81
+ FROM ancestors`,
82
+ {
83
+ replacements: hasNodeKey ? { parent, nodeKey } : { parent },
84
+ type: import_sequelize.QueryTypes.SELECT,
85
+ transaction: hookOptions.transaction
86
+ }
87
+ );
88
+ if ((_c = rows[0]) == null ? void 0 : _c.hasCycle) {
89
+ throw new import_validation_error.PostgresValidationError("Cycle detected in tree collection {{name}}", { name: this.name });
90
+ }
91
+ });
92
+ this.model.addHook("beforeBulkCreate", (_nodes, hookOptions) => {
93
+ hookOptions.individualHooks = true;
94
+ });
95
+ this.model.addHook("beforeBulkUpdate", (hookOptions) => {
96
+ const { attributes } = hookOptions;
97
+ if (!hookOptions.individualHooks && Object.prototype.hasOwnProperty.call(attributes || {}, this.treeForeignKey)) {
98
+ throw new import_validation_error.PostgresValidationError("Bulk changes to a tree parent require individual hooks");
99
+ }
100
+ });
101
+ }
102
+ updateOptions(options, mergeOptions) {
103
+ return super.updateOptions(normalizeTree(options), mergeOptions);
104
+ }
105
+ setRepository() {
106
+ this.repository = new import_adjacency_list_repository.PostgresAdjacencyListRepository(this);
107
+ }
108
+ get treeForeignKey() {
109
+ var _a;
110
+ const foreignKey = (_a = this.treeParentField) == null ? void 0 : _a.options.foreignKey;
111
+ if (typeof foreignKey === "string") return foreignKey;
112
+ return typeof this.options.postgresTree === "string" ? this.options.postgresTree : "parentId";
113
+ }
114
+ }
115
+ // Annotate the CommonJS export names for ESM import in node:
116
+ 0 && (module.exports = {
117
+ PostgresTreeCollection
118
+ });
@@ -0,0 +1,412 @@
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 field_hooks_exports = {};
28
+ __export(field_hooks_exports, {
29
+ buildArrayForeignKeyField: () => buildArrayForeignKeyField,
30
+ fieldReferencesColumn: () => fieldReferencesColumn,
31
+ getRelationLockTables: () => getRelationLockTables,
32
+ removesPhysicalColumn: () => removesPhysicalColumn,
33
+ syncFieldAction: () => syncFieldAction
34
+ });
35
+ module.exports = __toCommonJS(field_hooks_exports);
36
+ var import_sequelize = require("sequelize");
37
+ var import_lodash = require("lodash");
38
+ var import_postgres_collection_manager = require("../postgres-collection-manager");
39
+ var import_validation_error = require("../utils/validation-error");
40
+ const RELATION_TYPES = /* @__PURE__ */ new Set(["belongsTo", "belongsToMany", "belongsToArray", "hasOne", "hasMany"]);
41
+ const RELATION_INTERFACES = {
42
+ m2o: "belongsTo",
43
+ obo: "belongsTo",
44
+ o2m: "hasMany",
45
+ oho: "hasOne",
46
+ m2m: "belongsToMany",
47
+ m2m_array: "belongsToArray"
48
+ };
49
+ function removesPhysicalColumn(collection, name) {
50
+ const field = collection.getField(name);
51
+ if (!field || field.isRelationField()) return false;
52
+ const columnName = field.columnName();
53
+ return !collection.getFields().some((other) => other.name !== name && !other.isRelationField() && other.columnName() === columnName);
54
+ }
55
+ const ARRAY_ELEMENT_TYPE_MAP = {
56
+ nanoid: "string",
57
+ sequence: "string",
58
+ uid: "string",
59
+ snowflakeId: "bigInt"
60
+ };
61
+ function fieldReferencesColumn(values, sourceCollection, targetCollection, columns) {
62
+ const candidates = new Set(Array.isArray(columns) ? columns : [columns]);
63
+ const type = values.type;
64
+ if (values.target === targetCollection) {
65
+ if ((type === "belongsTo" || type === "belongsToMany" || type === "belongsToArray") && candidates.has(String(values.targetKey || "id"))) {
66
+ return true;
67
+ }
68
+ if ((type === "hasOne" || type === "hasMany") && values.foreignKey && candidates.has(String(values.foreignKey))) {
69
+ return true;
70
+ }
71
+ }
72
+ if (sourceCollection === targetCollection) {
73
+ if ((type === "belongsTo" || type === "belongsToArray") && values.foreignKey && candidates.has(String(values.foreignKey))) {
74
+ return true;
75
+ }
76
+ if ((type === "hasOne" || type === "hasMany" || type === "belongsToMany") && candidates.has(String(values.sourceKey || "id"))) {
77
+ return true;
78
+ }
79
+ }
80
+ return values.through === targetCollection && (Boolean(values.foreignKey) && candidates.has(String(values.foreignKey)) || Boolean(values.otherKey) && candidates.has(String(values.otherKey)));
81
+ }
82
+ function buildArrayForeignKeyField(manager, collectionName, relationOptions) {
83
+ var _a, _b, _c;
84
+ if (relationOptions.type !== "belongsToArray") return void 0;
85
+ const foreignKey = typeof relationOptions.foreignKey === "string" ? relationOptions.foreignKey : void 0;
86
+ const target = typeof relationOptions.target === "string" ? relationOptions.target : void 0;
87
+ const targetKey = typeof relationOptions.targetKey === "string" ? relationOptions.targetKey : "id";
88
+ if (!foreignKey || !target || foreignKey === relationOptions.name) return void 0;
89
+ const sourceCollection = manager.getCollection(collectionName);
90
+ if (!sourceCollection || sourceCollection.getField(foreignKey)) return void 0;
91
+ const targetFieldType = String(((_c = (_b = (_a = manager.getCollection(target)) == null ? void 0 : _a.getField(targetKey)) == null ? void 0 : _b.options) == null ? void 0 : _c.type) || "bigInt");
92
+ const elementType = ARRAY_ELEMENT_TYPE_MAP[targetFieldType] || targetFieldType;
93
+ return {
94
+ name: foreignKey,
95
+ field: foreignKey,
96
+ type: "set",
97
+ dataType: "array",
98
+ elementType,
99
+ interface: "json",
100
+ isForeignKey: true,
101
+ uiSchema: {
102
+ type: "object",
103
+ title: foreignKey,
104
+ "x-component": "Input.JSON",
105
+ "x-read-pretty": true
106
+ }
107
+ };
108
+ }
109
+ function normalizeValues(input) {
110
+ const values = { ...input.settings || {}, ...input };
111
+ delete values.settings;
112
+ if (!values.type && values.interface && RELATION_INTERFACES[values.interface]) {
113
+ values.type = RELATION_INTERFACES[values.interface];
114
+ }
115
+ return values;
116
+ }
117
+ function defaultThroughTable(collectionName, target) {
118
+ return import_sequelize.Utils.camelize(
119
+ [collectionName, target].map((item) => item.toLowerCase()).sort().join("_")
120
+ );
121
+ }
122
+ function getRelationLockTables(manager, collectionName, input, fieldName) {
123
+ var _a, _b, _c, _d;
124
+ const schema = ((_b = (_a = manager.db) == null ? void 0 : _a.options) == null ? void 0 : _b.schema) || "public";
125
+ const tables = /* @__PURE__ */ new Set();
126
+ const addTable = (name) => {
127
+ var _a2;
128
+ const col = manager.getCollection(name);
129
+ const tableName = ((_a2 = col == null ? void 0 : col.options) == null ? void 0 : _a2.tableName) || name;
130
+ tables.add(`${schema}.${tableName}`);
131
+ };
132
+ addTable(collectionName);
133
+ const values = normalizeValues(input);
134
+ const resolvedName = fieldName || (typeof values.name === "string" ? values.name : void 0);
135
+ const existing = resolvedName ? (_d = (_c = manager.getCollection(collectionName)) == null ? void 0 : _c.getField(resolvedName)) == null ? void 0 : _d.options : void 0;
136
+ const addRelationTables = (candidate) => {
137
+ if (!candidate) return;
138
+ const type = candidate.type;
139
+ if (typeof candidate.target === "string" && candidate.target && type && RELATION_TYPES.has(type)) {
140
+ addTable(candidate.target);
141
+ if (type === "belongsToMany") {
142
+ const through = typeof candidate.through === "string" && candidate.through ? candidate.through : defaultThroughTable(collectionName, candidate.target);
143
+ addTable(through);
144
+ }
145
+ }
146
+ };
147
+ addRelationTables(existing);
148
+ addRelationTables(existing ? { ...existing, ...values } : values);
149
+ return [...tables].sort();
150
+ }
151
+ async function ensureBelongsTo(manager, collectionName, name, values, input, transaction, replaceActions = false) {
152
+ var _a, _b, _c;
153
+ const target = typeof values.target === "string" ? values.target : void 0;
154
+ if (!target) throw new import_validation_error.PostgresValidationError("Relation field {{name}} requires a target", { name });
155
+ const targetCollection = manager.getCollection(target);
156
+ if (((_a = targetCollection == null ? void 0 : targetCollection.options) == null ? void 0 : _a.view) || ((_b = targetCollection == null ? void 0 : targetCollection.options) == null ? void 0 : _b.sql)) {
157
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
158
+ }
159
+ const targetKey = typeof values.targetKey === "string" && values.targetKey ? values.targetKey : ((_c = targetCollection == null ? void 0 : targetCollection.model) == null ? void 0 : _c.primaryKeyAttribute) || "id";
160
+ const foreignKey = typeof values.foreignKey === "string" && values.foreignKey ? values.foreignKey : import_sequelize.Utils.camelize([import_sequelize.Utils.singularize(name), targetKey].join("_"));
161
+ await manager.ensureForeignKey(
162
+ collectionName,
163
+ {
164
+ foreignKey,
165
+ targetKey,
166
+ target,
167
+ onDelete: typeof values.onDelete === "string" && values.onDelete ? values.onDelete : void 0,
168
+ onUpdate: typeof values.onUpdate === "string" && values.onUpdate ? values.onUpdate : void 0,
169
+ replaceActions
170
+ },
171
+ transaction
172
+ );
173
+ if (!input.type) input.type = "belongsTo";
174
+ if (!input.target) input.target = target;
175
+ if (!input.targetKey) input.targetKey = targetKey;
176
+ if (!input.foreignKey) input.foreignKey = foreignKey;
177
+ }
178
+ async function ensureHasRelation(manager, collectionName, name, type, values, input, transaction, replaceActions = false) {
179
+ var _a, _b, _c;
180
+ const target = typeof values.target === "string" ? values.target : void 0;
181
+ if (!target) throw new import_validation_error.PostgresValidationError("Relation field {{name}} requires a target", { name });
182
+ const sourceCollection = manager.getCollection(collectionName);
183
+ const targetCollection = manager.getCollection(target);
184
+ if (!targetCollection) {
185
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: target });
186
+ }
187
+ const sourceKey = typeof values.sourceKey === "string" && values.sourceKey ? values.sourceKey : ((_a = sourceCollection == null ? void 0 : sourceCollection.model) == null ? void 0 : _a.primaryKeyAttribute) || "id";
188
+ const foreignKey = typeof values.foreignKey === "string" && values.foreignKey ? values.foreignKey : import_sequelize.Utils.camelize([import_sequelize.Utils.singularize(collectionName), sourceKey].join("_"));
189
+ if (((_b = targetCollection.options) == null ? void 0 : _b.view) || ((_c = targetCollection.options) == null ? void 0 : _c.sql)) {
190
+ if (!targetCollection.getField(foreignKey)) {
191
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
192
+ }
193
+ } else {
194
+ await manager.ensureForeignKey(
195
+ target,
196
+ {
197
+ foreignKey,
198
+ targetKey: sourceKey,
199
+ target: collectionName,
200
+ onDelete: typeof values.onDelete === "string" && values.onDelete ? values.onDelete : void 0,
201
+ onUpdate: typeof values.onUpdate === "string" && values.onUpdate ? values.onUpdate : void 0,
202
+ replaceActions
203
+ },
204
+ transaction
205
+ );
206
+ }
207
+ if (!input.type) input.type = type;
208
+ if (!input.target) input.target = target;
209
+ if (!input.sourceKey) input.sourceKey = sourceKey;
210
+ if (!input.foreignKey) input.foreignKey = foreignKey;
211
+ }
212
+ async function ensureBelongsToMany(manager, collectionName, name, values, input, transaction, replaceActions = false) {
213
+ var _a, _b, _c, _d;
214
+ const target = typeof values.target === "string" ? values.target : void 0;
215
+ if (!target) throw new import_validation_error.PostgresValidationError("Relation field {{name}} requires a target", { name });
216
+ const sourceCollection = manager.getCollection(collectionName);
217
+ const targetCollection = manager.getCollection(target);
218
+ if (!targetCollection) {
219
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: target });
220
+ }
221
+ if (((_a = targetCollection.options) == null ? void 0 : _a.view) || ((_b = targetCollection.options) == null ? void 0 : _b.sql)) {
222
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
223
+ }
224
+ const sourceKey = typeof values.sourceKey === "string" && values.sourceKey ? values.sourceKey : ((_c = sourceCollection == null ? void 0 : sourceCollection.model) == null ? void 0 : _c.primaryKeyAttribute) || "id";
225
+ const targetKey = typeof values.targetKey === "string" && values.targetKey ? values.targetKey : ((_d = targetCollection.model) == null ? void 0 : _d.primaryKeyAttribute) || "id";
226
+ const foreignKey = typeof values.foreignKey === "string" && values.foreignKey ? values.foreignKey : import_sequelize.Utils.camelize([import_sequelize.Utils.singularize(collectionName), sourceKey].join("_"));
227
+ const otherKey = typeof values.otherKey === "string" && values.otherKey ? values.otherKey : import_sequelize.Utils.camelize([import_sequelize.Utils.singularize(target), targetKey].join("_"));
228
+ const through = typeof values.through === "string" && values.through ? values.through : defaultThroughTable(collectionName, target);
229
+ await manager.ensureJoinTable(
230
+ collectionName,
231
+ {
232
+ through,
233
+ foreignKey,
234
+ otherKey,
235
+ sourceKey,
236
+ targetKey,
237
+ target,
238
+ onDelete: typeof values.onDelete === "string" && values.onDelete ? values.onDelete : void 0,
239
+ onUpdate: typeof values.onUpdate === "string" && values.onUpdate ? values.onUpdate : void 0,
240
+ replaceActions
241
+ },
242
+ transaction
243
+ );
244
+ if (!input.type) input.type = "belongsToMany";
245
+ if (!input.target) input.target = target;
246
+ if (!input.sourceKey) input.sourceKey = sourceKey;
247
+ if (!input.targetKey) input.targetKey = targetKey;
248
+ if (!input.foreignKey) input.foreignKey = foreignKey;
249
+ if (!input.otherKey) input.otherKey = otherKey;
250
+ if (!input.through) input.through = through;
251
+ }
252
+ async function ensureBelongsToArray(manager, collectionName, name, values, input, transaction) {
253
+ var _a, _b;
254
+ const target = typeof values.target === "string" ? values.target : void 0;
255
+ if (!target) throw new import_validation_error.PostgresValidationError("Relation field {{name}} requires a target", { name });
256
+ const targetCollection = manager.getCollection(target);
257
+ if (!targetCollection) {
258
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: target });
259
+ }
260
+ if ((_a = targetCollection.options) == null ? void 0 : _a.sql) {
261
+ throw new import_validation_error.PostgresValidationError("This collection is read-only");
262
+ }
263
+ const targetKey = typeof values.targetKey === "string" && values.targetKey ? values.targetKey : ((_b = targetCollection.model) == null ? void 0 : _b.primaryKeyAttribute) || "id";
264
+ const foreignKey = typeof values.foreignKey === "string" && values.foreignKey ? values.foreignKey : import_sequelize.Utils.camelize([import_sequelize.Utils.singularize(name), targetKey].join("_"));
265
+ if (name === foreignKey) {
266
+ throw new import_validation_error.PostgresValidationError(
267
+ "Foreign key {{foreignKey}} cannot have the same name as relation field {{name}}",
268
+ {
269
+ foreignKey,
270
+ name
271
+ }
272
+ );
273
+ }
274
+ await manager.ensureForeignKeyArray(collectionName, { foreignKey, targetKey, target }, transaction);
275
+ if (!input.type) input.type = "belongsToArray";
276
+ if (!input.target) input.target = target;
277
+ if (!input.targetKey) input.targetKey = targetKey;
278
+ if (!input.foreignKey) input.foreignKey = foreignKey;
279
+ }
280
+ async function syncFieldAction(manager, action, collectionName, fieldName, input, transaction) {
281
+ const collection = manager.getCollection(collectionName);
282
+ if (!collection) {
283
+ throw new import_validation_error.PostgresValidationError("Collection {{name}} does not exist", { name: collectionName });
284
+ }
285
+ const values = normalizeValues(input);
286
+ const name = fieldName || values.name;
287
+ if (!name) {
288
+ throw new import_validation_error.PostgresValidationError("Field name is required");
289
+ }
290
+ const field = collection.getField(name);
291
+ if (action === "destroy") {
292
+ if (!field) {
293
+ throw new import_validation_error.PostgresValidationError("Field {{name}} does not exist", { name });
294
+ }
295
+ if (!removesPhysicalColumn(collection, name)) {
296
+ return;
297
+ }
298
+ const columnNames = [name, field.columnName()];
299
+ for (const candidate of manager.getCollections()) {
300
+ for (const reference of candidate.getFields()) {
301
+ if (fieldReferencesColumn(reference.options, candidate.name, collectionName, columnNames)) {
302
+ throw new import_validation_error.PostgresValidationError("Field {{name}} is referenced by {{collection}}.{{field}}", {
303
+ name,
304
+ collection: candidate.name,
305
+ field: reference.name
306
+ });
307
+ }
308
+ }
309
+ }
310
+ await manager.removeField(collectionName, name, false, transaction);
311
+ return;
312
+ }
313
+ if (!field) {
314
+ if (values.type === "belongsTo") {
315
+ await ensureBelongsTo(manager, collectionName, name, values, input, transaction);
316
+ return;
317
+ }
318
+ if (values.type === "hasMany" || values.type === "hasOne") {
319
+ await ensureHasRelation(manager, collectionName, name, values.type, values, input, transaction);
320
+ return;
321
+ }
322
+ if (values.type === "belongsToMany") {
323
+ await ensureBelongsToMany(manager, collectionName, name, values, input, transaction);
324
+ return;
325
+ }
326
+ if (values.type === "belongsToArray") {
327
+ await ensureBelongsToArray(manager, collectionName, name, values, input, transaction);
328
+ return;
329
+ }
330
+ (0, import_postgres_collection_manager.applyPostgresArrayDataType)(values);
331
+ if (values.dataType === "array") {
332
+ input.dataType = "array";
333
+ if (input.elementType === void 0 && typeof values.elementType === "string") {
334
+ input.elementType = values.elementType;
335
+ }
336
+ }
337
+ await manager.addField(collectionName, { ...values, name }, transaction);
338
+ return;
339
+ }
340
+ if (action === "create") {
341
+ throw new import_validation_error.PostgresValidationError("Field {{name}} already exists", { name });
342
+ }
343
+ if (["autoIncrement", "primaryKey"].some(
344
+ (key) => Object.prototype.hasOwnProperty.call(values, key) && Boolean(values[key]) !== Boolean(field.options[key])
345
+ )) {
346
+ throw new import_validation_error.PostgresValidationError("Field {{name}} cannot change generated-id or primary-key settings", { name });
347
+ }
348
+ if (values.type && RELATION_TYPES.has(field.options.type) !== RELATION_TYPES.has(values.type)) {
349
+ throw new import_validation_error.PostgresValidationError("Field {{name}} cannot be changed between a relation and a physical column", {
350
+ name
351
+ });
352
+ }
353
+ if (RELATION_TYPES.has(field.options.type)) {
354
+ const merged = { ...field.options, ...values };
355
+ if (field.options.type === "belongsTo" && ["target", "foreignKey", "targetKey", "onDelete", "onUpdate"].some(
356
+ (key) => Object.prototype.hasOwnProperty.call(values, key) && !(0, import_lodash.isEqual)(values[key], field.options[key])
357
+ )) {
358
+ await ensureBelongsTo(manager, collectionName, name, merged, input, transaction, true);
359
+ } else if ((field.options.type === "hasMany" || field.options.type === "hasOne") && ["target", "foreignKey", "sourceKey", "onDelete", "onUpdate"].some(
360
+ (key) => Object.prototype.hasOwnProperty.call(values, key) && !(0, import_lodash.isEqual)(values[key], field.options[key])
361
+ )) {
362
+ await ensureHasRelation(manager, collectionName, name, field.options.type, merged, input, transaction, true);
363
+ } else if (field.options.type === "belongsToMany" && ["target", "through", "foreignKey", "otherKey", "sourceKey", "targetKey", "onDelete", "onUpdate"].some(
364
+ (key) => Object.prototype.hasOwnProperty.call(values, key) && !(0, import_lodash.isEqual)(values[key], field.options[key])
365
+ )) {
366
+ await ensureBelongsToMany(manager, collectionName, name, merged, input, transaction, true);
367
+ } else if (field.options.type === "belongsToArray" && ["target", "foreignKey", "targetKey"].some(
368
+ (key) => Object.prototype.hasOwnProperty.call(values, key) && !(0, import_lodash.isEqual)(values[key], field.options[key])
369
+ )) {
370
+ await ensureBelongsToArray(manager, collectionName, name, merged, input, transaction);
371
+ }
372
+ return;
373
+ }
374
+ const effectiveType = values.type ?? field.options.type;
375
+ const effectiveElementType = values.elementType ?? field.options.elementType;
376
+ const effectiveDataType = values.dataType !== void 0 ? values.dataType : field.options.dataType;
377
+ if ((effectiveType === "array" || effectiveType === "set") && typeof effectiveElementType === "string" && effectiveElementType.trim().length > 0 && (effectiveDataType === void 0 || effectiveDataType === null || effectiveDataType === "")) {
378
+ const rawTypeIsArray = field.options.rawType === void 0 ? void 0 : (0, import_postgres_collection_manager.isPostgresPhysicalArrayRawType)(field.options.rawType);
379
+ const columnIsArray = rawTypeIsArray !== void 0 ? rawTypeIsArray : await manager.isPhysicalArrayColumn(collectionName, field.columnName(), transaction);
380
+ if (columnIsArray !== false) {
381
+ values.dataType = "array";
382
+ input.dataType = "array";
383
+ }
384
+ }
385
+ const changes = {};
386
+ for (const key of [
387
+ "type",
388
+ "dataType",
389
+ "allowNull",
390
+ "defaultValue",
391
+ "unique",
392
+ "length",
393
+ "precision",
394
+ "scale",
395
+ "elementType"
396
+ ]) {
397
+ if (Object.prototype.hasOwnProperty.call(values, key) && !(0, import_lodash.isEqual)(values[key], field.options[key])) {
398
+ Object.assign(changes, { [key]: values[key] });
399
+ }
400
+ }
401
+ if (Object.keys(changes).length) {
402
+ await manager.updateField(collectionName, name, changes, transaction);
403
+ }
404
+ }
405
+ // Annotate the CommonJS export names for ESM import in node:
406
+ 0 && (module.exports = {
407
+ buildArrayForeignKeyField,
408
+ fieldReferencesColumn,
409
+ getRelationLockTables,
410
+ removesPhysicalColumn,
411
+ syncFieldAction
412
+ });