@abedmurrar/objection 4.0.0-alpha.0 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +103 -67
  2. package/lib/index.mjs +6 -0
  3. package/lib/initialize.js +6 -9
  4. package/lib/model/AjvValidator.js +235 -282
  5. package/lib/model/Model.js +653 -823
  6. package/lib/model/ModifierNotFoundError.js +5 -7
  7. package/lib/model/NotFoundError.js +14 -18
  8. package/lib/model/RelationDoesNotExistError.js +6 -9
  9. package/lib/model/ValidationError.js +33 -41
  10. package/lib/model/Validator.js +15 -21
  11. package/lib/model/getModel.js +1 -3
  12. package/lib/model/graph/ModelGraph.js +44 -64
  13. package/lib/model/graph/ModelGraphBuilder.js +164 -217
  14. package/lib/model/graph/ModelGraphEdge.js +31 -43
  15. package/lib/model/graph/ModelGraphNode.js +192 -231
  16. package/lib/model/inheritModel.js +9 -18
  17. package/lib/model/modelBindKnex.js +48 -62
  18. package/lib/model/modelClone.js +79 -98
  19. package/lib/model/modelColPropMap.js +16 -26
  20. package/lib/model/modelConcurrency.js +24 -0
  21. package/lib/model/modelId.js +44 -49
  22. package/lib/model/modelJsonAttributes.js +56 -76
  23. package/lib/model/modelParseRelations.js +68 -67
  24. package/lib/model/modelQueryProps.js +76 -107
  25. package/lib/model/modelSet.js +92 -112
  26. package/lib/model/modelTableMetadata.js +60 -72
  27. package/lib/model/modelToJson.js +120 -150
  28. package/lib/model/modelUtils.js +30 -37
  29. package/lib/model/modelValidate.js +34 -42
  30. package/lib/model/modelValues.js +78 -91
  31. package/lib/model/modelVisitor.js +22 -29
  32. package/lib/objection.js +42 -67
  33. package/lib/queryBuilder/FunctionBuilder.js +231 -279
  34. package/lib/queryBuilder/InternalOptions.js +19 -24
  35. package/lib/queryBuilder/JoinBuilder.js +116 -149
  36. package/lib/queryBuilder/QueryBuilder.js +1009 -1271
  37. package/lib/queryBuilder/QueryBuilderBase.js +647 -865
  38. package/lib/queryBuilder/QueryBuilderContext.js +14 -21
  39. package/lib/queryBuilder/QueryBuilderContextBase.js +20 -29
  40. package/lib/queryBuilder/QueryBuilderOperationSupport.js +462 -536
  41. package/lib/queryBuilder/QueryBuilderUserContext.js +19 -25
  42. package/lib/queryBuilder/RawBuilder.js +58 -73
  43. package/lib/queryBuilder/ReferenceBuilder.js +232 -270
  44. package/lib/queryBuilder/RelationExpression.js +322 -380
  45. package/lib/queryBuilder/StaticHookArguments.js +94 -106
  46. package/lib/queryBuilder/ValueBuilder.js +100 -112
  47. package/lib/queryBuilder/expressions.js +86 -116
  48. package/lib/queryBuilder/functions/mysql.js +642 -697
  49. package/lib/queryBuilder/graph/GraphAction.js +44 -59
  50. package/lib/queryBuilder/graph/GraphData.js +7 -9
  51. package/lib/queryBuilder/graph/GraphFetcher.js +115 -151
  52. package/lib/queryBuilder/graph/GraphNodeDbExistence.js +114 -152
  53. package/lib/queryBuilder/graph/GraphOperation.js +16 -22
  54. package/lib/queryBuilder/graph/GraphOptions.js +143 -185
  55. package/lib/queryBuilder/graph/GraphUpsert.js +167 -241
  56. package/lib/queryBuilder/graph/delete/GraphDelete.js +8 -13
  57. package/lib/queryBuilder/graph/delete/GraphDeleteAction.js +44 -62
  58. package/lib/queryBuilder/graph/insert/GraphInsert.js +99 -128
  59. package/lib/queryBuilder/graph/insert/GraphInsertAction.js +151 -193
  60. package/lib/queryBuilder/graph/insert/JoinRowGraphInsertAction.js +57 -79
  61. package/lib/queryBuilder/graph/patch/GraphPatch.js +8 -13
  62. package/lib/queryBuilder/graph/patch/GraphPatchAction.js +181 -234
  63. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsert.js +16 -21
  64. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsertAction.js +80 -110
  65. package/lib/queryBuilder/join/JoinResultColumn.js +14 -18
  66. package/lib/queryBuilder/join/JoinResultParser.js +88 -101
  67. package/lib/queryBuilder/join/RelationJoiner.js +205 -288
  68. package/lib/queryBuilder/join/TableNode.js +117 -144
  69. package/lib/queryBuilder/join/TableTree.js +60 -76
  70. package/lib/queryBuilder/join/utils.js +10 -16
  71. package/lib/queryBuilder/operations/DelegateOperation.js +93 -133
  72. package/lib/queryBuilder/operations/DeleteOperation.js +33 -37
  73. package/lib/queryBuilder/operations/FindByIdOperation.js +20 -28
  74. package/lib/queryBuilder/operations/FindByIdsOperation.js +17 -23
  75. package/lib/queryBuilder/operations/FindOperation.js +114 -131
  76. package/lib/queryBuilder/operations/FirstOperation.js +14 -19
  77. package/lib/queryBuilder/operations/FromOperation.js +69 -88
  78. package/lib/queryBuilder/operations/InsertAndFetchOperation.js +28 -39
  79. package/lib/queryBuilder/operations/InsertGraphAndFetchOperation.js +25 -35
  80. package/lib/queryBuilder/operations/InsertGraphOperation.js +77 -98
  81. package/lib/queryBuilder/operations/InsertOperation.js +132 -165
  82. package/lib/queryBuilder/operations/InstanceDeleteOperation.js +27 -36
  83. package/lib/queryBuilder/operations/InstanceFindOperation.js +9 -13
  84. package/lib/queryBuilder/operations/InstanceInsertOperation.js +13 -17
  85. package/lib/queryBuilder/operations/InstanceUpdateOperation.js +32 -46
  86. package/lib/queryBuilder/operations/JoinRelatedOperation.js +66 -86
  87. package/lib/queryBuilder/operations/KnexOperation.js +4 -7
  88. package/lib/queryBuilder/operations/MergeOperation.js +32 -45
  89. package/lib/queryBuilder/operations/ObjectionToKnexConvertingOperation.js +131 -150
  90. package/lib/queryBuilder/operations/OnBuildKnexOperation.js +17 -23
  91. package/lib/queryBuilder/operations/OnBuildOperation.js +17 -23
  92. package/lib/queryBuilder/operations/OnErrorOperation.js +17 -23
  93. package/lib/queryBuilder/operations/QueryBuilderOperation.js +231 -270
  94. package/lib/queryBuilder/operations/RangeOperation.js +30 -40
  95. package/lib/queryBuilder/operations/RelateOperation.js +14 -21
  96. package/lib/queryBuilder/operations/ReturningOperation.js +12 -18
  97. package/lib/queryBuilder/operations/RunAfterOperation.js +17 -23
  98. package/lib/queryBuilder/operations/RunBeforeOperation.js +17 -23
  99. package/lib/queryBuilder/operations/UnrelateOperation.js +12 -17
  100. package/lib/queryBuilder/operations/UpdateAndFetchOperation.js +48 -65
  101. package/lib/queryBuilder/operations/UpdateOperation.js +104 -129
  102. package/lib/queryBuilder/operations/UpsertGraphAndFetchOperation.js +25 -35
  103. package/lib/queryBuilder/operations/UpsertGraphOperation.js +36 -55
  104. package/lib/queryBuilder/operations/WhereCompositeOperation.js +30 -39
  105. package/lib/queryBuilder/operations/WhereInOperation.js +34 -36
  106. package/lib/queryBuilder/operations/eager/EagerOperation.js +37 -52
  107. package/lib/queryBuilder/operations/eager/JoinEagerOperation.js +34 -44
  108. package/lib/queryBuilder/operations/eager/NaiveEagerOperation.js +4 -7
  109. package/lib/queryBuilder/operations/eager/WhereInEagerOperation.js +193 -251
  110. package/lib/queryBuilder/operations/jsonApi/WhereJsonHasOperation.js +18 -25
  111. package/lib/queryBuilder/operations/jsonApi/WhereJsonNotObjectOperation.js +25 -41
  112. package/lib/queryBuilder/operations/jsonApi/WhereJsonOperation.js +19 -20
  113. package/lib/queryBuilder/operations/jsonApi/WhereJsonOverlapsOperation.js +23 -21
  114. package/lib/queryBuilder/operations/jsonApi/mysqlJsonApi.js +106 -118
  115. package/lib/queryBuilder/operations/jsonApi/postgresJsonApi.js +79 -108
  116. package/lib/queryBuilder/operations/select/SelectOperation.js +37 -53
  117. package/lib/queryBuilder/operations/select/Selection.js +94 -105
  118. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeMsSqlOperation.js +68 -101
  119. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeOperation.js +65 -75
  120. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeSqliteOperation.js +75 -84
  121. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.js +760 -859
  122. package/lib/queryBuilder/parsers/relationExpressionParser.js +840 -952
  123. package/lib/queryBuilder/transformations/CompositeQueryTransformation.js +10 -15
  124. package/lib/queryBuilder/transformations/QueryTransformation.js +4 -6
  125. package/lib/queryBuilder/transformations/WrapMysqlModifySubqueryTransformation.js +35 -49
  126. package/lib/queryBuilder/transformations/index.js +3 -9
  127. package/lib/queryBuilder/whereScopes.js +158 -186
  128. package/lib/relations/Relation.js +293 -375
  129. package/lib/relations/RelationDeleteOperation.js +24 -28
  130. package/lib/relations/RelationFindOperation.js +108 -138
  131. package/lib/relations/RelationInsertOperation.js +24 -32
  132. package/lib/relations/RelationOwner.js +175 -209
  133. package/lib/relations/RelationProperty.js +186 -223
  134. package/lib/relations/RelationUpdateOperation.js +23 -29
  135. package/lib/relations/belongsToOne/BelongsToOneDeleteOperation.js +16 -21
  136. package/lib/relations/belongsToOne/BelongsToOneInsertOperation.js +30 -41
  137. package/lib/relations/belongsToOne/BelongsToOneRelateOperation.js +36 -47
  138. package/lib/relations/belongsToOne/BelongsToOneRelation.js +42 -50
  139. package/lib/relations/belongsToOne/BelongsToOneUnrelateOperation.js +43 -58
  140. package/lib/relations/hasMany/HasManyInsertOperation.js +40 -56
  141. package/lib/relations/hasMany/HasManyRelateOperation.js +45 -61
  142. package/lib/relations/hasMany/HasManyRelation.js +38 -46
  143. package/lib/relations/hasMany/HasManyUnrelateOperation.js +25 -32
  144. package/lib/relations/hasOne/HasOneRelation.js +9 -12
  145. package/lib/relations/hasOneThrough/HasOneThroughRelation.js +9 -12
  146. package/lib/relations/manyToMany/ManyToManyModifyMixin.js +73 -95
  147. package/lib/relations/manyToMany/ManyToManyRelation.js +374 -473
  148. package/lib/relations/manyToMany/ManyToManySqliteModifyMixin.js +23 -30
  149. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperation.js +8 -10
  150. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperationBase.js +20 -25
  151. package/lib/relations/manyToMany/delete/ManyToManyDeleteSqliteOperation.js +8 -12
  152. package/lib/relations/manyToMany/find/ManyToManyFindOperation.js +77 -100
  153. package/lib/relations/manyToMany/insert/ManyToManyInsertOperation.js +37 -49
  154. package/lib/relations/manyToMany/relate/ManyToManyRelateOperation.js +58 -74
  155. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperation.js +10 -13
  156. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperationBase.js +26 -33
  157. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateSqliteOperation.js +10 -15
  158. package/lib/relations/manyToMany/update/ManyToManyUpdateOperation.js +8 -10
  159. package/lib/relations/manyToMany/update/ManyToManyUpdateOperationBase.js +61 -78
  160. package/lib/relations/manyToMany/update/ManyToManyUpdateSqliteOperation.js +8 -12
  161. package/lib/transaction.js +53 -83
  162. package/lib/utils/assert.js +15 -21
  163. package/lib/utils/buildUtils.js +17 -19
  164. package/lib/utils/classUtils.js +7 -11
  165. package/lib/utils/cloneDeep.js +365 -0
  166. package/lib/utils/createModifier.js +36 -41
  167. package/lib/utils/deprecate.js +8 -12
  168. package/lib/utils/identifierMapping.js +153 -192
  169. package/lib/utils/internalPropUtils.js +4 -8
  170. package/lib/utils/knexUtils.js +61 -56
  171. package/lib/utils/mixin.js +16 -23
  172. package/lib/utils/mysqlJsonPath.js +55 -40
  173. package/lib/utils/normalizeIds.js +110 -127
  174. package/lib/utils/objectUtils.js +236 -338
  175. package/lib/utils/parseFieldExpression.js +66 -44
  176. package/lib/utils/postgresJsonPath.js +48 -62
  177. package/lib/utils/promiseUtils/after.js +10 -13
  178. package/lib/utils/promiseUtils/afterReturn.js +10 -13
  179. package/lib/utils/promiseUtils/index.js +15 -17
  180. package/lib/utils/promiseUtils/isPromise.js +6 -9
  181. package/lib/utils/promiseUtils/map.js +75 -89
  182. package/lib/utils/promiseUtils/mapAfterAllReturn.js +17 -23
  183. package/lib/utils/promiseUtils/try.js +15 -18
  184. package/lib/utils/resolveModel.js +91 -94
  185. package/lib/utils/tmpColumnUtils.js +4 -13
  186. package/package.json +50 -23
  187. package/typings/objection/index.d.mts +362 -0
  188. package/typings/objection/index.d.ts +36 -9
  189. package/lib/.eslintrc.json +0 -8
  190. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.pegjs +0 -97
  191. package/lib/queryBuilder/parsers/relationExpressionParser.pegjs +0 -141
  192. package/lib/utils/clone.js +0 -2329
