Code coverage report for upstream/lib/dao-factory.js

Statements: 69.3% (465 / 671)      Branches: 61.52% (267 / 434)      Functions: 64.9% (98 / 151)      Lines: 69.38% (460 / 663)     

All files » upstream/lib/ » dao-factory.js
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 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 14171               1 1 435                                                   435                   435   435 409   26     435   435 435 435 435     1   6151       1 16     1 8861     1 7559           1 1   1 37 37                                                   1 466   466 466   466 1121 98       466 466 466   466 466     466 466 466       466 791     466   466   466 466 3     466 442           442     466 466 838     466 466         466   466 466 466 466   466 2352 116   2352 991   2352 5       2352         466 466 468     466 466 1067     466 466 466 466 466   466     1 748     748 748   748 1496       1496 2   2 2       2             1496 7112 2     7112 3556 585     7112 3556 307         1496 7114 3558       7114       748 748   748 748     1 446   446   446 446 446     446   446     446 367         79         1   367     367     1       1                               1 942     1 17                       17 17     17             17 1     16 22   22 30 30 30 30   30   6 1 1 1     1           6 6 5 5 5   1                 24 24     30 26   4 1         15       1 91     1 168   168 168 119 20   20       111     160   160             1 37 37     37   37                         1 98       98 4 4       94         94 15 15 15 4   11   79 3   3 3 3     3 76 2   2       2 74 73   73 9   9       71 1 1   1     1   1       92 92   92             1                                                   1 8 8 8     8   8 8         1 8       8 8   8             8     8 1     7     7             1       1       1 791   791 2     791 32 36       791     791     1 256 256   256       256       256     1                                                                                 1 1     1       1 1     1 1         1 1       1     1                                                     1 83 83   83           83         83     83 83     83       194   83 83 83 83       83 83   83       83 83 83                                                                   83   83   83 194   194       194 182 182     182 182       194     83   83         83       83 83       83 83   83                                                             83                               1 3 3   3       3 3 3       3   3             3 3     3 3       3 3 3           3 3       3 3       3       3                                         3         3                                                 3                         1 28       28 28 28   28 25 25     28 28 28 28       28 28   28 28       28 28 28           28 28       28 28       28       28                                         28         28                                                     28         28 28 28     28 28     28               1       1                             1             1 252                                         252     1 466 466     1 466                       466 67     466 442 442   442       466 466   466 399     466 1121     466 884 832         1 466   466   466 403     403         1 36 36 36 36 36 40   30 30   30 30   30 30   30       1 40 20     40 35     40 38 9 9     38 4     38 2 2 1 1 1     1   2   36       38   36 36       36 12       36 28     28 2 2   2                 2     28 28 28           28 5     28   8   8 2     8   8           2       1 435 991         435     1 168   7666       1 1   1    
var Utils       = require("./utils")
  , DAO         = require("./dao")
  , DataTypes   = require("./data-types")
  , Util        = require('util')
  , sql         = require('sql')
  , SqlString   = require('./sql-string')
  , Transaction = require('./transaction')
 
