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

84.85% Statements 420/495
81.35% Branches 253/311
83.95% Functions 68/81
85.02% Lines 420/494
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 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137                      1264×     1264×       1264× 1264×     1264× 1264× 5686×     1264× 1264×   1264×   1264×                                                                                                                                                                         12× 12×   12×         12×           12×   12×       12×       12× 12×                                                 567× 567× 567× 567× 567×       567×         566× 566× 566× 27×                   539×                       539×     539×     539× 3517× 539×       539×                   539×       539×                       539× 539× 539×   3196× 115×       3081× 54×     3027× 1275× 1275×     1752×         539× 539× 3196× 539×       539×     539× 395×     539×   539× 539×     539× 123× 123× 249×   416× 124× 124×     539×     539× 247× 247×   1972× 273×       1699× 26×     1673× 690× 690×     983×         247× 1972× 247×       247×   247×                         247×       539×     539× 247× 247× 292× 292× 292×       539×   539×                             27× 27× 27× 27× 27× 27×   27× 20× 20×   27× 25× 25× 29× 29× 18× 18× 18× 18×     18×             27× 61× 61×           61× 61× 26×       61× 30× 30× 30× 28×   30× 27×       30×   30× 30× 30×     30×       61× 61× 61×     27× 27×     1790× 1790× 1790× 1790× 1790× 1790× 453×   1337×     1010× 21× 43× 43×     43× 43×     21×     21×       989× 227×     762× 695×     67× 67× 51×       16× 16× 40× 22× 22× 20×   22× 24×   22×   18×   16× 16×   16×         16× 12× 12×   12×       12× 12×     12×   12×                                                 16× 12×                                           1337×       1337× 362×     975× 975× 1010×     1010×     975×                                                           15×         15×         15×       15×       15×     13×     13×     13× 13×     13×   13×                   10×   10×                   10×   10×                                                                               83×       83×   83×   83× 83×     83×   83×                                                                                         21×   21×                                     1210× 1210×           1210×   1210×   1210× 1210× 415×       1210×         1210×     1210× 1210× 526× 526× 526×     526× 517×   526×     526× 784× 247×   537× 537×     537× 175×   537×     526×     526×     526×     526×     684× 684×     684× 240×   684×           62×   62× 20×   20× 20× 20× 26× 26×               20× 20× 20×     20×   18× 18× 10×       10×   18× 18×         42×   42×   46× 46× 46×   46× 22×   24× 24×       24× 24× 24× 24×   24× 24× 24× 24×     24× 24× 24× 44×         24× 24×       42×     42×                   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;
var async = require('async');
var DeepCursor = require('./deepCursor');
var Criteria = require('./criteria');
var crypto = require('crypto');
 
// 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;
 
  // define the methodName
  var methods = ['find', 'findOne', 'findOrCreate', 'createEach', 'findOrCreateEach', 'count', 'create', 'destroy', 'update', 'findAll'];
  this._methodName = _.find(methods.concat(_.keys(context)), function(key) {
    return context[key] === method;
  }) || 'unknownMethod';
 
  this._criteria = criteria;
  this._values = values || null;
 
  this._deferred = null; // deferred object for promises
 
  return this;
};
 
Deferred.prototype.toString = function() {
  var criteria = Criteria.toString(this._criteria);
  var str = this._context.identity + '.' + this._methodName + '(' + criteria + ')';
 
  // check if there are deep populate
  Iif (this._criteria.paths) {
    var paths = _.sortBy(_.keys(this._criteria.paths), function(name) {
      return name;
    });
    for (var path in paths) {
      var joins = this._criteria.paths[path].joins;
      // sort joins by alias
      _.sortBy(joins, function(join) {
        return join.alias;
      }).forEach(function(join) {
        if (!join.junctionTable) {
          var joinCriteria = Criteria.toString(join.criteria);
          str += '.populate(' + path + '.' + join.alias + ',' + joinCriteria + ')';
        }
      });
    }
  } else Iif (this._criteria.joins) {
    // sort join by alias
    _.sortBy(this._criteria.joins, function(join) {
      return join.alias;
    }).forEach(function(join) {
      if (!join.junctionTable) {
        var joinCriteria = Criteria.toString(join.criteria);
        str += '.populate(' + join.alias + ',' + joinCriteria + ')';
      }
    });
  }
  return str;
};
 