@@ -1,31 +1,24 @@
1
1
  'use strict';
2
-
3
2
  const { withWhereScope } = require('./whereScopes');
4
3
  const { wrapError } = require('db-errors');
5
-
6
4
  const { raw } = require('./RawBuilder');
7
5
  const { createModifier } = require('../utils/createModifier');
8
6
  const { ValidationErrorType } = require('../model/ValidationError');
9
7
  const { isObject, isString, isFunction, last, flatten } = require('../utils/objectUtils');
10
8
  const { RelationExpression, DuplicateRelationError } = require('./RelationExpression');
11
9
  const { assertIdNotUndefined } = require('../utils/assert');
12
-
13
10
  const { Selection } = require('./operations/select/Selection');
14
-
15
11
  const { QueryBuilderContext } = require('./QueryBuilderContext');
16
12
  const { QueryBuilderBase } = require('./QueryBuilderBase');
17
-
18
13
  const { FindOperation } = require('./operations/FindOperation');
19
14
  const { DeleteOperation } = require('./operations/DeleteOperation');
20
15
  const { UpdateOperation } = require('./operations/UpdateOperation');
21
16
  const { InsertOperation } = require('./operations/InsertOperation');
22
17
  const { RelateOperation } = require('./operations/RelateOperation');
23
18
  const { UnrelateOperation } = require('./operations/UnrelateOperation');
24
-
25
19
  const { JoinEagerOperation } = require('./operations/eager/JoinEagerOperation');
26
20
  const { NaiveEagerOperation } = require('./operations/eager/NaiveEagerOperation');
27
21
  const { WhereInEagerOperation } = require('./operations/eager/WhereInEagerOperation');
28
-
29
22
  const { InsertGraphAndFetchOperation } = require('./operations/InsertGraphAndFetchOperation');
30
23
  const { UpsertGraphAndFetchOperation } = require('./operations/UpsertGraphAndFetchOperation');
31
24
  const { InsertAndFetchOperation } = require('./operations/InsertAndFetchOperation');
@@ -46,1353 +39,1098 @@ const { RangeOperation } = require('./operations/RangeOperation');
46
39
  const { FirstOperation } = require('./operations/FirstOperation');
47
40
  const { FromOperation } = require('./operations/FromOperation');
48
41
  const { KnexOperation } = require('./operations/KnexOperation');
