@tachybase/database 0.23.8

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 (226) hide show
  1. package/.turbo/turbo-build.log +10 -0
  2. package/LICENSE +201 -0
  3. package/lib/collection-factory.d.ts +17 -0
  4. package/lib/collection-factory.js +52 -0
  5. package/lib/collection-group-manager.d.ts +26 -0
  6. package/lib/collection-group-manager.js +57 -0
  7. package/lib/collection-importer.d.ts +7 -0
  8. package/lib/collection-importer.js +74 -0
  9. package/lib/collection.d.ts +138 -0
  10. package/lib/collection.js +686 -0
  11. package/lib/database-utils/index.d.ts +9 -0
  12. package/lib/database-utils/index.js +71 -0
  13. package/lib/database-utils/traverseJSON.d.ts +10 -0
  14. package/lib/database-utils/traverseJSON.js +126 -0
  15. package/lib/database.d.ts +201 -0
  16. package/lib/database.js +765 -0
  17. package/lib/decorators/must-have-filter-decorator.d.ts +2 -0
  18. package/lib/decorators/must-have-filter-decorator.js +38 -0
  19. package/lib/decorators/target-collection-decorator.d.ts +2 -0
  20. package/lib/decorators/target-collection-decorator.js +47 -0
  21. package/lib/decorators/transaction-decorator.d.ts +1 -0
  22. package/lib/decorators/transaction-decorator.js +88 -0
  23. package/lib/eager-loading/eager-loading-tree.d.ts +31 -0
  24. package/lib/eager-loading/eager-loading-tree.js +439 -0
  25. package/lib/errors/identifier-error.d.ts +3 -0
  26. package/lib/errors/identifier-error.js +35 -0
  27. package/lib/errors/zero-column-table-error.d.ts +2 -0
  28. package/lib/errors/zero-column-table-error.js +31 -0
  29. package/lib/features/references-map.d.ts +18 -0
  30. package/lib/features/references-map.js +109 -0
  31. package/lib/features/referential-integrity-check.d.ts +8 -0
  32. package/lib/features/referential-integrity-check.js +83 -0
  33. package/lib/field-repository/array-field-repository.d.ts +28 -0
  34. package/lib/field-repository/array-field-repository.js +197 -0
  35. package/lib/fields/array-field.d.ts +11 -0
  36. package/lib/fields/array-field.js +57 -0
  37. package/lib/fields/belongs-to-field.d.ts +17 -0
  38. package/lib/fields/belongs-to-field.js +154 -0
  39. package/lib/fields/belongs-to-many-field.d.ts +20 -0
  40. package/lib/fields/belongs-to-many-field.js +187 -0
  41. package/lib/fields/boolean-field.d.ts +8 -0
  42. package/lib/fields/boolean-field.js +36 -0
  43. package/lib/fields/context-field.d.ts +14 -0
  44. package/lib/fields/context-field.js +70 -0
  45. package/lib/fields/date-field.d.ts +13 -0
  46. package/lib/fields/date-field.js +64 -0
  47. package/lib/fields/field.d.ts +43 -0
  48. package/lib/fields/field.js +156 -0
  49. package/lib/fields/has-inverse-field.d.ts +4 -0
  50. package/lib/fields/has-inverse-field.js +15 -0
  51. package/lib/fields/has-many-field.d.ts +68 -0
  52. package/lib/fields/has-many-field.js +156 -0
  53. package/lib/fields/has-one-field.d.ts +68 -0
  54. package/lib/fields/has-one-field.js +150 -0
  55. package/lib/fields/index.d.ts +46 -0
  56. package/lib/fields/index.js +65 -0
  57. package/lib/fields/json-field.d.ts +14 -0
  58. package/lib/fields/json-field.js +54 -0
  59. package/lib/fields/nanoid-field.d.ts +13 -0
  60. package/lib/fields/nanoid-field.js +58 -0
  61. package/lib/fields/number-field.d.ts +41 -0
  62. package/lib/fields/number-field.js +85 -0
  63. package/lib/fields/password-field.d.ts +21 -0
  64. package/lib/fields/password-field.js +95 -0
  65. package/lib/fields/radio-field.d.ts +16 -0
  66. package/lib/fields/radio-field.js +66 -0
  67. package/lib/fields/relation-field.d.ts +21 -0
  68. package/lib/fields/relation-field.js +79 -0
  69. package/lib/fields/set-field.d.ts +10 -0
  70. package/lib/fields/set-field.js +46 -0
  71. package/lib/fields/sort-field.d.ts +16 -0
  72. package/lib/fields/sort-field.js +187 -0
  73. package/lib/fields/string-field.d.ts +8 -0
  74. package/lib/fields/string-field.js +36 -0
  75. package/lib/fields/text-field.d.ts +8 -0
  76. package/lib/fields/text-field.js +36 -0
  77. package/lib/fields/time-field.d.ts +8 -0
  78. package/lib/fields/time-field.js +36 -0
  79. package/lib/fields/uid-field.d.ts +13 -0
  80. package/lib/fields/uid-field.js +63 -0
  81. package/lib/fields/uuid-field.d.ts +9 -0
  82. package/lib/fields/uuid-field.js +45 -0
  83. package/lib/fields/virtual-field.d.ts +8 -0
  84. package/lib/fields/virtual-field.js +36 -0
  85. package/lib/filter-match.d.ts +1 -0
  86. package/lib/filter-match.js +66 -0
  87. package/lib/filter-parser.d.ts +21 -0
  88. package/lib/filter-parser.js +230 -0
  89. package/lib/helpers.d.ts +3 -0
  90. package/lib/helpers.js +167 -0
  91. package/lib/index.d.ts +30 -0
  92. package/lib/index.js +114 -0
  93. package/lib/inherited-collection.d.ts +14 -0
  94. package/lib/inherited-collection.js +138 -0
  95. package/lib/inherited-map.d.ts +21 -0
  96. package/lib/inherited-map.js +113 -0
  97. package/lib/inherited-sync-runner.d.ts +4 -0
  98. package/lib/inherited-sync-runner.js +175 -0
  99. package/lib/listeners/adjacency-list.d.ts +2 -0
  100. package/lib/listeners/adjacency-list.js +42 -0
  101. package/lib/listeners/append-child-collection-name-after-repository-find.d.ts +6 -0
  102. package/lib/listeners/append-child-collection-name-after-repository-find.js +66 -0
  103. package/lib/listeners/index.d.ts +2 -0
  104. package/lib/listeners/index.js +33 -0
  105. package/lib/magic-attribute-model.d.ts +8 -0
  106. package/lib/magic-attribute-model.js +203 -0
  107. package/lib/migration.d.ts +35 -0
  108. package/lib/migration.js +103 -0
  109. package/lib/mock-database.d.ts +25 -0
  110. package/lib/mock-database.js +126 -0
  111. package/lib/model-hook.d.ts +12 -0
  112. package/lib/model-hook.js +92 -0
  113. package/lib/model.d.ts +23 -0
  114. package/lib/model.js +152 -0
  115. package/lib/operators/array.d.ts +2 -0
  116. package/lib/operators/array.js +158 -0
  117. package/lib/operators/association.d.ts +2 -0
  118. package/lib/operators/association.js +35 -0
  119. package/lib/operators/boolean.d.ts +2 -0
  120. package/lib/operators/boolean.js +38 -0
  121. package/lib/operators/child-collection.d.ts +2 -0
  122. package/lib/operators/child-collection.js +67 -0
  123. package/lib/operators/date.d.ts +2 -0
  124. package/lib/operators/date.js +140 -0
  125. package/lib/operators/empty.d.ts +5 -0
  126. package/lib/operators/empty.js +89 -0
  127. package/lib/operators/eq.d.ts +2 -0
  128. package/lib/operators/eq.js +35 -0
  129. package/lib/operators/index.d.ts +5 -0
  130. package/lib/operators/index.js +56 -0
  131. package/lib/operators/jsonb.d.ts +2 -0
  132. package/lib/operators/jsonb.js +50 -0
  133. package/lib/operators/ne.d.ts +2 -0
  134. package/lib/operators/ne.js +40 -0
  135. package/lib/operators/notIn.d.ts +2 -0
  136. package/lib/operators/notIn.js +33 -0
  137. package/lib/operators/string.d.ts +2 -0
  138. package/lib/operators/string.js +109 -0
  139. package/lib/operators/utils.d.ts +4 -0
  140. package/lib/operators/utils.js +40 -0
  141. package/lib/options-parser.d.ts +37 -0
  142. package/lib/options-parser.js +332 -0
  143. package/lib/playground.d.ts +1 -0
  144. package/lib/playground.js +43 -0
  145. package/lib/query-interface/mysql-query-interface.d.ts +35 -0
  146. package/lib/query-interface/mysql-query-interface.js +122 -0
  147. package/lib/query-interface/postgres-query-interface.d.ts +32 -0
  148. package/lib/query-interface/postgres-query-interface.js +189 -0
  149. package/lib/query-interface/query-interface-builder.d.ts +2 -0
  150. package/lib/query-interface/query-interface-builder.js +46 -0
  151. package/lib/query-interface/query-interface.d.ts +42 -0
  152. package/lib/query-interface/query-interface.js +46 -0
  153. package/lib/query-interface/sqlite-query-interface.d.ts +35 -0
  154. package/lib/query-interface/sqlite-query-interface.js +131 -0
  155. package/lib/relation-repository/belongs-to-many-repository.d.ts +21 -0
  156. package/lib/relation-repository/belongs-to-many-repository.js +280 -0
  157. package/lib/relation-repository/belongs-to-repository.d.ts +6 -0
  158. package/lib/relation-repository/belongs-to-repository.js +39 -0
  159. package/lib/relation-repository/hasmany-repository.d.ts +10 -0
  160. package/lib/relation-repository/hasmany-repository.js +182 -0
  161. package/lib/relation-repository/hasone-repository.d.ts +6 -0
  162. package/lib/relation-repository/hasone-repository.js +39 -0
  163. package/lib/relation-repository/multiple-relation-repository.d.ts +20 -0
  164. package/lib/relation-repository/multiple-relation-repository.js +229 -0
  165. package/lib/relation-repository/relation-repository.d.ts +29 -0
  166. package/lib/relation-repository/relation-repository.js +202 -0
  167. package/lib/relation-repository/single-relation-repository.d.ts +25 -0
  168. package/lib/relation-repository/single-relation-repository.js +162 -0
  169. package/lib/relation-repository/types.d.ts +7 -0
  170. package/lib/relation-repository/types.js +15 -0
  171. package/lib/repositories/tree-repository/adjacency-list-repository.d.ts +18 -0
  172. package/lib/repositories/tree-repository/adjacency-list-repository.js +183 -0
  173. package/lib/repositories/view-repository.d.ts +3 -0
  174. package/lib/repositories/view-repository.js +32 -0
  175. package/lib/repository.d.ts +206 -0
  176. package/lib/repository.js +597 -0
  177. package/lib/sql-collection/index.d.ts +2 -0
  178. package/lib/sql-collection/index.js +23 -0
  179. package/lib/sql-collection/query-generator.d.ts +10 -0
  180. package/lib/sql-collection/query-generator.js +70 -0
  181. package/lib/sql-collection/sql-collection.d.ts +7 -0
  182. package/lib/sql-collection/sql-collection.js +69 -0
  183. package/lib/sql-collection/sql-model.d.ts +16 -0
  184. package/lib/sql-collection/sql-model.js +168 -0
  185. package/lib/sql-parser/index.d.ts +10 -0
  186. package/lib/sql-parser/index.js +10699 -0
  187. package/lib/sql-parser/postgres.d.ts +10 -0
  188. package/lib/sql-parser/postgres.js +31506 -0
  189. package/lib/sql-parser/sql.pegjs +1297 -0
  190. package/lib/sync-runner.d.ts +30 -0
  191. package/lib/sync-runner.js +277 -0
  192. package/lib/types.d.ts +49 -0
  193. package/lib/types.js +15 -0
  194. package/lib/update-associations.d.ts +60 -0
  195. package/lib/update-associations.js +405 -0
  196. package/lib/update-guard.d.ts +28 -0
  197. package/lib/update-guard.js +202 -0
  198. package/lib/utils.d.ts +7 -0
  199. package/lib/utils.js +127 -0
  200. package/lib/value-parsers/array-value-parser.d.ts +8 -0
  201. package/lib/value-parsers/array-value-parser.js +58 -0
  202. package/lib/value-parsers/base-value-parser.d.ts +12 -0
  203. package/lib/value-parsers/base-value-parser.js +63 -0
  204. package/lib/value-parsers/boolean-value-parser.d.ts +4 -0
  205. package/lib/value-parsers/boolean-value-parser.js +52 -0
  206. package/lib/value-parsers/date-value-parser.d.ts +5 -0
  207. package/lib/value-parsers/date-value-parser.js +88 -0
  208. package/lib/value-parsers/index.d.ts +12 -0
  209. package/lib/value-parsers/index.js +78 -0
  210. package/lib/value-parsers/json-value-parser.d.ts +4 -0
  211. package/lib/value-parsers/json-value-parser.js +47 -0
  212. package/lib/value-parsers/number-value-parser.d.ts +4 -0
  213. package/lib/value-parsers/number-value-parser.js +58 -0
  214. package/lib/value-parsers/string-value-parser.d.ts +8 -0
  215. package/lib/value-parsers/string-value-parser.js +64 -0
  216. package/lib/value-parsers/to-many-value-parser.d.ts +13 -0
  217. package/lib/value-parsers/to-many-value-parser.js +108 -0
  218. package/lib/value-parsers/to-one-value-parser.d.ts +4 -0
  219. package/lib/value-parsers/to-one-value-parser.js +48 -0
  220. package/lib/view/field-type-map.d.ts +97 -0
  221. package/lib/view/field-type-map.js +90 -0
  222. package/lib/view/view-inference.d.ts +32 -0
  223. package/lib/view/view-inference.js +146 -0
  224. package/lib/view-collection.d.ts +6 -0
  225. package/lib/view-collection.js +45 -0
  226. package/package.json +38 -0