/**
 * 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.offshore.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;
 
};
 
/**
 * Set _cacheKey and _cacheTime before execute the request.
 *
 * @param {String} key, the key to identify cache.
 * @param {Integer} time, the maximum time the cache must be used.
 * @param {Function} cb, callback
 * @return callback with parameters (err, results)
 */
Deferred.prototype.cache = function(key, time, cb) {
  var self = this;
  var callback, cacheKey, cacheTime;
 
  Iif (this._methodName !== 'find' && this._methodName !== 'findOne') {
    return cb(new Error(this._methodName + ' can not be cached'));
  }
 
  // define optional parameters
  if (cb && _.isFunction(cb)) {
    callback = cb;
    cacheTime = time;
    cacheKey = key;
  } else if (time && _.isFunction(time)) {
    callback = time;
    cacheTime = key;
  } else Eif (key && _.isFunction(key)) {
    callback = key;
  } else {
    console.log(new Error('Error: No Callback supplied, you must define a callback.').message);
    return;
  }
 
  cacheKey = cacheKey || crypto.createHash('sha1').update(this.toString()).digest('hex');
 
  Iif (cacheTime && !_.isNumber(cacheTime)) {
    throw new Error('Cache Time must be a number');
  }
 
  Iif (!_.isString(cacheKey)) {
    throw new Error('Cache Key must be a string');
  }
  // Check cache
  this._context.offshore.cache.get(cacheKey, function(err, cache) {
    if (err) {
      // if no cache
      Eif (err === self._context.offshore.cache.errors.NO_CACHE) {
        // execute the request and cache results
        return self.exec(function(err, data) {
          Iif (err) {
            return callback(err);
          }
          self._context.offshore.cache.set(cacheKey, data, cacheTime);
          callback(null, data);
        });
      }
      // return the error
      return callback(err);
    }
    // cache found return its value
    return callback(null, cache);
  });
};
 
/**
 * 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);
    if (keyName && keyName.indexOf('.') > -1) {
      return self.populatePath(keyName, criteria);
    }
    ////////////////////////////////////////////////////////////////////////
    // TODO:
    // instead of doing this, target the relevant pieces of code
    // with weird expectations and teach them a lesson
    // e.g. `lib/offshore/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.offshore.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.offshore.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.offshore.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
      if(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.offshore.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.offshore.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.offshore.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
        if(customSelect && !_.includes(criteria.select, key)) {
          return;
        }
 
        if (!_.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.offshore.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);
    }
 
    // get the association default criteria
    criteria = Criteria.merge(criteria, this._context.offshore.collections[this._context.identity]._attributes[keyName].criteria);
 
    // Append the criteria to the correct join if available
    if (criteria && joins.length > 1) {
      joins[1].criteria = this._context.offshore.collections[joins[1].child]._transformer.serialize(criteria);
      joins[1].criteria.select = join.select;
    } else Eif (criteria) {
      joins[0].criteria = this._context.offshore.collections[joins[0].child]._transformer.serialize(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)
    );
  }
};
 
/**
 * populate a path
 */
 