49
-
50
42
  class QueryBuilder extends QueryBuilderBase {
51
- static init(self, modelClass) {
52
- super.init(self, modelClass);
53
-
54
- self._resultModelClass = null;
55
- self._explicitRejectValue = null;
56
- self._explicitResolveValue = null;
57
- self._modifiers = {};
58
-
59
- self._allowedGraphExpression = null;
60
- self._findOperationOptions = modelClass.defaultFindOptions;
61
- self._relatedQueryFor = null;
62
- self._isRelatedQuery = false;
63
- self._forError = null;
64
-
65
- self._findOperationFactory = findOperationFactory;
66
- self._insertOperationFactory = insertOperationFactory;
67
- self._updateOperationFactory = updateOperationFactory;
68
- self._patchOperationFactory = patchOperationFactory;
69
- self._relateOperationFactory = relateOperationFactory;
70
- self._unrelateOperationFactory = unrelateOperationFactory;
71
- self._deleteOperationFactory = deleteOperationFactory;
72
- }
73
-
74
- static get QueryBuilderContext() {
75
- return QueryBuilderContext;
76
- }
77
-
78
- static parseRelationExpression(expr) {
79
- return RelationExpression.create(expr).toPojo();
80
- }
81
-
82
- tableName(newTableName) {
83
- return this.tableNameFor(this.modelClass().getTableName(), newTableName);
84
- }
85
-
86
- tableRef() {
87
- return this.tableRefFor(this.modelClass().getTableName());
88
- }
89
-
90
- alias(alias) {
91
- return this.aliasFor(this.modelClass().getTableName(), alias);
92
- }
93
-
94
- fullIdColumnFor(modelClass) {
95
- const tableName = this.tableRefFor(modelClass);
96
- const idColumn = modelClass.getIdColumn();
97
-
98
- if (Array.isArray(idColumn)) {
99
- return idColumn.map((col) => `${tableName}.${col}`);
100
- } else {
101
- return `${tableName}.${idColumn}`;
102
- }
103
- }
104
-
105
- fullIdColumn() {
106
- return this.fullIdColumnFor(this.modelClass());
107
- }
108
-
109
- modifiers(modifiers) {
110
- if (arguments.length === 0) {
111
- return { ...this._modifiers };
112
- } else {
113
- this._modifiers = { ...this._modifiers, ...modifiers };
114
- return this;
115
- }
116
- }
117
-
118
- modify(modifier, ...args) {
119
- if (!modifier) {
120
- return this;
121
- }
122
-
123
- modifier = createModifier({
124
- modifier,
125
- modelClass: this.modelClass(),
126
- modifiers: this._modifiers,
127
- });
128
-
129
- modifier(this, ...args);
130
- return this;
131
- }
132
-
133
- reject(error) {
134
- this._explicitRejectValue = error;
135
- return this;
136
- }
137
-
138
- resolve(value) {
139
- this._explicitResolveValue = value;
140
- return this;
141
- }
142
-
143
- isExplicitlyResolvedOrRejected() {
144
- return !!(this._explicitRejectValue || this._explicitResolveValue);
145
- }
146
-
147
- isExecutable() {
148
- return !this.isExplicitlyResolvedOrRejected() && !findQueryExecutorOperation(this);
149
- }
150
-
151
- findOperationFactory(factory) {
152
- this._findOperationFactory = factory;
153
- return this;
154
- }
155
-
156
- insertOperationFactory(factory) {
157
- this._insertOperationFactory = factory;
158
- return this;
159
- }
160
-
161
- updateOperationFactory(factory) {
162
- this._updateOperationFactory = factory;
163
- return this;
164
- }
165
-
166
- patchOperationFactory(factory) {
167
- this._patchOperationFactory = factory;
168
- return this;
169
- }
170
-
171
- deleteOperationFactory(factory) {
172
- this._deleteOperationFactory = factory;
173
- return this;
174
- }
175
-
176
- relateOperationFactory(factory) {
177
- this._relateOperationFactory = factory;
178
- return this;
179
- }
180
-
181
- unrelateOperationFactory(factory) {
182
- this._unrelateOperationFactory = factory;
183
- return this;
184
- }
185
-
186
- withGraphFetched(exp, options = {}) {
187
- return this._withGraph(exp, options, getWhereInEagerAlgorithm(this));
188
- }
189
-
190
- withGraphJoined(exp, options = {}) {
191
- return this._withGraph(exp, options, getJoinEagerAlgorithm(this));
192
- }
193
-
194
- _withGraph(exp, options, algorithm) {
195
- const eagerOp = ensureEagerOperation(this, algorithm);
196
- const parsedExp = parseRelationExpression(this.modelClass(), exp);
197
-
198
- eagerOp.expression = eagerOp.expression.merge(parsedExp);
199
- eagerOp.graphOptions = { ...eagerOp.graphOptions, ...options };
200
-
201
- checkEager(this);
202
- return this;
203
- }
204
-
205
- allowGraph(exp) {
206
- const currentExpr = this._allowedGraphExpression || RelationExpression.create();
207
-
208
- this._allowedGraphExpression = currentExpr.merge(
209
- parseRelationExpression(this.modelClass(), exp),
210
- );
211
-
212
- checkEager(this);
213
- return this;
214
- }
215
-
216
- allowedGraphExpression() {
217
- return this._allowedGraphExpression;
218
- }
219
-
220
- graphExpressionObject() {
221
- const eagerOp = this.findOperation(EagerOperation);
222
-
223
- if (eagerOp && !eagerOp.expression.isEmpty) {
224
- return eagerOp.expression.toPojo();
225
- } else {
226
- return null;
227
- }
228
- }
229
-
230
- graphModifiersAtPath() {
231
- const eagerOp = this.findOperation(EagerOperation);
232
-
233
- if (eagerOp && !eagerOp.expression.isEmpty) {
234
- return eagerOp.modifiersAtPath.map((it) => Object.assign({}, it));
235
- } else {
236
- return [];
237
- }
238
- }
239
-
240
- modifyGraph(path, modifier) {
241
- const eagerOp = ensureEagerOperation(this);
242
- eagerOp.modifiersAtPath.push({ path, modifier });
243
- return this;
244
- }
245
-
246
- findOptions(opt) {
247
- if (arguments.length !== 0) {
248
- this._findOperationOptions = Object.assign({}, this._findOperationOptions, opt);
249
- return this;
250
- } else {
251
- return this._findOperationOptions;
252
- }
253
- }
254
-
255
- resultModelClass() {
256
- return this._resultModelClass || this.modelClass();
257
- }
258
-
259
- isFind() {
260
- return !(
261
- this.isInsert() ||
262
- this.isUpdate() ||
263
- this.isDelete() ||
264
- this.isRelate() ||
265
- this.isUnrelate()
266
- );
267
- }
268
-
269
- isInsert() {
270
- return this.has(InsertOperation);
271
- }
272
-
273
- isUpdate() {
274
- return this.has(UpdateOperation);
275
- }
276
-
277
- isDelete() {
278
- return this.has(DeleteOperation);
279
- }
280
-
281
- isRelate() {
282
- return this.has(RelateOperation);
283
- }
284
-
285
- isUnrelate() {
286
- return this.has(UnrelateOperation);
287
- }
288
-
289
- hasWheres() {
290
- const queryWithoutGraph = this.clone().clearWithGraph();
291
- return prebuildQuery(queryWithoutGraph).has(QueryBuilderBase.WhereSelector);
292
- }
293
-
294
- hasSelects() {
295
- return this.has(QueryBuilderBase.SelectSelector);
296
- }
297
-
298
- hasWithGraph() {
299
- const eagerOp = this.findOperation(EagerOperation);
300
- return !!eagerOp && !eagerOp.expression.isEmpty;
301
- }
302
-
303
- isSelectAll() {
304
- if (this._operations.length === 0) {
305
- return true;
306
- }
307
-
308
- const tableRef = this.tableRef();
309
- const tableName = this.tableName();
310
-
311
- return this.everyOperation((op) => {
312
- if (op.constructor === SelectOperation) {
313
- // SelectOperations with zero selections are the ones that only have
314
- // raw items or other non-trivial selections.
315
- return (
316
- op.selections.length > 0 &&
317
- op.selections.every((select) => {
318
- return (!select.table || select.table === tableRef) && select.column === '*';
319
- })
320
- );
321
- } else if (op.constructor === FromOperation) {
322
- return op.table === tableName;
323
- } else if (op.name === 'as' || op.is(FindOperation) || op.is(OnErrorOperation)) {
324
- return true;
325
- } else {
326
- return false;
327
- }
328
- });
329
- }
330
-
331
- toString() {
332
- return '[object QueryBuilder]';
333
- }
334
-
335
- clone() {
336
- const builder = this.emptyInstance();
337
-
338
- // Call the super class's clone implementation.
339
- this.baseCloneInto(builder);
340
-
341
- builder._resultModelClass = this._resultModelClass;
342
-
343
- builder._explicitRejectValue = this._explicitRejectValue;
344
- builder._explicitResolveValue = this._explicitResolveValue;
345
- builder._modifiers = { ...this._modifiers };
346
-
347
- builder._allowedGraphExpression = this._allowedGraphExpression;
348
- builder._findOperationOptions = this._findOperationOptions;
349
- builder._relatedQueryFor = this._relatedQueryFor;
350
-
351
- return builder;
352
- }
353
-
354
- emptyInstance() {
355
- const builder = new this.constructor(this.modelClass());
356
-
357
- builder._findOperationFactory = this._findOperationFactory;
358
- builder._insertOperationFactory = this._insertOperationFactory;
359
- builder._updateOperationFactory = this._updateOperationFactory;
360
- builder._patchOperationFactory = this._patchOperationFactory;
361
- builder._relateOperationFactory = this._relateOperationFactory;
362
- builder._unrelateOperationFactory = this._unrelateOperationFactory;
363
- builder._deleteOperationFactory = this._deleteOperationFactory;
364
- builder._relatedQueryFor = this._relatedQueryFor;
365
- builder._isRelatedQuery = this._isRelatedQuery;
366
- builder._forError = this._forError;
367
-
368
- return builder;
369
- }
370
-
371
- clearWithGraph() {
372
- this.clear(EagerOperation);
373
- return this;
374
- }
375
-
376
- clearWithGraphFetched() {
377
- this.clear(WhereInEagerOperation);
378
- return this;
379
- }
380
-
381
- clearAllowGraph() {
382
- this._allowedGraphExpression = null;
383
- return this;
384
- }
385
-
386
- clearModifiers() {
387
- this._modifiers = {};
388
- return this;
389
- }
390
-
391
- clearReject() {
392
- this._explicitRejectValue = null;
393
- return this;
394
- }
395
-
396
- clearResolve() {
397
- this._explicitResolveValue = null;
398
- return this;
399
- }
400
-
401
- castTo(modelClass) {
402
- this._resultModelClass = modelClass || null;
403
- return this;
404
- }
405
-
406
- then(...args) {
407
- const promise = this.execute();
408
- return promise.then(...args);
409
- }
410
-
411
- catch(...args) {
412
- const promise = this.execute();
413
- return promise.catch(...args);
414
- }
415
-
416
- async resultSize() {
417
- const knex = this.knex();
418
- const builder = this.clone().clear(/orderBy|offset|limit/);
419
-
420
- const countQuery = knex.count('* as count').from((knexBuilder) => {
421
- builder.toKnexQuery(knexBuilder).as('temp');
422
- });
423
-
424
- if (this.internalOptions().debug) {
425
- countQuery.debug();
426
- }
427
-
428
- const result = await countQuery;
429
- return result[0] && result[0].count ? parseInt(result[0].count) : 0;
430
- }
431
-
432
- toKnexQuery(knexBuilder = this.knex().queryBuilder()) {
433
- const prebuiltQuery = prebuildQuery(this.clone());
434
- return buildKnexQuery(prebuiltQuery, knexBuilder);
435
- }
436
-
437
- async execute() {
438
- // Take a clone so that we don't modify this instance during execution.
439
- const builder = this.clone();
440
-
441
- try {
442
- await beforeExecute(builder);
443
- const result = await doExecute(builder);
444
- return await afterExecute(builder, result);
445
- } catch (error) {
446
- return await handleExecuteError(builder, error);
447
- }
448
- }
449
-
450
- throwIfNotFound(data = {}) {
451
- return this.runAfter((result) => {
452
- if (
453
- (Array.isArray(result) && result.length === 0) ||
454
- result === null ||
455
- result === undefined ||
456
- result === 0
457
- ) {
458
- throw this.modelClass().createNotFoundError(this.context(), data);
459
- } else {
460
- return result;
461
- }
462
- });
463
- }
464
-
465
- findSelection(selection, explicit = false) {
466
- let noSelectStatements = true;
467
- let selectionInstance = null;
468
-
469
- this.forEachOperation(true, (op) => {
470
- if (op.constructor === SelectOperation) {
471
- selectionInstance = op.findSelection(this, selection);
472
- noSelectStatements = false;
473
-
43
+ static init(self, modelClass) {
44
+ super.init(self, modelClass);
45
+ self._resultModelClass = null;
46
+ self._explicitRejectValue = null;
47
+ self._explicitResolveValue = null;
48
+ self._modifiers = {};
49
+ self._allowedGraphExpression = null;
50
+ self._findOperationOptions = modelClass.defaultFindOptions;
51
+ self._relatedQueryFor = null;
52
+ self._isRelatedQuery = false;
53
+ self._forError = null;
54
+ self._findOperationFactory = findOperationFactory;
55
+ self._insertOperationFactory = insertOperationFactory;
56
+ self._updateOperationFactory = updateOperationFactory;
57
+ self._patchOperationFactory = patchOperationFactory;
58
+ self._relateOperationFactory = relateOperationFactory;
59
+ self._unrelateOperationFactory = unrelateOperationFactory;
60
+ self._deleteOperationFactory = deleteOperationFactory;
61
+ }
62
+ static get QueryBuilderContext() {
63
+ return QueryBuilderContext;
64
+ }
65
+ static parseRelationExpression(expr) {
66
+ return RelationExpression.create(expr).toPojo();
67
+ }
68
+ tableName(newTableName) {
69
+ return this.tableNameFor(this.modelClass().getTableName(), newTableName);
70
+ }
71
+ tableRef() {
72
+ return this.tableRefFor(this.modelClass().getTableName());
73
+ }
74
+ alias(alias) {
75
+ return this.aliasFor(this.modelClass().getTableName(), alias);
76
+ }
77
+ fullIdColumnFor(modelClass) {
78
+ const tableName = this.tableRefFor(modelClass);
79
+ const idColumn = modelClass.getIdColumn();
80
+ if (Array.isArray(idColumn)) {
81
+ return idColumn.map((col) => `${tableName}.${col}`);
82
+ }
83
+ else {
84
+ return `${tableName}.${idColumn}`;
85
+ }
86
+ }
87
+ fullIdColumn() {
88
+ return this.fullIdColumnFor(this.modelClass());
89
+ }
90
+ modifiers(modifiers) {
91
+ if (arguments.length === 0) {
92
+ return { ...this._modifiers };
93
+ }
94
+ else {
95
+ this._modifiers = { ...this._modifiers, ...modifiers };
96
+ return this;
97
+ }
98
+ }
99
+ modify(modifier, ...args) {
100
+ if (!modifier) {
101
+ return this;
102
+ }
103
+ modifier = createModifier({
104
+ modifier,
105
+ modelClass: this.modelClass(),
106
+ modifiers: this._modifiers,
107
+ });
108
+ modifier(this, ...args);
109
+ return this;
110
+ }
111
+ reject(error) {
112
+ this._explicitRejectValue = error;
113
+ return this;
114
+ }
115
+ resolve(value) {
116
+ this._explicitResolveValue = value;
117
+ return this;
118
+ }
119
+ isExplicitlyResolvedOrRejected() {
120
+ return !!(this._explicitRejectValue || this._explicitResolveValue);
121
+ }
122
+ isExecutable() {
123
+ return !this.isExplicitlyResolvedOrRejected() && !findQueryExecutorOperation(this);
124
+ }
125
+ findOperationFactory(factory) {
126
+ this._findOperationFactory = factory;
127
+ return this;
128
+ }
129
+ insertOperationFactory(factory) {
130
+ this._insertOperationFactory = factory;
131
+ return this;
132
+ }
133
+ updateOperationFactory(factory) {
134
+ this._updateOperationFactory = factory;
135
+ return this;
136
+ }
137
+ patchOperationFactory(factory) {
138
+ this._patchOperationFactory = factory;
139
+ return this;
140
+ }
141
+ deleteOperationFactory(factory) {
142
+ this._deleteOperationFactory = factory;
143
+ return this;
144
+ }
145
+ relateOperationFactory(factory) {
146
+ this._relateOperationFactory = factory;
147
+ return this;
148
+ }
149
+ unrelateOperationFactory(factory) {
150
+ this._unrelateOperationFactory = factory;
151
+ return this;
152
+ }
153
+ withGraphFetched(exp, options = {}) {
154
+ return this._withGraph(exp, options, getWhereInEagerAlgorithm(this));
155
+ }
156
+ withGraphJoined(exp, options = {}) {
157
+ return this._withGraph(exp, options, getJoinEagerAlgorithm(this));
158
+ }
159
+ _withGraph(exp, options, algorithm) {
160
+ const eagerOp = ensureEagerOperation(this, algorithm);
161
+ const parsedExp = parseRelationExpression(this.modelClass(), exp);
162
+ eagerOp.expression = eagerOp.expression.merge(parsedExp);
163
+ eagerOp.graphOptions = { ...eagerOp.graphOptions, ...options };
164
+ checkEager(this);
165
+ return this;
166
+ }
167
+ allowGraph(exp) {
168
+ const currentExpr = this._allowedGraphExpression || RelationExpression.create();
169
+ this._allowedGraphExpression = currentExpr.merge(parseRelationExpression(this.modelClass(), exp));
170
+ checkEager(this);
171
+ return this;
172
+ }
173
+ allowedGraphExpression() {
174
+ return this._allowedGraphExpression;
175
+ }
176
+ graphExpressionObject() {
177
+ const eagerOp = this.findOperation(EagerOperation);
178
+ if (eagerOp && !eagerOp.expression.isEmpty) {
179
+ return eagerOp.expression.toPojo();
180
+ }
181
+ else {
182
+ return null;
183
+ }
184
+ }
185
+ graphModifiersAtPath() {
186
+ const eagerOp = this.findOperation(EagerOperation);
187
+ if (eagerOp && !eagerOp.expression.isEmpty) {
188
+ return eagerOp.modifiersAtPath.map((it) => Object.assign({}, it));
189
+ }
190
+ else {
191
+ return [];
192
+ }
193
+ }
194
+ modifyGraph(path, modifier) {
195
+ const eagerOp = ensureEagerOperation(this);
196
+ eagerOp.modifiersAtPath.push({ path, modifier });
197
+ return this;
198
+ }
199
+ findOptions(opt) {
200
+ if (arguments.length !== 0) {
201
+ this._findOperationOptions = Object.assign({}, this._findOperationOptions, opt);
202
+ return this;
203
+ }
204
+ else {
205
+ return this._findOperationOptions;
206
+ }
207
+ }
208
+ resultModelClass() {
209
+ return this._resultModelClass || this.modelClass();
210
+ }
211
+ isFind() {
212
+ if (this.isInsert === QueryBuilder.prototype.isInsert &&
213
+ this.isUpdate === QueryBuilder.prototype.isUpdate &&
214
+ this.isDelete === QueryBuilder.prototype.isDelete &&
215
+ this.isRelate === QueryBuilder.prototype.isRelate &&
216
+ this.isUnrelate === QueryBuilder.prototype.isUnrelate) {
217
+ // The same as below in one walk of the operations instead of five.
218
+ return !this.has(isWriteOperation);
219
+ }
220
+ return !(this.isInsert() ||
221
+ this.isUpdate() ||
222
+ this.isDelete() ||
223
+ this.isRelate() ||
224
+ this.isUnrelate());
225
+ }
226
+ isInsert() {
227
+ return this.has(InsertOperation);
228
+ }
229
+ isUpdate() {
230
+ return this.has(UpdateOperation);
231
+ }
232
+ isDelete() {
233
+ return this.has(DeleteOperation);
234
+ }
235
+ isRelate() {
236
+ return this.has(RelateOperation);
237
+ }
238
+ isUnrelate() {
239
+ return this.has(UnrelateOperation);
240
+ }
241
+ hasWheres() {
242
+ const queryWithoutGraph = this.clone().clearWithGraph();
243
+ return prebuildQuery(queryWithoutGraph).has(QueryBuilderBase.WhereSelector);
244
+ }
245
+ hasSelects() {
246
+ return this.has(QueryBuilderBase.SelectSelector);
247
+ }
248
+ hasWithGraph() {
249
+ const eagerOp = this.findOperation(EagerOperation);
250
+ return !!eagerOp && !eagerOp.expression.isEmpty;
251
+ }
252
+ isSelectAll() {
253
+ if (this._operations.length === 0) {
254
+ return true;
255
+ }
256
+ const tableRef = this.tableRef();
257
+ const tableName = this.tableName();
258
+ return this.everyOperation((op) => {
259
+ if (op.constructor === SelectOperation) {
260
+ // SelectOperations with zero selections are the ones that only have
261
+ // raw items or other non-trivial selections.
262
+ return (op.selections.length > 0 &&
263
+ op.selections.every((select) => {
264
+ return (!select.table || select.table === tableRef) && select.column === '*';
265
+ }));
266
+ }
267
+ else if (op.constructor === FromOperation) {
268
+ return op.table === tableName;
269
+ }
270
+ else if (op.name === 'as' || op.is(FindOperation) || op.is(OnErrorOperation)) {
271
+ return true;
272
+ }
273
+ else {
274
+ return false;
275
+ }
276
+ });
277
+ }
278
+ toString() {
279
+ return '[object QueryBuilder]';
280
+ }
281
+ clone() {
282
+ const builder = this.emptyInstance();
283
+ // Call the super class's clone implementation.
284
+ this.baseCloneInto(builder);
285
+ builder._resultModelClass = this._resultModelClass;
286
+ builder._explicitRejectValue = this._explicitRejectValue;
287
+ builder._explicitResolveValue = this._explicitResolveValue;
288
+ builder._modifiers = { ...this._modifiers };
289
+ builder._allowedGraphExpression = this._allowedGraphExpression;
290
+ builder._findOperationOptions = this._findOperationOptions;
291
+ builder._relatedQueryFor = this._relatedQueryFor;
292
+ return builder;
293
+ }
294
+ emptyInstance() {
295
+ const builder = new this.constructor(this.modelClass());
296
+ builder._findOperationFactory = this._findOperationFactory;
297
+ builder._insertOperationFactory = this._insertOperationFactory;
298
+ builder._updateOperationFactory = this._updateOperationFactory;
299
+ builder._patchOperationFactory = this._patchOperationFactory;
300
+ builder._relateOperationFactory = this._relateOperationFactory;
301
+ builder._unrelateOperationFactory = this._unrelateOperationFactory;
302
+ builder._deleteOperationFactory = this._deleteOperationFactory;
303
+ builder._relatedQueryFor = this._relatedQueryFor;
304
+ builder._isRelatedQuery = this._isRelatedQuery;
305
+ builder._forError = this._forError;
306
+ return builder;
307
+ }
308
+ clearWithGraph() {
309
+ this.clear(EagerOperation);
310
+ return this;
311
+ }
312
+ clearWithGraphFetched() {
313
+ this.clear(WhereInEagerOperation);
314
+ return this;
315
+ }
316
+ clearAllowGraph() {
317
+ this._allowedGraphExpression = null;
318
+ return this;
319
+ }
320
+ clearModifiers() {
321
+ this._modifiers = {};
322
+ return this;
323
+ }
324
+ clearReject() {
325
+ this._explicitRejectValue = null;
326
+ return this;
327
+ }
328
+ clearResolve() {
329
+ this._explicitResolveValue = null;
330
+ return this;
331
+ }
332
+ castTo(modelClass) {
333
+ this._resultModelClass = modelClass || null;
334
+ return this;
335
+ }
336
+ then(...args) {
337
+ const promise = this.execute();
338
+ return promise.then(...args);
339
+ }
340
+ catch(...args) {
341
+ const promise = this.execute();
342
+ return promise.catch(...args);
343
+ }
344
+ finally(...args) {
345
+ const promise = this.execute();
346
+ return promise.finally(...args);
347
+ }
348
+ async resultSize() {
349
+ const knex = this.knex();
350
+ const builder = this.clone().clear(/orderBy|offset|limit/);
351
+ const countQuery = knex.count('* as count').from((knexBuilder) => {
352
+ builder.toKnexQuery(knexBuilder).as('temp');
353
+ });
354
+ if (this.internalOptions().debug) {
355
+ countQuery.debug();
356
+ }
357
+ const result = await countQuery;
358
+ return result[0] && result[0].count ? parseInt(result[0].count, 10) : 0;
359
+ }
360
+ toKnexQuery(knexBuilder = this.knex().queryBuilder()) {
361
+ const prebuiltQuery = prebuildQuery(this.clone());
362
+ return buildKnexQuery(prebuiltQuery, knexBuilder);
363
+ }
364
+ async execute() {
365
+ // Take a clone so that we don't modify this instance during execution.
366
+ const builder = this.clone();
367
+ try {
368
+ await beforeExecute(builder);
369
+ const result = await doExecute(builder);
370
+ return await afterExecute(builder, result);
371
+ }
372
+ catch (error) {
373
+ return await handleExecuteError(builder, error);
374
+ }
375
+ }
376
+ throwIfNotFound(data = {}) {
377
+ return this.runAfter((result) => {
378
+ if ((Array.isArray(result) && result.length === 0) ||
379
+ result === null ||
380
+ result === undefined ||
381
+ result === 0) {
382
+ throw this.modelClass().createNotFoundError(this.context(), data);
383
+ }
384
+ else {
385
+ return result;
386
+ }
387
+ });
388
+ }
389
+ findSelection(selection, explicit = false) {
390
+ let noSelectStatements = true;
391
+ let selectionInstance = null;
392
+ this.forEachOperation(true, (op) => {
393
+ if (op.constructor === SelectOperation) {
394
+ selectionInstance = op.findSelection(this, selection);
395
+ noSelectStatements = false;
396
+ if (selectionInstance) {
397
+ return false;
398
+ }
399
+ }
400
+ });
474
401
  if (selectionInstance) {
475
- return false;
402
+ return selectionInstance;
476
403
  }
477
- }
478
- });
479
-
480
- if (selectionInstance) {
481
- return selectionInstance;
482
- }
483
-
484
- if (noSelectStatements && !explicit) {
485
- const selectAll = new Selection(this.tableRef(), '*');
486
-
487
- if (Selection.doesSelect(this, selectAll, selection)) {
488
- return selectAll;
489
- } else {
490
- return null;
491
- }
492
- } else {
493
- return null;
494
- }
495
- }
496
-
497
- findAllSelections() {
498
- let allSelections = [];
499
-
500
- this.forEachOperation(true, (op) => {
501
- if (op.constructor === SelectOperation) {
502
- allSelections = allSelections.concat(op.selections);
503
- }
504
- });
505
-
506
- return allSelections;
507
- }
508
-
509
- hasSelection(selection, explicit) {
510
- return this.findSelection(selection, explicit) !== null;
511
- }
512
-
513
- hasSelectionAs(selection, alias, explicit) {
514
- selection = Selection.create(selection);
515
- const foundSelection = this.findSelection(selection, explicit);
516
-
517
- if (foundSelection === null) {
518
- return false;
519
- } else {
520
- if (foundSelection.column === '*') {
521
- // * selects the columns with their column names as aliases.
522
- return selection.column === alias;
523
- } else {
524
- return foundSelection.name === alias;
525
- }
526
- }
527
- }
528
-
529
- traverse(modelClass, traverser) {
530
- if (typeof traverser === 'undefined') {
531
- traverser = modelClass;
532
- modelClass = null;
533
- }
534
-
535
- return this.runAfter((result) => {
536
- this.resultModelClass().traverse(modelClass, result, traverser);
537
- return result;
538
- });
539
- }
540
-
541
- page(page, pageSize) {
542
- return this.range(+page * +pageSize, (+page + 1) * +pageSize - 1);
543
- }
544
-
545
- columnInfo({ table = null } = {}) {
546
- table = table || this.tableName();
547
-
548
- const knex = this.knex();
549
- const tableParts = table.split('.');
550
- const columnInfoQuery = knex(last(tableParts)).columnInfo();
551
- const schema = this.internalOptions().schema;
552
-
553
- if (schema) {
554
- columnInfoQuery.withSchema(schema);
555
- } else if (tableParts.length > 1) {
556
- columnInfoQuery.withSchema(tableParts[0]);
557
- }
558
-
559
- if (this.internalOptions().debug) {
560
- columnInfoQuery.debug();
561
- }
562
-
563
- return columnInfoQuery;
564
- }
565
-
566
- withSchema(schema) {
567
- this.internalOptions().schema = schema;
568
- this.internalContext().onBuild.push((builder) => {
569
- if (!builder.has(/withSchema/)) {
570
- // Need to push this operation to the front because knex doesn't use the
571
- // schema for operations called before `withSchema`.
572
- builder.addOperationToFront(new KnexOperation('withSchema'), [schema]);
573
- }
574
- });
575
-
576
- return this;
577
- }
578
-
579
- debug /* istanbul ignore next */() {
580
- this.internalOptions().debug = true;
581
- this.internalContext().onBuild.push((builder) => {
582
- builder.addOperation(new KnexOperation('debug'), []);
583
- });
584
-
585
- return this;
586
- }
587
-
588
- insert(modelsOrObjects) {
589
- return writeOperation(this, () => {
590
- const insertOperation = this._insertOperationFactory(this);
591
-
592
- this.addOperation(insertOperation, [modelsOrObjects]);
593
- });
594
- }
595
-
596
- insertAndFetch(modelsOrObjects) {
597
- return writeOperation(this, () => {
598
- const insertOperation = this._insertOperationFactory(this);
599
-
600
- const insertAndFetchOperation = new InsertAndFetchOperation('insertAndFetch', {
601
- delegate: insertOperation,
602
- });
603
-
604
- this.addOperation(insertAndFetchOperation, [modelsOrObjects]);
605
- });
606
- }
607
-
608
- insertGraph(modelsOrObjects, opt) {
609
- return writeOperation(this, () => {
610
- const insertOperation = this._insertOperationFactory(this);
611
-
612
- const insertGraphOperation = new InsertGraphOperation('insertGraph', {
613
- delegate: insertOperation,
614
- opt,
615
- });
616
-
617
- this.addOperation(insertGraphOperation, [modelsOrObjects]);
618
- });
619
- }
620
-
621
- insertGraphAndFetch(modelsOrObjects, opt) {
622
- return writeOperation(this, () => {
623
- const insertOperation = this._insertOperationFactory(this);
624
-
625
- const insertGraphOperation = new InsertGraphOperation('insertGraph', {
626
- delegate: insertOperation,
627
- opt,
628
- });
629
-
630
- const insertGraphAndFetchOperation = new InsertGraphAndFetchOperation('insertGraphAndFetch', {
631
- delegate: insertGraphOperation,
632
- });
633
-
634
- return this.addOperation(insertGraphAndFetchOperation, [modelsOrObjects]);
635
- });
636
- }
637
-
638
- update(modelOrObject) {
639
- return writeOperation(this, () => {
640
- const updateOperation = this._updateOperationFactory(this);
641
-
642
- this.addOperation(updateOperation, [modelOrObject]);
643
- });
644
- }
645
-
646
- updateAndFetch(modelOrObject) {
647
- return writeOperation(this, () => {
648
- const updateOperation = this._updateOperationFactory(this);
649
-
650
- if (!(updateOperation.instance instanceof this.modelClass())) {
651
- throw new Error('updateAndFetch can only be called for instance operations');
652
- }
653
-
654
- const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
655
- delegate: updateOperation,
656
- });
657
-
658
- // patchOperation is an instance update operation that already adds the
659
- // required "where id = $" clause.
660
- updateAndFetch.skipIdWhere = true;
661
-
662
- this.addOperation(updateAndFetch, [updateOperation.instance.$id(), modelOrObject]);
663
- });
664
- }
665
-
666
- updateAndFetchById(id, modelOrObject) {
667
- return writeOperation(this, () => {
668
- const updateOperation = this._updateOperationFactory(this);
669
-
670
- const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
671
- delegate: updateOperation,
672
- });
673
-
674
- this.addOperation(updateAndFetch, [id, modelOrObject]);
675
- });
676
- }
677
-
678
- upsertGraph(modelsOrObjects, upsertOptions) {
679
- return writeOperation(this, () => {
680
- const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
681
- upsertOptions,
682
- });
683
-
684
- this.addOperation(upsertGraphOperation, [modelsOrObjects]);
685
- });
686
- }
687
-
688
- upsertGraphAndFetch(modelsOrObjects, upsertOptions) {
689
- return writeOperation(this, () => {
690
- const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
691
- upsertOptions,
692
- });
693
-
694
- const upsertGraphAndFetchOperation = new UpsertGraphAndFetchOperation('upsertGraphAndFetch', {
695
- delegate: upsertGraphOperation,
696
- });
697
-
698
- return this.addOperation(upsertGraphAndFetchOperation, [modelsOrObjects]);
699
- });
700
- }
701
-
702
- patch(modelOrObject) {
703
- return writeOperation(this, () => {
704
- const patchOperation = this._patchOperationFactory(this);
705
-
706
- this.addOperation(patchOperation, [modelOrObject]);
707
- });
708
- }
709
-
710
- patchAndFetch(modelOrObject) {
711
- return writeOperation(this, () => {
712
- const patchOperation = this._patchOperationFactory(this);
713
-
714
- if (!(patchOperation.instance instanceof this.modelClass())) {
715
- throw new Error('patchAndFetch can only be called for instance operations');
716
- }
717
-
718
- const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
719
- delegate: patchOperation,
720
- });
721
-
722
- // patchOperation is an instance update operation that already adds the
723
- // required "where id = $" clause.
724
- patchAndFetch.skipIdWhere = true;
725
-
726
- this.addOperation(patchAndFetch, [patchOperation.instance.$id(), modelOrObject]);
727
- });
728
- }
729
-
730
- patchAndFetchById(id, modelOrObject) {
731
- return writeOperation(this, () => {
732
- const patchOperation = this._patchOperationFactory(this);
733
-
734
- const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
735
- delegate: patchOperation,
736
- });
737
-
738
- this.addOperation(patchAndFetch, [id, modelOrObject]);
739
- });
740
- }
741
-
742
- delete(...args) {
743
- return writeOperation(this, () => {
744
- if (args.length) {
745
- throw new Error(
746
- `Don't pass arguments to delete(). You should use it like this: delete().where('foo', 'bar').andWhere(...)`,
747
- );
748
- }
749
-
750
- const deleteOperation = this._deleteOperationFactory(this);
751
- this.addOperation(deleteOperation, args);
752
- });
753
- }
754
-
755
- del(...args) {
756
- return this.delete(...args);
757
- }
758
-
759
- relate(...args) {
760
- return writeOperation(this, () => {
761
- const relateOperation = this._relateOperationFactory(this);
762
-
763
- this.addOperation(relateOperation, args);
764
- });
765
- }
766
-
767
- unrelate(...args) {
768
- return writeOperation(this, () => {
769
- if (args.length) {
770
- throw new Error(
771
- `Don't pass arguments to unrelate(). You should use it like this: unrelate().where('foo', 'bar').andWhere(...)`,
772
- );
773
- }
774
-
775
- const unrelateOperation = this._unrelateOperationFactory(this);
776
- this.addOperation(unrelateOperation, args);
777
- });
778
- }
779
-
780
- increment(propertyName, howMuch) {
781
- const columnName = this.modelClass().propertyNameToColumnName(propertyName);
782
-
783
- return this.patch({
784
- [columnName]: raw('?? + ?', [columnName, howMuch]),
785
- });
786
- }
787
-
788
- decrement(propertyName, howMuch) {
789
- const columnName = this.modelClass().propertyNameToColumnName(propertyName);
790
-
791
- return this.patch({
792
- [columnName]: raw('?? - ?', [columnName, howMuch]),
793
- });
794
- }
795
-
796
- findOne(...args) {
797
- return this.where.apply(this, args).first();
798
- }
799
-
800
- range(...args) {
801
- return this.clear(RangeOperation).addOperation(new RangeOperation('range'), args);
802
- }
803
-
804
- first(...args) {
805
- return this.addOperation(new FirstOperation('first'), args);
806
- }
807
-
808
- joinRelated(expression, options) {
809
- ensureJoinRelatedOperation(this, 'innerJoin').addCall({
810
- expression,
811
- options,
812
- });
813
-
814
- return this;
815
- }
816
-
817
- innerJoinRelated(expression, options) {
818
- ensureJoinRelatedOperation(this, 'innerJoin').addCall({
819
- expression,
820
- options,
821
- });
822
-
823
- return this;
824
- }
825
-
826
- outerJoinRelated(expression, options) {
827
- ensureJoinRelatedOperation(this, 'outerJoin').addCall({
828
- expression,
829
- options,
830
- });
831
-
832
- return this;
833
- }
834
-
835
- fullOuterJoinRelated(expression, options) {
836
- ensureJoinRelatedOperation(this, 'fullOuterJoin').addCall({
837
- expression,
838
- options,
839
- });
840
-
841
- return this;
842
- }
843
-
844
- leftJoinRelated(expression, options) {
845
- ensureJoinRelatedOperation(this, 'leftJoin').addCall({
846
- expression,
847
- options,
848
- });
849
-
850
- return this;
851
- }
852
-
853
- leftOuterJoinRelated(expression, options) {
854
- ensureJoinRelatedOperation(this, 'leftOuterJoin').addCall({
855
- expression,
856
- options,
857
- });
858
-
859
- return this;
860
- }
861
-
862
- rightJoinRelated(expression, options) {
863
- ensureJoinRelatedOperation(this, 'rightJoin').addCall({
864
- expression,
865
- options,
866
- });
867
-
868
- return this;
869
- }
870
-
871
- rightOuterJoinRelated(expression, options) {
872
- ensureJoinRelatedOperation(this, 'rightOuterJoin').addCall({
873
- expression,
874
- options,
875
- });
876
-
877
- return this;
878
- }
879
-
880
- deleteById(id) {
881
- return withWhereScope(this, () => this.findById(id))
882
- .delete()
883
- .runBefore((_, builder) => {
884
- if (!builder.internalOptions().skipUndefined) {
885
- assertIdNotUndefined(id, `undefined was passed to deleteById`);
404
+ if (noSelectStatements && !explicit) {
405
+ const selectAll = new Selection(this.tableRef(), '*');
406
+ if (Selection.doesSelect(this, selectAll, selection)) {
407
+ return selectAll;
408
+ }
409
+ else {
410
+ return null;
411
+ }
412
+ }
413
+ else {
414
+ return null;
415
+ }
416
+ }
417
+ findAllSelections() {
418
+ let allSelections = [];
419
+ this.forEachOperation(true, (op) => {
420
+ if (op.constructor === SelectOperation) {
421
+ allSelections = allSelections.concat(op.selections);
422
+ }
423
+ });
424
+ return allSelections;
425
+ }
426
+ hasSelection(selection, explicit) {
427
+ return this.findSelection(selection, explicit) !== null;
428
+ }
429
+ hasSelectionAs(selection, alias, explicit) {
430
+ selection = Selection.create(selection);
431
+ const foundSelection = this.findSelection(selection, explicit);
432
+ if (foundSelection === null) {
433
+ return false;
434
+ }
435
+ else {
436
+ if (foundSelection.column === '*') {
437
+ // * selects the columns with their column names as aliases.
438
+ return selection.column === alias;
439
+ }
440
+ else {
441
+ return foundSelection.name === alias;
442
+ }
886
443
  }
887
- });
888
- }
889
-
890
- findById(...args) {
891
- return this.addOperation(new FindByIdOperation('findById'), args).first();
892
- }
893
-
894
- findByIds(...args) {
895
- return this.addOperation(new FindByIdsOperation('findByIds'), args);
896
- }
897
-
898
- runBefore(...args) {
899
- return this.addOperation(new RunBeforeOperation('runBefore'), args);
900
- }
901
-
902
- onBuild(...args) {
903
- return this.addOperation(new OnBuildOperation('onBuild'), args);
904
- }
905
-
906
- onBuildKnex(...args) {
907
- return this.addOperation(new OnBuildKnexOperation('onBuildKnex'), args);
908
- }
909
-
910
- runAfter(...args) {
911
- return this.addOperation(new RunAfterOperation('runAfter'), args);
912
- }
913
-
914
- onError(...args) {
915
- return this.addOperation(new OnErrorOperation('onError'), args);
916
- }
917
-
918
- from(...args) {
919
- return this.addOperation(new FromOperation('from'), args);
920
- }
921
-
922
- updateFrom(...args) {
923
- return this.addOperation(new KnexOperation('updateFrom'), args);
924
- }
925
-
926
- table(...args) {
927
- return this.addOperation(new FromOperation('table'), args);
928
- }
929
-
930
- for(relatedQueryFor) {
931
- if (arguments.length === 0) {
932
- return this._relatedQueryFor;
933
- }
934
-
935
- if (this._forError !== null) {
936
- // Keep the first error.
937
- } else if (!this._isRelatedQuery) {
938
- // Without this check `Model.query().for(1).delete()` would delete all rows.
939
- this._forError = new Error(
940
- 'for() can only be used with queries created using the static relatedQuery() method',
941
- );
942
- } else if (!this.isFind()) {
943
- // The owner has already been passed to the write operation.
944
- this._forError = new Error(
945
- 'for() must be called before the write methods ' +
946
- '(insert, update, patch, delete, relate, unrelate, increment, decrement)',
947
- );
948
- }
949
-
950
- this._relatedQueryFor = relatedQueryFor;
951
- return this;
952
- }
444
+ }
445
+ traverse(modelClass, traverser) {
446
+ if (typeof traverser === 'undefined') {
447
+ traverser = modelClass;
448
+ modelClass = null;
449
+ }
450
+ return this.runAfter((result) => {
451
+ this.resultModelClass().traverse(modelClass, result, traverser);
452
+ return result;
453
+ });
454
+ }
455
+ page(page, pageSize) {
456
+ return this.range(+page * +pageSize, (+page + 1) * +pageSize - 1);
457
+ }
458
+ columnInfo({ table = null } = {}) {
459
+ table = table || this.tableName();
460
+ const knex = this.knex();
461
+ const tableParts = table.split('.');
462
+ const columnInfoQuery = knex(last(tableParts)).columnInfo();
463
+ const schema = this.internalOptions().schema;
464
+ if (schema) {
465
+ columnInfoQuery.withSchema(schema);
466
+ }
467
+ else if (tableParts.length > 1) {
468
+ columnInfoQuery.withSchema(tableParts[0]);
469
+ }
470
+ if (this.internalOptions().debug) {
471
+ columnInfoQuery.debug();
472
+ }
473
+ return columnInfoQuery;
474
+ }
475
+ withSchema(schema) {
476
+ this.internalOptions().schema = schema;
477
+ this.internalContext().onBuild.push((builder) => {
478
+ if (!builder.has(/withSchema/)) {
479
+ // Need to push this operation to the front because knex doesn't use the
480
+ // schema for operations called before `withSchema`.
481
+ builder.addOperationToFront(new KnexOperation('withSchema'), [schema]);
482
+ }
483
+ });
484
+ return this;
485
+ }
486
+ debug /* istanbul ignore next */() {
487
+ this.internalOptions().debug = true;
488
+ this.internalContext().onBuild.push((builder) => {
489
+ builder.addOperation(new KnexOperation('debug'), []);
490
+ });
491
+ return this;
492
+ }
493
+ insert(modelsOrObjects) {
494
+ return writeOperation(this, () => {
495
+ const insertOperation = this._insertOperationFactory(this);
496
+ this.addOperation(insertOperation, [modelsOrObjects]);
497
+ });
498
+ }
499
+ insertAndFetch(modelsOrObjects) {
500
+ return writeOperation(this, () => {
501
+ const insertOperation = this._insertOperationFactory(this);
502
+ const insertAndFetchOperation = new InsertAndFetchOperation('insertAndFetch', {
503
+ delegate: insertOperation,
504
+ });
505
+ this.addOperation(insertAndFetchOperation, [modelsOrObjects]);
506
+ });
507
+ }
508
+ insertGraph(modelsOrObjects, opt) {
509
+ return writeOperation(this, () => {
510
+ const insertOperation = this._insertOperationFactory(this);
511
+ const insertGraphOperation = new InsertGraphOperation('insertGraph', {
512
+ delegate: insertOperation,
513
+ opt,
514
+ });
515
+ this.addOperation(insertGraphOperation, [modelsOrObjects]);
516
+ });
517
+ }
518
+ insertGraphAndFetch(modelsOrObjects, opt) {
519
+ return writeOperation(this, () => {
520
+ const insertOperation = this._insertOperationFactory(this);
521
+ const insertGraphOperation = new InsertGraphOperation('insertGraph', {
522
+ delegate: insertOperation,
523
+ opt,
524
+ });
525
+ const insertGraphAndFetchOperation = new InsertGraphAndFetchOperation('insertGraphAndFetch', {
526
+ delegate: insertGraphOperation,
527
+ });
528
+ return this.addOperation(insertGraphAndFetchOperation, [modelsOrObjects]);
529
+ });
530
+ }
531
+ update(modelOrObject) {
532
+ return writeOperation(this, () => {
533
+ const updateOperation = this._updateOperationFactory(this);
534
+ this.addOperation(updateOperation, [modelOrObject]);
535
+ });
536
+ }
537
+ updateAndFetch(modelOrObject) {
538
+ return writeOperation(this, () => {
539
+ const updateOperation = this._updateOperationFactory(this);
540
+ if (!(updateOperation.instance instanceof this.modelClass())) {
541
+ throw new Error('updateAndFetch can only be called for instance operations');
542
+ }
543
+ const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
544
+ delegate: updateOperation,
545
+ });
546
+ // patchOperation is an instance update operation that already adds the
547
+ // required "where id = $" clause.
548
+ updateAndFetch.skipIdWhere = true;
549
+ this.addOperation(updateAndFetch, [updateOperation.instance.$id(), modelOrObject]);
550
+ });
551
+ }
552
+ updateAndFetchById(id, modelOrObject) {
553
+ return writeOperation(this, () => {
554
+ const updateOperation = this._updateOperationFactory(this);
555
+ const updateAndFetch = new UpdateAndFetchOperation('updateAndFetch', {
556
+ delegate: updateOperation,
557
+ });
558
+ this.addOperation(updateAndFetch, [id, modelOrObject]);
559
+ });
560
+ }
561
+ upsertGraph(modelsOrObjects, upsertOptions) {
562
+ return writeOperation(this, () => {
563
+ const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
564
+ upsertOptions,
565
+ });
566
+ this.addOperation(upsertGraphOperation, [modelsOrObjects]);
567
+ });
568
+ }
569
+ upsertGraphAndFetch(modelsOrObjects, upsertOptions) {
570
+ return writeOperation(this, () => {
571
+ const upsertGraphOperation = new UpsertGraphOperation('upsertGraph', {
572
+ upsertOptions,
573
+ });
574
+ const upsertGraphAndFetchOperation = new UpsertGraphAndFetchOperation('upsertGraphAndFetch', {
575
+ delegate: upsertGraphOperation,
576
+ });
577
+ return this.addOperation(upsertGraphAndFetchOperation, [modelsOrObjects]);
578
+ });
579
+ }
580
+ patch(modelOrObject) {
581
+ return writeOperation(this, () => {
582
+ const patchOperation = this._patchOperationFactory(this);
583
+ this.addOperation(patchOperation, [modelOrObject]);
584
+ });
585
+ }
586
+ patchAndFetch(modelOrObject) {
587
+ return writeOperation(this, () => {
588
+ const patchOperation = this._patchOperationFactory(this);
589
+ if (!(patchOperation.instance instanceof this.modelClass())) {
590
+ throw new Error('patchAndFetch can only be called for instance operations');
591
+ }
592
+ const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
593
+ delegate: patchOperation,
594
+ });
595
+ // patchOperation is an instance update operation that already adds the
596
+ // required "where id = $" clause.
597
+ patchAndFetch.skipIdWhere = true;
598
+ this.addOperation(patchAndFetch, [patchOperation.instance.$id(), modelOrObject]);
599
+ });
600
+ }
601
+ patchAndFetchById(id, modelOrObject) {
602
+ return writeOperation(this, () => {
603
+ const patchOperation = this._patchOperationFactory(this);
604
+ const patchAndFetch = new UpdateAndFetchOperation('patchAndFetch', {
605
+ delegate: patchOperation,
606
+ });
607
+ this.addOperation(patchAndFetch, [id, modelOrObject]);
608
+ });
609
+ }
610
+ delete(...args) {
611
+ return writeOperation(this, () => {
612
+ if (args.length) {
613
+ throw new Error(`Don't pass arguments to delete(). You should use it like this: delete().where('foo', 'bar').andWhere(...)`);
614
+ }
615
+ const deleteOperation = this._deleteOperationFactory(this);
616
+ this.addOperation(deleteOperation, args);
617
+ });
618
+ }
619
+ del(...args) {
620
+ return this.delete(...args);
621
+ }
622
+ relate(...args) {
623
+ return writeOperation(this, () => {
624
+ const relateOperation = this._relateOperationFactory(this);
625
+ this.addOperation(relateOperation, args);
626
+ });
627
+ }
628
+ unrelate(...args) {
629
+ return writeOperation(this, () => {
630
+ if (args.length) {
631
+ throw new Error(`Don't pass arguments to unrelate(). You should use it like this: unrelate().where('foo', 'bar').andWhere(...)`);
632
+ }
633
+ const unrelateOperation = this._unrelateOperationFactory(this);
634
+ this.addOperation(unrelateOperation, args);
635
+ });
636
+ }
637
+ increment(propertyName, howMuch) {
638
+ const columnName = this.modelClass().propertyNameToColumnName(propertyName);
639
+ return this.patch({
640
+ [columnName]: raw('?? + ?', [columnName, howMuch]),
641
+ });
642
+ }
643
+ decrement(propertyName, howMuch) {
644
+ const columnName = this.modelClass().propertyNameToColumnName(propertyName);
645
+ return this.patch({
646
+ [columnName]: raw('?? - ?', [columnName, howMuch]),
647
+ });
648
+ }
649
+ findOne(...args) {
650
+ return this.where.apply(this, args).first();
651
+ }
652
+ range(...args) {
653
+ return this.clear(RangeOperation).addOperation(new RangeOperation('range'), args);
654
+ }
655
+ first(...args) {
656
+ return this.addOperation(new FirstOperation('first'), args);
657
+ }
658
+ joinRelated(expression, options) {
659
+ ensureJoinRelatedOperation(this, 'innerJoin').addCall({
660
+ expression,
661
+ options,
662
+ });
663
+ return this;
664
+ }
665
+ innerJoinRelated(expression, options) {
666
+ ensureJoinRelatedOperation(this, 'innerJoin').addCall({
667
+ expression,
668
+ options,
669
+ });
670
+ return this;
671
+ }
672
+ outerJoinRelated(expression, options) {
673
+ ensureJoinRelatedOperation(this, 'outerJoin').addCall({
674
+ expression,
675
+ options,
676
+ });
677
+ return this;
678
+ }
679
+ fullOuterJoinRelated(expression, options) {
680
+ ensureJoinRelatedOperation(this, 'fullOuterJoin').addCall({
681
+ expression,
682
+ options,
683
+ });
684
+ return this;
685
+ }
686
+ leftJoinRelated(expression, options) {
687
+ ensureJoinRelatedOperation(this, 'leftJoin').addCall({
688
+ expression,
689
+ options,
690
+ });
691
+ return this;
692
+ }
693
+ leftOuterJoinRelated(expression, options) {
694
+ ensureJoinRelatedOperation(this, 'leftOuterJoin').addCall({
695
+ expression,
696
+ options,
697
+ });
698
+ return this;
699
+ }
700
+ rightJoinRelated(expression, options) {
701
+ ensureJoinRelatedOperation(this, 'rightJoin').addCall({
702
+ expression,
703
+ options,
704
+ });
705
+ return this;
706
+ }
707
+ rightOuterJoinRelated(expression, options) {
708
+ ensureJoinRelatedOperation(this, 'rightOuterJoin').addCall({
709
+ expression,
710
+ options,
711
+ });
712
+ return this;
713
+ }
714
+ deleteById(id) {
715
+ return withWhereScope(this, () => this.findById(id))
716
+ .delete()
717
+ .runBefore((_, builder) => {
718
+ if (!builder.internalOptions().skipUndefined) {
719
+ assertIdNotUndefined(id, `undefined was passed to deleteById`);
720
+ }
721
+ });
722
+ }
723
+ findById(...args) {
724
+ return this.addOperation(new FindByIdOperation('findById'), args).first();
725
+ }
726
+ findByIds(...args) {
727
+ return this.addOperation(new FindByIdsOperation('findByIds'), args);
728
+ }
729
+ runBefore(...args) {
730
+ return this.addOperation(new RunBeforeOperation('runBefore'), args);
731
+ }
732
+ onBuild(...args) {
733
+ return this.addOperation(new OnBuildOperation('onBuild'), args);
734
+ }
735
+ onBuildKnex(...args) {
736
+ return this.addOperation(new OnBuildKnexOperation('onBuildKnex'), args);
737
+ }
738
+ runAfter(...args) {
739
+ return this.addOperation(new RunAfterOperation('runAfter'), args);
740
+ }
741
+ onError(...args) {
742
+ return this.addOperation(new OnErrorOperation('onError'), args);
743
+ }
744
+ from(...args) {
745
+ return this.addOperation(new FromOperation('from'), args);
746
+ }
747
+ updateFrom(...args) {
748
+ return this.addOperation(new KnexOperation('updateFrom'), args);
749
+ }
750
+ table(...args) {
751
+ return this.addOperation(new FromOperation('table'), args);
752
+ }
753
+ for(relatedQueryFor) {
754
+ if (arguments.length === 0) {
755
+ return this._relatedQueryFor;
756
+ }
757
+ if (this._forError !== null) {
758
+ // Keep the first error.
759
+ }
760
+ else if (!this._isRelatedQuery) {
761
+ // Without this check `Model.query().for(1).delete()` would delete all rows.
762
+ this._forError = new Error('for() can only be used with queries created using the static relatedQuery() method');
763
+ }
764
+ else if (!this.isFind()) {
765
+ // The owner has already been passed to the write operation.
766
+ this._forError = new Error('for() must be called before the write methods ' +
767
+ '(insert, update, patch, delete, relate, unrelate, increment, decrement)');
768
+ }
769
+ this._relatedQueryFor = relatedQueryFor;
770
+ return this;
771
+ }
953
772
  }