@@ -0,0 +1,686 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
+ var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
35
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
36
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
37
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
38
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
39
+ var __runInitializers = (array, flags, self, value) => {
40
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
41
+ return value;
42
+ };
43
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
44
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
45
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
46
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
47
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
48
+ return __privateGet(this, extra);
49
+ }, set [name](x) {
50
+ return __privateSet(this, extra, x);
51
+ } }, name));
52
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
53
+ for (var i = decorators.length - 1; i >= 0; i--) {
54
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
55
+ if (k) {
56
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
57
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
58
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
59
+ }
60
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
61
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
62
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
63
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
64
+ }
65
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
66
+ };
67
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
68
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
69
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
70
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
71
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
72
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
73
+ var collection_exports = {};
74
+ __export(collection_exports, {
75
+ Collection: () => Collection
76
+ });
77
+ module.exports = __toCommonJS(collection_exports);
78
+ var import_events = require("events");
79
+ var import_deepmerge = __toESM(require("deepmerge"));
80
+ var import_lodash = __toESM(require("lodash"));
81
+ var import_sequelize = require("sequelize");
82
+ var import_model = require("./model");
83
+ var import_adjacency_list_repository = require("./repositories/tree-repository/adjacency-list-repository");
84
+ var import_repository = require("./repository");
85
+ var import_utils = require("./utils");
86
+ var _setField_dec, _a, _init;
87
+ function EnsureAtomicity(originalMethod, context) {
88
+ const newMethod = /* @__PURE__ */ __name(function(...args) {
89
+ const model = this.model;
90
+ const beforeAssociationKeys = Object.keys(model.associations);
91
+ const beforeRawAttributes = Object.keys(model.rawAttributes);
92
+ try {
93
+ return originalMethod.apply(this, args);
94
+ } catch (error) {
95
+ const afterAssociationKeys = Object.keys(model.associations);
96
+ const createdAssociationKeys = import_lodash.default.difference(afterAssociationKeys, beforeAssociationKeys);
97
+ for (const key of createdAssociationKeys) {
98
+ delete this.model.associations[key];
99
+ }
100
+ const afterRawAttributes = Object.keys(model.rawAttributes);
101
+ const createdRawAttributes = import_lodash.default.difference(afterRawAttributes, beforeRawAttributes);
102
+ for (const key of createdRawAttributes) {
103
+ delete this.model.rawAttributes[key];
104
+ }
105
+ throw error;
106
+ }
107
+ }, "newMethod");
108
+ return newMethod;
109
+ }
110
+ __name(EnsureAtomicity, "EnsureAtomicity");
111
+ const _Collection = class _Collection extends (_a = import_events.EventEmitter, _setField_dec = [EnsureAtomicity], _a) {
112
+ constructor(options, context) {
113
+ super();
114
+ __runInitializers(_init, 5, this);
115
+ __publicField(this, "options");
116
+ __publicField(this, "context");
117
+ __publicField(this, "isThrough");
118
+ __publicField(this, "fields", /* @__PURE__ */ new Map());
119
+ __publicField(this, "model");
120
+ __publicField(this, "repository");
121
+ this.context = context;
122
+ this.options = options;
123
+ this.checkOptions(options);
124
+ this.bindFieldEventListener();
125
+ this.modelInit();
126
+ this.db.modelCollection.set(this.model, this);
127
+ this.db.tableNameCollectionMap.set(this.getTableNameWithSchemaAsString(), this);
128
+ if (!options.inherits) {
129
+ this.setFields(options.fields);
130
+ }
131
+ this.setRepository(options.repository);
132
+ this.setSortable(options.sortable);
133
+ }
134
+ get filterTargetKey() {
135
+ var _a2;
136
+ const targetKey = (_a2 = this.options) == null ? void 0 : _a2.filterTargetKey;
137
+ if (targetKey && this.model.getAttributes()[targetKey]) {
138
+ return targetKey;
139
+ }
140
+ if (this.model.primaryKeyAttributes.length > 1) {
141
+ return null;
142
+ }
143
+ return this.model.primaryKeyAttribute;
144
+ }
145
+ get name() {
146
+ return this.options.name;
147
+ }
148
+ get origin() {
149
+ return this.options.origin || "core";
150
+ }
151
+ get titleField() {
152
+ return this.options.titleField || this.model.primaryKeyAttribute;
153
+ }
154
+ get db() {
155
+ return this.context.database;
156
+ }
157
+ get treeParentField() {
158
+ for (const [_2, field] of this.fields) {
159
+ if (field.options.treeParent) {
160
+ return field;
161
+ }
162
+ }
163
+ }
164
+ get treeChildrenField() {
165
+ for (const [_2, field] of this.fields) {
166
+ if (field.options.treeChildren) {
167
+ return field;
168
+ }
169
+ }
170
+ }
171
+ tableName() {
172
+ const { name, tableName } = this.options;
173
+ const tName = tableName || name;
174
+ return this.options.underscored ? (0, import_utils.snakeCase)(tName) : tName;
175
+ }
176
+ /**
177
+ * TODO
178
+ */
179
+ modelInit() {
180
+ if (this.model) {
181
+ return;
182
+ }
183
+ const { name, model, autoGenId = true } = this.options;
184
+ let M = import_model.Model;
185
+ if (this.context.database.sequelize.isDefined(name)) {
186
+ const m = this.context.database.sequelize.model(name);
187
+ if (m.isThrough) {
188
+ this.model = m;
189
+ this.model.database = this.context.database;
190
+ this.model.collection = this;
191
+ return;
192
+ }
193
+ }
194
+ if (typeof model === "string") {
195
+ M = this.context.database.models.get(model) || import_model.Model;
196
+ } else if (model) {
197
+ M = model;
198
+ }
199
+ this.model = class extends M {
200
+ };
201
+ this.model.init(null, this.sequelizeModelOptions());
202
+ if (!autoGenId) {
203
+ this.model.removeAttribute("id");
204
+ }
205
+ this.model.database = this.context.database;
206
+ this.model.collection = this;
207
+ }
208
+ setRepository(repository) {
209
+ let repo = import_repository.Repository;
210
+ if (typeof repository === "string") {
211
+ repo = this.context.database.repositories.get(repository) || import_repository.Repository;
212
+ }
213
+ if (this.options.tree == "adjacency-list" || this.options.tree == "adjacencyList") {
214
+ repo = import_adjacency_list_repository.AdjacencyListRepository;
215
+ }
216
+ this.repository = new repo(this);
217
+ }
218
+ forEachField(callback) {
219
+ return [...this.fields.values()].forEach(callback);
220
+ }
221
+ findField(callback) {
222
+ return [...this.fields.values()].find(callback);
223
+ }
224
+ hasField(name) {
225
+ return this.fields.has(name);
226
+ }
227
+ getField(name) {
228
+ return this.fields.get(name);
229
+ }
230
+ getFields() {
231
+ return [...this.fields.values()];
232
+ }
233
+ addField(name, options) {
234
+ return this.setField(name, options);
235
+ }
236
+ checkFieldType(name, options) {
237
+ if (!this.options.underscored) {
238
+ return;
239
+ }
240
+ const fieldName = options.field || (0, import_utils.snakeCase)(name);
241
+ const field = this.findField((f) => {
242
+ if (f.name === name) {
243
+ return false;
244
+ }
245
+ if (f.field) {
246
+ return f.field === fieldName;
247
+ }
248
+ return (0, import_utils.snakeCase)(f.name) === fieldName;
249
+ });
250
+ if (!field) {
251
+ return;
252
+ }
253
+ if (options.type !== field.type) {
254
+ throw new Error(`fields with same column must be of the same type ${JSON.stringify(options)}`);
255
+ }
256
+ }
257
+ correctOptions(options) {
258
+ if (options.primaryKey && options.autoIncrement) {
259
+ delete options.defaultValue;
260
+ }
261
+ }
262
+ setField(name, options) {
263
+ (0, import_utils.checkIdentifier)(name);
264
+ this.checkFieldType(name, options);
265
+ const { database } = this.context;
266
+ if (options.source) {
267
+ const [sourceCollectionName, sourceFieldName] = options.source.split(".");
268
+ const sourceCollection = this.db.collections.get(sourceCollectionName);
269
+ if (!sourceCollection) {
270
+ this.db.logger.warn(
271
+ `source collection "${sourceCollectionName}" not found for field "${name}" at collection "${this.name}"`
272
+ );
273
+ } else {
274
+ const sourceField = sourceCollection.fields.get(sourceFieldName);
275
+ if (!sourceField) {
276
+ this.db.logger.warn(
277
+ `source field "${sourceFieldName}" not found for field "${name}" at collection "${this.name}"`
278
+ );
279
+ } else {
280
+ options = { ...import_lodash.default.omit(sourceField.options, ["name", "primaryKey"]), ...options };
281
+ }
282
+ }
283
+ }
284
+ this.correctOptions(options);
285
+ this.emit("field.beforeAdd", name, options, { collection: this });
286
+ const field = database.buildField(
287
+ { name, ...options },
288
+ {
289
+ ...this.context,
290
+ collection: this
291
+ }
292
+ );
293
+ const oldField = this.fields.get(name);
294
+ if (oldField && oldField.options.inherit && field.typeToString() != oldField.typeToString()) {
295
+ throw new Error(
296
+ `Field type conflict: cannot set "${name}" on "${this.name}" to ${options.type}, parent "${name}" type is ${oldField.options.type}`
297
+ );
298
+ }
299
+ if (this.options.autoGenId !== false && options.primaryKey) {
300
+ this.model.removeAttribute("id");
301
+ }
302
+ this.removeField(name);
303
+ this.fields.set(name, field);
304
+ this.emit("field.afterAdd", field);
305
+ this.db.emit("field.afterAdd", {
306
+ collection: this,
307
+ field
308
+ });
309
+ if (this.isParent()) {
310
+ for (const child of this.context.database.inheritanceMap.getChildren(this.name, {
311
+ deep: false
312
+ })) {
313
+ const childCollection = this.db.getCollection(child);
314
+ const existField = childCollection.getField(name);
315
+ if (!existField || existField.options.inherit) {
316
+ childCollection.setField(name, {
317
+ ...options,
318
+ inherit: true
319
+ });
320
+ }
321
+ }
322
+ }
323
+ return field;
324
+ }
325
+ setFields(fields, resetFields = true) {
326
+ if (!Array.isArray(fields)) {
327
+ return;
328
+ }
329
+ if (resetFields) {
330
+ this.resetFields();
331
+ }
332
+ for (const { name, ...options } of fields) {
333
+ this.addField(name, options);
334
+ }
335
+ }
336
+ resetFields() {
337
+ const fieldNames = this.fields.keys();
338
+ for (const fieldName of fieldNames) {
339
+ this.removeField(fieldName);
340
+ }
341
+ }
342
+ remove() {
343
+ return this.context.database.removeCollection(this.name);
344
+ }
345
+ async removeFieldFromDb(name, options) {
346
+ const field = this.getField(name);
347
+ if (!field) {
348
+ return;
349
+ }
350
+ const attribute = this.model.rawAttributes[name];
351
+ if (!attribute) {
352
+ field.remove();
353
+ return;
354
+ }
355
+ if (this.isInherited() && this.parentFields().has(name)) {
356
+ return;
357
+ }
358
+ if (this.model._virtualAttributes.has(this.name)) {
359
+ field.remove();
360
+ return;
361
+ }
362
+ if (this.model.options.timestamps !== false) {
363
+ let timestampsFields = ["createdAt", "updatedAt", "deletedAt"];
364
+ if (this.db.options.underscored) {
365
+ timestampsFields = timestampsFields.map((fieldName) => (0, import_utils.snakeCase)(fieldName));
366
+ }
367
+ if (timestampsFields.includes(field.columnName())) {
368
+ this.fields.delete(name);
369
+ return;
370
+ }
371
+ }
372
+ const sortable = this.options.sortable;
373
+ if (sortable) {
374
+ let sortField;
375
+ if (sortable === true) {
376
+ sortField = "sort";
377
+ } else if (typeof sortable === "string") {
378
+ sortField = sortable;
379
+ } else if (sortable.name) {
380
+ sortField = sortable.name || "sort";
381
+ }
382
+ if (field.name === sortField) {
383
+ return;
384
+ }
385
+ }
386
+ if (this.isView()) {
387
+ field.remove();
388
+ return;
389
+ }
390
+ const columnReferencesCount = import_lodash.default.filter(this.model.rawAttributes, (attr) => attr.field == field.columnName()).length;
391
+ if (await field.existsInDb({
392
+ transaction: options == null ? void 0 : options.transaction
393
+ }) && columnReferencesCount == 1) {
394
+ const columns = await this.model.sequelize.getQueryInterface().describeTable(this.getTableNameWithSchema(), options);
395
+ if (Object.keys(columns).length == 1) {
396
+ await this.removeFromDb({
397
+ ...options,
398
+ cascade: true,
399
+ dropCollection: false
400
+ });
401
+ } else {
402
+ const queryInterface = this.db.sequelize.getQueryInterface();
403
+ await queryInterface.removeColumn(this.getTableNameWithSchema(), field.columnName(), options);
404
+ }
405
+ }
406
+ field.remove();
407
+ }
408
+ async removeFromDb(options) {
409
+ if (!this.isView() && await this.existsInDb({
410
+ transaction: options == null ? void 0 : options.transaction
411
+ })) {
412
+ const queryInterface = this.db.sequelize.getQueryInterface();
413
+ await queryInterface.dropTable(this.getTableNameWithSchema(), options);
414
+ }
415
+ if ((options == null ? void 0 : options.dropCollection) !== false) {
416
+ return this.remove();
417
+ }
418
+ }
419
+ async existsInDb(options) {
420
+ return this.db.queryInterface.collectionTableExists(this, options);
421
+ }
422
+ removeField(name) {
423
+ if (!this.fields.has(name)) {
424
+ return;
425
+ }
426
+ const field = this.fields.get(name);
427
+ const bool = this.fields.delete(name);
428
+ if (bool) {
429
+ if (this.isParent()) {
430
+ for (const child of this.db.inheritanceMap.getChildren(this.name, {
431
+ deep: false
432
+ })) {
433
+ const childCollection = this.db.getCollection(child);
434
+ const existField = childCollection.getField(name);
435
+ if (existField && existField.options.inherit) {
436
+ childCollection.removeField(name);
437
+ }
438
+ }
439
+ }
440
+ this.emit("field.afterRemove", field);
441
+ }
442
+ return field;
443
+ }
444
+ /**
445
+ * TODO
446
+ */
447
+ updateOptions(options, mergeOptions) {
448
+ let newOptions = import_lodash.default.cloneDeep(options);
449
+ newOptions = (0, import_deepmerge.default)(this.options, newOptions, mergeOptions);
450
+ this.context.database.emit("beforeUpdateCollection", this, newOptions);
451
+ this.options = newOptions;
452
+ this.setFields(options.fields, false);
453
+ if (options.repository) {
454
+ this.setRepository(options.repository);
455
+ }
456
+ this.context.database.emit("afterUpdateCollection", this);
457
+ return this;
458
+ }
459
+ setSortable(sortable) {
460
+ if (!sortable) {
461
+ return;
462
+ }
463
+ if (sortable === true) {
464
+ this.setField("sort", {
465
+ type: "sort",
466
+ hidden: true
467
+ });
468
+ }
469
+ if (typeof sortable === "string") {
470
+ this.setField(sortable, {
471
+ type: "sort",
472
+ hidden: true
473
+ });
474
+ } else if (typeof sortable === "object") {
475
+ const { name, ...opts } = sortable;
476
+ this.setField(name || "sort", { type: "sort", hidden: true, ...opts });
477
+ }
478
+ }
479
+ /**
480
+ * TODO
481
+ *
482
+ * @param name
483
+ * @param options
484
+ */
485
+ updateField(name, options) {
486
+ if (!this.hasField(name)) {
487
+ throw new Error(`field ${name} not exists`);
488
+ }
489
+ if (options.name && options.name !== name) {
490
+ this.removeField(name);
491
+ }
492
+ this.setField(options.name || name, options);
493
+ }
494
+ addIndex(index) {
495
+ if (!index) {
496
+ return;
497
+ }
498
+ const indexes = this.model.options.indexes || [];
499
+ let indexName = [];
500
+ let indexItem;
501
+ if (typeof index === "string") {
502
+ indexItem = {
503
+ fields: [index]
504
+ };
505
+ indexName = [index];
506
+ } else if (Array.isArray(index)) {
507
+ indexItem = {
508
+ fields: index
509
+ };
510
+ indexName = index;
511
+ } else if (index == null ? void 0 : index.fields) {
512
+ indexItem = index;
513
+ indexName = index.fields;
514
+ }
515
+ if (import_lodash.default.isEqual(this.model.primaryKeyAttributes, indexName)) {
516
+ return;
517
+ }
518
+ const name = this.model.primaryKeyAttributes.join(",");
519
+ if (name.startsWith(`${indexName.join(",")},`)) {
520
+ return;
521
+ }
522
+ for (const item of indexes) {
523
+ if (import_lodash.default.isEqual(item.fields, indexName)) {
524
+ return;
525
+ }
526
+ const name2 = item.fields.join(",");
527
+ if (name2.startsWith(`${indexName.join(",")},`)) {
528
+ return;
529
+ }
530
+ }
531
+ if (!indexItem) {
532
+ return;
533
+ }
534
+ indexes.push(indexItem);
535
+ const tableName = this.model.getTableName();
536
+ this.model._indexes = this.model.options.indexes.map((index2) => import_sequelize.Utils.nameIndex(this.model._conformIndex(index2), tableName)).map((item) => {
537
+ if (item.name && item.name.length > 63) {
538
+ item.name = "i_" + (0, import_utils.md5)(item.name);
539
+ }
540
+ return item;
541
+ });
542
+ this.refreshIndexes();
543
+ }
544
+ removeIndex(fields) {
545
+ if (!fields) {
546
+ return;
547
+ }
548
+ const indexes = this.model._indexes;
549
+ this.model._indexes = indexes.filter((item) => {
550
+ return !import_lodash.default.isEqual(item.fields, fields);
551
+ });
552
+ this.refreshIndexes();
553
+ }
554
+ refreshIndexes() {
555
+ const indexes = this.model._indexes;
556
+ this.model._indexes = import_lodash.default.uniqBy(
557
+ indexes.filter((item) => {
558
+ return item.fields.every(
559
+ (field) => Object.values(this.model.rawAttributes).find((fieldVal) => fieldVal.field === field)
560
+ );
561
+ }).map((item) => {
562
+ if (this.options.underscored) {
563
+ item.fields = item.fields.map((field) => (0, import_utils.snakeCase)(field));
564
+ }
565
+ return item;
566
+ }),
567
+ "name"
568
+ );
569
+ }
570
+ async sync(syncOptions) {
571
+ const modelNames = /* @__PURE__ */ new Set([this.model.name]);
572
+ const { associations } = this.model;
573
+ for (const associationKey in associations) {
574
+ const association = associations[associationKey];
575
+ modelNames.add(association.target.name);
576
+ if (association.through) {
577
+ modelNames.add(association.through.model.name);
578
+ }
579
+ }
580
+ const models = [];
581
+ this.context.database.sequelize.modelManager.forEachModel((model) => {
582
+ if (modelNames.has(model.name)) {
583
+ models.push(model);
584
+ }
585
+ });
586
+ for (const model of models) {
587
+ await model.sync(
588
+ syncOptions || {
589
+ force: false,
590
+ alter: {
591
+ drop: false
592
+ }
593
+ }
594
+ );
595
+ }
596
+ }
597
+ isInherited() {
598
+ return false;
599
+ }
600
+ isParent() {
601
+ return this.context.database.inheritanceMap.isParentNode(this.name);
602
+ }
603
+ getTableNameWithSchema() {
604
+ const tableName = this.model.tableName;
605
+ if (this.collectionSchema() && this.db.inDialect("postgres")) {
606
+ return this.db.utils.addSchema(tableName, this.collectionSchema());
607
+ }
608
+ return tableName;
609
+ }
610
+ tableNameAsString(options) {
611
+ const tableNameWithSchema = this.getTableNameWithSchema();
612
+ if (import_lodash.default.isString(tableNameWithSchema)) {
613
+ return tableNameWithSchema;
614
+ }
615
+ const schema = tableNameWithSchema.schema;
616
+ const tableName = tableNameWithSchema.tableName;
617
+ if ((options == null ? void 0 : options.ignorePublicSchema) && schema === "public") {
618
+ return tableName;
619
+ }
620
+ return `${schema}.${tableName}`;
621
+ }
622
+ getTableNameWithSchemaAsString() {
623
+ const tableName = this.model.tableName;
624
+ if (this.collectionSchema() && this.db.inDialect("postgres")) {
625
+ return `${this.collectionSchema()}.${tableName}`;
626
+ }
627
+ return tableName;
628
+ }
629
+ quotedTableName() {
630
+ return this.db.utils.quoteTable(this.getTableNameWithSchema());
631
+ }
632
+ collectionSchema() {
633
+ if (this.options.schema) {
634
+ return this.options.schema;
635
+ }
636
+ if (this.db.options.schema) {
637
+ return this.db.options.schema;
638
+ }
639
+ if (this.db.inDialect("postgres")) {
640
+ return "public";
641
+ }
642
+ return void 0;
643
+ }
644
+ isView() {
645
+ return false;
646
+ }
647
+ sequelizeModelOptions() {
648
+ const { name } = this.options;
649
+ return {
650
+ ...import_lodash.default.omit(this.options, ["name", "fields", "model", "targetKey"]),
651
+ modelName: name,
652
+ sequelize: this.context.database.sequelize,
653
+ tableName: this.tableName()
654
+ };
655
+ }
656
+ bindFieldEventListener() {
657
+ this.on("field.afterAdd", (field) => {
658
+ field.bind();
659
+ });
660
+ this.on("field.afterRemove", (field) => {
661
+ field.unbind();
662
+ this.db.emit("field.afterRemove", field);
663
+ });
664
+ }
665
+ checkOptions(options) {
666
+ (0, import_utils.checkIdentifier)(options.name);
667
+ this.checkTableName();
668
+ }
669
+ checkTableName() {
670
+ const tableName = this.tableName();
671
+ for (const [k, collection] of this.db.collections) {
672
+ if (collection.name != this.options.name && tableName === collection.tableName() && collection.collectionSchema() === this.collectionSchema()) {
673
+ throw new Error(`collection ${collection.name} and ${this.name} have same tableName "${tableName}"`);
674
+ }
675
+ }
676
+ }
677
+ };
678
+ _init = __decoratorStart(_a);
679
+ __decorateElement(_init, 1, "setField", _setField_dec, _Collection);
680
+ __decoratorMetadata(_init, _Collection);
681
+ __name(_Collection, "Collection");
682
+ let Collection = _Collection;
683
+ // Annotate the CommonJS export names for ESM import in node:
684
+ 0 && (module.exports = {
685
+ Collection
686
+ });
@@ -0,0 +1,9 @@
1
+ import Database from '../database';
2
+ export default class DatabaseUtils {
3
+ db: Database;
4
+ constructor(db: Database);
5
+ addSchema(tableName: any, schema?: any): any;
6
+ quoteTable(tableName: any): any;
7
+ schema(): string;
8
+ }
9
+ export * from './traverseJSON';