Deferred.prototype.populatePath = function(path, criteria) {
  var self = this;
  var pathChunks = path.split('.');
  var collections = this._context.offshore.collections;
  var parentName = this._context.identity;
  var currentPath = this._context.identity;
  var parentAttributes = collections[parentName]._attributes;
 
  if (!this._criteria.paths) {
    this._criteria.paths = {};
    this._criteria.paths[currentPath] = {joins: [], children: {}};
  }
  if (this._criteria.joins) {
    var currentPathRef = this._criteria.paths[currentPath];
    for (var i in this._criteria.joins) {
      var join = this._criteria.joins[i];
      if (!currentPathRef.children[join.alias] || !currentPathRef.children[join.alias].primaryKey) {
        var collections = this._context.offshore.collections;
        var childAttr = collections[this._context.identity].attributes[join.alias];
        var childCollection = childAttr.collection || childAttr.model;
        currentPathRef.children[join.alias] = {
          collectionName: childCollection,
          primaryKey: _.find(_.keys(collections[childCollection].attributes), function(attr) {
            return collections[childCollection].attributes[attr].primaryKey;
          })
        };
      }
    }
  }
 
  for (var j = 0; j < pathChunks.length; j++) {
    var currentAlias = pathChunks[j];
    Iif (!parentAttributes[currentAlias] || !(parentAttributes[currentAlias].model || parentAttributes[currentAlias].collection)) {
      throw new Error(
        'In ' + util.format('`.populate("%s")`', path) +
        ', attempting to populate an attribute that doesn\'t exist'
      );
    }
    var childName = parentAttributes[currentAlias].model || parentAttributes[currentAlias].collection;
    if (!this._criteria.paths[currentPath]) {
      this._criteria.paths[currentPath] = {joins: [], children: {}};
    }
 
    // if true, the alias does not exist in the current path, adding it
    if (_.keys(this._criteria.paths[currentPath].children).indexOf(currentAlias) === -1) {
      var joins;
      var parent = this;
      if (parentName !== this._context.identity) {
        parent = collections[parentName].find();
      }
      if (_.last(pathChunks) === currentAlias) {
        joins = parent.populate(currentAlias, criteria)._criteria.joins;
      } else {
        joins = parent.populate(currentAlias)._criteria.joins;
      }
 
      self._criteria.paths[currentPath].joins = Array.prototype.concat(self._criteria.paths[currentPath].joins || [], joins);
 
      var childAttributes = collections[childName].attributes;
      var childPk = _.find(_.keys(childAttributes), function(attr) {
        return childAttributes[attr].primaryKey;
      });
 
      this._criteria.paths[currentPath].children[currentAlias] = {collectionName: childName, primaryKey: childPk};
    }
 
    // child become parent for next loop
    parentName = childName;
    parentAttributes = collections[parentName]._attributes;
    currentPath += '.' + currentAlias;
  }
 
  this.exec = this.execDeep;
  return this;
};
 