954
-
955
773
  Object.defineProperties(QueryBuilder.prototype, {
956
- isObjectionQueryBuilder: {
957
- enumerable: false,
958
- writable: false,
959
- value: true,
960
- },
774
+ isObjectionQueryBuilder: {
775
+ enumerable: false,
776
+ writable: false,
777
+ value: true,
778
+ },
961
779
  });
962
-
780
+ function isWriteOperation(op) {
781
+ return (op.is(InsertOperation) ||
782
+ op.is(UpdateOperation) ||
783
+ op.is(DeleteOperation) ||
784
+ op.is(RelateOperation) ||
785
+ op.is(UnrelateOperation));
786
+ }
963
787
  function ensureEagerOperation(builder, algorithm = null) {
964
- const modelClass = builder.modelClass();
965
- const defaultGraphOptions = modelClass.getDefaultGraphOptions();
966
- const eagerOp = builder.findOperation(EagerOperation);
967
-
968
- if (algorithm) {
969
- const EagerOperationClass = getOperationClassForEagerAlgorithm(builder, algorithm);
970
-
971
- if (eagerOp instanceof EagerOperationClass) {
972
- return eagerOp;
973
- } else {
974
- const newEagerOp = new EagerOperationClass('eager', {
975
- defaultGraphOptions,
976
- });
977
-
978
- if (eagerOp) {
979
- newEagerOp.cloneFrom(eagerOp);
980
- }
981
-
982
- builder.clear(EagerOperation);
983
- builder.addOperation(newEagerOp);
984
-
985
- return newEagerOp;
986
- }
987
- } else {
988
- if (eagerOp) {
989
- return eagerOp;
990
- } else {
991
- const EagerOperationClass = getOperationClassForEagerAlgorithm(
992
- builder,
993
- getWhereInEagerAlgorithm(builder),
994
- );
995
-
996
- const newEagerOp = new EagerOperationClass('eager', {
997
- defaultGraphOptions,
998
- });
999
-
1000
- builder.addOperation(newEagerOp);
1001
-
1002
- return newEagerOp;
1003
- }
1004
- }
788
+ const modelClass = builder.modelClass();
789
+ const defaultGraphOptions = modelClass.getDefaultGraphOptions();
790
+ const eagerOp = builder.findOperation(EagerOperation);
791
+ if (algorithm) {
792
+ const EagerOperationClass = getOperationClassForEagerAlgorithm(builder, algorithm);
793
+ if (eagerOp instanceof EagerOperationClass) {
794
+ return eagerOp;
795
+ }
796
+ else {
797
+ const newEagerOp = new EagerOperationClass('eager', {
798
+ defaultGraphOptions,
799
+ });
800
+ if (eagerOp) {
801
+ newEagerOp.cloneFrom(eagerOp);
802
+ }
803
+ builder.clear(EagerOperation);
804
+ builder.addOperation(newEagerOp);
805
+ return newEagerOp;
806
+ }
807
+ }
808
+ else {
809
+ if (eagerOp) {
810
+ return eagerOp;
811
+ }
812
+ else {
813
+ const EagerOperationClass = getOperationClassForEagerAlgorithm(builder, getWhereInEagerAlgorithm(builder));
814
+ const newEagerOp = new EagerOperationClass('eager', {
815
+ defaultGraphOptions,
816
+ });
817
+ builder.addOperation(newEagerOp);
818
+ return newEagerOp;
819
+ }
820
+ }
1005
821
  }
