all files / lib/waterline/query/ deferred.js

82.13% Statements 170/207
79.84% Branches 99/124
76.47% Functions 26/34
84.69% Lines 166/196
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                      635× 635×   635× 635× 635× 635×   635×   635×                                                                                                                       162× 162× 162× 162× 162×       162×         161× 161×                   161×                       161×     161×     161× 939× 161×       161×                   161×       161×                       161× 161× 161×   826× 29×       797×       797× 545× 545×     252×         161× 161× 826× 161×       161×     161× 121×     161×   161× 161×     161× 61× 61× 123×   100×     161×     161× 67× 67×   336× 67×       269×       269× 269× 269×               67× 336× 67×       67×   67×                         67×       161× 67× 67× 94× 94× 94×       161×   161×                                                                                                                               10×   10×                   10×   10×                                                                           54×     54×   54×   54× 54×     54×   54×                                                                                         13×   13×                                     635×           635×     635× 635×     635×         635×             19× 18×   19×               18×                                                           10×     10×    
/**
 * Deferred Object
 *
 * Used for building up a Query
 */
 
var util = require('util');
var Promise = require('bluebird');
var _ = require('lodash');
var normalize = require('../utils/normalize');
var utils = require('../utils/helpers');
var acyclicTraversal = require('../utils/acyclicTraversal');
var hasOwnProperty = utils.object.hasOwnProperty;
 
// Alias "catch" as "fail", for backwards compatibility with projects
// that were created using Q
Promise.prototype.fail = Promise.prototype.catch;
 
var Deferred = module.exports = function(context, method, criteria, values) {
 
  Iif (!context) return new Error('Must supply a context to a new Deferred object. Usage: new Deferred(context, method, criteria)');
  Iif (!method) return new Error('Must supply a method to a new Deferred object. Usage: new Deferred(context, method, criteria)');
 
  this._context = context;
  this._method = method;
  this._criteria = criteria;
  this._values = values || null;
 
  this._deferred = null; // deferred object for promises
 
  return this;
};
 
 
/**
 * Add join clause(s) to the criteria object to populate
 * the specified alias all the way down (or at least until a
 * circular pattern is detected.)
 *
 * @param  {String} keyName  [the initial alias aka named relation]
 * @param  {Object} criteria [optional]
 * @return this
 * @chainable
 *
 * WARNING:
 * This method is not finished yet!!
 */
Deferred.prototype.populateDeep = function(keyName, criteria) {
 
  // The identity of the initial model
  var identity = this._context.identity;
 
  // The input schema
  var schema = this._context.waterline.schema;
 
  // Kick off recursive function to traverse the schema graph.
  var plan = acyclicTraversal(schema, identity, keyName);
 
  // TODO: convert populate plan into a join plan
  // this._criteria.joins = ....
 
  // TODO: also merge criteria object into query
 
  return this;
};
 
/**
 * Populate all associations of a collection.
 *
 * @return this
 * @chainable
 */
Deferred.prototype.populateAll = function(criteria) {
  var self = this;
  this._context.associations.forEach(function(association) {
    self.populate(association.alias, criteria);
  });
  return this;
 
};
 
/**
 * Add a `joins` clause to the criteria object.
 *
 * Used for populating associations.
 *
 * @param {String|Array} key, the key to populate or array of string keys
 * @return this
 * @chainable
 */
 