Deferred.prototype.whereDeep = function(ParentName, where, cb) {
  var self = this;
  var values = _.clone(where);
  var collections = this._context.offshore.collections;
  var schema = this._context.offshore.schema[ParentName];
  var attributes = collections[ParentName].attributes;
  if (!where) {
    return cb(null, where);
  }
  async.map(_.keys(values), function(property, next) {
 
    // check if there is something to solve
    if ((property === 'or' || property === 'and') && _.isArray(values[property])) {
      return async.forEachOf(values[property], function(inner, index, next) {
        self.whereDeep(ParentName, inner, function(err, where) {
          Iif (err) {
            return next(err);
          }
          values[property][index] = where;
          next();
        });
      }, function(err) {
        Iif (err) {
          return next(err);
        }
        next(null, {key: property, value: values[property]});
      });
    }
 
    if (!attributes[property]) {
      return next(null, {key: property, value: values[property]});
    }
 
    if (!_.isPlainObject(values[property])) {
      return next(null, {key: property, value: values[property]});
    }
 
    var childName =  attributes[property]['collection'] || attributes[property]['model'];
    if (!childName) {
      return next(null, {key: property, value: values[property]});
    }
 
    // check if there is an attribute to resolve in criteria
    var childAttributes = _.keys(collections[childName].attributes);
    var deepKeys = function(obj) {
      if (obj && _.isObject(obj)) {
        var keys = [];
        if (_.isPlainObject(obj)) {
          keys = _.keys(obj);
        }
        for (key in obj) {
          keys = keys.concat(deepKeys(obj[key]));
        }
        return keys;
      }
      return [];
    };
    var criteriaKey = deepKeys(values[property]);
    var resolving = _.intersection(childAttributes, criteriaKey);
 
    Iif (resolving.length === 0) {
      return next(null, {key: property, value: values[property]});
    }
 
    // resolve hasMany
    if (hasOwnProperty(attributes[property], 'collection')) {
      var via = collections[ParentName].attributes[property].via;
      var childCollectionCriteria = _.clone(values[property]);
      // get the association default criteria
      childCollectionCriteria = Criteria.merge(childCollectionCriteria, collections[ParentName]._attributes[property].criteria);
 
      // offshore criteria should support {'!': null}
      // childCollectionCriteria[via] = {'!': null};
      collections[childName]._loadQuery(self._context._query).find(childCollectionCriteria).exec(function(err, data) {
        Iif (err) {
          return next(err);
        }
        var via = collections[ParentName].attributes[property].via;
        // if its a ManytoOne relation
        if (hasOwnProperty(collections[childName].attributes[via], 'model')) {
          var val = _.map(data, function(child) {
            return child[collections[ParentName].attributes[property].via];
          });
 
          val = _.filter(val, function(pk) {
            Iif (_.isUndefined(pk) || _.isNull(pk)) {
              return false;
            }
            return true;
          });
 
          return next(null, {
            key: collections[ParentName].primaryKey,
            value: _.uniq(val)
          });
        }
        // if it's a manyToMany relation
        var junctionTable;
        var junctionCriteria = {};
        // check if it's a throughTable
        if (hasOwnProperty(attributes[property], 'through')) {
          junctionTable = attributes[property]['through'];
          var associationKey = ParentName + '.' + property;
          var throughPk = self._context.offshore.schema[junctionTable].throughTable[associationKey];
          junctionCriteria[throughPk] = _.map(data, function(coll) {
            return coll[collections[childName].primaryKey];
          });
        } else {
          junctionTable = schema.attributes[property]['references'];
          var collectionSchema = self._context.offshore.schema[childName].attributes;
          junctionCriteria[collectionSchema[via].onKey || collectionSchema[via].on] = _.map(data, function(child) {
            return child[collections[childName].primaryKey];
          });
        }
 
        // get the association default criteria
        junctionCriteria = Criteria.merge(junctionCriteria, collections[ParentName]._attributes[property].criteria);
 
        collections[junctionTable]._loadQuery(self._context._query).find(junctionCriteria, function(err, data) {
          Iif (err) {
            return next(err);
          }
          next(null, {
            key: collections[ParentName].primaryKey,
            value: _.map(data, function(junction) {
              // throughTable
              if (hasOwnProperty(attributes[property], 'through')) {
                return junction[attributes[property].via];
              } else {
                // junctionTable
                return junction[schema.attributes[property].onKey || schema.attributes[property].on];
              }
            })
          });
        });
      });
    } else {
      // resolve belongsTo
      var child = collections[childName]._loadQuery(self._context._query);
      var belongToCriteria = _.clone(values[property]);
 
      // get the association default criteria
      belongToCriteria = Criteria.merge(belongToCriteria, collections[ParentName]._attributes[property].criteria);
 
      child.find(belongToCriteria).exec(function(err, data) {
        Iif (err) {
          return next(err);
        }
        next(null, {
          key: property,
          value: _.map(data, function(childData) {
            return childData[child.primaryKey];
          })
        });
      });
    }
  }, function(err, res) {
    Iif (err) {
      return cb(err);
    }
 
    if (!res.length) {
      return cb();
    }
 
    var where = {};
    res.forEach(function(keyObject) {
      Iif (where[keyObject.key] && _.isArray(where[keyObject.key]) && _.isArray(keyObject.value)) {
        where[keyObject.key] = _.intersection(where[keyObject.key], keyObject.value);
      } else {
        where[keyObject.key] = keyObject.value;
      }
    });
    cb(null, where);
  });
};
 
