| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725 |
3×
3×
3×
3×
3×
3×
638×
638×
638×
638×
638×
638×
638×
638×
638×
3×
638×
638×
638×
638×
627×
627×
400×
400×
400×
3×
638×
638×
9791×
3×
638×
638×
483×
483×
483×
483×
483×
155×
155×
155×
3×
155×
155×
155×
155×
155×
155×
204×
178×
178×
194×
194×
194×
194×
129×
129×
65×
65×
65×
60×
60×
65×
5×
178×
155×
3×
155×
155×
155×
151×
151×
151×
151×
222×
49×
151×
102×
102×
102×
53×
53×
53×
53×
34×
53×
53×
53×
3×
155×
155×
155×
155×
227×
227×
227×
2×
521×
521×
521×
521×
227×
67×
67×
67×
67×
67×
67×
67×
67×
67×
67×
67×
67×
160×
160×
160×
160×
160×
155×
3×
717×
717×
717×
3×
400×
400×
400×
400×
54×
3×
400×
400×
400×
54×
54×
54×
54×
67×
66×
66×
54×
54×
54×
54×
54×
31×
31×
31×
31×
31×
31×
31×
54×
54×
2×
4×
4×
4×
4×
4×
52×
54×
31×
31×
23×
23×
23×
400×
3×
54×
54×
54×
54×
54×
79×
79×
79×
25×
79×
79×
79×
79×
79×
79×
3×
79×
79×
56×
56×
56×
23×
23×
23×
43×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
23×
40×
93×
23×
23×
23×
3×
102×
102×
267×
267×
102×
102×
102×
|
/**
* Module Dependencies
*/
var _ = require('lodash');
var async = require('async');
var utils = require('../../utils/helpers');
var normalize = require('../../utils/normalize');
var hasOwnProperty = utils.object.hasOwnProperty;
/**
* Builds up a set of operations to perform based on search criteria.
*
* This allows the ability to do cross-adapter joins as well as fake joins
* on adapters that haven't implemented the join interface yet.
*/
var Operations = module.exports = function(context, criteria, parent, metaContainer) {
// Build up a cache
this.cache = {};
// Set context
this.context = context;
// Set criteria
this.criteria = criteria;
// Set parent
this.parent = parent;
this.metaContainer = metaContainer;
// Hold a default value for pre-combined results (native joins)
this.preCombined = false;
// Seed the Cache
this._seedCache();
// Build Up Operations
this.operations = this._buildOperations();
return this;
};
/*
***********************************************************************************
* PUBLIC METHODS
***********************************************************************************/
/**
* Run Operations
*
* Execute a set of generated operations returning an array of results that can
* joined in-memory to build out a valid results set.
*
* @param {Function} cb
* @api public
*/
Operations.prototype.run = function run(cb) {
var self = this;
// Grab the parent operation, it will always be the very first operation
var parentOp = this.operations.shift();
// Run The Parent Operation
this._runOperation(parentOp.collection, parentOp.method, parentOp.criteria, function(err, results) {
if (err) return cb(err);
// Set the cache values
self.cache[parentOp.collection] = results;
// If results are empty, or we're already combined, nothing else to so do return
if (!results || self.preCombined) return cb(null, { combined: true, cache: self.cache });
// Run child operations and populate the cache
self._execChildOpts(results, function(err) {
Iif (err) return cb(err);
cb(null, { combined: self.preCombined, cache: self.cache });
});
});
};
/*
***********************************************************************************
* PRIVATE METHODS
***********************************************************************************/
/**
* Seed Cache with empty values.
*
* For each Waterline Collection set an empty array of values into the cache.
*
* @api private
*/
Operations.prototype._seedCache = function _seedCache() {
var self = this;
// Fill the cache with empty values for each collection
Object.keys(this.context.waterline.schema).forEach(function(key) {
self.cache[key] = [];
});
};
/**
* Build up the operations needed to perform the query based on criteria.
*
* @return {Array}
* @api private
*/
Operations.prototype._buildOperations = function _buildOperations() {
var operations = [];
// Check if joins were used, if not only a single operation is needed on a single connection
if (!hasOwnProperty(this.criteria, 'joins')) {
// Grab the collection
var collection = this.context.waterline.collections[this.context.identity];
// Find the name of the connection to run the query on using the dictionary
var connectionName = collection.adapterDictionary[this.parent];
if (!connectionName) connectionName = collection.adapterDictionary.find;
operations.push({
connection: connectionName,
collection: this.context.identity,
method: this.parent,
criteria: this.criteria
});
return operations;
}
// Joins were used in this operation. Lets grab the connections needed for these queries. It may
// only be a single connection in a simple case or it could be multiple connections in some cases.
var connections = this._getConnections();
// Now that all the connections are created, build up operations needed to accomplish the end
// goal of getting all the results no matter which connection they are on. To do this,
// figure out if a connection supports joins and if so pass down a criteria object containing
// join instructions. If joins are not supported by a connection, build a series of operations
// to achieve the end result.
operations = this._stageOperations(connections);
return operations;
};
/**
* Stage Operation Sets
*
* @param {Object} connections
* @api private
*/
Operations.prototype._stageOperations = function _stageOperations(connections) {
var self = this;
var operations = [];
// Build the parent operation and set it as the first operation in the array
operations = operations.concat(this._createParentOperation(connections));
// Parent Connection Name
var parentConnection = this.context.adapterDictionary[this.parent];
// Parent Operation
var parentOperation = operations[0];
// For each additional connection build operations
Object.keys(connections).forEach(function(connection) {
// Ignore the connection used for the parent operation if a join can be used on it.
// This means all of the operations for the query can take place on a single connection
// using a single query.
if (connection === parentConnection && parentOperation.method === 'join') return;
// Operations are needed that will be run after the parent operation has been completed.
// If there are more than a single join, set the parent join and build up children operations.
// This occurs in a many-to-many relationship when a join table is needed.
// Criteria is omitted until after the parent operation has been run so that an IN query can
// be formed on child operations.
var localOpts = [];
connections[connection].joins.forEach(function(join, idx) {
var optCollection = self.context.waterline.collections[join.child];
var optConnectionName = optCollection.adapterDictionary['find'];
var operation = {
connection: optConnectionName,
collection: join.child,
method: 'find',
join: join
};
// If this is the first join, it can't have any parents
if (idx === 0) {
localOpts.push(operation);
return;
}
// Look into the previous operations and see if this is a child of any of them
var child = false;
localOpts.forEach(function(localOpt) {
if (localOpt.join.child !== join.parent) return;
localOpt.child = operation;
child = true;
});
if (child) return;
localOpts.push(operation);
});
operations = operations.concat(localOpts);
});
return operations;
};
/**
* Create The Parent Operation
*
* @param {Object} connections
* @return {Object}
* @api private
*/
Operations.prototype._createParentOperation = function _createParentOperation(connections) {
var nativeJoin = this.context.adapter.hasJoin();
var operation,
connectionName,
connection;
// If the parent supports native joins, check if all the joins on the connection can be
// run on the same connection and if so just send the entire criteria down to the connection.
if (nativeJoin) {
connectionName = this.context.adapterDictionary.join;
connection = connections[connectionName];
// Hold any joins that can't be run natively on this connection
var unsupportedJoins = false;
// Pull out any unsupported joins
connection.joins.forEach(function(join) {
if (connection.collections.indexOf(join.child) > -1) return;
unsupportedJoins = true;
});
// If all the joins were supported then go ahead and build an operation.
if (!unsupportedJoins) {
operation = [{
connection: connectionName,
collection: this.context.identity,
method: 'join',
criteria: this.criteria
}];
// Set the preCombined flag
this.preCombined = true;
return operation;
}
}
// Remove the joins from the criteria object, this will be an in-memory join
var tmpCriteria = _.cloneDeep(this.criteria);
delete tmpCriteria.joins;
connectionName = this.context.adapterDictionary[this.parent];
// If findOne was used, use the same connection `find` is on.
if (this.parent === 'findOne' && !connectionName) {
connectionName = this.context.adapterDictionary.find;
}
connection = connections[connectionName];
operation = [{
connection: connectionName,
collection: this.context.identity,
method: this.parent,
criteria: tmpCriteria
}];
return operation;
};
/**
* Get the connections used in this query and the join logic for each piece.
*
* @return {Object}
* @api private
*/
Operations.prototype._getConnections = function _getConnections() {
var self = this;
var connections = {};
// Default structure for connection objects
var defaultConnection = {
collections: [],
children: [],
joins: []
};
// For each join build a connection item to build up an entire collection/connection registry
// for this query. Using this, queries should be able to be seperated into discrete queries
// which can be run on connections in parallel.
this.criteria.joins.forEach(function(join) {
var connection;
var parentConnection;
var childConnection;
function getConnection(collName) {
var collection = self.context.waterline.collections[collName];
var connectionName = collection.adapterDictionary['find'];
connections[connectionName] = connections[connectionName] || _.cloneDeep(defaultConnection);
return connections[connectionName];
}
// If this join is a junctionTable, find the parent operation and add it to that connections
// children instead of creating a new operation on another connection. This allows cross-connection
// many-to-many joins to be used where the join relies on the results of the parent operation
// being run first.
if (join.junctionTable) {
// Find the previous join
var parentJoin = _.find(self.criteria.joins, function(otherJoin) {
return otherJoin.child == join.parent;
});
// Grab the parent join connection
var parentJoinConnection = getConnection(parentJoin.parent);
// Find the connection the parent and child collections belongs to
parentConnection = getConnection(join.parent);
childConnection = getConnection(join.child);
// Update the registry
parentConnection.collections.push(join.parent);
childConnection.collections.push(join.child);
parentConnection.children.push(join.parent);
// Ensure the arrays are made up only of unique values
parentConnection.collections = _.uniq(parentConnection.collections);
childConnection.collections = _.uniq(childConnection.collections);
parentConnection.children = _.uniq(parentConnection.children);
// Add the join to the correct joins array. We want it to be on the same
// connection as the operation before so the timing is correct.
parentJoinConnection.joins = parentJoinConnection.joins.concat(join);
// Build up the connection registry like normal
} else {
parentConnection = getConnection(join.parent);
childConnection = getConnection(join.child);
parentConnection.collections.push(join.parent);
childConnection.collections.push(join.child);
parentConnection.joins = parentConnection.joins.concat(join);
}
});
return connections;
};
/**
* Run An Operation
*
* Performs an operation and runs a supplied callback.
*
* @param {Object} collectionName
* @param {String} method
* @param {Object} criteria
* @param {Function} cb
*
* @api private
*/
Operations.prototype._runOperation = function _runOperation(collectionName, method, criteria, cb) {
// Ensure the collection exist
Iif (!hasOwnProperty(this.context.waterline.collections, collectionName)) {
return cb(new Error('Invalid Collection specfied in operation.'));
}
// Find the connection object to run the operation
var collection = this.context.waterline.collections[collectionName];
// Run the operation
collection.adapter[method](criteria, cb, this.metaContainer);
};
/**
* Execute Child Operations
*
* If joins are used and an adapter doesn't support them, there will be child operations that will
* need to be run. Parse each child operation and run them along with any tree joins and return
* an array of children results that can be combined with the parent results.
*
* @param {Array} parentResults
* @param {Function} cb
*/
Operations.prototype._execChildOpts = function _execChildOpts(parentResults, cb) {
var self = this;
// Build up a set of child operations that will need to be run
// based on the results returned from the parent operation.
this._buildChildOpts(parentResults, function(err, opts) {
Iif (err) return cb(err);
// Run the generated operations in parallel
async.each(opts, function(item, next) {
self._collectChildResults(item, next);
}, cb);
});
};
/**
* Build Child Operations
*
* Using the results of a parent operation, build up a set of operations that contain criteria
* based on what is returned from a parent operation. These can be arrays containing more than
* one operation for each child, which will happen when "join tables" would be used.
*
* Each set should be able to be run in parallel.
*
* @param {Array} parentResults
* @param {Function} cb
* @return {Array}
* @api private
*/
Operations.prototype._buildChildOpts = function _buildChildOpts(parentResults, cb) {
var self = this;
var opts = [];
// Build up operations that can be run in parallel using the results of the parent operation
async.each(this.operations, function(item, next) {
var localOpts = [];
var parents = [];
var idx = 0;
// Go through all the parent records and build up an array of keys to look in. This
// will be used in an IN query to grab all the records needed for the "join".
parentResults.forEach(function(result) {
if (!hasOwnProperty(result, item.join.parentKey)) return;
Iif (result[item.join.parentKey] === null || typeof result[item.join.parentKey] === undefined) return;
parents.push(result[item.join.parentKey]);
});
// If no parents match the join criteria, don't build up an operation
Iif (parents.length === 0) return next();
// Build up criteria that will be used inside an IN query
var criteria = {};
criteria[item.join.childKey] = parents;
var _tmpCriteria = {};
// Check if the join contains any criteria
if (item.join.criteria) {
var userCriteria = _.cloneDeep(item.join.criteria);
_tmpCriteria = _.cloneDeep(userCriteria);
_tmpCriteria = normalize.criteria(_tmpCriteria);
// Ensure `where` criteria is properly formatted
Eif (hasOwnProperty(userCriteria, 'where')) {
Iif (userCriteria.where === undefined) {
delete userCriteria.where;
} else {
// If an array of primary keys was passed in, normalize the criteria
Iif (Array.isArray(userCriteria.where)) {
var pk = self.context.waterline.collections[item.join.child].primaryKey;
var obj = {};
obj[pk] = _.clone(userCriteria.where);
userCriteria.where = obj;
}
}
}
criteria = _.merge(userCriteria, { where: criteria });
}
// Normalize criteria
criteria = normalize.criteria(criteria);
// If criteria contains a skip or limit option, an operation will be needed for each parent.
if (hasOwnProperty(_tmpCriteria, 'skip') || hasOwnProperty(_tmpCriteria, 'limit')) {
parents.forEach(function(parent) {
var tmpCriteria = _.cloneDeep(criteria);
tmpCriteria.where[item.join.childKey] = parent;
// Mixin the user defined skip and limit
if (hasOwnProperty(_tmpCriteria, 'skip')) tmpCriteria.skip = _tmpCriteria.skip;
Eif (hasOwnProperty(_tmpCriteria, 'limit')) tmpCriteria.limit = _tmpCriteria.limit;
// Build a simple operation to run with criteria from the parent results.
// Give it an ID so that children operations can reference it if needed.
localOpts.push({
id: idx,
collection: item.collection,
method: item.method,
criteria: tmpCriteria,
join: item.join
});
});
} else {
// Build a simple operation to run with criteria from the parent results.
// Give it an ID so that children operations can reference it if needed.
localOpts.push({
id: idx,
collection: item.collection,
method: item.method,
criteria: criteria,
join: item.join
});
}
// If there are child records, add the opt but don't add the criteria
if (!item.child) {
opts.push(localOpts);
return next();
}
localOpts.push({
collection: item.child.collection,
method: item.child.method,
parent: idx,
join: item.child.join
});
// Add the local opt to the opts array
opts.push(localOpts);
next();
}, function(err) {
cb(err, opts);
});
};
/**
* Collect Child Operation Results
*
* Run a set of child operations and return the results in a namespaced array
* that can later be used to do an in-memory join.
*
* @param {Array} opts
* @param {Function} cb
* @api private
*/
Operations.prototype._collectChildResults = function _collectChildResults(opts, cb) {
var self = this;
var intermediateResults = [];
var i = 0;
Iif (!opts || opts.length === 0) return cb(null, {});
// Run the operations and any child operations in series so that each can access the
// results of the previous operation.
async.eachSeries(opts, function(opt, next) {
self._runChildOperations(intermediateResults, opt, function(err, values) {
Iif (err) return next(err);
// If there are multiple operations and we are on the first one lets put the results
// into an intermediate results array
if (opts.length > 1 && i === 0) {
intermediateResults = intermediateResults.concat(values);
}
// Add values to the cache key
self.cache[opt.collection] = self.cache[opt.collection] || [];
self.cache[opt.collection] = self.cache[opt.collection].concat(values);
// Ensure the values are unique
var pk = self._findCollectionPK(opt.collection);
self.cache[opt.collection] = _.uniq(self.cache[opt.collection], pk);
i++;
next();
});
}, cb);
};
/**
* Run A Child Operation
*
* Executes a child operation and appends the results as a namespaced object to the
* main operation results object.
*
* @param {Object} optResults
* @param {Object} opt
* @param {Function} callback
* @api private
*/
Operations.prototype._runChildOperations = function _runChildOperations(intermediateResults, opt, cb) {
var self = this;
// Check if value has a parent, if so a join table was used and we need to build up dictionary
// values that can be used to join the parent and the children together.
// If the operation doesn't have a parent operation run it
if (!hasOwnProperty(opt, 'parent')) {
return self._runOperation(opt.collection, opt.method, opt.criteria, function(err, values) {
Iif (err) return cb(err);
cb(null, values);
});
}
// If the operation has a parent, look into the optResults and build up a criteria
// object using the results of a previous operation
var parents = [];
// Normalize to array
var res = _.cloneDeep(intermediateResults);
// Build criteria that can be used with an `in` query
res.forEach(function(result) {
parents.push(result[opt.join.parentKey]);
});
var criteria = {};
criteria[opt.join.childKey] = parents;
// Check if the join contains any criteria
Eif (opt.join.criteria) {
var userCriteria = _.cloneDeep(opt.join.criteria);
// Ensure `where` criteria is properly formatted
Eif (hasOwnProperty(userCriteria, 'where')) {
Iif (userCriteria.where === undefined) {
delete userCriteria.where;
}
}
delete userCriteria.sort;
delete userCriteria.skip;
delete userCriteria.limit;
criteria = _.merge({}, userCriteria, { where: criteria });
}
criteria = normalize.criteria(criteria);
// Empty the cache for the join table so we can only add values used
var cacheCopy = _.cloneDeep(self.cache[opt.join.parent]);
self.cache[opt.join.parent] = [];
self._runOperation(opt.collection, opt.method, criteria, function(err, values) {
Iif (err) return cb(err);
// Build up the new join table result
values.forEach(function(val) {
cacheCopy.forEach(function(copy) {
if (copy[opt.join.parentKey] === val[opt.join.childKey]) self.cache[opt.join.parent].push(copy);
});
});
// Ensure the values are unique
var pk = self._findCollectionPK(opt.join.parent);
self.cache[opt.join.parent] = _.uniq(self.cache[opt.join.parent], pk);
cb(null, values);
});
};
/**
* Find A Collection's Primary Key
*
* @param {String} collectionName
* @api private
* @return {String}
*/
Operations.prototype._findCollectionPK = function _findCollectionPK(collectionName) {
var pk;
for (var attribute in this.context.waterline.collections[collectionName]._attributes) {
var attr = this.context.waterline.collections[collectionName]._attributes[attribute];
if (hasOwnProperty(attr, 'primaryKey') && attr.primaryKey) {
pk = attr.columnName || attribute;
break;
}
}
return pk || null;
};
|