1006
-
1007
822
  function getWhereInEagerAlgorithm(builder) {
1008
- return builder.modelClass().WhereInEagerAlgorithm;
823
+ return builder.modelClass().WhereInEagerAlgorithm;
1009
824
  }
1010
-
1011
825
  function getJoinEagerAlgorithm(builder) {
1012
- return builder.modelClass().JoinEagerAlgorithm;
826
+ return builder.modelClass().JoinEagerAlgorithm;
1013
827
  }
1014
-
1015
828
  function getNaiveEagerAlgorithm(builder) {
1016
- return builder.modelClass().NaiveEagerAlgorithm;
829
+ return builder.modelClass().NaiveEagerAlgorithm;
1017
830
  }
1018
-
1019
831
  function getOperationClassForEagerAlgorithm(builder, algorithm) {
1020
- if (algorithm === getJoinEagerAlgorithm(builder)) {
1021
- return JoinEagerOperation;
1022
- } else if (algorithm === getNaiveEagerAlgorithm(builder)) {
1023
- return NaiveEagerOperation;
1024
- } else {
1025
- return WhereInEagerOperation;
1026
- }
832
+ if (algorithm === getJoinEagerAlgorithm(builder)) {
833
+ return JoinEagerOperation;
834
+ }
835
+ else if (algorithm === getNaiveEagerAlgorithm(builder)) {
836
+ return NaiveEagerOperation;
837
+ }
838
+ else {
839
+ return WhereInEagerOperation;
840
+ }
1027
841
  }
