| 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 |
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
492×
492×
492×
492×
492×
492×
121×
371×
371×
1×
16×
1×
1×
371×
111×
170×
115×
115×
371×
1×
1×
370×
370×
370×
370×
370×
260×
260×
110×
76×
34×
34×
173×
34×
34×
34×
34×
34×
34×
34×
52×
52×
52×
34×
34×
34×
34×
52×
34×
34×
7×
7×
34×
2×
370×
251×
251×
251×
255×
251×
251×
251×
251×
251×
255×
251×
449×
449×
449×
2×
2×
2×
2×
449×
262×
262×
262×
449×
449×
449×
449×
449×
180×
269×
1×
268×
5×
268×
3×
48×
3×
3×
268×
268×
268×
45×
58×
46×
46×
268×
268×
268×
257×
257×
212×
212×
45×
26×
19×
19×
98×
19×
19×
19×
19×
19×
19×
19×
25×
25×
25×
19×
19×
19×
32×
41×
33×
33×
33×
9×
33×
8×
1×
8×
1×
19×
2×
257×
248×
248×
248×
248×
572×
248×
248×
248×
248×
248×
572×
248×
3×
| /**
* Basic Finder Queries
*/
var usageError = require('../../utils/usageError');
var utils = require('../../utils/helpers');
var normalize = require('../../utils/normalize');
var sorter = require('../../utils/sorter');
var Deferred = require('../deferred');
var Joins = require('./joins');
var Operations = require('./operations');
var Integrator = require('../integrator');
var waterlineCriteria = require('waterline-criteria');
var _ = require('lodash');
var async = require('async');
var hasOwnProperty = utils.object.hasOwnProperty;
module.exports = {
/**
* Find a single record that meets criteria
*
* @param {Object} criteria to search
* @param {Function} callback
* @return Deferred object if no callback
*/
findOne: function(criteria, cb, metaContainer) {
var self = this;
Iif (typeof criteria === 'function') {
cb = criteria;
criteria = null;
}
// If the criteria is an array of objects, wrap it in an "or"
Iif (Array.isArray(criteria) && _.all(criteria, function(crit) {return _.isObject(crit);})) {
criteria = {or: criteria};
}
// Check if criteria is an integer or string and normalize criteria
// to object, using the specified primary key field.
criteria = normalize.expandPK(self, criteria);
// Normalize criteria
criteria = normalize.criteria(criteria);
// Return Deferred or pass to adapter
if (typeof cb !== 'function') {
return new Deferred(this, this.findOne, criteria);
}
// Transform Search Criteria
criteria = self._transformer.serialize(criteria);
// If a projection is being used, ensure that the Primary Key is included
if(criteria.select) {
_.each(this._schema.schema, function(val, key) {
if (_.has(val, 'primaryKey') && val.primaryKey) {
criteria.select.push(key);
}
});
criteria.select = _.uniq(criteria.select);
}
// serialize populated object
if (criteria.joins) {
criteria.joins.forEach(function(join) {
if (join.criteria && join.criteria.where) {
var joinCollection = self.waterline.collections[join.child];
join.criteria.where = joinCollection._transformer.serialize(join.criteria.where);
}
});
}
// If there was something defined in the criteria that would return no results, don't even
// run the query and just return an empty result set.
if (criteria === false || criteria.where === null) {
// Build Default Error Message
var err = '.findOne() requires a criteria. If you want the first record try .find().limit(1)';
return cb(new Error(err));
}
// Build up an operations set
var operations = new Operations(self, criteria, 'findOne', metaContainer);
// Run the operations
operations.run(function(err, values) {
Iif (err) return cb(err);
Iif (!values.cache) return cb();
// If no joins are used grab the only item from the cache and pass to the returnResults
// function.
if (!criteria.joins) {
values = values.cache[self.identity];
return returnResults(values);
}
// If the values are already combined, return the results
if (values.combined) {
return returnResults(values.cache[self.identity]);
}
// Find the primaryKey of the current model so it can be passed down to the integrator.
// Use 'id' as a good general default;
var primaryKey = 'id';
Object.keys(self._schema.schema).forEach(function(key) {
if (self._schema.schema[key].hasOwnProperty('primaryKey') && self._schema.schema[key].primaryKey) {
primaryKey = key;
}
});
// Perform in-memory joins
Integrator(values.cache, criteria.joins, primaryKey, function(err, results) {
Iif (err) return cb(err);
Iif (!results) return cb();
// We need to run one last check on the results using the criteria. This allows a self
// association where we end up with two records in the cache both having each other as
// embedded objects and we only want one result. However we need to filter any join criteria
// out of the top level where query so that searchs by primary key still work.
var tmpCriteria = _.cloneDeep(criteria.where);
Iif (!tmpCriteria) tmpCriteria = {};
criteria.joins.forEach(function(join) {
Iif (!hasOwnProperty(join, 'alias')) return;
// Check for `OR` criteria
Iif (hasOwnProperty(tmpCriteria, 'or')) {
tmpCriteria.or.forEach(function(search) {
if (!hasOwnProperty(search, join.alias)) return;
delete search[join.alias];
});
return;
}
Eif (!hasOwnProperty(tmpCriteria, join.alias)) return;
delete tmpCriteria[join.alias];
});
// Pass results into Waterline-Criteria
var _criteria = { where: tmpCriteria };
results = waterlineCriteria('parent', { parent: results }, _criteria).results;
results.forEach(function(res) {
// Go Ahead and perform any sorts on the associated data
criteria.joins.forEach(function(join) {
if (!join.criteria) return;
var c = normalize.criteria(join.criteria);
if (!c.sort) return;
var alias = join.alias;
res[alias] = sorter(res[alias], c.sort);
});
});
returnResults(results);
});
function returnResults(results) {
if (!results) return cb();
// Normalize results to an array
if (!Array.isArray(results) && results) results = [results];
// Unserialize each of the results before attempting any join logic on them
var unserializedModels = [];
results.forEach(function(result) {
unserializedModels.push(self._transformer.unserialize(result));
});
var models = [];
var joins = criteria.joins ? criteria.joins : [];
var data = new Joins(joins, unserializedModels, self.identity, self._schema.schema, self.waterline.collections);
// If `data.models` is invalid (not an array) return early to avoid getting into trouble.
Iif (!data || !data.models || !data.models.forEach) {
return cb(new Error('Values returned from operations set are not an array...'));
}
// Create a model for the top level values
data.models.forEach(function(model) {
models.push(new self._model(model, data.options));
});
cb(null, models[0]);
}
});
},
/**
* Find All Records that meet criteria
*
* @param {Object} search criteria
* @param {Object} options
* @param {Function} callback
* @return Deferred object if no callback
*/
find: function(criteria, options, cb, metaContainer) {
var self = this;
var usage = utils.capitalize(this.identity) + '.find([criteria],[options]).exec(callback|switchback)';
if (typeof criteria === 'function') {
cb = criteria;
criteria = null;
Eif(arguments.length === 1) {
options = null;
}
}
// If options is a function, we want to check for any more values before nulling
// them out or overriding them.
if (typeof options === 'function') {
// If cb also exists it means there is a metaContainer value
Iif (cb) {
metaContainer = cb;
cb = options;
options = null;
} else {
cb = options;
options = null;
}
}
// If the criteria is an array of objects, wrap it in an "or"
Iif (Array.isArray(criteria) && _.all(criteria, function(crit) {return _.isObject(crit);})) {
criteria = {or: criteria};
}
// Check if criteria is an integer or string and normalize criteria
// to object, using the specified primary key field.
criteria = normalize.expandPK(self, criteria);
// Normalize criteria
criteria = normalize.criteria(criteria);
// Validate Arguments
Iif (typeof criteria === 'function' || typeof options === 'function') {
return usageError('Invalid options specified!', usage, cb);
}
// Return Deferred or pass to adapter
if (typeof cb !== 'function') {
return new Deferred(this, this.find, criteria, options);
}
// If there was something defined in the criteria that would return no results, don't even
// run the query and just return an empty result set.
if (criteria === false) {
return cb(null, []);
}
// Fold in options
if (options === Object(options) && criteria === Object(criteria)) {
criteria = _.extend({}, criteria, options);
}
// If a projection is being used, ensure that the Primary Key is included
if(criteria.select) {
_.each(this._schema.schema, function(val, key) {
if (_.has(val, 'primaryKey') && val.primaryKey) {
criteria.select.push(key);
}
});
criteria.select = _.uniq(criteria.select);
}
// Transform Search Criteria
Iif (!self._transformer) {
throw new Error('Waterline can not access transformer-- maybe the context of the method is being overridden?');
}
criteria = self._transformer.serialize(criteria);
// serialize populated object
if (criteria.joins) {
criteria.joins.forEach(function(join) {
if (join.criteria && join.criteria.where) {
var joinCollection = self.waterline.collections[join.child];
join.criteria.where = joinCollection._transformer.serialize(join.criteria.where);
}
});
}
// Build up an operations set
var operations = new Operations(self, criteria, 'find', metaContainer);
// Run the operations
operations.run(function(err, values) {
if (err) return cb(err);
Iif (!values.cache) return cb();
// If no joins are used grab current collection's item from the cache and pass to the returnResults
// function.
if (!criteria.joins) {
values = values.cache[self.identity];
return returnResults(values);
}
// If the values are already combined, return the results
if (values.combined) {
return returnResults(values.cache[self.identity]);
}
// Find the primaryKey of the current model so it can be passed down to the integrator.
// Use 'id' as a good general default;
var primaryKey = 'id';
Object.keys(self._schema.schema).forEach(function(key) {
if (self._schema.schema[key].hasOwnProperty('primaryKey') && self._schema.schema[key].primaryKey) {
primaryKey = key;
}
});
// Perform in-memory joins
Integrator(values.cache, criteria.joins, primaryKey, function(err, results) {
Iif (err) return cb(err);
Iif (!results) return cb();
// We need to run one last check on the results using the criteria. This allows a self
// association where we end up with two records in the cache both having each other as
// embedded objects and we only want one result. However we need to filter any join criteria
// out of the top level where query so that searchs by primary key still work.
var tmpCriteria = _.cloneDeep(criteria.where);
if (!tmpCriteria) tmpCriteria = {};
criteria.joins.forEach(function(join) {
Iif (!hasOwnProperty(join, 'alias')) return;
// Check for `OR` criteria
Iif (hasOwnProperty(tmpCriteria, 'or')) {
tmpCriteria.or.forEach(function(search) {
if (!hasOwnProperty(search, join.alias)) return;
delete search[join.alias];
});
return;
}
Eif (!hasOwnProperty(tmpCriteria, join.alias)) return;
delete tmpCriteria[join.alias];
});
// Pass results into Waterline-Criteria
var _criteria = { where: tmpCriteria };
results = waterlineCriteria('parent', { parent: results }, _criteria).results;
// Serialize values coming from an in-memory join before modelizing
results.forEach(function(res) {
// Go Ahead and perform any sorts on the associated data
criteria.joins.forEach(function(join) {
if (!join.criteria) return;
var c = normalize.criteria(join.criteria);
var alias = join.alias;
if (c.sort) {
res[alias] = sorter(res[alias], c.sort);
}
// If a junction table was used we need to do limit and skip in-memory
// This is where it gets nasty, paginated stuff here is a pain and needs work
// Hopefully we can get a chance to re-do it in WL2 and not have this. Basically
// if you need paginated populates try and have all the tables in the query on the
// same connection so it can be done in a nice single query.
if (!join.junctionTable) return;
if (c.skip) {
res[alias].splice(0, c.skip);
}
if (c.limit) {
res[alias] = _.take(res[alias], c.limit);
}
});
});
returnResults(results);
});
function returnResults(results) {
if (!results) return cb(null, []);
// Normalize results to an array
Iif (!Array.isArray(results) && results) results = [results];
// Unserialize each of the results before attempting any join logic on them
var unserializedModels = [];
Eif (results) {
results.forEach(function(result) {
unserializedModels.push(self._transformer.unserialize(result));
});
}
var models = [];
var joins = criteria.joins ? criteria.joins : [];
var data = new Joins(joins, unserializedModels, self.identity, self._schema.schema, self.waterline.collections);
// NOTE:
// If a "belongsTo" (i.e. HAS_FK) association is null, should it be transformed into
// an empty array here? That is not what is happening currently, and it can cause
// unexpected problems when implementing the native join method as an adapter implementor.
// ~Mike June 22, 2014
// If `data.models` is invalid (not an array) return early to avoid getting into trouble.
Iif (!data || !data.models || !data.models.forEach) {
return cb(new Error('Values returned from operations set are not an array...'));
}
// Create a model for the top level values
data.models.forEach(function(model) {
models.push(new self._model(model, data.options));
});
cb(null, models);
}
});
},
where: function() {
this.find.apply(this, Array.prototype.slice.call(arguments));
},
select: function() {
this.find.apply(this, Array.prototype.slice.call(arguments));
},
/**
* findAll
* [[ Deprecated! ]]
*
* @param {Object} criteria
* @param {Object} options
* @param {Function} cb
*/
findAll: function(criteria, options, cb) {
if (typeof criteria === 'function') {
cb = criteria;
criteria = null;
options = null;
}
if (typeof options === 'function') {
cb = options;
options = null;
}
// Return Deferred or pass to adapter
if (typeof cb !== 'function') {
return new Deferred(this, this.findAll, criteria);
}
cb(new Error('In Waterline >= 0.9, findAll() has been deprecated in favor of find().' +
'\nPlease visit the migration guide at http://sailsjs.org for help upgrading.'));
}
};
|