Deferred.prototype.populate = function(keyName, criteria) {
 
  var self = this;
  var joins = [];
  var pk = 'id';
  var attr;
  var join;
 
  // Adds support for arrays into keyName so that a list of
  // populates can be passed
  if (_.isArray(keyName)) {
    keyName.forEach(function(populate) {
      self.populate(populate, criteria);
    });
    return this;
  }
 
  // Normalize sub-criteria
  try {
    criteria = normalize.criteria(criteria);
 
    ////////////////////////////////////////////////////////////////////////
    // TODO:
    // instead of doing this, target the relevant pieces of code
    // with weird expectations and teach them a lesson
    // e.g. `lib/waterline/query/finders/operations.js:665:12`
    // (delete userCriteria.sort)
    //
    // Except make sure `where` exists
    criteria.where = criteria.where === false ? false : (criteria.where || {});
    ////////////////////////////////////////////////////////////////////////
 
  } catch (e) {
    throw new Error(
      'Could not parse sub-criteria passed to ' +
      util.format('`.populate("%s")`', keyName) +
      '\nSub-criteria:\n' + util.inspect(criteria, false, null) +
      '\nDetails:\n' + util.inspect(e, false, null)
    );
  }
 
  try {
 
    // Set the attr value to the generated schema attribute
    attr = this._context.waterline.schema[this._context.identity].attributes[keyName];
 
    // Get the current collection's primary key attribute
    Object.keys(this._context._attributes).forEach(function(key) {
      if (hasOwnProperty(self._context._attributes[key], 'primaryKey') && self._context._attributes[key].primaryKey) {
        pk = self._context._attributes[key].columnName || key;
      }
    });
 
    Iif (!attr) {
      throw new Error(
        'In ' + util.format('`.populate("%s")`', keyName) +
        ', attempting to populate an attribute that doesn\'t exist'
      );
    }
 
    // Grab the key being populated to check if it is a has many to belongs to
    // If it's a belongs_to the adapter needs to know that it should replace the foreign key
    // with the associated value.
    var parentKey = this._context.waterline.collections[this._context.identity].attributes[keyName];
 
    // Build the initial join object that will link this collection to either another collection
    // or to a junction table.
    join = {
      parent: this._context.identity,
      parentKey: attr.columnName || pk,
      child: attr.references,
      childKey: attr.on,
      alias: keyName,
      removeParentKey: !!parentKey.model,
      model: !!hasOwnProperty(parentKey, 'model'),
      collection: !!hasOwnProperty(parentKey, 'collection')
    };
 
    // Build select object to use in the integrator
    var select = [];
    var customSelect = criteria.select && _.isArray(criteria.select);
    _.each(this._context.waterline.schema[attr.references].attributes, function(val, key) {
      // Ignore virtual attributes
      if(_.has(val, 'collection')) {
        return;
      }
 
      // Check if the user has defined a custom select and if so normalize it
      Iif(customSelect && !_.includes(criteria.select, key)) {
        return;
      }
 
      if (!_.has(val, 'columnName')) {
        select.push(key);
        return;
      }
 
      select.push(val.columnName);
    });
 
    // Ensure the PK and FK on the child are always selected - otherwise things
    // like the integrator won't work correctly
    var childPk;
    _.each(this._context.waterline.schema[attr.references].attributes, function(val, key) {
      if(_.has(val, 'primaryKey') && val.primaryKey) {
        childPk = val.columnName || key;
      }
    });
 
    select.push(childPk);
 
    // Add the foreign key for collections
    if(join.collection) {
      select.push(attr.on);
    }
 
    join.select = select;
 
    var schema = this._context.waterline.schema[attr.references];
    var reference = null;
 
    // If linking to a junction table the attributes shouldn't be included in the return value
    if (schema.junctionTable) {
      join.select = false;
      reference = _.find(schema.attributes, function(attribute) {
        return attribute.references && attribute.columnName !== attr.on;
      });
    } else if (schema.throughTable && schema.throughTable[self._context.identity + '.' + keyName]) {
      join.select = false;
      reference = schema.attributes[schema.throughTable[self._context.identity + '.' + keyName]];
    }
 
    joins.push(join);
 
    // If a junction table is used add an additional join to get the data
    if (reference && hasOwnProperty(attr, 'on')) {
      var selects = [];
      _.each(this._context.waterline.schema[reference.references].attributes, function(val, key) {
        // Ignore virtual attributes
        if(_.has(val, 'collection')) {
          return;
        }
 
        // Check if the user has defined a custom select and if so normalize it
        Iif(customSelect && !_.includes(criteria.select, key)) {
          return;
        }
 
        Eif (!_.has(val, 'columnName')) {
          selects.push(key);
          return;
        }
 
        selects.push(val.columnName);
      });
 
      // Ensure the PK and FK are always selected - otherwise things like the
      // integrator won't work correctly
      _.each(this._context.waterline.schema[reference.references].attributes, function(val, key) {
        if(_.has(val, 'primaryKey') && val.primaryKey) {
          childPk = val.columnName || key;
        }
      });
 
      selects.push(childPk);
 
      join = {
        parent: attr.references,
        parentKey: reference.columnName,
        child: reference.references,
        childKey: reference.on,
        select: _.uniq(selects),
        alias: keyName,
        junctionTable: true,
        removeParentKey: !!parentKey.model,
        model: false,
        collection: true
      };
 
      joins.push(join);
    }
 
    // Append the criteria to the correct join if available
    if (criteria && joins.length > 1) {
      joins[1].criteria = criteria;
      joins[1].criteria.select = join.select;
    } else Eif (criteria) {
      joins[0].criteria = criteria;
      joins[0].criteria.select = join.select;
    }
 
    // Set the criteria joins
    this._criteria.joins = Array.prototype.concat(this._criteria.joins || [], joins);
 
    return this;
  } catch (e) {
    throw new Error(
      'Encountered unexpected error while building join instructions for ' +
      util.format('`.populate("%s")`', keyName) +
      '\nDetails:\n' +
      util.inspect(e, false, null)
    );
  }
};
 