1028
-
1029
842
  function parseRelationExpression(modelClass, exp) {
1030
- try {
1031
- return RelationExpression.create(exp);
1032
- } catch (err) {
1033
- if (err instanceof DuplicateRelationError) {
1034
- throw modelClass.createValidationError({
1035
- type: ValidationErrorType.RelationExpression,
1036
- message: `Duplicate relation name "${err.relationName}" in relation expression "${exp}". For example, use "${err.relationName}.[foo, bar]" instead of "[${err.relationName}.foo, ${err.relationName}.bar]".`,
1037
- });
1038
- } else {
1039
- throw modelClass.createValidationError({
1040
- type: ValidationErrorType.RelationExpression,
1041
- message: `Invalid relation expression "${exp}"`,
1042
- });
1043
- }
1044
- }
843
+ try {
844
+ return RelationExpression.create(exp);
845
+ }
846
+ catch (err) {
847
+ if (err instanceof DuplicateRelationError) {
848
+ throw modelClass.createValidationError({
849
+ type: ValidationErrorType.RelationExpression,
850
+ message: `Duplicate relation name "${err.relationName}" in relation expression "${exp}". For example, use "${err.relationName}.[foo, bar]" instead of "[${err.relationName}.foo, ${err.relationName}.bar]".`,
851
+ });
852
+ }
853
+ else {
854
+ throw modelClass.createValidationError({
855
+ type: ValidationErrorType.RelationExpression,
856
+ message: `Invalid relation expression "${exp}"`,
857
+ });
858
+ }
859
+ }
1045
860
  }