module.exports = (function() {
  var DAOFactory = function(name, attributes, options) {
    this.options = Utils._.extend({
      timestamps: true,
      createdAt: 'createdAt',
      updatedAt: 'updatedAt',
      deletedAt: 'deletedAt',
      touchedAt: 'touchedAt',
      instanceMethods: {},
      classMethods: {},
      validate: {},
      freezeTableName: false,
      underscored: false,
      syncOnAssociation: true,
      paranoid: false,
      whereCollection: null,
      schema: null,
      schemaDelimiter: '',
      language: 'en',
      defaultScope: null,
      scopes: null,
      hooks: {
        beforeCreate: [],
        afterCreate: []
      }
    }, options || {})
 
    // error check options
    Utils._.each(options.validate, function(validator, validatorType) {
      if (Utils._.contains(Utils._.keys(attributes), validatorType)) {
        throw new Error("A model validator function must not have the same name as a field. Model: " + name + ", field/validation name: " + validatorType)
      }
 
      if (!Utils._.isFunction(validator)) {
        throw new Error("Members of the validate option must be functions. Model: " + name + ", error with validate member " + validatorType)
      }
    })
 
    this.name = name
 
    if (!this.options.tableName) {
      this.tableName = this.options.freezeTableName ? name : Utils.pluralize(name, this.options.language)
    } else {
      this.tableName = this.options.tableName
    }
 
    attributes = replaceReferencesWithTableNames(attributes)
 
    this.rawAttributes     = attributes
    this.daoFactoryManager = null // defined in init function
    this.associations      = {}
    this.scopeObj          = {}
  }
 
  Object.defineProperty(DAOFactory.prototype, 'attributes', {
    get: function() {
      return this.QueryGenerator.attributesToSQL(this.rawAttributes)
    }
  })
 
  Object.defineProperty(DAOFactory.prototype, 'sequelize', {
    get: function() { return this.daoFactoryManager.sequelize }
  })
 
  Object.defineProperty(DAOFactory.prototype, 'QueryInterface', {
    get: function() { return this.daoFactoryManager.sequelize.getQueryInterface() }
  })
 
  Object.defineProperty(DAOFactory.prototype, 'QueryGenerator', {
    get: function() { return this.QueryInterface.QueryGenerator }
  })
 
  // inject the node-sql methods to the dao factory in order to
  // receive the syntax sugar ...
 
  ;(function() {
    var instance = sql.define({ name: "dummy", columns: [] })
 
    for (var methodName in instance) {
      ;(function(methodName) {
        DAOFactory.prototype[methodName] = function() {
          var dataset = this.dataset()
            , result  = dataset[methodName].apply(dataset, arguments)
            , dialect = this.daoFactoryManager.sequelize.options.dialect
            , self    = this
 
          result.toSql = function() {
            var query = result.toQuery()
            return SqlString.format(query.text.replace(/(\$\d)/g, '?'), query.values, null, dialect) + ';'
          }
 
          result.exec = function(options) {
            options = Utils._.extend({
              transaction: null,
              type:        'SELECT'
            }, options || {})
 
            return self.QueryInterface.queryAndEmit([result.toSql(), self, options], 'snafu')
          }
 
          return result
        }
      })(methodName)
    }
  })()
 
  DAOFactory.prototype.init = function(daoFactoryManager) {
    var self = this;
 
    this.daoFactoryManager = daoFactoryManager
    this.primaryKeys       = {};
 
    Utils._.each(this.attributes, function(dataTypeString, attributeName) {
      if (dataTypeString.indexOf('PRIMARY KEY') !== -1) {
        self.primaryKeys[attributeName] = dataTypeString
      }
    })
 
    this.primaryKeyAttributes = Object.keys(this.primaryKeys)
    this.primaryKeyCount = this.primaryKeyAttributes.length
    this.options.hasPrimaryKeys = this.hasPrimaryKeys = this.primaryKeyCount > 0
 
    Eif (typeof this.options.defaultScope === "object") {
      Utils.injectScope.call(this, this.options.defaultScope)
    }
 
    addDefaultAttributes.call(this)
    addOptionalClassMethods.call(this)
    findAutoIncrementField.call(this)
 
    // DAO prototype
    // WTF ... ?
    this.DAO = function() {
      DAO.apply(this, arguments);
    }
 
    Util.inherits(this.DAO, DAO);
 
    this.DAO.prototype.rawAttributes = this.rawAttributes;
 
    this.DAO.prototype._hasPrimaryKeys = this.options.hasPrimaryKeys
    this.DAO.prototype._isPrimaryKey = Utils._.memoize(function (key) {
      return self.primaryKeyAttributes.indexOf(key) !== -1
    })
 
    if (this.options.timestamps) {
      this.DAO.prototype._timestampAttributes = {
        createdAt: Utils._.underscoredIf(this.options.createdAt, this.options.underscored),
        updatedAt: Utils._.underscoredIf(this.options.updatedAt, this.options.underscored),
        deletedAt: Utils._.underscoredIf(this.options.deletedAt, this.options.underscored)
      }
 
      this.DAO.prototype._readOnlyAttributes = Object.keys(this.DAO.prototype._timestampAttributes)
    }
 
    this.DAO.prototype._hasReadOnlyAttributes = this.DAO.prototype._readOnlyAttributes && this.DAO.prototype._readOnlyAttributes.length
    this.DAO.prototype._isReadOnlyAttribute = Utils._.memoize(function (key) {
      return self.DAO.prototype._hasReadOnlyAttributes && self.DAO.prototype._readOnlyAttributes.indexOf(key) !== -1
    })
 
    Eif (this.options.instanceMethods) {
      Utils._.each(this.options.instanceMethods, function(fct, name) {
        self.DAO.prototype[name] = fct
      })
    }
 
    this.refreshAttributes();
 
    this.DAO.prototype.booleanValues = []
    this.DAO.prototype.dateAttributes = []
    this.DAO.prototype.defaultValues = {}
    this.DAO.prototype.validators    = {}
 
    Utils._.each(this.rawAttributes, function (definition, name) {
      if (((definition === DataTypes.BOOLEAN) || (definition.type === DataTypes.BOOLEAN))) {
        self.DAO.prototype.booleanValues.push(name);
      }
      if (((definition === DataTypes.DATE) || (definition.type === DataTypes.DATE) || (definition.originalType === DataTypes.DATE))) {
        self.DAO.prototype.dateAttributes.push(name);
      }
      if (definition.hasOwnProperty('defaultValue')) {
        self.DAO.prototype.defaultValues[name] = Utils._.partial(
          Utils.toDefaultValue, definition.defaultValue)
      }
 
      Iif (definition.hasOwnProperty('validate')) {
        self.DAO.prototype.validators[name] = definition.validate;
      }
    })
 
    this.DAO.prototype._hasBooleanAttributes = !!this.DAO.prototype.booleanValues.length
    this.DAO.prototype._isBooleanAttribute = Utils._.memoize(function (key) {
      return self.DAO.prototype.booleanValues.indexOf(key) !== -1
    })
 
    this.DAO.prototype._hasDateAttributes = !!this.DAO.prototype.dateAttributes.length
    this.DAO.prototype._isDateAttribute = Utils._.memoize(function (key) {
      return self.DAO.prototype.dateAttributes.indexOf(key) !== -1
    })
 
    this.DAO.prototype.__factory        = this
    this.DAO.prototype.daoFactory       = this
    this.DAO.prototype.Model            = this
    this.DAO.prototype.hasDefaultValues = !Utils._.isEmpty(this.DAO.prototype.defaultValues)
    this.DAO.prototype.daoFactoryName   = this.name
 
    return this
  }
 
  DAOFactory.prototype.refreshAttributes = function() {
    var self = this
      , attributeManipulation = {};
 
    this.DAO.prototype._customGetters = {}
    this.DAO.prototype._customSetters = {}
 
    Utils._.each(['get', 'set'], function(type) {
      var opt   = type + 'terMethods'
        , funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {})
        , _custom = type === 'get' ? self.DAO.prototype._customGetters : self.DAO.prototype._customSetters
 
      Utils._.each(funcs, function (method, attribute) {
        _custom[attribute] = method
 
        Eif (type === 'get') {
          funcs[attribute] = function() {
            return this.get(attribute)
          }
        }
        Iif (type === 'set') {
          funcs[attribute] = function(value) {
            return this.set(attribute, value)
          }
        }
      })
 
      Utils._.each(self.rawAttributes, function(options, attribute) {
        if (options.hasOwnProperty(type)) {
          _custom[attribute] = options[type]
        }
 
        if (type === 'get') {
          funcs[attribute] = function() {
            return this.get(attribute)
          }
        }
        if (type === 'set') {
          funcs[attribute] = function(value) {
            return this.set(attribute, value)
          }
        }
      })
 
      Utils._.each(funcs, function(fct, name) {
        if (!attributeManipulation[name]) {
          attributeManipulation[name] = {
            configurable: true
          }
        }
        attributeManipulation[name][type] = fct
      })
    })
 
    this.DAO.prototype._hasCustomGetters = Object.keys(this.DAO.prototype._customGetters).length
    this.DAO.prototype._hasCustomSetters = Object.keys(this.DAO.prototype._customSetters).length
 
    Object.defineProperties(this.DAO.prototype, attributeManipulation)
    this.DAO.prototype.attributes = Object.keys(this.DAO.prototype.rawAttributes)
  }
 
  DAOFactory.prototype.sync = function(options) {
    options = Utils._.extend({}, this.options, options || {})
 
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var doQuery = function() {
        self
          .QueryInterface
          .createTable(self.getTableName(), self.attributes, options)
          .success(function() { emitter.emit('success', self) })
          .error(function(err) { emitter.emit('error', err) })
          .on('sql', function(sql) { emitter.emit('sql', sql) })
      }
 
      if (options.force) {
        self
          .drop(options)
          .success(doQuery)
          .error(function(err) { emitter.emit('error', err) })
      } else {
        doQuery()
      }
    }).run()
  }
 
  DAOFactory.prototype.drop = function(options) {
    // Only Postgres' QueryGenerator.dropTableQuery() will add schema manually
    var isPostgres = this.options.dialect === "postgres" || (!!this.daoFactoryManager && this.daoFactoryManager.sequelize.options.dialect === "postgres")
     , tableName = isPostgres ? this.tableName : this.getTableName()
 
    return this.QueryInterface.dropTable(tableName, options)
  }
 
  DAOFactory.prototype.dropSchema = function(schema) {
    return this.QueryInterface.dropSchema(schema)
  }
 
  DAOFactory.prototype.schema = function(schema, options) {
    this.options.schema = schema
 
    if (!!options) {
      if (typeof options === "string") {
        this.options.schemaDelimiter = options
      } else {
        if (!!options.schemaDelimiter) {
          this.options.schemaDelimiter = options.schemaDelimiter
        }
      }
    }
 
    return this
  }
 
  DAOFactory.prototype.getTableName = function() {
    return this.QueryGenerator.addSchema(this)
  }
 
  DAOFactory.prototype.scope = function(option) {
    var self = Object.create(this)
      , type
      , options
      , merge
      , i
      , scope
      , scopeName
      , scopeOptions
      , argLength = arguments.length
      , lastArg = arguments[argLength-1]
 
    // Set defaults
    scopeOptions = (typeof lastArg === "object" && !Array.isArray(lastArg) ? lastArg : {}) || {} // <-- for no arguments
    scopeOptions.silent = (scopeOptions !== null && scopeOptions.hasOwnProperty('silent') ? scopeOptions.silent : true)
 
    // Clear out any predefined scopes...
    self.scopeObj = {}
 
    // Possible formats for option:
    // String of arguments: 'hello', 'world', 'etc'
    // Array: ['hello', 'world', 'etc']
    // Object: {merge: 'hello'}, {method: ['scopeName' [, args1, args2..]]}, {merge: true, method: ...}
 
    if (argLength < 1 || !option) {
      return self
    }
 
    for (i = 0; i < argLength; i++) {
      options = Array.isArray(arguments[i]) ? arguments[i] : [arguments[i]]
 
      options.forEach(function(o){
        type = typeof o
        scope = null
        merge = false
        scopeName = null
 
        if (type === "object") {
          // Right now we only support a merge functionality for objects
          if (!!o.merge) {
            merge = true
            scopeName = o.merge[0]
            Iif (Array.isArray(o.merge) && !!self.options.scopes[scopeName]) {
              scope = self.options.scopes[scopeName].apply(self, o.merge.splice(1))
            }
            else Iif (typeof o.merge === "string") {
              scopeName = o.merge
              scope = self.options.scopes[scopeName]
            }
          }
 
          Eif (!!o.method) {
            if (Array.isArray(o.method) && !!self.options.scopes[o.method[0]]) {
              scopeName = o.method[0]
              scope = self.options.scopes[scopeName].apply(self, o.method.splice(1))
              merge = !!o.merge
            }
            else Iif (!!self.options.scopes[o.method]) {
              scopeName = o.method
              scope = self.options.scopes[scopeName].apply(self)
            }
          } else {
            scopeName = o
            scope = self.options.scopes[scopeName]
          }
        } else {
          scopeName = o
          scope = self.options.scopes[scopeName]
        }
 
        if (!!scope) {
          Utils.injectScope.call(self, scope, merge)
        }
        else if (scopeOptions.silent !== true && !!scopeName) {
          throw new Error("Invalid scope " + scopeName + " called.")
        }
      })
    }
 
    return self
  }
 
  // alias for findAll
  DAOFactory.prototype.all = function(options, queryOptions) {
    return this.findAll(options, queryOptions)
  }
 
  DAOFactory.prototype.findAll = function(options, queryOptions) {
    var hasJoin = false
 
    options = optClone(options)
    if (typeof options === 'object') {
      if (options.hasOwnProperty('include') && options.include) {
        hasJoin = true
 
        validateIncludedElements.call(this, options)
      }
 
      // whereCollection is used for non-primary key updates
      this.options.whereCollection = options.where || null
    }
 
    options = paranoidClause.call(this, options)
 
    return this.QueryInterface.select(this, this.tableName, options, Utils._.defaults({
      type:    'SELECT',
      hasJoin: hasJoin
    }, queryOptions, { transaction: (options || {}).transaction }))
  }
 
  //right now, the caller (has-many-double-linked) is in charge of the where clause
  DAOFactory.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
    var optcpy = Utils._.clone(options)
    optcpy.attributes = optcpy.attributes || [this.QueryInterface.quoteIdentifier(this.tableName)+".*"]
 
    // whereCollection is used for non-primary key updates
    this.options.whereCollection = optcpy.where || null;
 
    return this.QueryInterface.select(this, [this.getTableName(), joinTableName], optcpy, Utils._.defaults({
      type: 'SELECT'
    }, queryOptions, { transaction: (options || {}).transaction }))
  }
 
 /**
  * Search for an instance.
  *
  * @param  {Object} options Options to describe the scope of the search.
  *   @param {Array} include A list of associations which shall get eagerly loaded. Supported is either { include: [ DaoFactory1, DaoFactory2, ...] } or { include: [ { daoFactory: DaoFactory1, as: 'Alias' } ] }.
  * @param  {Object} set the query options, e.g. raw, specifying that you want raw data instead of built DAOs
  * @return {Object}         A promise which fires `success`, `error`, `complete` and `sql`.
  */
  DAOFactory.prototype.find = function(options, queryOptions) {
    var hasJoin = false
 
    // no options defined?
    // return an emitter which emits null
    if ([null, undefined].indexOf(options) !== -1) {
      return new Utils.CustomEventEmitter(function(emitter) {
        setTimeout(function() { emitter.emit('success', null) }, 10)
      }).run()
    }
 
    var primaryKeys = this.primaryKeys
      , keys        = Object.keys(primaryKeys)
      , keysLength  = keys.length
 
    // options is not a hash but an id
    if (typeof options === 'number') {
      var oldOption = options
      options = { where: {} }
      if (keysLength === 1) {
        options.where[keys[0]] = oldOption
      } else {
        options.where.id = oldOption
      }
    } else if (Utils._.size(primaryKeys) && Utils.argsArePrimaryKeys(arguments, primaryKeys)) {
      var where = {}
 
      Utils._.each(arguments, function(arg, i) {
        var key = keys[i]
        where[key] = arg
      })
 
      options = { where: where }
    } else if (typeof options === 'string' && parseInt(options, 10).toString() === options) {
      var parsedId = parseInt(options, 10)
 
      Iif (!Utils._.isFinite(parsedId)) {
        throw new Error('Invalid argument to find(). Must be an id or an options object.')
      }
 
      options = { where: parsedId }
    } else if (typeof options === 'object') {
      options = Utils._.clone(options)
 
      if (options.hasOwnProperty('include') && options.include) {
        hasJoin = true
 
        validateIncludedElements.call(this, options)
      }
 
      // whereCollection is used for non-primary key updates
      this.options.whereCollection = options.where || null
    } else Eif (typeof options === "string") {
      var where = {}
 
      Iif (this.primaryKeyCount === 1) {
        where[primaryKeys[keys[0]]] = options;
        options = where;
      } else Eif (this.primaryKeyCount < 1) {
        // Revert to default behavior which is {where: [int]}
        options = {where: parseInt(Number(options) || 0, 0)}
      }
    }
 
    options = paranoidClause.call(this, options)
    options.limit = 1
 
    return this.QueryInterface.select(this, this.getTableName(), options, Utils._.defaults({
      plain: true,
      type: 'SELECT',
      hasJoin: hasJoin
    }, queryOptions))
  }
 
  DAOFactory.prototype.aggregate = function(field, aggregateFunction, options) {
    var tableField;
 
    if (field == '*') {
      tableField = field
    } else {
      tableField = this.QueryInterface.QueryGenerator.quoteIdentifier(field)
    }
 
    options = Utils._.extend({ attributes: [] }, options || {})
    options.attributes.push([aggregateFunction + '(' + tableField + ')', aggregateFunction])
 
    if (!options.dataType) {
      if (this.rawAttributes[field]) {
        options.dataType = this.rawAttributes[field]
      } else {
        // Use FLOAT as fallback
        options.dataType = DataTypes.FLOAT
      }
    }
 
    options = paranoidClause.call(this, options)
 
    return this.QueryInterface.rawSelect(this.getTableName(), options, aggregateFunction)
  }
 
  DAOFactory.prototype.count = function(options) {
    options = Utils._.clone(options || {})
    return new Utils.CustomEventEmitter(function (emitter) {
      options.attributes = [
        [this.sequelize.fn('COUNT', this.sequelize.col(this.tableName+'.*')), 'count']
      ]
      options.includeIgnoreAttributes = false
 
      this.find(options, {raw: true, transaction: options.transaction}).proxy(emitter, {events: ['sql', 'error']}).success(function (result) {
        emitter.emit('success', parseInt(result.count, 10))
      })
    }.bind(this)).run()
  }
 
  DAOFactory.prototype.findAndCountAll = function(findOptions, queryOptions) {
    var self  = this
      // no limit, offset, order, attributes for the options given to count()
      , countOptions = Utils._.omit(findOptions || {}, ['offset', 'limit', 'order', 'attributes'])
 
    return new Utils.CustomEventEmitter(function (emitter) {
      var emit = {
        okay : function(count, results) {     // emit success
          emitter.emit('success', {
            count: count || 0,
            rows : (results && Array.isArray(results) ? results : [])
          })
        }
      }
 
      self.count(countOptions)
          .proxy(emitter, {events: ['sql', 'error']})
          .success(function(count) {
            if (count === 0) {
              return emit.okay(count) // no records, no need for another query
            }
 
            self.findAll(findOptions, queryOptions)
              .proxy(emitter, {events: ['sql', 'error']})
              .success(function(results) {
                emit.okay(count, results)
              })
          })
 
    }).run()
  }
 
  DAOFactory.prototype.max = function(field, options) {
    return this.aggregate(field, 'max', options)
  }
 
  DAOFactory.prototype.min = function(field, options) {
    return this.aggregate(field, 'min', options)
  }
 
  DAOFactory.prototype.build = function(values, options) {
    options = options || { isNewRecord: true, isDirty: true }
 
    if (options.hasOwnProperty('include') && options.include && !options.includeValidated) {
      validateIncludedElements.call(this, options)
    }
 
    if (options.includeNames) {
      options.includeNames = options.includeNames.concat(options.includeNames.map(function (key) {
        return key.slice(0,1).toLowerCase() + key.slice(1)
      }))
    }
 
    var self     = this
      , instance = new this.DAO(values, options)
 
    return instance
  }
 
  DAOFactory.prototype.create = function(values, fieldsOrOptions) {
    Utils.validateParameter(values, Object, { optional: true })
    Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#create' })
 
    Iif (fieldsOrOptions instanceof Array) {
      fieldsOrOptions = { fields: fieldsOrOptions }
    }
 
    fieldsOrOptions = Utils._.extend({
      transaction: null
    }, fieldsOrOptions || {})
 
    return this.build(values).save(fieldsOrOptions)
  }
 
  DAOFactory.prototype.findOrInitialize = DAOFactory.prototype.findOrBuild = function (params, defaults, options) {
    defaults = defaults || {}
    options  = options  || {}
 
    var self          = this
      , defaultKeys   = Object.keys(defaults)
      , defaultLength = defaultKeys.length
 
    if (!options.transaction && defaults.transaction && (defaults.transaction instanceof Transaction)) {
      options.transaction = defaults.transaction
      delete defaults.transaction
    }
 
    return new Utils.CustomEventEmitter(function (emitter) {
      self.find({
        where: params
      }, options).success(function (instance) {
        if (instance === null) {
          var i = 0
 
          for (i = 0; i < defaultLength; i++) {
            params[defaultKeys[i]] = defaults[defaultKeys[i]]
          }
 
          var build = self.build(params)
 
          build.hookValidate({skip: Object.keys(params)}).success(function (instance) {
            emitter.emit('success', build, true)
          })
          .error(function (error) {
            emitter.emit('error', error)
          })
        } else {
          emitter.emit('success', instance, false)
        }
      }).error(function (error) {
        emitter.emit('error', error)
      })
    }).run()
  }
 
  DAOFactory.prototype.findOrCreate = function (where, defaults, options) {
    var self   = this
      , params = {}
 
    options = Utils._.extend({
      transaction: null
    }, options || {})
 
    for (var attrname in where) {
      params[attrname] = where[attrname]
    }
 
    return new Utils.CustomEventEmitter(function (emitter) {
      self.find({
        where: params
      }, {
        transaction: options.transaction
      }).success(function (instance) {
        Eif (instance === null) {
          for (var attrname in defaults) {
            params[attrname] = defaults[attrname]
          }
 
          self
            .create(params, options)
            .success(function (instance) {
              emitter.emit('success', instance, true)
            })
            .error( function (error) {
              emitter.emit('error', error)
            })
        } else {
          emitter.emit('success', instance, false)
        }
      }).error(function (error) {
        emitter.emit('error', error)
      });
    }).run()
  }
 
  /**
   * Create and insert multiple instances
   *
   * @param  {Array} records List of objects (key/value pairs) to create instances from
   * @param  {Array} fields Fields to insert (defaults to all fields)
   * @return {Object}       A promise which fires `success`, `error`, `complete` and `sql`.
   *
   * Note: the `success` handler is not passed any arguments. To obtain DAOs for
   * the newly created values, you will need to query for them again. This is
   * because MySQL and SQLite do not make it easy to obtain back automatically
   * generated IDs and other default values in a way that can be mapped to
   * multiple records
   */
  DAOFactory.prototype.bulkCreate = function(records, fieldsOrOptions, options) {
    Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#bulkCreate' })
    Utils.validateParameter(options, 'undefined', { deprecated: Object, optional: true, index: 3, method: 'DAOFactory#bulkCreate' })
 
    Iif (!records.length) {
      return new Utils.CustomEventEmitter(function(emitter) {
        emitter.emit('success', [])
      }).run();
    }
 
    options = Utils._.extend({
      validate: false,
      hooks: false
    }, options || {})
 
    Iif (fieldsOrOptions instanceof Array) {
      options.fields = fieldsOrOptions
    } else {
      options.fields = options.fields || []
      options = Utils._.extend(options, fieldsOrOptions)
    }
 
    var self          = this
      , updatedAtAttr = Utils._.underscoredIf(self.options.updatedAt, self.options.underscored)
      , createdAtAttr = Utils._.underscoredIf(self.options.createdAt, self.options.underscored)
      , errors        = []
      , daos          = records.map(function(v) { return self.build(v) })
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var done = function() {
        self.runHooks('afterBulkCreate', daos, options.fields, function(err, newRecords, newFields) {
          Iif (!!err) {
            return emitter.emit('error', err)
          }
 
          daos           = newRecords || daos
          options.fields = newFields  || options.fields
 
          emitter.emit('success', daos, options.fields)
        })
      }
 
      var next = function() {
        Eif (options.hooks === false) {
          return runQuery()
        }
 
        var i = 0
        var iterate = function(i) {
          self.runHooks('beforeCreate', daos[i], function(err, newValues) {
            if (!!err) {
              return emitter.emit('error', err)
            }
 
            daos[i] = newValues || daos[i]
            daos[i].save({ transaction: options.transaction }).error(function(err) {
              emitter.emit('error', err)
            }).success(function() {
              self.runHooks('afterCreate', daos[i], function(err, newValues) {
                if (!!err) {
                  return emitter.emit('error', err)
                }
 
                daos[i] = newValues || daos[i]
                i++
                if (i >= daos.length) {
                  return done()
                }
 
                iterate(i)
              })
            })
          })
        }
 
        iterate(i)
      }
 
      var runQuery = function() {
        // we will re-create from DAOs, which may have set up default attributes
        records = []
 
        daos.forEach(function(dao) {
          var values = options.fields.length > 0 ? {} : dao.dataValues
 
          options.fields.forEach(function(field) {
            values[field] = dao.dataValues[field]
          })
 
          if (self.options.timestamps) {
            Eif (!values[createdAtAttr]) {
              values[createdAtAttr] = Utils.now(self.daoFactoryManager.sequelize.options.dialect)
            }
 
            Eif (!values[updatedAtAttr]) {
              values[updatedAtAttr] = Utils.now(self.daoFactoryManager.sequelize.options.dialect)
            }
          }
 
          records.push(values)
        })
 
        self.QueryInterface.bulkInsert(self.tableName, records, options)
        .on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
        .error(function(err) {
          emitter.emit('error', err)
        }).success(function(rows) {
          done()
        })
      }
 
      self.runHooks('beforeBulkCreate', daos, options.fields, function(err, newRecords, newFields) {
        Iif (!!err) {
          return emitter.emit('error', err)
        }
 
        daos           = newRecords || daos
        options.fields = newFields  || options.fields
 
        Iif (options.validate === true) {
          if (options.hooks === true) {
            var iterate = function(i) {
              daos[i].hookValidate({skip: options.fields}).error(function(err) {
                errors[errors.length] = {record: v, errors: err}
                i++
                if (i > daos.length) {
                  if (errors.length > 0) {
                    return emitter.emit('error', errors)
                  }
 
                  return next()
                }
                iterate(i)
              })
            }
          } else {
            daos.forEach(function(v) {
              var valid = v.validate({skip: options.fields})
              if (valid !== null) {
                errors[errors.length] = {record: v, errors: valid}
              }
            })
 
            if (errors.length > 0) {
              return emitter.emit('error', errors)
            }
 
            next()
          }
        } else {
          next()
        }
      })
    }).run()
  }
 
  /**
   * Delete multiple instances
   *
   * @param  {Object} where   Options to describe the scope of the search.
   * @param  {Object} options Possible options are:
                              - hooks: If set to true, destroy will find all records within the where parameter and will execute before/afterDestroy hooks on each row
                              - limit: How many rows to delete
                              - truncate: If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored
   * @return {Object}         A promise which fires `success`, `error`, `complete` and `sql`.
   */
  DAOFactory.prototype.destroy = function(where, options) {
    options = options || {}
    options.force = options.force === undefined ? false : Boolean(options.force)
 
    var self  = this
      , query = null
      , args  = []
 
    return new Utils.CustomEventEmitter(function(emitter) {
      self.runHooks(self.options.hooks.beforeBulkDestroy, where, function(err, newWhere) {
        Iif (!!err) {
          return emitter.emit('error', err)
        }
 
        where = newWhere || where
 
        Iif (self.options.timestamps && self.options.paranoid && options.force === false) {
          var attr = Utils._.underscoredIf(self.options.deletedAt, self.options.underscored)
          var attrValueHash = {}
          attrValueHash[attr] = Utils.now()
          query = 'bulkUpdate'
          args  = [self.tableName, attrValueHash, where]
        } else {
          query = 'bulkDelete'
          args  = [self.tableName, where, options]
        }
 
        var runQuery = function(err, records) {
          Iif (!!err) {
            return emitter.emit('error', err)
          }
 
          query = self.QueryInterface[query].apply(self.QueryInterface, args)
          query.on('sql', function(sql) {
            emitter.emit('sql', sql)
          })
          .error(function(err) {
            emitter.emit('error', err)
          })
          .success(function(results) {
            var finished = function(err) {
              Iif (!!err) {
                return emitter.emit('error', err)
              }
 
              self.runHooks(self.options.hooks.afterBulkDestroy, where, function(err) {
                Iif (!!err) {
                  return emitter.emit('error', err)
                }
 
                emitter.emit('success', results)
              })
            }
 
            Iif (options && options.hooks === true) {
              var tick = 0
              var next = function(i) {
                self.runHooks(self.options.hooks.afterDestroy, records[i], function(err, newValues) {
                  if (!!err) {
                    return finished(err)
                  }
 
                  records[i].dataValues = !!newValues ? newValues.dataValues : records[i].dataValues
                  tick++
 
                  if (tick >= records.length) {
                    return finished()
                  }
 
                  next(tick)
                })
              }
 
              next(tick)
            } else {
              finished()
            }
          })
        }
 
        Iif (options && options.hooks === true) {
          var tick = 0
          self.all({where: where}).error(function(err) { emitter.emit('error', err) })
          .success(function(records) {
            var next = function(i) {
              self.runHooks(self.options.hooks.beforeDestroy, records[i], function(err, newValues) {
                if (!!err) {
                  return runQuery(err)
                }
 
                records[i].dataValues = !!newValues ? newValues.dataValues : records[i].dataValues
                tick++
 
                if (tick >= records.length) {
                  return runQuery(null, records)
                }
 
                next(tick)
              })
            }
 
            next(tick)
          })
          //
        } else {
          runQuery()
        }
      })
    }).run()
  }
 
  /**
   * Update multiple instances
   *
   * @param  {Object} attrValueHash A hash of fields to change and their new values
   * @param  {Object} where         Options to describe the scope of the search.
   * @return {Object}               A promise which fires `success`, `error`, `complete` and `sql`.
   */
  DAOFactory.prototype.update = function(attrValueHash, where, options) {
    var self  = this
      , query = null
      , tick  = 0
 
    options = options || {}
    options.validate  = options.validate === undefined ? true : Boolean(options.validate)
    options.hooks     = options.hooks === undefined ? false : Boolean(options.hooks)
 
    if (self.options.timestamps) {
      var attr = Utils._.underscoredIf(self.options.updatedAt, self.options.underscored)
      attrValueHash[attr] = Utils.now()
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var runSave = function() {
        self.runHooks(self.options.hooks.beforeBulkUpdate, attrValueHash, where, function(err, attributes, _where) {
          Iif (!!err) {
            return emitter.emit('error', err)
          }
 
          where         = _where || where
          attrValueHash = attributes || attrValueHash
 
          var runQuery = function(err, records) {
            Iif (!!err) {
              return emitter.emit('error', err)
            }
 
            query = self.QueryInterface.bulkUpdate(self.tableName, attrValueHash, where, options)
            query.on('sql', function(sql) {
              emitter.emit('sql', sql)
            })
            .error(function(err) {
              emitter.emit('error', err)
            })
            .success(function(results) {
              var finished = function(err, records) {
                Iif (!!err) {
                  return emitter.emit('error', err)
                }
 
                self.runHooks(self.options.hooks.afterBulkUpdate, attrValueHash, where, function(err) {
                  Iif (!!err) {
                    return emitter.emit('error', err)
                  }
 
                  emitter.emit('success', records)
                })
              }
 
              Iif (options && options.hooks === true && !!records && records.length > 0) {
                var tick = 0
                var next = function(i) {
                  self.runHooks(self.options.hooks.afterUpdate, records[i], function(err, newValues) {
                    if (!!err) {
                      return finished(err)
                    }
 
                    records[i].dataValues = !!newValues ? newValues.dataValues : records[i].dataValues
                    tick++
 
                    if (tick >= records.length) {
                      return finished(null, records)
                    }
 
                    next(tick)
                  })
                }
 
                next(tick)
              } else {
                finished(null, results)
              }
            })
          }
 
          Iif (options.hooks === true) {
            self.all({where: where}).error(function(err) { emitter.emit('error', err) })
            .success(function(records) {
              if (records === null || records.length < 1) {
                return runQuery(null)
              }
 
              var next = function(i) {
                self.runHooks(self.options.hooks.beforeUpdate, records[i], function(err, newValues) {
                  if (!!err) {
                    return runQuery(err)
                  }
 
                  records[i].dataValues = !!newValues ? newValues.dataValues : records[i].dataValues
                  tick++
 
                  if (tick >= records.length) {
                    return runQuery(null, records)
                  }
 
                  next(tick)
                })
              }
 
              next(tick)
            })
          } else {
            runQuery()
          }
        })
      }
 
      Eif (options.validate === true) {
        var build = self.build(attrValueHash)
        build.hookValidate({skip: Object.keys(attrValueHash)}).error(function(err) {
          emitter.emit('error', err)
        }).success(function(attributes) {
          Eif (!!attributes && !!attributes.dataValues) {
            attrValueHash = Utils._.pick.apply(Utils._, [].concat(attributes.dataValues).concat(Object.keys(attrValueHash)))
          }
 
          runSave()
        })
      } else {
        runSave()
      }
    }).run()
  }
 
  DAOFactory.prototype.describe = function(schema) {
    return this.QueryInterface.describeTable(this.tableName, schema || this.options.schema || undefined)
  }
 
  DAOFactory.prototype.dataset = function() {
    if (!this.__sql) {
      this.__setSqlDialect()
    }
 
    var instance   = this.__sql.define({ name: this.tableName, columns: [] })
      , attributes = this.attributes
 
    Object.keys(attributes).forEach(function(key) {
      instance.addColumn(key, attributes[key])
    })
 
    return instance
  }
 
  DAOFactory.prototype.__setSqlDialect = function() {
    var dialect = this.daoFactoryManager.sequelize.options.dialect
    this.__sql = sql.setDialect(dialect === 'mariadb' ? 'mysql' : dialect)
  }
 
  // private
 
  var paranoidClause = function(options) {
    Iif (this.options.paranoid === true) {
      options = options || {}
      options.where = options.where || {}
 
      var deletedAtCol = Utils._.underscoredIf(this.options.deletedAt, this.options.underscored)
 
      // Don't overwrite our explicit deletedAt search value if we provide one
      if (!!options.where[deletedAtCol]) {
        return options
      }
 
      if (typeof options.where === "string") {
        options.where += ' AND ' + this.QueryInterface.quoteIdentifier(deletedAtCol) + ' IS NULL '
      }
      else if (Array.isArray(options.where)) {
        options.where[0] += ' AND ' + this.QueryInterface.quoteIdentifier(deletedAtCol) + ' IS NULL '
      } else {
        options.where[deletedAtCol] = null
      }
    }
 
    return options
  }
 
  var addOptionalClassMethods = function() {
    var self = this
    Utils._.each(this.options.classMethods || {}, function(fct, name) { self[name] = fct })
  }
 
  var addDefaultAttributes = function() {
    var self              = this
      , head = {}
      , tail = {}
      , head = {
        id: {
          type: DataTypes.INTEGER,
          allowNull: false,
          primaryKey: true,
          autoIncrement: true
        }
      }
 
    if (this.hasPrimaryKeys) {
      head = {}
    }
 
    if (this.options.timestamps) {
      tail[Utils._.underscoredIf(this.options.createdAt, this.options.underscored)] = {type: DataTypes.DATE, allowNull: false}
      tail[Utils._.underscoredIf(this.options.updatedAt, this.options.underscored)] = {type: DataTypes.DATE, allowNull: false}
 
      Iif (this.options.paranoid)
        tail[Utils._.underscoredIf(this.options.deletedAt, this.options.underscored)] = {type: DataTypes.DATE}
    }
 
    var existingAttributes = Utils._.clone(self.rawAttributes)
    self.rawAttributes = {}
 
    Utils._.each(head, function(value, attr) {
      self.rawAttributes[attr] = value
    })
 
    Utils._.each(existingAttributes, function(value, attr) {
      self.rawAttributes[attr] = value
    })
 
    Utils._.each(tail, function(value, attr) {
      if (Utils._.isUndefined(self.rawAttributes[attr])) {
        self.rawAttributes[attr] = value
      }
    })
  }
 
  var findAutoIncrementField = function() {
    var fields = this.QueryGenerator.findAutoIncrementField(this)
 
    this.autoIncrementField = null
 
    fields.forEach(function(field) {
      Iif (this.autoIncrementField) {
        throw new Error('Invalid DAO definition. Only one autoincrement field allowed.')
      } else {
        this.autoIncrementField = field
      }
    }.bind(this))
  }
 
  var validateIncludedElements = function(options) {
    options.includeNames = []
    options.includeMap = {}
    options.hasSingleAssociation = false
    options.hasMultiAssociation = false
    options.include = options.include.map(function(include) {
      include = validateIncludedElement.call(this, include, options.daoFactory)
 
      options.includeMap[include.as] = include
      options.includeNames.push(include.as)
 
      if (include.association.isMultiAssociation) options.hasMultiAssociation = true
      if (include.association.isSingleAssociation) options.hasSingleAssociation = true
 
      options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || !!include.where
      options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || !!include.required
 
      return include
    }.bind(this))
  };
 
  var validateIncludedElement = function(include, parent) {
    if (include instanceof DAOFactory) {
      include = { daoFactory: include, as: include.tableName }
    }
 
    if (typeof parent === "undefined") {
      parent = this
    }
 
    if (typeof include === 'object') {
      if (include.hasOwnProperty('model')) {
        include.daoFactory = include.model
        delete include.model
      }
 
      if (!include.hasOwnProperty('as')) {
        include.as = include.daoFactory.tableName
      }
 
      if (include.hasOwnProperty('attributes')) {
        var primaryKeys;
        if (include.daoFactory.hasPrimaryKeys) {
          primaryKeys = []
          for (var field_name in include.daoFactory.primaryKeys) {
            primaryKeys.push(field_name)
          }
        } else {
          primaryKeys = ['id']
        }
        include.attributes = include.attributes.concat(primaryKeys)
      } else {
        include.attributes = Object.keys(include.daoFactory.attributes)
      }
 
      // pseudo include just needed the attribute logic, return
      if (include._pseudo) return include
 
      Eif (include.hasOwnProperty('daoFactory') && (include.hasOwnProperty('as'))) {
        var usesAlias   = (include.as !== include.daoFactory.tableName)
          , association = (usesAlias ? parent.getAssociationByAlias(include.as) : parent.getAssociation(include.daoFactory))
 
        // If single (1:1) association, we singularize the alias, so it will match the automatically generated alias of belongsTo/HasOne
        if (association && !usesAlias && association.isSingleAssociation) {
          include.as = Utils.singularize(include.daoFactory.tableName, include.daoFactory.options.language)
        }
 
        // check if the current daoFactory is actually associated with the passed daoFactory - or it's a pseudo include
        if (association && (!association.options.as || (association.options.as === include.as))) {
          include.association = association
 
          // If through, we create a pseudo child include, to ease our parsing later on
          if (Object(include.association.through) === include.association.through) {
            Eif (!include.include) include.include = []
            var through = include.association.through
 
            include.through = {
              daoFactory: through,
              as: Utils.singularize(through.tableName, through.options.language),
              association: {
                isSingleAssociation: true
              },
              _pseudo: true
            }
 
            include.include.push(include.through)
          }
 
          Eif (include.required === undefined) {
            include.required = false
            Iif (include.where) {
              include.required = true
            }
          }
 
          // Validate child includes
          if (include.hasOwnProperty('include')) {
            validateIncludedElements(include)
          }
 
          return include
        } else {
          var msg = include.daoFactory.name
 
          if (usesAlias) {
            msg += " (" + include.as + ")"
          }
 
          msg += " is not associated to " + this.name + "!"
 
          throw new Error(msg)
        }
      } else {
        throw new Error('Include malformed. Expected attributes: daoFactory, as!')
      }
    } else {
      throw new Error('Include unexpected. Element has to be either an instance of DAOFactory or an object.')
    }
  }
 
  var replaceReferencesWithTableNames = function(attributes) {
    Object.keys(attributes).forEach(function(attrName) {
      Iif (attributes[attrName].references instanceof DAOFactory) {
        attributes[attrName].references = attributes[attrName].references.tableName
      }
    })
 
    return attributes
  }
 
  var optClone = function (options) {
    return Utils._.cloneDeep(options, function (elem) {
      // The DAOFactories used for include are pass by ref, so don't clone them. Otherwise return undefined, meaning, 'handle this lodash'
      return elem instanceof DAOFactory ? elem : undefined
    })
  }
 
  Utils._.extend(DAOFactory.prototype, require("./associations/mixin"))
  Utils._.extend(DAOFactory.prototype, require(__dirname + '/hooks'))
 
  return DAOFactory
})()