/**
 * Add projections to the parent
 *
 * @param {Array} attributes to select
 * @return this
 */
 
Deferred.prototype.select = function(attributes) {
  if(!_.isArray(attributes)) {
    attributes = [attributes];
  }
 
  var select = this._criteria.select || [];
  select = select.concat(attributes);
  this._criteria.select = _.uniq(select);
 
  return this;
};
 
/**
 * Add a Where clause to the criteria object
 *
 * @param {Object} criteria to append
 * @return this
 */
 
Deferred.prototype.where = function(criteria) {
 
  Iif (!criteria) return this;
 
  // 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};
  }
 
  // Normalize criteria
  criteria = normalize.criteria(criteria);
 
  // Wipe out the existing WHERE clause if the specified criteria ends up `false`
  // (since neither could match anything)
  Iif (criteria === false) {
    this._criteria = false;
  }
 
  if (!criteria || !criteria.where) return this;
 
  Iif (!this._criteria) this._criteria = {};
  var where = this._criteria.where || {};
 
  // Merge with existing WHERE clause
  Object.keys(criteria.where).forEach(function(key) {
    where[key] = criteria.where[key];
  });
 
  this._criteria.where = where;
 
  return this;
};
 
/**
 * Add a Limit clause to the criteria object
 *
 * @param {Integer} number to limit
 * @return this
 */
 
Deferred.prototype.limit = function(limit) {
  this._criteria.limit = limit;
 
  return this;
};
 
/**
 * Add a Skip clause to the criteria object
 *
 * @param {Integer} number to skip
 * @return this
 */
 
Deferred.prototype.skip = function(skip) {
  this._criteria.skip = skip;
 
  return this;
};
 
/**
 * Add a Paginate clause to the criteria object
 *
 * This is syntatical sugar that calls skip and
 * limit from a single function.
 *
 * @param {Object} page and limit
 * @return this
 */
Deferred.prototype.paginate = function(options) {
  var defaultLimit = 10;
 
  if (options === undefined) options = { page: 0, limit: defaultLimit };
 
  var page = options.page || 0;
  var limit = options.limit || defaultLimit;
  var skip = 0;
 
  Iif (page > 0 && limit === 0) skip = page - 1;
  if (page > 0 && limit > 0) skip = (page * limit) - limit;
 
  this
  .skip(skip)
  .limit(limit);
 
  return this;
};
 
/**
 * Add a groupBy clause to the criteria object
 *
 * @param {Array|Arguments} Keys to group by
 * @return this
 */
