@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,332 @@
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var options_parser_exports = {};
30
+ __export(options_parser_exports, {
31
+ OptionsParser: () => OptionsParser
32
+ });
33
+ module.exports = __toCommonJS(options_parser_exports);
34
+ var import_lodash = __toESM(require("lodash"));
35
+ var import_qs = __toESM(require("qs"));
36
+ var import_sequelize = require("sequelize");
37
+ var import_filter_parser = __toESM(require("./filter-parser"));
38
+ const debug = require("debug")("noco-database");
39
+ const _OptionsParser = class _OptionsParser {
40
+ options;
41
+ database;
42
+ collection;
43
+ model;
44
+ filterParser;
45
+ context;
46
+ constructor(options, context) {
47
+ const { collection } = context;
48
+ this.collection = collection;
49
+ this.model = collection.model;
50
+ this.options = options;
51
+ this.database = collection.context.database;
52
+ this.filterParser = new import_filter_parser.default(options == null ? void 0 : options.filter, {
53
+ collection,
54
+ app: {
55
+ ctx: options == null ? void 0 : options.context
56
+ }
57
+ });
58
+ this.context = context;
59
+ }
60
+ static appendInheritInspectAttribute(include, collection) {
61
+ if (include.find((item) => (item == null ? void 0 : item[1]) === "__tableName")) {
62
+ return;
63
+ }
64
+ include.push([
65
+ import_sequelize.Sequelize.literal(`(select relname from pg_class where pg_class.oid = "${collection.name}".tableoid)`),
66
+ "__tableName"
67
+ ]);
68
+ include.push([
69
+ import_sequelize.Sequelize.literal(`
70
+ (SELECT n.nspname
71
+ FROM pg_class c
72
+ JOIN pg_namespace n ON n.oid = c.relnamespace
73
+ WHERE c.oid = "${collection.name}".tableoid)
74
+ `),
75
+ "__schemaName"
76
+ ]);
77
+ }
78
+ isAssociation(key) {
79
+ return this.model.associations[key] !== void 0;
80
+ }
81
+ isAssociationPath(path) {
82
+ return this.isAssociation(path.split(".")[0]);
83
+ }
84
+ toSequelizeParams() {
85
+ var _a, _b;
86
+ const queryParams = this.filterParser.toSequelizeParams();
87
+ if ((_a = this.options) == null ? void 0 : _a.filterByTk) {
88
+ queryParams.where = {
89
+ [import_sequelize.Op.and]: [
90
+ queryParams.where,
91
+ {
92
+ [this.context.targetKey || this.collection.filterTargetKey]: this.options.filterByTk
93
+ }
94
+ ]
95
+ };
96
+ }
97
+ if ((_b = this.options) == null ? void 0 : _b.include) {
98
+ if (!queryParams.include) {
99
+ queryParams.include = [];
100
+ }
101
+ queryParams.include.push(...import_lodash.default.castArray(this.options.include));
102
+ }
103
+ return this.parseSort(this.parseFields(queryParams));
104
+ }
105
+ /**
106
+ * parser sort options
107
+ * @param filterParams
108
+ * @protected
109
+ */
110
+ parseSort(filterParams) {
111
+ var _a;
112
+ let sort = ((_a = this.options) == null ? void 0 : _a.sort) || [];
113
+ if (typeof sort === "string") {
114
+ sort = sort.split(",");
115
+ }
116
+ const orderParams = [];
117
+ for (const sortKey of sort) {
118
+ let direction = sortKey.startsWith("-") ? "DESC" : "ASC";
119
+ const sortField = sortKey.replace("-", "").split(".");
120
+ if (this.database.inDialect("postgres", "sqlite")) {
121
+ direction = `${direction} NULLS LAST`;
122
+ }
123
+ if (sortField.length > 1) {
124
+ let associationModel = this.model;
125
+ for (let i = 0; i < sortField.length - 1; i++) {
126
+ const associationKey = sortField[i];
127
+ sortField[i] = associationModel.associations[associationKey].target;
128
+ associationModel = sortField[i];
129
+ }
130
+ } else {
131
+ const rawField = this.model.rawAttributes[sortField[0]];
132
+ sortField[0] = (rawField == null ? void 0 : rawField.field) || sortField[0];
133
+ }
134
+ sortField.push(direction);
135
+ if (this.database.isMySQLCompatibleDialect()) {
136
+ orderParams.push([import_sequelize.Sequelize.fn("ISNULL", import_sequelize.Sequelize.col(`${this.model.name}.${sortField[0]}`))]);
137
+ }
138
+ orderParams.push(sortField);
139
+ }
140
+ if (orderParams.length > 0) {
141
+ return {
142
+ order: orderParams,
143
+ ...filterParams
144
+ };
145
+ }
146
+ return filterParams;
147
+ }
148
+ parseFields(filterParams) {
149
+ var _a, _b, _c, _d;
150
+ const appends = ((_a = this.options) == null ? void 0 : _a.appends) || [];
151
+ const except = [];
152
+ if ((_b = this.options) == null ? void 0 : _b.attributes) {
153
+ return {
154
+ attributes: this.options.attributes
155
+ };
156
+ }
157
+ let attributes = {
158
+ include: [],
159
+ exclude: []
160
+ };
161
+ if (this.collection.isParent()) {
162
+ _OptionsParser.appendInheritInspectAttribute(attributes.include, this.collection);
163
+ }
164
+ if ((_c = this.options) == null ? void 0 : _c.fields) {
165
+ attributes = [];
166
+ if (this.collection.isParent()) {
167
+ _OptionsParser.appendInheritInspectAttribute(attributes, this.collection);
168
+ }
169
+ for (const field of this.options.fields) {
170
+ if (this.isAssociationPath(field)) {
171
+ appends.push(field);
172
+ } else {
173
+ attributes.push(field);
174
+ }
175
+ }
176
+ }
177
+ if ((_d = this.options) == null ? void 0 : _d.except) {
178
+ for (const exceptKey of this.options.except) {
179
+ if (this.isAssociationPath(exceptKey)) {
180
+ except.push(exceptKey);
181
+ } else {
182
+ if (Array.isArray(attributes)) continue;
183
+ attributes.exclude.push(exceptKey);
184
+ }
185
+ }
186
+ }
187
+ return {
188
+ attributes,
189
+ ...this.parseExcept(except, this.parseAppends(appends, filterParams))
190
+ };
191
+ }
192
+ parseExcept(except, filterParams) {
193
+ if (!except) return filterParams;
194
+ const setExcept = /* @__PURE__ */ __name((queryParams, except2) => {
195
+ const exceptPath = except2.split(".");
196
+ const association = exceptPath[0];
197
+ const lastLevel = exceptPath.length <= 2;
198
+ const existIncludeIndex = queryParams["include"].findIndex((include) => include["association"] == association);
199
+ if (existIncludeIndex == -1) {
200
+ return;
201
+ }
202
+ if (lastLevel) {
203
+ if (Array.isArray(queryParams["include"][existIncludeIndex]["attributes"])) {
204
+ return;
205
+ } else {
206
+ if (!queryParams["include"][existIncludeIndex]["attributes"]["exclude"]) {
207
+ queryParams["include"][existIncludeIndex]["attributes"]["exclude"] = [];
208
+ }
209
+ queryParams["include"][existIncludeIndex]["attributes"]["exclude"].push(exceptPath[1]);
210
+ }
211
+ } else {
212
+ setExcept(queryParams["include"][existIncludeIndex], exceptPath.filter((_, index) => index !== 0).join("."));
213
+ }
214
+ }, "setExcept");
215
+ for (const exceptKey of except) {
216
+ setExcept(filterParams, exceptKey);
217
+ }
218
+ return filterParams;
219
+ }
220
+ parseAppendWithOptions(append) {
221
+ const parts = append.split("(");
222
+ const obj = {
223
+ name: parts[0]
224
+ };
225
+ if (parts.length > 1) {
226
+ const optionsStr = parts[1].replace(")", "");
227
+ obj.options = import_qs.default.parse(optionsStr);
228
+ obj.raw = `(${optionsStr})`;
229
+ }
230
+ return obj;
231
+ }
232
+ parseAppends(appends, filterParams) {
233
+ if (!appends) return filterParams;
234
+ appends = import_lodash.default.sortBy(appends, (append) => append.split(".").length);
235
+ const setInclude = /* @__PURE__ */ __name((model, queryParams, append) => {
236
+ var _a;
237
+ const appendWithOptions = this.parseAppendWithOptions(append);
238
+ append = appendWithOptions.name;
239
+ const appendFields = append.split(".");
240
+ const appendAssociation = appendFields[0];
241
+ const associations = model.associations;
242
+ let lastLevel = false;
243
+ if (appendFields.length == 1) {
244
+ lastLevel = true;
245
+ }
246
+ if (appendFields.length == 2) {
247
+ const association = associations[appendFields[0]];
248
+ if (!association) {
249
+ throw new Error(`association ${appendFields[0]} in ${model.name} not found`);
250
+ }
251
+ const associationModel = associations[appendFields[0]].target;
252
+ if (associationModel.rawAttributes[appendFields[1]]) {
253
+ lastLevel = true;
254
+ }
255
+ }
256
+ if (queryParams["include"] == void 0) {
257
+ queryParams["include"] = [];
258
+ }
259
+ let existIncludeIndex = queryParams["include"].findIndex(
260
+ (include) => include["association"] == appendAssociation
261
+ );
262
+ if (existIncludeIndex != -1) {
263
+ delete queryParams["include"][existIncludeIndex]["fromFilter"];
264
+ if (Array.isArray(queryParams["include"][existIncludeIndex]["attributes"]) && queryParams["include"][existIncludeIndex]["attributes"].length == 0) {
265
+ queryParams["include"][existIncludeIndex]["attributes"] = {
266
+ include: []
267
+ };
268
+ }
269
+ }
270
+ if (lastLevel && existIncludeIndex != -1 && ((_a = import_lodash.default.get(queryParams, ["include", existIncludeIndex, "attributes", "include"])) == null ? void 0 : _a.length) == 0) {
271
+ return;
272
+ }
273
+ if (existIncludeIndex == -1) {
274
+ queryParams["include"].push({
275
+ association: appendAssociation,
276
+ options: appendWithOptions.options || {}
277
+ });
278
+ existIncludeIndex = queryParams["include"].length - 1;
279
+ }
280
+ if (lastLevel) {
281
+ let attributes = queryParams["include"][existIncludeIndex]["attributes"] || {
282
+ include: []
283
+ // all fields are output by default
284
+ };
285
+ if (appendFields.length == 2) {
286
+ if (!Array.isArray(attributes)) {
287
+ attributes = [];
288
+ }
289
+ const attributeName = appendFields[1];
290
+ attributes.push(attributeName);
291
+ } else {
292
+ if (Array.isArray(attributes) && attributes.length == 0) {
293
+ attributes = {
294
+ include: []
295
+ };
296
+ }
297
+ }
298
+ queryParams["include"][existIncludeIndex] = {
299
+ ...queryParams["include"][existIncludeIndex],
300
+ attributes
301
+ };
302
+ } else {
303
+ const existInclude = queryParams["include"][existIncludeIndex];
304
+ if (existInclude.attributes && Array.isArray(existInclude.attributes) && existInclude.attributes.length == 0) {
305
+ existInclude.attributes = {
306
+ include: []
307
+ };
308
+ }
309
+ let nextAppend = appendFields.filter((_, index) => index !== 0).join(".");
310
+ if (appendWithOptions.raw) {
311
+ nextAppend += appendWithOptions.raw;
312
+ }
313
+ setInclude(
314
+ model.associations[queryParams["include"][existIncludeIndex].association].target,
315
+ queryParams["include"][existIncludeIndex],
316
+ nextAppend
317
+ );
318
+ }
319
+ }, "setInclude");
320
+ for (const append of appends) {
321
+ setInclude(this.model, filterParams, append);
322
+ }
323
+ debug("filter params: %o", filterParams);
324
+ return filterParams;
325
+ }
326
+ };
327
+ __name(_OptionsParser, "OptionsParser");
328
+ let OptionsParser = _OptionsParser;
329
+ // Annotate the CommonJS export names for ESM import in node:
330
+ 0 && (module.exports = {
331
+ OptionsParser
332
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,43 @@
1
+ var import_database = require("./database");
2
+ const db = new import_database.Database({
3
+ dialect: "sqlite",
4
+ dialectModule: require("sqlite3"),
5
+ storage: ":memory:"
6
+ });
7
+ (async () => {
8
+ const User = db.collection({
9
+ name: "users",
10
+ fields: [{ type: "string", name: "name" }]
11
+ });
12
+ const Post = db.collection({
13
+ name: "posts",
14
+ fields: [
15
+ { type: "string", name: "title" },
16
+ {
17
+ type: "belongsTo",
18
+ name: "user"
19
+ }
20
+ ]
21
+ });
22
+ await db.sync();
23
+ const repository = User.repository;
24
+ await repository.createMany({
25
+ records: [
26
+ { name: "u1", posts: [{ title: "u1t1" }] },
27
+ { name: "u2", posts: [{ title: "u2t1" }] },
28
+ { name: "u3", posts: [{ title: "u3t1" }] }
29
+ ]
30
+ });
31
+ const Model = User.model;
32
+ const user = await Model.findOne({
33
+ subQuery: false,
34
+ where: {
35
+ "$posts.title$": "u1t1"
36
+ },
37
+ include: { association: "posts", attributes: [] },
38
+ attributes: {
39
+ include: []
40
+ }
41
+ });
42
+ console.log(user.toJSON());
43
+ })();
@@ -0,0 +1,35 @@
1
+ import { Transaction, Transactionable } from 'sequelize';
2
+ import { Collection } from '../collection';
3
+ import QueryInterface, { TableInfo } from './query-interface';
4
+ export default class MysqlQueryInterface extends QueryInterface {
5
+ constructor(db: any);
6
+ collectionTableExists(collection: Collection, options?: Transactionable): Promise<boolean>;
7
+ listViews(): Promise<[unknown[], unknown]>;
8
+ viewColumnUsage(options: {
9
+ viewName: string;
10
+ schema?: string;
11
+ }): Promise<{
12
+ [view_column_name: string]: {
13
+ column_name: string;
14
+ table_name: string;
15
+ table_schema?: string;
16
+ };
17
+ }>;
18
+ parseSQL(sql: string): any;
19
+ viewDef(viewName: string): Promise<string>;
20
+ showTableDefinition(tableInfo: TableInfo): Promise<any>;
21
+ getAutoIncrementInfo(options: {
22
+ tableInfo: TableInfo;
23
+ fieldName: string;
24
+ }): Promise<{
25
+ seqName?: string;
26
+ currentVal: number;
27
+ }>;
28
+ setAutoIncrementVal(options: {
29
+ tableInfo: TableInfo;
30
+ columnName: string;
31
+ seqName?: string;
32
+ currentVal: number;
33
+ transaction?: Transaction;
34
+ }): Promise<void>;
35
+ }
@@ -0,0 +1,122 @@
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var mysql_query_interface_exports = {};
30
+ __export(mysql_query_interface_exports, {
31
+ default: () => MysqlQueryInterface
32
+ });
33
+ module.exports = __toCommonJS(mysql_query_interface_exports);
34
+ var import_sql_parser = __toESM(require("../sql-parser"));
35
+ var import_query_interface = __toESM(require("./query-interface"));
36
+ const _MysqlQueryInterface = class _MysqlQueryInterface extends import_query_interface.default {
37
+ constructor(db) {
38
+ super(db);
39
+ }
40
+ async collectionTableExists(collection, options) {
41
+ const transaction = options == null ? void 0 : options.transaction;
42
+ const tableName = collection.model.tableName;
43
+ const databaseName = this.db.options.database;
44
+ const sql = `SELECT TABLE_NAME
45
+ FROM INFORMATION_SCHEMA.TABLES
46
+ WHERE TABLE_SCHEMA = '${databaseName}'
47
+ AND TABLE_NAME = '${tableName}'`;
48
+ const results = await this.db.sequelize.query(sql, { type: "SELECT", transaction });
49
+ return results.length > 0;
50
+ }
51
+ async listViews() {
52
+ const sql = `SELECT TABLE_NAME as name, VIEW_DEFINITION as definition
53
+ FROM information_schema.views
54
+ WHERE TABLE_SCHEMA = DATABASE()
55
+ ORDER BY TABLE_NAME;`;
56
+ return await this.db.sequelize.query(sql, { type: "SELECT" });
57
+ }
58
+ async viewColumnUsage(options) {
59
+ try {
60
+ const { ast } = this.parseSQL(await this.viewDef(options.viewName));
61
+ const columns = ast.columns;
62
+ const results = [];
63
+ for (const column of columns) {
64
+ if (column.expr.type === "column_ref") {
65
+ results.push([
66
+ column.as || column.expr.column,
67
+ {
68
+ column_name: column.expr.column,
69
+ table_name: column.expr.table
70
+ }
71
+ ]);
72
+ }
73
+ }
74
+ return Object.fromEntries(results);
75
+ } catch (e) {
76
+ this.db.logger.warn(e);
77
+ return {};
78
+ }
79
+ }
80
+ parseSQL(sql) {
81
+ return import_sql_parser.default.parse(sql);
82
+ }
83
+ async viewDef(viewName) {
84
+ const viewDefinition = await this.db.sequelize.query(`SHOW CREATE VIEW ${viewName}`, { type: "SELECT" });
85
+ const createView = viewDefinition[0]["Create View"];
86
+ const regex = /(?<=AS\s)([\s\S]*)/i;
87
+ const match = createView.match(regex);
88
+ const sql = match[0];
89
+ return sql;
90
+ }
91
+ async showTableDefinition(tableInfo) {
92
+ const { tableName } = tableInfo;
93
+ const sql = `SHOW CREATE TABLE ${tableName}`;
94
+ const results = await this.db.sequelize.query(sql, { type: "SELECT" });
95
+ return results[0]["Create Table"];
96
+ }
97
+ async getAutoIncrementInfo(options) {
98
+ const { tableInfo, fieldName } = options;
99
+ const sql = `SELECT AUTO_INCREMENT as currentVal
100
+ FROM information_schema.tables
101
+ WHERE table_schema = DATABASE()
102
+ AND table_name = '${tableInfo.tableName}';`;
103
+ const results = await this.db.sequelize.query(sql, { type: "SELECT" });
104
+ let currentVal = results[0]["currentVal"];
105
+ if (currentVal === null) {
106
+ const maxSql = `SELECT MAX(${fieldName}) as currentVal
107
+ FROM ${tableInfo.tableName};`;
108
+ const maxResults = await this.db.sequelize.query(maxSql, { type: "SELECT" });
109
+ currentVal = maxResults[0]["currentVal"];
110
+ }
111
+ return {
112
+ currentVal
113
+ };
114
+ }
115
+ async setAutoIncrementVal(options) {
116
+ const { tableInfo, columnName, seqName, currentVal, transaction } = options;
117
+ const sql = `ALTER TABLE ${tableInfo.tableName} AUTO_INCREMENT = ${currentVal};`;
118
+ await this.db.sequelize.query(sql, { transaction });
119
+ }
120
+ };
121
+ __name(_MysqlQueryInterface, "MysqlQueryInterface");
122
+ let MysqlQueryInterface = _MysqlQueryInterface;
@@ -0,0 +1,32 @@
1
+ import { Transaction } from 'sequelize';
2
+ import { Collection } from '../collection';
3
+ import QueryInterface, { TableInfo } from './query-interface';
4
+ export default class PostgresQueryInterface extends QueryInterface {
5
+ constructor(db: any);
6
+ setAutoIncrementVal(options: {
7
+ tableInfo: TableInfo;
8
+ columnName: string;
9
+ seqName?: string;
10
+ currentVal?: number;
11
+ transaction?: Transaction;
12
+ }): Promise<void>;
13
+ getAutoIncrementInfo(options: {
14
+ tableInfo: TableInfo;
15
+ fieldName: string;
16
+ }): Promise<{
17
+ seqName?: string;
18
+ currentVal: number;
19
+ }>;
20
+ collectionTableExists(collection: Collection, options?: any): Promise<any>;
21
+ listViews(): Promise<[unknown[], unknown]>;
22
+ viewDef(viewName: string): Promise<string>;
23
+ parseSQL(sql: string): any;
24
+ viewColumnUsage(options: any): Promise<{
25
+ [view_column_name: string]: {
26
+ column_name: string;
27
+ table_name: string;
28
+ table_schema?: string;
29
+ };
30
+ }>;
31
+ showTableDefinition(tableInfo: TableInfo): Promise<any>;
32
+ }