@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,597 @@
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 repository_exports = {};
74
+ __export(repository_exports, {
75
+ Repository: () => Repository
76
+ });
77
+ module.exports = __toCommonJS(repository_exports);
78
+ var import_flat = require("flat");
79
+ var import_lodash = __toESM(require("lodash"));
80
+ var import_sequelize = require("sequelize");
81
+ var import_must_have_filter_decorator = __toESM(require("./decorators/must-have-filter-decorator"));
82
+ var import_target_collection_decorator = __toESM(require("./decorators/target-collection-decorator"));
83
+ var import_transaction_decorator = require("./decorators/transaction-decorator");
84
+ var import_eager_loading_tree = require("./eager-loading/eager-loading-tree");
85
+ var import_array_field_repository = require("./field-repository/array-field-repository");
86
+ var import_fields = require("./fields");
87
+ var import_filter_parser = __toESM(require("./filter-parser"));
88
+ var import_options_parser = require("./options-parser");
89
+ var import_belongs_to_many_repository = require("./relation-repository/belongs-to-many-repository");
90
+ var import_belongs_to_repository = require("./relation-repository/belongs-to-repository");
91
+ var import_hasmany_repository = require("./relation-repository/hasmany-repository");
92
+ var import_hasone_repository = require("./relation-repository/hasone-repository");
93
+ var import_update_associations = require("./update-associations");
94
+ var import_update_guard = require("./update-guard");
95
+ var _destroy_dec, _updateMany_dec, _update_dec, _createMany_dec, _create_dec, _init;
96
+ const debug = require("debug")("noco-database");
97
+ const transaction = (0, import_transaction_decorator.transactionWrapperBuilder)(function() {
98
+ return this.collection.model.sequelize.transaction();
99
+ });
100
+ const _RelationRepositoryBuilder = class _RelationRepositoryBuilder {
101
+ collection;
102
+ associationName;
103
+ association;
104
+ builderMap = {
105
+ HasOne: import_hasone_repository.HasOneRepository,
106
+ BelongsTo: import_belongs_to_repository.BelongsToRepository,
107
+ BelongsToMany: import_belongs_to_many_repository.BelongsToManyRepository,
108
+ HasMany: import_hasmany_repository.HasManyRepository,
109
+ ArrayField: import_array_field_repository.ArrayFieldRepository
110
+ };
111
+ constructor(collection, associationName) {
112
+ this.collection = collection;
113
+ this.associationName = associationName;
114
+ this.association = this.collection.model.associations[this.associationName];
115
+ if (!this.association) {
116
+ const field = collection.getField(associationName);
117
+ if (field && field instanceof import_fields.ArrayField) {
118
+ this.association = {
119
+ associationType: "ArrayField"
120
+ };
121
+ }
122
+ }
123
+ }
124
+ of(id) {
125
+ if (!this.association) {
126
+ return;
127
+ }
128
+ const klass = this.builder()[this.association.associationType];
129
+ return new klass(this.collection, this.associationName, id);
130
+ }
131
+ builder() {
132
+ return this.builderMap;
133
+ }
134
+ };
135
+ __name(_RelationRepositoryBuilder, "RelationRepositoryBuilder");
136
+ let RelationRepositoryBuilder = _RelationRepositoryBuilder;
137
+ _create_dec = [transaction()], _createMany_dec = [transaction()], _update_dec = [transaction(), (0, import_must_have_filter_decorator.default)(), import_target_collection_decorator.default], _updateMany_dec = [transaction()], _destroy_dec = [transaction((args, transaction2) => {
138
+ return {
139
+ filterByTk: args[0],
140
+ transaction: transaction2
141
+ };
142
+ })];
143
+ const _Repository = class _Repository {
144
+ constructor(collection) {
145
+ __runInitializers(_init, 5, this);
146
+ __publicField(this, "database");
147
+ __publicField(this, "collection");
148
+ __publicField(this, "model");
149
+ this.database = collection.context.database;
150
+ this.collection = collection;
151
+ this.model = collection.model;
152
+ }
153
+ static valuesToFilter(values, filterKeys) {
154
+ const filterAnd = [];
155
+ const flattedValues = (0, import_flat.flatten)(values);
156
+ const keyWithOutArrayIndex = /* @__PURE__ */ __name((key) => {
157
+ const chunks = key.split(".");
158
+ return chunks.filter((chunk) => {
159
+ return !chunk.match(/\d+/);
160
+ }).join(".");
161
+ }, "keyWithOutArrayIndex");
162
+ for (const filterKey of filterKeys) {
163
+ let filterValue;
164
+ for (const flattedKey of Object.keys(flattedValues)) {
165
+ const flattedKeyWithoutIndex = keyWithOutArrayIndex(flattedKey);
166
+ if (flattedKeyWithoutIndex === filterKey) {
167
+ if (filterValue) {
168
+ if (Array.isArray(filterValue)) {
169
+ filterValue.push(flattedValues[flattedKey]);
170
+ } else {
171
+ filterValue = [filterValue, flattedValues[flattedKey]];
172
+ }
173
+ } else {
174
+ filterValue = flattedValues[flattedKey];
175
+ }
176
+ }
177
+ }
178
+ if (filterValue) {
179
+ filterAnd.push({
180
+ [filterKey]: filterValue
181
+ });
182
+ }
183
+ }
184
+ return {
185
+ $and: filterAnd
186
+ };
187
+ }
188
+ /**
189
+ * return count by filter
190
+ */
191
+ async count(countOptions) {
192
+ var _a;
193
+ let options = countOptions ? import_lodash.default.clone(countOptions) : {};
194
+ const transaction2 = await this.getTransaction(options);
195
+ if (countOptions == null ? void 0 : countOptions.filter) {
196
+ options = {
197
+ ...options,
198
+ ...this.parseFilter(countOptions.filter, countOptions)
199
+ };
200
+ }
201
+ if (countOptions == null ? void 0 : countOptions.filterByTk) {
202
+ options["where"] = {
203
+ [import_sequelize.Op.and]: [
204
+ options["where"] || {},
205
+ {
206
+ [this.collection.filterTargetKey]: options.filterByTk
207
+ }
208
+ ]
209
+ };
210
+ }
211
+ const queryOptions = {
212
+ ...options,
213
+ distinct: Boolean(this.collection.model.primaryKeyAttribute)
214
+ };
215
+ if (((_a = queryOptions.include) == null ? void 0 : _a.length) === 0) {
216
+ delete queryOptions.include;
217
+ }
218
+ const count = await this.collection.model.count({
219
+ ...queryOptions,
220
+ transaction: transaction2
221
+ });
222
+ return count;
223
+ }
224
+ async aggregate(options) {
225
+ var _a;
226
+ const { method, field } = options;
227
+ const queryOptions = this.buildQueryOptions({
228
+ ...options,
229
+ fields: []
230
+ });
231
+ (_a = options.optionsTransformer) == null ? void 0 : _a.call(options, queryOptions);
232
+ const hasAssociationFilter = /* @__PURE__ */ __name(() => {
233
+ if (queryOptions.include && queryOptions.include.length > 0) {
234
+ const filterInclude = queryOptions.include.filter((include) => {
235
+ var _a2;
236
+ return Object.keys(include.where || {}).length > 0 || ((_a2 = JSON.stringify(queryOptions == null ? void 0 : queryOptions.filter)) == null ? void 0 : _a2.includes(include.association));
237
+ });
238
+ return filterInclude.length > 0;
239
+ }
240
+ return false;
241
+ }, "hasAssociationFilter");
242
+ if (hasAssociationFilter()) {
243
+ const primaryKeyField = this.model.primaryKeyAttribute;
244
+ const queryInterface = this.database.sequelize.getQueryInterface();
245
+ const findOptions = {
246
+ ...queryOptions,
247
+ raw: true,
248
+ includeIgnoreAttributes: false,
249
+ attributes: [
250
+ [
251
+ import_sequelize.Sequelize.literal(
252
+ `DISTINCT ${queryInterface.quoteIdentifiers(`${this.collection.name}.${primaryKeyField}`)}`
253
+ ),
254
+ primaryKeyField
255
+ ]
256
+ ]
257
+ };
258
+ const ids = await this.model.findAll(findOptions);
259
+ return await this.model.aggregate(field, method, {
260
+ ...import_lodash.default.omit(queryOptions, ["where", "include"]),
261
+ where: {
262
+ [primaryKeyField]: ids.map((node) => node[primaryKeyField])
263
+ }
264
+ });
265
+ }
266
+ return await this.model.aggregate(field, method, queryOptions);
267
+ }
268
+ /**
269
+ * find
270
+ * @param options
271
+ */
272
+ async find(options = {}) {
273
+ if ((options == null ? void 0 : options.targetCollection) && (options == null ? void 0 : options.targetCollection) !== this.collection.name) {
274
+ return await this.database.getCollection(options.targetCollection).repository.find(options);
275
+ }
276
+ const model = this.collection.model;
277
+ const transaction2 = await this.getTransaction(options);
278
+ const opts = {
279
+ subQuery: false,
280
+ ...this.buildQueryOptions(options)
281
+ };
282
+ let rows;
283
+ if (opts.include && opts.include.length > 0) {
284
+ const eagerLoadingTree = import_eager_loading_tree.EagerLoadingTree.buildFromSequelizeOptions({
285
+ model,
286
+ rootAttributes: opts.attributes,
287
+ includeOption: opts.include,
288
+ rootOrder: opts.order,
289
+ rootQueryOptions: opts,
290
+ db: this.database
291
+ });
292
+ await eagerLoadingTree.load(transaction2);
293
+ rows = eagerLoadingTree.root.instances;
294
+ } else {
295
+ rows = await model.findAll({
296
+ ...opts,
297
+ transaction: transaction2
298
+ });
299
+ }
300
+ await this.collection.db.emitAsync("afterRepositoryFind", {
301
+ findOptions: options,
302
+ dataCollection: this.collection,
303
+ data: rows
304
+ });
305
+ return rows;
306
+ }
307
+ /**
308
+ * find and count
309
+ * @param options
310
+ */
311
+ async findAndCount(options) {
312
+ options = {
313
+ ...options,
314
+ transaction: await this.getTransaction(options)
315
+ };
316
+ const count = await this.count(options);
317
+ const results = count ? await this.find(options) : [];
318
+ return [results, count];
319
+ }
320
+ /**
321
+ * Find By Id
322
+ *
323
+ */
324
+ findById(id) {
325
+ return this.collection.model.findByPk(id);
326
+ }
327
+ /**
328
+ * Find one record from database
329
+ *
330
+ * @param options
331
+ */
332
+ async findOne(options) {
333
+ const transaction2 = await this.getTransaction(options);
334
+ const rows = await this.find({ ...options, limit: 1, transaction: transaction2 });
335
+ return rows.length === 1 ? rows[0] : null;
336
+ }
337
+ /**
338
+ * Get the first record matching the attributes or create it.
339
+ */
340
+ async firstOrCreate(options) {
341
+ const { filterKeys, values, transaction: transaction2, hooks } = options;
342
+ const filter = _Repository.valuesToFilter(values, filterKeys);
343
+ const instance = await this.findOne({ filter, transaction: transaction2 });
344
+ if (instance) {
345
+ return instance;
346
+ }
347
+ return this.create({ values, transaction: transaction2, hooks });
348
+ }
349
+ async updateOrCreate(options) {
350
+ const { filterKeys, values, transaction: transaction2, hooks } = options;
351
+ const filter = _Repository.valuesToFilter(values, filterKeys);
352
+ const instance = await this.findOne({ filter, transaction: transaction2 });
353
+ if (instance) {
354
+ return await this.update({
355
+ filterByTk: instance.get(this.collection.filterTargetKey || this.collection.model.primaryKeyAttribute),
356
+ values,
357
+ transaction: transaction2,
358
+ hooks
359
+ });
360
+ }
361
+ return this.create({ values, transaction: transaction2, hooks });
362
+ }
363
+ async create(options) {
364
+ if (Array.isArray(options.values)) {
365
+ return this.createMany({
366
+ ...options,
367
+ records: options.values
368
+ });
369
+ }
370
+ const transaction2 = await this.getTransaction(options);
371
+ const guard = import_update_guard.UpdateGuard.fromOptions(this.model, {
372
+ ...options,
373
+ action: "create",
374
+ underscored: this.collection.options.underscored
375
+ });
376
+ const values = guard.sanitize(options.values || {});
377
+ const instance = await this.model.create(values, {
378
+ ...options,
379
+ transaction: transaction2
380
+ });
381
+ if (!instance) {
382
+ return;
383
+ }
384
+ await (0, import_update_associations.updateAssociations)(instance, values, {
385
+ ...options,
386
+ transaction: transaction2
387
+ });
388
+ if (options.hooks !== false) {
389
+ await this.database.emitAsync(`${this.collection.name}.afterCreateWithAssociations`, instance, {
390
+ ...options,
391
+ transaction: transaction2
392
+ });
393
+ await this.database.emitAsync(`${this.collection.name}.afterSaveWithAssociations`, instance, {
394
+ ...options,
395
+ transaction: transaction2
396
+ });
397
+ instance.clearChangedWithAssociations();
398
+ }
399
+ return instance;
400
+ }
401
+ async createMany(options) {
402
+ const transaction2 = await this.getTransaction(options);
403
+ const { records } = options;
404
+ const instances = [];
405
+ for (const values of records) {
406
+ const instance = await this.create({ ...options, values, transaction: transaction2 });
407
+ instances.push(instance);
408
+ }
409
+ return instances;
410
+ }
411
+ async update(options) {
412
+ if (Array.isArray(options.values)) {
413
+ return this.updateMany({
414
+ ...options,
415
+ records: options.values
416
+ });
417
+ }
418
+ const transaction2 = await this.getTransaction(options);
419
+ const guard = import_update_guard.UpdateGuard.fromOptions(this.model, { ...options, underscored: this.collection.options.underscored });
420
+ const values = guard.sanitize(options.values);
421
+ if (options.individualHooks === false) {
422
+ const { model: Model2 } = this.collection;
423
+ const primaryKeyField = Model2.primaryKeyField || Model2.primaryKeyAttribute;
424
+ const queryOptions2 = this.buildQueryOptions({
425
+ ...options,
426
+ fields: [primaryKeyField]
427
+ });
428
+ const rows = await this.find({
429
+ ...queryOptions2,
430
+ transaction: transaction2
431
+ });
432
+ const [result] = await Model2.update(values, {
433
+ where: {
434
+ [primaryKeyField]: rows.map((row) => row.get(primaryKeyField))
435
+ },
436
+ fields: options.fields,
437
+ hooks: options.hooks,
438
+ validate: options.validate,
439
+ sideEffects: options.sideEffects,
440
+ limit: options.limit,
441
+ silent: options.silent,
442
+ transaction: transaction2
443
+ });
444
+ return result;
445
+ }
446
+ const queryOptions = this.buildQueryOptions(options);
447
+ const instances = await this.find({
448
+ ...queryOptions,
449
+ transaction: transaction2
450
+ });
451
+ for (const instance of instances) {
452
+ await (0, import_update_associations.updateModelByValues)(instance, values, {
453
+ ...options,
454
+ sanitized: true,
455
+ transaction: transaction2
456
+ });
457
+ }
458
+ if (options.hooks !== false) {
459
+ for (const instance of instances) {
460
+ await this.database.emitAsync(`${this.collection.name}.afterUpdateWithAssociations`, instance, {
461
+ ...options,
462
+ transaction: transaction2
463
+ });
464
+ await this.database.emitAsync(`${this.collection.name}.afterSaveWithAssociations`, instance, {
465
+ ...options,
466
+ transaction: transaction2
467
+ });
468
+ instance.clearChangedWithAssociations();
469
+ }
470
+ }
471
+ return instances;
472
+ }
473
+ async updateMany(options) {
474
+ const transaction2 = await this.getTransaction(options);
475
+ const { records } = options;
476
+ const instances = [];
477
+ for (const values of records) {
478
+ const filterByTk = values[this.model.primaryKeyAttribute];
479
+ if (!filterByTk) {
480
+ throw new Error("filterByTk invalid");
481
+ }
482
+ const instance = await this.update({ values, filterByTk, transaction: transaction2 });
483
+ instances.push(instance);
484
+ }
485
+ return instances;
486
+ }
487
+ async destroy(options) {
488
+ const transaction2 = await this.getTransaction(options);
489
+ const modelFilterKey = this.collection.filterTargetKey;
490
+ options = options;
491
+ if (options["individualHooks"] === void 0) {
492
+ options["individualHooks"] = true;
493
+ }
494
+ const filterByTk = options.filterByTk && !import_lodash.default.isArray(options.filterByTk) ? [options.filterByTk] : options.filterByTk;
495
+ if (this.collection.model.primaryKeyAttributes.length !== 1 && filterByTk && !import_lodash.default.get(this.collection.options, "filterTargetKey")) {
496
+ if (this.collection.model.primaryKeyAttributes.length > 1) {
497
+ throw new Error(`filterByTk is not supported for composite primary key`);
498
+ } else {
499
+ throw new Error(`filterByTk is not supported for collection that has no primary key`);
500
+ }
501
+ }
502
+ if (filterByTk && !options.filter) {
503
+ return await this.model.destroy({
504
+ ...options,
505
+ where: {
506
+ [modelFilterKey]: {
507
+ [import_sequelize.Op.in]: filterByTk
508
+ }
509
+ },
510
+ transaction: transaction2
511
+ });
512
+ }
513
+ if (options.filter) {
514
+ if (this.collection.model.primaryKeyAttributes.length !== 1 && !import_lodash.default.get(this.collection.options, "filterTargetKey")) {
515
+ const queryOptions = {
516
+ ...this.buildQueryOptions(options)
517
+ };
518
+ return await this.model.destroy({
519
+ ...queryOptions,
520
+ transaction: transaction2
521
+ });
522
+ }
523
+ let pks = (await this.find({
524
+ filter: options.filter,
525
+ transaction: transaction2
526
+ })).map((instance) => instance.get(modelFilterKey));
527
+ if (filterByTk) {
528
+ pks = import_lodash.default.intersection(
529
+ pks.map((i) => `${i}`),
530
+ filterByTk.map((i) => `${i}`)
531
+ );
532
+ }
533
+ return await this.destroy({
534
+ ...import_lodash.default.omit(options, "filter"),
535
+ filterByTk: pks,
536
+ transaction: transaction2
537
+ });
538
+ }
539
+ if (options.truncate) {
540
+ return await this.model.destroy({
541
+ ...options,
542
+ truncate: true,
543
+ transaction: transaction2
544
+ });
545
+ }
546
+ }
547
+ /**
548
+ * @param association target association
549
+ */
550
+ relation(association) {
551
+ return new RelationRepositoryBuilder(this.collection, association);
552
+ }
553
+ buildQueryOptions(options) {
554
+ const parser = new import_options_parser.OptionsParser(options, {
555
+ collection: this.collection
556
+ });
557
+ const params = parser.toSequelizeParams();
558
+ debug("sequelize query params %o", params);
559
+ if (options.where && params.where) {
560
+ params.where = {
561
+ [import_sequelize.Op.and]: [params.where, options.where]
562
+ };
563
+ }
564
+ return { where: {}, ...options, ...params };
565
+ }
566
+ parseFilter(filter, options) {
567
+ const parser = new import_filter_parser.default(filter, {
568
+ collection: this.collection,
569
+ app: {
570
+ ctx: options == null ? void 0 : options.context
571
+ }
572
+ });
573
+ return parser.toSequelizeParams();
574
+ }
575
+ async getTransaction(options, autoGen = false) {
576
+ if (import_lodash.default.isPlainObject(options) && options.transaction) {
577
+ return options.transaction;
578
+ }
579
+ if (autoGen) {
580
+ return await this.model.sequelize.transaction();
581
+ }
582
+ return null;
583
+ }
584
+ };
585
+ _init = __decoratorStart(null);
586
+ __decorateElement(_init, 1, "create", _create_dec, _Repository);
587
+ __decorateElement(_init, 1, "createMany", _createMany_dec, _Repository);
588
+ __decorateElement(_init, 1, "update", _update_dec, _Repository);
589
+ __decorateElement(_init, 1, "updateMany", _updateMany_dec, _Repository);
590
+ __decorateElement(_init, 1, "destroy", _destroy_dec, _Repository);
591
+ __decoratorMetadata(_init, _Repository);
592
+ __name(_Repository, "Repository");
593
+ let Repository = _Repository;
594
+ // Annotate the CommonJS export names for ESM import in node:
595
+ 0 && (module.exports = {
596
+ Repository
597
+ });
@@ -0,0 +1,2 @@
1
+ export * from './sql-model';
2
+ export * from './sql-collection';
@@ -0,0 +1,23 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var sql_collection_exports = {};
16
+ module.exports = __toCommonJS(sql_collection_exports);
17
+ __reExport(sql_collection_exports, require("./sql-model"), module.exports);
18
+ __reExport(sql_collection_exports, require("./sql-collection"), module.exports);
19
+ // Annotate the CommonJS export names for ESM import in node:
20
+ 0 && (module.exports = {
21
+ ...require("./sql-model"),
22
+ ...require("./sql-collection")
23
+ });
@@ -0,0 +1,10 @@
1
+ import { GroupOption, Order, ProjectionAlias, WhereOptions } from 'sequelize';
2
+ import { SQLModel } from './sql-model';
3
+ export declare function selectQuery(tableName: string, options: {
4
+ attributes?: (string | ProjectionAlias)[];
5
+ where?: WhereOptions;
6
+ order?: Order;
7
+ group?: GroupOption;
8
+ limit?: number;
9
+ offset?: number;
10
+ }, model: SQLModel): string;