Deferred.prototype.groupBy = function() {
  buildAggregate.call(this, 'groupBy', Array.prototype.slice.call(arguments));
  return this;
};
 
 
/**
 * Add a Sort clause to the criteria object
 *
 * @param {String|Object} key and order
 * @return this
 */
 
Deferred.prototype.sort = function(criteria) {
 
  Iif (!criteria) return this;
 
  // Normalize criteria
  criteria = normalize.criteria({ sort: criteria });
 
  var sort = this._criteria.sort || {};
 
  Object.keys(criteria.sort).forEach(function(key) {
    sort[key] = criteria.sort[key];
  });
 
  this._criteria.sort = sort;
 
  return this;
};
 
/**
 * Add a Sum clause to the criteria object
 *
 * @param {Array|Arguments} Keys to sum over
 * @return this
 */
Deferred.prototype.sum = function() {
  buildAggregate.call(this, 'sum', Array.prototype.slice.call(arguments));
  return this;
};
 
/**
 * Add an Average clause to the criteria object
 *
 * @param {Array|Arguments} Keys to average over
 * @return this
 */
Deferred.prototype.average = function() {
  buildAggregate.call(this, 'average', Array.prototype.slice.call(arguments));
  return this;
};
 
/**
 * Add a min clause to the criteria object
 *
 * @param {Array|Arguments} Keys to min over
 * @return this
 */
Deferred.prototype.min = function() {
  buildAggregate.call(this, 'min', Array.prototype.slice.call(arguments));
  return this;
};
 
/**
 * Add a min clause to the criteria object
 *
 * @param {Array|Arguments} Keys to min over
 * @return this
 */
Deferred.prototype.max = function() {
  buildAggregate.call(this, 'max', Array.prototype.slice.call(arguments));
  return this;
};
 
 
/**
 * Add values to be used in update or create query
 *
 * @param {Object, Array} values
 * @return this
 */
 
Deferred.prototype.set = function(values) {
  this._values = values;
 
  return this;
};
 
/**
 * Pass metadata down to the adapter that won't be processed or touched by Waterline
 */
 
Deferred.prototype.meta = function(data) {
  this._meta = data;
  return this;
};
 
/**
 * Execute a Query using the method passed into the
 * constuctor.
 *
 * @param {Function} callback
 * @return callback with parameters (err, results)
 */
 
Deferred.prototype.exec = function(cb) {
  Iif (!cb) {
    console.log('Error: No Callback supplied, you must define a callback.');
    return;
  }
 
  // Normalize callback/switchback
  cb = normalize.callback(cb);
 
  // Set up arguments + callback
  var args = [this._criteria, cb];
  if (this._values) args.splice(1, 0, this._values);
 
  // If there is a meta value, throw it on the very end
  Iif(this._meta) {
    args.push(this._meta);
  }
 
  // Pass control to the adapter with the appropriate arguments.
  this._method.apply(this._context, args);
};
 
/**
 * Executes a Query, and returns a promise
 */
 
Deferred.prototype.toPromise = function() {
  if (!this._deferred) {
    this._deferred = Promise.promisify(this.exec).bind(this)();
  }
  return this._deferred;
};
 
/**
 * Executes a Query, and returns a promise that applies cb/ec to the
 * result/error.
 */
 
Deferred.prototype.then = function(cb, ec) {
  return this.toPromise().then(cb, ec);
};
 
/**
 * Applies results to function fn.apply, and returns a promise
 */
 
Deferred.prototype.spread = function(cb) {
  return this.toPromise().spread(cb);
};
 
/**
 * returns a promise and gets resolved with error
 */
 
Deferred.prototype.catch = function(cb) {
  return this.toPromise().catch(cb);
};
 
 
/**
 * Alias "catch" as "fail"
 */
Deferred.prototype.fail = Deferred.prototype.catch;
 
/**
 * Build An Aggregate Criteria Option
 *
 * @param {String} key
 * @api private
 */
 
function buildAggregate(key, args) {
 
  // If passed in a list, set that as the min criteria
  if (args[0] instanceof Array) {
    args = args[0];
  }
 
  this._criteria[key] = args || {};
}