1046
-
1047
861
  function checkEager(builder) {
1048
- const eagerOp = builder.findOperation(EagerOperation);
1049
-
1050
- if (!eagerOp) {
1051
- return;
1052
- }
1053
-
1054
- const expr = eagerOp.expression;
1055
- const allowedExpr = builder.allowedGraphExpression();
1056
-
1057
- if (expr.numChildren > 0 && allowedExpr && !allowedExpr.isSubExpression(expr)) {
1058
- const modelClass = builder.modelClass();
1059
-
1060
- builder.reject(
1061
- modelClass.createValidationError({
1062
- type: ValidationErrorType.UnallowedRelation,
1063
- message: 'eager expression not allowed',
1064
- }),
1065
- );
1066
- }
862
+ const eagerOp = builder.findOperation(EagerOperation);
863
+ if (!eagerOp) {
864
+ return;
865
+ }
866
+ const expr = eagerOp.expression;
867
+ const allowedExpr = builder.allowedGraphExpression();
868
+ if (expr.numChildren > 0 && allowedExpr && !allowedExpr.isSubExpression(expr)) {
869
+ const modelClass = builder.modelClass();
870
+ builder.reject(modelClass.createValidationError({
871
+ type: ValidationErrorType.UnallowedRelation,
872
+ message: 'eager expression not allowed',
873
+ }));
874
+ }
1067
875
  }
1068
-
1069
876
  function findQueryExecutorOperation(builder) {
1070
- return builder.findOperation((op) => op.hasQueryExecutor());
877
+ return builder.findOperation((op) => op.hasQueryExecutor());
1071
878
  }
1072
-
1073
879
  function checkForUsage(builder) {
1074
- if (builder._forError !== null) {
1075
- throw builder._forError;
1076
- }
880
+ if (builder._forError !== null) {
881
+ throw builder._forError;
882
+ }
1077
883
  }
1078
-
1079
884
  function beforeExecute(builder) {
1080
- let promise = Promise.resolve();
1081
-
1082
- // This needs to be checked before any hooks are called.
1083
- checkForUsage(builder);
1084
-
1085
- builder = addImplicitOperations(builder);
1086
-
1087
- // Resolve all before hooks before building and executing the query
1088
- // and the rest of the hooks.
1089
- promise = chainOperationHooks(promise, builder, 'onBefore1');
1090
- promise = chainOperationHooks(promise, builder, 'onBefore2');
1091
-
1092
- promise = chainHooks(promise, builder, builder.context().runBefore);
1093
- promise = chainHooks(promise, builder, builder.internalContext().runBefore);
1094
-
1095
- promise = chainOperationHooks(promise, builder, 'onBefore3');
1096
-
1097
- return promise;
885
+ let promise = Promise.resolve();
886
+ // This needs to be checked before any hooks are called.
887
+ checkForUsage(builder);
888
+ builder = addImplicitOperations(builder);
889
+ // Resolve all before hooks before building and executing the query
890
+ // and the rest of the hooks.
891
+ promise = chainOperationHooks(promise, builder, 'onBefore1');
892
+ promise = chainOperationHooks(promise, builder, 'onBefore2');
893
+ promise = chainHooks(promise, builder, builder.context().runBefore);
894
+ promise = chainHooks(promise, builder, builder.internalContext().runBefore);
895
+ promise = chainOperationHooks(promise, builder, 'onBefore3');
896
+ return promise;
1098
897
  }
1099
-
1100
898
  function doExecute(builder) {
1101
- let promise = Promise.resolve();
1102
-
1103
- builder = callOnBuildHooks(builder);
1104
- const queryExecutorOperation = findQueryExecutorOperation(builder);
1105
-
1106
- const explicitRejectValue = builder._explicitRejectValue;
1107
- const explicitResolveValue = builder._explicitResolveValue;
1108
-
1109
- if (explicitRejectValue !== null) {
1110
- promise = Promise.reject(explicitRejectValue);
1111
- } else if (explicitResolveValue !== null) {
1112
- promise = Promise.resolve(explicitResolveValue);
1113
- } else if (queryExecutorOperation !== null) {
1114
- promise = Promise.resolve(queryExecutorOperation.queryExecutor(builder));
1115
- } else {
1116
- promise = Promise.resolve(buildKnexQuery(builder));
1117
-
1118
- promise = chainOperationHooks(promise, builder, 'onRawResult');
1119
- promise = promise.then((result) => createModels(result, builder));
1120
- }
1121
-
1122
- return promise;
899
+ let promise = Promise.resolve();
900
+ builder = callOnBuildHooks(builder);
901
+ const queryExecutorOperation = findQueryExecutorOperation(builder);
902
+ const explicitRejectValue = builder._explicitRejectValue;
903
+ const explicitResolveValue = builder._explicitResolveValue;
904
+ if (explicitRejectValue !== null) {
905
+ promise = Promise.reject(explicitRejectValue);
906
+ }
907
+ else if (explicitResolveValue !== null) {
908
+ promise = Promise.resolve(explicitResolveValue);
909
+ }
910
+ else if (queryExecutorOperation !== null) {
911
+ promise = Promise.resolve(queryExecutorOperation.queryExecutor(builder));
912
+ }
913
+ else {
914
+ promise = Promise.resolve(buildKnexQuery(builder));
915
+ promise = chainOperationHooks(promise, builder, 'onRawResult');
916
+ promise = promise.then((result) => createModels(result, builder));
917
+ }
918
+ return promise;
1123
919
  }
1124
-
1125
920
  function afterExecute(builder, result) {
1126
- let promise = Promise.resolve(result);
1127
-
1128
- promise = chainOperationHooks(promise, builder, 'onAfter1');
1129
- promise = chainOperationHooks(promise, builder, 'onAfter2');
1130
-
1131
- promise = chainHooks(promise, builder, builder.context().runAfter);
1132
- promise = chainHooks(promise, builder, builder.internalContext().runAfter);
1133
-
1134
- promise = chainOperationHooks(promise, builder, 'onAfter3');
1135
-
1136
- return promise;
921
+ let promise = Promise.resolve(result);
922
+ promise = chainOperationHooks(promise, builder, 'onAfter1');
923
+ promise = chainOperationHooks(promise, builder, 'onAfter2');
924
+ promise = chainHooks(promise, builder, builder.context().runAfter);
925
+ promise = chainHooks(promise, builder, builder.internalContext().runAfter);
926
+ promise = chainOperationHooks(promise, builder, 'onAfter3');
927
+ return promise;
1137
928
  }
1138
-
1139
929
  class ReturnImmediatelyException {
1140
- constructor(value) {
1141
- this.value = value;
1142
- }
930
+ constructor(value) {
931
+ this.value = value;
932
+ }
1143
933
  }
1144
-
1145
934
  function handleReturnImmediatelyValue(builder) {
1146
- const { returnImmediatelyValue } = builder.internalOptions();
1147
- if (returnImmediatelyValue !== undefined) {
1148
- throw new ReturnImmediatelyException(returnImmediatelyValue);
1149
- }
935
+ const { returnImmediatelyValue } = builder.internalOptions();
936
+ if (returnImmediatelyValue !== undefined) {
937
+ throw new ReturnImmediatelyException(returnImmediatelyValue);
938
+ }
1150
939
  }
1151
-
1152
940
  function handleExecuteError(builder, err) {
1153
- if (err instanceof ReturnImmediatelyException) {
1154
- return Promise.resolve(err.value);
1155
- }
1156
-
1157
- let promise = Promise.reject(wrapError(err));
1158
-
1159
- builder.forEachOperation(true, (op) => {
1160
- if (op.hasOnError()) {
1161
- promise = promise.catch((err) =>
1162
- builder.callAsyncOperationMethod(op, 'onError', [builder, err]),
1163
- );
1164
- }
1165
- });
1166
-
1167
- return promise;
941
+ if (err instanceof ReturnImmediatelyException) {
942
+ return Promise.resolve(err.value);
943
+ }
944
+ let promise = Promise.reject(wrapError(err));
945
+ builder.forEachOperation(true, (op) => {
946
+ if (op.hasOnError()) {
947
+ promise = promise.catch((err) => builder.callAsyncOperationMethod(op, 'onError', [builder, err]));
948
+ }
949
+ });
950
+ return promise;
1168
951
  }