/**
 * 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) && _.every(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 (_.isUndefined(options)) {
    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 Offshore
 */
 
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) {
  var self = this;
  Iif (!cb) {
    console.log('Error: No Callback supplied, you must define a callback.');
    return;
  }
 
  // Normalize callback/switchback
  cb = normalize.callback(cb);
 
  var execute = function() {
    // Set up arguments + callback
    var args = [self._criteria, cb];
    if (self._values) {
      args.splice(1, 0, self._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.
    self._method.apply(self._context, args);
  };
 
  var queryWhere = self._criteria ? self._criteria.where : null;
  if (this._criteria && this._criteria.joins && _.isArray(this._criteria.joins)) {
    async.parallel([function(next) {
        self.whereDeep(self._context.identity, queryWhere, function(err, where) {
          Iif (err) {
            return next(err);
          }
          if (self._criteria && where) {
            self._criteria.where = where;
          }
          next();
        });
      }, function(next) {
        async.forEachOf(self._criteria.joins, function(join, index, next) {
          if (!join.criteria || !join.criteria.where) {
            return next();
          }
          self.whereDeep(join.child, join.criteria.where, function(err, where) {
            Iif (err) {
              next(err);
            }
            if (where) {
              self._criteria.joins[index].criteria.where = where;
            }
            next();
          });
        }, function(err) {
          Iif (err) {
            return next(err);
          }
          next();
        });
      }], function(err) {
      Iif (err) {
        return cb(err);
      }
      execute();
    });
  } else {
    self.whereDeep(self._context.identity, queryWhere, function(err, where) {
      Iif (err) {
        return cb(err);
      }
      if (self._criteria && where) {
        self._criteria.where = where;
      }
      execute();
    });
  }
};
 
 
Deferred.prototype.execDeep = function(cb, cursor) {
  var self = this;
  // if this is the first layer (path root)
  if (!cursor) {
    cb = normalize.callback(cb);
 
    Eif (this._criteria.joins) {
      var currentPathRef = this._criteria.paths[this._context.identity];
      for (var i in this._criteria.joins) {
        var join = this._criteria.joins[i];
        if (!currentPathRef.children[join.alias] || !currentPathRef.children[join.alias].primaryKey) {
          var collections = this._context.offshore.collections;
          var childAttr = collections[this._context.identity].attributes[join.alias];
          var childCollection = childAttr.collection || childAttr.model;
          currentPathRef.children[join.alias] = {
            collectionName: childCollection,
            primaryKey: _.find(_.keys(collections[childCollection].attributes), function(attr) {
              return collections[childCollection].attributes[attr].primaryKey;
            })
          };
        }
      }
    }
    var deferred = new Deferred(this._context, this._method, this._criteria);
    deferred.exec(function(err, res) {
      Iif (err) {
        return cb(err);
      }
      if (_.isUndefined(res)) {
        return cb(err, res);
      }
      var data = [];
      if (_.isArray(res)) {
        res.forEach(function(r) {
          data.push(r.toRawData());
        });
 
      } else {
        data = res.toRawData();
      }
      cursor = new DeepCursor(self._context.identity, data, self._criteria.paths);
      self.execDeep(cb, cursor);
    });
 
  } else {
 
    var previousChildren = self._criteria.paths[cursor.path].children;
 
    async.each(_.keys(previousChildren), function(alias, next) {
 
      var currentPath = cursor.path + '.' + alias;
      var currentModel = previousChildren[alias].collectionName;
      var currentPk = previousChildren[alias].primaryKey;
 
      if (!self._criteria.paths[currentPath]) {
        return next();
      }
      var joins = self._criteria.paths[currentPath].joins;
      Iif (!joins.length) {
        return next();
      }
 
      var pathCursor = cursor.getChildPath(currentPath);
      var where = {};
      where[currentPk] = _.uniq(pathCursor.getParents());
      var criteria = {where: where, joins: joins};
 
      var collections = self._context.offshore.collections;
      var deferred = new Deferred(collections[currentModel]._loadQuery(self._context._query), require('./finders/basic').find, criteria);
      deferred.exec(function(err, newLevel) {
        Iif (err) {
          return next(err);
        }
        var data = [];
        Eif (_.isArray(newLevel)) {
          newLevel.forEach(function(r) {
            data.push(r.toRawData());
          });
        } else {
          data = newLevel.toRawData();
        }
        pathCursor.zip(data);
        self.execDeep(next, pathCursor);
      });
 
    }, function(err) {
      Iif (err) {
        return cb(err);
      }
      return cb(null, cursor.getRoot());
    });
  }
};
 
 
/**
 * 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 || {};
}