all files / lib/offshore/query/finders/ basic.js

66.57% Statements 223/335
71.55% Branches 166/232
53.73% Functions 36/67
68.37% Lines 214/313
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          12× 12× 24×   12× 12× 12×                             721×   721×           721×           721×     721×     721× 206×       515×     515× 16×             515× 179× 280× 185× 185×             515×         514×     514× 514× 514×       514× 336× 336×       178× 101×       77×   77× 417× 77×         77× 77× 77×           77× 77×   77× 121×     121×                 121× 52×         77× 77× 77×     77× 121× 79× 79×   79×                                         79×                                         79×                                         79×                                       79×   27×       77×       514×     401×     401× 401× 403×     401× 401× 401×     401×         401× 403×     401×                             1300× 1300×   1300×             1300×     746×         746× 746×           1300×           1300×     1300×     1300×         1300× 547×         753×       752×       752× 64×             752×     752×         752× 347× 504× 504× 352×   504× 178×           752×     752× 752× 741×       741× 394× 394×       347× 194×         153×   153× 906× 153×         153× 153× 153×           153× 153×   153× 223×     223×                 223×         153×   153×   153×     254× 382× 255× 255× 255× 159×     255×                       12×         255×                       12×         255×                       12×         255× 18×   12×       12×                   255×   127× 41×     127× 43×           153×       741×     732×     732×   732× 732× 1230×       732× 732× 732×                 732×         732× 1230×     732×                                                                                        
/**
 * 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 offshoreCriteria = require('offshore-criteria');
var _ = require('lodash');
var async = require('async');
var hasOwnProperty = utils.object.hasOwnProperty;
 
function groupBy( array , groupBykeys, fct) {
  var groups = {};
  array.forEach(function(item) {
    var groupValues = [];
    groupBykeys.forEach(function(key) {
      groupValues.push(item[key]);
    });
    var group = JSON.stringify(groupValues);
    groups[group] = groups[group] || [];
    groups[group].push(item);
  });
  return Object.keys(groups).map(function(group){
    return fct(groups[group]);
  });
}
 
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) && _.every(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.offshore.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, 'parentKey')) return;
 
          // Check for `OR` criteria
          Iif (hasOwnProperty(tmpCriteria, 'or')) {
            tmpCriteria.or.forEach(function(search) {
              if (hasOwnProperty(search, join.parentKey)) {
                delete search[join.parentKey];
              }
            });
            return;
          }
 
          if (hasOwnProperty(tmpCriteria, join.parentKey)) {
            delete tmpCriteria[join.parentKey];
          }
        });
 
        // Pass results into Offshore-Criteria
        var _criteria = { where: tmpCriteria };
        results = offshoreCriteria('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);
            var alias = join.alias;
 
            Iif (c.average && _.isArray(res[alias])) {
              if (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var average = {};
                  c.groupBy.forEach(function(groupBy) {
                    average[groupBy] = group[0][groupBy];
                  });
                  average[c.average[0]] = _.meanBy(group, function(item) {
                    return item[c.average[0]];
                  });
                  return average;
                });
              } else {
                var average = {};
                average[c.average[0]] = _.meanBy(res[alias], function(item) {
                  return item[c.average[0]];
                });
                res[alias] = [average];
              }
            }
 
            Iif (c.min && _.isArray(res[alias])) {
              if (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var min = {};
                  c.groupBy.forEach(function(groupBy) {
                    min[groupBy] = group[0][groupBy];
                  });
                  min[c.min[0]] = _.minBy(group, function(item) {
                    return item[c.min[0]];
                  });
                  return min;
                });
              } else {
                var min = {};
                min[c.min[0]] = _.minBy(res[alias], function(item) {
                  return item[c.min[0]];
                })[c.min[0]];
                res[alias] = [min];
              }
            }
 
            Iif (c.max && _.isArray(res[alias])) {
              if (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var max = {};
                  c.groupBy.forEach(function(groupBy) {
                    max[groupBy] = group[0][groupBy];
                  });
                  max[c.max[0]] = _.maxBy(group, function(item) {
                    return item[c.max[0]];
                  });
                  return max;
                });
              } else {
                var max = {};
                max[c.max[0]] = _.maxBy(res[alias], function(item) {
                  return item[c.max[0]];
                })[c.max[0]];
                res[alias] = [max];
              }
            }
 
            Iif (c.sum && _.isArray(res[alias])) {
              if (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var sum = {};
                  c.groupBy.forEach(function(groupBy) {
                    sum[groupBy] = group[0][groupBy];
                  });
                  sum[c.sum[0]] = _.sumBy(group, function(item) {
                    return item[c.sum[0]];
                  });
                  return sum;
                });
              } else {
                var sum = {};
                sum[c.sum[0]] = _.sumBy(res[alias], function(item) {
                  return item[c.sum[0]];
                });
                res[alias] = [sum];
              }
            }
            if (!c.sort) return;
 
            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.offshore.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)._loadQuery(self._query));
        });
 
        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) && _.every(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('Offshore 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) {
        var joinCollection = self.offshore.collections[join.child];
        if (join.criteria && join.criteria.where) {
          join.criteria.where = joinCollection._transformer.serialize(join.criteria.where);
        }
        if (join.criteria && join.criteria.sort) {
          join.criteria.sort = joinCollection._transformer.serialize(join.criteria.sort);
        }
      });
    }
 
    // 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, 'parentKey')) return;
 
          // Check for `OR` criteria
          Iif (hasOwnProperty(tmpCriteria, 'or')) {
            tmpCriteria.or.forEach(function(search) {
              if (hasOwnProperty(search, join.parentKey)) {
                delete search[join.parentKey];
              }
            });
            return;
          }
 
          if (hasOwnProperty(tmpCriteria, join.parentKey)) {
            delete tmpCriteria[join.parentKey];
          }
        });
 
        // Pass results into Offshore-Criteria
        var _criteria = { where: tmpCriteria };
 
        results = offshoreCriteria('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 (c.average && _.isArray(res[alias])) {
              Iif (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var average = {};
                  c.groupBy.forEach(function(groupBy) {
                    average[groupBy] = group[0][groupBy];
                  });
                  average[c.average[0]] = _.meanBy(group, function(item) {
                    return item[c.average[0]];
                  });
                  return average;
                });
              } else {
                var average = {};
                average[c.average[0]] = _.meanBy(res[alias], function(item) {
                  return item[c.average[0]];
                });
                res[alias] = [average];
              }
            }
 
            if (c.min && _.isArray(res[alias])) {
              Iif (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var min = {};
                  c.groupBy.forEach(function(groupBy) {
                    min[groupBy] = group[0][groupBy];
                  });
                  min[c.min[0]] = _.minBy(group, function(item) {
                    return item[c.min[0]];
                  });
                  return min;
                });
              } else {
                var min = {};
                min[c.min[0]] = _.minBy(res[alias], function(item) {
                  return item[c.min[0]];
                })[c.min[0]];
                res[alias] = [min];
              }
            }
 
            if (c.max && _.isArray(res[alias])) {
              Iif (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var max = {};
                  c.groupBy.forEach(function(groupBy) {
                    max[groupBy] = group[0][groupBy];
                  });
                  max[c.max[0]] = _.maxBy(group, function(item) {
                    return item[c.max[0]];
                  });
                  return max;
                });
              } else {
                var max = {};
                max[c.max[0]] = _.maxBy(res[alias], function(item) {
                  return item[c.max[0]];
                })[c.max[0]];
                res[alias] = [max];
              }
            }
 
            if (c.sum && _.isArray(res[alias])) {
              if (c.groupBy && _.isArray(c.groupBy)) {
                res[alias] = groupBy(res[alias], c.groupBy, function(group) {
                  var sum = {};
                  c.groupBy.forEach(function(groupBy) {
                    sum[groupBy] = group[0][groupBy];
                  });
                  sum[c.sum[0]] = _.sumBy(group, function(item) {
                    return item[c.sum[0]];
                  });
                  return sum;
                });
              } else {
                var sum = {};
                sum[c.sum[0]] = _.sumBy(res[alias], function(item) {
                  return item[c.sum[0]];
                });
                res[alias] = [sum];
              }
            }
 
            // 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.offshore.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)._loadQuery(self._query));
        });
 
        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 Offshore >= 0.9, findAll() has been deprecated in favor of find().' +
                '\nPlease visit the migration guide at http://sailsjs.org for help upgrading.'));
  }
 
};