1169
-
1170
952
  function chainOperationHooks(promise, builder, hookName) {
1171
- return promise.then((result) => {
1172
- let promise = Promise.resolve(result);
1173
-
1174
- builder.forEachOperation(true, (op) => {
1175
- if (op.hasHook(hookName)) {
1176
- promise = promise.then((result) => {
1177
- const res = builder.callAsyncOperationMethod(op, hookName, [builder, result]);
1178
- handleReturnImmediatelyValue(builder);
1179
- return res;
953
+ return promise.then((result) => {
954
+ let promise = Promise.resolve(result);
955
+ builder.forEachOperation(true, (op) => {
956
+ if (op.hasHook(hookName)) {
957
+ promise = promise.then((result) => {
958
+ const res = builder.callAsyncOperationMethod(op, hookName, [builder, result]);
959
+ handleReturnImmediatelyValue(builder);
960
+ return res;
961
+ });
962
+ }
1180
963
  });
1181
- }
964
+ return promise;
1182
965
  });
1183
-
1184
- return promise;
1185
- });
1186
966
  }
1187
-
1188
967
  function ensureJoinRelatedOperation(builder, joinOperation) {
1189
- const opName = joinOperation + 'Relation';
1190
- let op = builder.findOperation(opName);
1191
-
1192
- if (!op) {
1193
- op = new JoinRelatedOperation(opName, { joinOperation });
1194
- builder.addOperation(op);
1195
- }
1196
-
1197
- return op;
968
+ const opName = joinOperation + 'Relation';
969
+ let op = builder.findOperation(opName);
970
+ if (!op) {
971
+ op = new JoinRelatedOperation(opName, { joinOperation });
972
+ builder.addOperation(op);
973
+ }
974
+ return op;
1198
975
  }
1199
-
1200
976
  function prebuildQuery(builder) {
1201
- checkForUsage(builder);
1202
-
1203
- builder = addImplicitOperations(builder);
1204
- builder = callOnBuildHooks(builder);
1205
-
1206
- const queryExecutorOperation = findQueryExecutorOperation(builder);
1207
-
1208
- if (queryExecutorOperation) {
1209
- return prebuildQuery(queryExecutorOperation.queryExecutor(builder));
1210
- } else {
1211
- return builder;
1212
- }
977
+ checkForUsage(builder);
978
+ builder = addImplicitOperations(builder);
979
+ builder = callOnBuildHooks(builder);
980
+ const queryExecutorOperation = findQueryExecutorOperation(builder);
981
+ if (queryExecutorOperation) {
982
+ return prebuildQuery(queryExecutorOperation.queryExecutor(builder));
983
+ }
984
+ else {
985
+ return builder;
986
+ }
1213
987
  }
1214
-
1215
988
  function addImplicitOperations(builder) {
1216
- if (builder.isFind()) {
1217
- // If no write operations have been called at this point this query is a
1218
- // find query and we need to call the custom find implementation.
1219
- addFindOperation(builder);
1220
- }
1221
-
1222
- if (builder.hasWithGraph()) {
1223
- moveEagerOperationToEnd(builder);
1224
- }
1225
-
1226
- return builder;
989
+ if (builder.isFind()) {
990
+ // If no write operations have been called at this point this query is a
991
+ // find query and we need to call the custom find implementation.
992
+ addFindOperation(builder);
993
+ }
994
+ if (builder.hasWithGraph()) {
995
+ moveEagerOperationToEnd(builder);
996
+ }
997
+ return builder;
1227
998
  }
1228
-
1229
999
  function addFindOperation(builder) {
1230
- if (!builder.has(FindOperation)) {
1231
- const operation = builder._findOperationFactory(builder);
1232
- builder.addOperationToFront(operation, []);
1233
- }
1000
+ if (!builder.has(FindOperation)) {
1001
+ const operation = builder._findOperationFactory(builder);
1002
+ builder.addOperationToFront(operation, []);
1003
+ }
1234
1004
  }
1235
-
1236
1005
  function moveEagerOperationToEnd(builder) {
1237
- const eagerOp = builder.findOperation(EagerOperation);
1238
-
1239
- builder.clear(EagerOperation);
1240
- builder.addOperation(eagerOp);
1006
+ const eagerOp = builder.findOperation(EagerOperation);
1007
+ builder.clear(EagerOperation);
1008
+ builder.addOperation(eagerOp);
1241
1009
  }
1242
-
1243
1010
  function callOnBuildHooks(builder) {
1244
- callOnBuildFuncs(builder, builder.context().onBuild);
1245
- callOnBuildFuncs(builder, builder.internalContext().onBuild);
1246
-
1247
- builder.executeOnBuild();
1248
- return builder;
1011
+ callOnBuildFuncs(builder, builder.context().onBuild);
1012
+ callOnBuildFuncs(builder, builder.internalContext().onBuild);
1013
+ builder.executeOnBuild();
1014
+ return builder;
1249
1015
  }
1250
-
1251
1016
  function callOnBuildFuncs(builder, func) {
1252
- if (isFunction(func)) {
1253
- func.call(builder, builder);
1254
- } else if (Array.isArray(func)) {
1255
- func.forEach((func) => callOnBuildFuncs(builder, func));
1256
- }
1017
+ if (isFunction(func)) {
1018
+ func.call(builder, builder);
1019
+ }
1020
+ else if (Array.isArray(func)) {
1021
+ func.forEach((func) => callOnBuildFuncs(builder, func));
1022
+ }
1257
1023
  }
1258
-
1259
1024
  function buildKnexQuery(builder, knexBuilder = builder.knex().queryBuilder()) {
1260
- knexBuilder = builder.executeOnBuildKnex(knexBuilder);
1261
-
1262
- const fromOperation = builder.findLastOperation(QueryBuilderBase.FromSelector);
1263
-
1264
- if (!builder.isPartial()) {
1265
- // Set the table only if it hasn't been explicitly set yet.
1266
- if (!fromOperation) {
1267
- knexBuilder = setDefaultTable(builder, knexBuilder);
1268
- }
1269
-
1270
- // Only add `table.*` select if there are no explicit selects
1271
- // and `from` is a table name and not a subquery.
1272
- if (!builder.hasSelects() && (!fromOperation || fromOperation.table)) {
1273
- knexBuilder = setDefaultSelect(builder, knexBuilder);
1274
- }
1275
- }
1276
-
1277
- return knexBuilder;
1025
+ knexBuilder = builder.executeOnBuildKnex(knexBuilder);
1026
+ const fromOperation = builder.findLastOperation(QueryBuilderBase.FromSelector);
1027
+ if (!builder.isPartial()) {
1028
+ // Set the table only if it hasn't been explicitly set yet.
1029
+ if (!fromOperation) {
1030
+ knexBuilder = setDefaultTable(builder, knexBuilder);
1031
+ }
1032
+ // Only add `table.*` select if there are no explicit selects
1033
+ // and `from` is a table name and not a subquery.
1034
+ if (!builder.hasSelects() && (!fromOperation || fromOperation.table)) {
1035
+ knexBuilder = setDefaultSelect(builder, knexBuilder);
1036
+ }
1037
+ }
1038
+ return knexBuilder;
1278
1039
  }
1279
-
1280
1040
  function setDefaultTable(builder, knexBuilder) {
1281
- const table = builder.tableName();
1282
- const tableRef = builder.tableRef();
1283
-
1284
- if (table === tableRef) {
1285
- return knexBuilder.table(table);
1286
- } else {
1287
- return knexBuilder.table(`${table} as ${tableRef}`);
1288
- }
1041
+ const table = builder.tableName();
1042
+ const tableRef = builder.tableRef();
1043
+ if (table === tableRef) {
1044
+ return knexBuilder.table(table);
1045
+ }
1046
+ else {
1047
+ return knexBuilder.table(`${table} as ${tableRef}`);
1048
+ }
1289
1049
  }
1290
-
1291
1050
  function setDefaultSelect(builder, knexBuilder) {
1292
- const tableRef = builder.tableRef();
1293
-
1294
- return knexBuilder.select(`${tableRef}.*`);
1051
+ const tableRef = builder.tableRef();
1052
+ return knexBuilder.select(`${tableRef}.*`);
1295
1053
  }
1296
-
1297
1054
  async function chainHooks(promise, builder, func) {
1298
- return promise.then((result) => {
1299
- let promise = Promise.resolve(result);
1300
-
1301
- if (isFunction(func)) {
1302
- promise = promise.then((result) => {
1303
- const res = func.call(builder, result, builder);
1304
- handleReturnImmediatelyValue(builder);
1305
- return res;
1306
- });
1307
- } else if (Array.isArray(func)) {
1308
- func.forEach((func) => {
1309
- promise = chainHooks(promise, builder, func);
1310
- });
1311
- }
1312
-
1313
- return promise;
1314
- });
1055
+ return promise.then((result) => {
1056
+ let promise = Promise.resolve(result);
1057
+ if (isFunction(func)) {
1058
+ promise = promise.then((result) => {
1059
+ const res = func.call(builder, result, builder);
1060
+ handleReturnImmediatelyValue(builder);
1061
+ return res;
1062
+ });
1063
+ }
1064
+ else if (Array.isArray(func)) {
1065
+ func.forEach((func) => {
1066
+ promise = chainHooks(promise, builder, func);
1067
+ });
1068
+ }
1069
+ return promise;
1070
+ });
1315
1071
  }
1316
-
1317
1072
  function createModels(result, builder) {
1318
- if (result === null || result === undefined) {
1319
- return null;
1320
- }
1321
-
1322
- if (builder.isInsert()) {
1323
- // results are applied to input models in `InsertOperation.onAfter1` instead.
1073
+ if (result === null || result === undefined) {
1074
+ return null;
1075
+ }
1076
+ if (builder.isInsert()) {
1077
+ // results are applied to input models in `InsertOperation.onAfter1` instead.
1078
+ return result;
1079
+ }
1080
+ const modelClass = builder.resultModelClass();
1081
+ if (Array.isArray(result)) {
1082
+ if (result.length && shouldBeConvertedToModel(result[0], modelClass)) {
1083
+ for (let i = 0, l = result.length; i < l; ++i) {
1084
+ result[i] = modelClass.fromDatabaseJson(result[i]);
1085
+ }
1086
+ }
1087
+ }
1088
+ else if (shouldBeConvertedToModel(result, modelClass)) {
1089
+ result = modelClass.fromDatabaseJson(result);
1090
+ }
1324
1091
  return result;
1325
- }
1326
-
1327
- const modelClass = builder.resultModelClass();
1328
-
1329
- if (Array.isArray(result)) {
1330
- if (result.length && shouldBeConvertedToModel(result[0], modelClass)) {
1331
- for (let i = 0, l = result.length; i < l; ++i) {
1332
- result[i] = modelClass.fromDatabaseJson(result[i]);
1333
- }
1334
- }
1335
- } else if (shouldBeConvertedToModel(result, modelClass)) {
1336
- result = modelClass.fromDatabaseJson(result);
1337
- }
1338
-
1339
- return result;
1340
1092
  }
1341
-
1342
1093
  function shouldBeConvertedToModel(obj, modelClass) {
1343
- return isObject(obj) && !(obj instanceof modelClass);
1094
+ return isObject(obj) && !(obj instanceof modelClass);
1344
1095
  }
1345
-
1346
1096
  function writeOperation(builder, cb) {
1347
- if (!builder.isFind()) {
1348
- return builder.reject(
1349
- new Error(
1350
- 'Double call to a write method. ' +
1351
- 'You can only call one of the write methods ' +
1352
- '(insert, update, patch, delete, relate, unrelate, increment, decrement) ' +
1353
- 'and only once per query builder.',
1354
- ),
1355
- );
1356
- }
1357
-
1358
- try {
1359
- cb();
1360
- return builder;
1361
- } catch (err) {
1362
- return builder.reject(err);
1363
- }
1097
+ if (!builder.isFind()) {
1098
+ return builder.reject(new Error('Double call to a write method. ' +
1099
+ 'You can only call one of the write methods ' +
1100
+ '(insert, update, patch, delete, relate, unrelate, increment, decrement) ' +
1101
+ 'and only once per query builder.'));
1102
+ }
1103
+ try {
1104
+ cb();
1105
+ return builder;
1106
+ }
1107
+ catch (err) {
1108
+ return builder.reject(err);
1109
+ }
1364
1110
  }
1365
-
1366
1111
  function findOperationFactory() {
1367
- return new FindOperation('find');
1112
+ return new FindOperation('find');
1368
1113
  }
1369
-
1370
1114
  function insertOperationFactory() {
1371
- return new InsertOperation('insert');
1115
+ return new InsertOperation('insert');
1372
1116
  }
1373
-
1374
1117
  function updateOperationFactory() {
1375
- return new UpdateOperation('update');
1118
+ return new UpdateOperation('update');
1376
1119
  }
1377
-
1378
1120
  function patchOperationFactory() {
1379
- return new UpdateOperation('patch', {
1380
- modelOptions: { patch: true },
1381
- });
1121
+ return new UpdateOperation('patch', {
1122
+ modelOptions: { patch: true },
1123
+ });
1382
1124
  }
1383
-
1384
1125
  function relateOperationFactory() {
1385
- return new RelateOperation('relate', {});
1126
+ return new RelateOperation('relate', {});
1386
1127
  }
1387
-
1388
1128
  function unrelateOperationFactory() {
1389
- return new UnrelateOperation('unrelate', {});
1129
+ return new UnrelateOperation('unrelate', {});
1390
1130
  }
1391
-
1392
1131
  function deleteOperationFactory() {
1393
- return new DeleteOperation('delete');
1132
+ return new DeleteOperation('delete');
1394
1133
  }
1395
-
1396
1134
  module.exports = {
1397
- QueryBuilder,
1135
+ QueryBuilder,
1398
1136
  };