Code coverage report for upstream/lib/query-interface.js

Statements: 48.58% (223 / 459)      Branches: 35.51% (76 / 214)      Functions: 44.44% (60 / 135)      Lines: 48.58% (222 / 457)     

All files » upstream/lib/ » query-interface.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 9371         1 1 1 1 1 1 1   1   1         1         1                                                     1                             1 446               446 2514 264   2250       446       446   446                                                                                                                                                     446 446   446 446 446         446           1   751 751   751     751 751   751       751                                             751 751 751                   1 203   203       203 203             203 203     203 384 13 13         203 384     203     203 203                 1         1 205   205 205   205 205 205               1                                                                 1                             1                       1                                           1                                                               1         1         1 203   203 203 22   181   181 384 384     181     181   181 384     181           1         1 262 262 261       1 83 83     1 48         48 48     48 30 3         48 48   48   48   45 45 45     3 3 3               1 28     28 28   28   28   28 28 28                   1 9           9 9     9 6 4 2   2             9 9 9                                                                         9 9       9   9   9   6 6 6     3 3 3       9     9         1 3 3   3 3   3   3   3 3 3                   1 289         289 18 18     18 18 72 25         289 289   289     1         1                                                                                     1                           1                       1                       1                       1                       1                                     1 172               1 218           1       1 12       12 12     1 12       12 12     1 12       12       12 12     1                         1 12       12       12 12         1 18     18 18 18     1 1967             1967 1967   1967 770       770       770   1197     1967     1960 1960 1960     6 6 6     1966       1967     1967       1    
var Utils                = require(__dirname + '/utils')
  , DataTypes            = require(__dirname + '/data-types')
  , SQLiteQueryInterface = require(__dirname + '/dialects/sqlite/query-interface')
  , Transaction          = require(__dirname + '/transaction')
 
module.exports = (function() {
  var QueryInterface = function(sequelize) {
    this.sequelize                = sequelize
    this.QueryGenerator           = require('./dialects/' + this.sequelize.options.dialect + '/query-generator')
    this.QueryGenerator.options   = this.sequelize.options
    this.QueryGenerator._dialect  = this.sequelize.dialect
    this.QueryGenerator.sequelize = this.sequelize
  }
  Utils.addEventEmitter(QueryInterface)
 
  QueryInterface.prototype.createSchema = function(schema) {
    var sql = this.QueryGenerator.createSchema(schema)
    return queryAndEmit.call(this, sql, 'createSchema')
  }
 
  QueryInterface.prototype.dropSchema = function(schema) {
    var sql = this.QueryGenerator.dropSchema(schema)
    return queryAndEmit.call(this, sql, 'dropSchema')
  }
 
  QueryInterface.prototype.dropAllSchemas = function() {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer()
 
      self.showAllSchemas().success(function(schemaNames) {
        schemaNames.forEach(function(schemaName) {
          chainer.add(self.dropSchema(schemaName))
        })
        chainer
          .run()
          .success(function() {
            self.emit('dropAllSchemas', null)
            emitter.emit('success', null)
          })
          .error(function(err) {
            self.emit('dropAllSchemas', err)
            emitter.emit('error', err)
          })
      }).error(function(err) {
        self.emit('dropAllSchemas', err)
        emitter.emit('error', err)
      })
    }).run()
  }
 
  QueryInterface.prototype.showAllSchemas = function() {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var showSchemasSql = self.QueryGenerator.showSchemasQuery()
      self.sequelize.query(showSchemasSql, null, { raw: true }).success(function(schemaNames) {
        self.emit('showAllSchemas', null)
        emitter.emit('success', Utils._.flatten(Utils._.map(schemaNames, function(value){ return (!!value.schema_name ? value.schema_name : value) })))
      }).error(function(err) {
        self.emit('showAllSchemas', err)
        emitter.emit('error', err)
      })
    }).run()
  }
 
  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    var attributeHashes   = {}
      , dataTypeValues    = Utils._.values(DataTypes)
      , keys              = Object.keys(attributes)
      , keyLen            = keys.length
      , self              = this
      , sql               = ''
      , i                 = 0
 
    for (i = 0; i < keyLen; i++) {
      if (dataTypeValues.indexOf(attributes[keys[i]]) > -1) {
        attributeHashes[keys[i]] = { type: attributes[keys[i]], allowNull: true }
      } else {
        attributeHashes[keys[i]] = attributes[keys[i]]
      }
    }
 
    options = Utils._.extend({
      logging: this.sequelize.options.logging
    }, options || {})
 
    return new Utils.CustomEventEmitter(function(emitter) {
      // Postgres requires a special SQL command for enums
      Iif (self.sequelize.options.dialect === "postgres") {
        var chainer = new Utils.QueryChainer()
          // For backwards-compatibility, public schemas don't need to
          // explicitly state their schema when creating a new enum type
          , getTableName = (!options || !options.schema || options.schema === "public" ? '' : options.schema + '_') + tableName
 
        for (i = 0; i < keyLen; i++) {
          if (attributes[keys[i]].toString().match(/^ENUM\(/)) {
            sql = self.QueryGenerator.pgListEnums(getTableName, keys[i], options)
            chainer.add(self.sequelize.query(sql, null, { plain: true, raw: true, type: 'SELECT', logging: options.logging }))
          }
        }
 
        chainer.runSerially().success(function(results) {
          var chainer2 = new Utils.QueryChainer()
            // Find the table that we're trying to create throgh DAOFactoryManager
            , daoTable = self.sequelize.daoFactoryManager.daos.filter(function(dao) { return dao.tableName === tableName })
            , enumIdx  = 0
 
          daoTable = daoTable.length > 0 ? daoTable[0] : null
 
          for (i = 0; i < keyLen; i++) {
            if (attributes[keys[i]].toString().match(/^ENUM\(/)) {
              // If the enum type doesn't exist then create it
              if (!results[enumIdx]) {
                sql = self.QueryGenerator.pgEnum(getTableName, keys[i], attributes[keys[i]], options)
                chainer2.add(self.sequelize.query(sql, null, { raw: true, logging: options.logging }))
              } else if (!!results[enumIdx] && !!daoTable) {
                var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value)
                  , vals = daoTable.rawAttributes[keys[i]].values
 
                vals.forEach(function(value, idx) {
                  // reset out after/before options since it's for every enum value
                  options.before = null
                  options.after = null
 
                  if (enumVals.indexOf(value) === -1) {
                    if (!!vals[idx+1]) {
                      options.before = vals[idx+1]
                    }
                    else if (!!vals[idx-1]) {
                      options.after = vals[idx-1]
                    }
 
                    chainer2.add(self.sequelize.query(self.QueryGenerator.pgEnumAdd(getTableName, keys[i], value, options)))
                  }
                })
              }
            }
          }
 
          attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
          sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)
 
          chainer2.run().success(function() {
            queryAndEmit
              .call(self, sql, 'createTable', options)
              .success(function(res) {
                self.emit('createTable', null)
                emitter.emit('success', res)
              })
              .error(function(err) {
                self.emit('createTable', err)
                emitter.emit('error', err)
              })
              .on('sql', function(sql)  {
                emitter.emit('sql', sql)
              })
          }).error(function(err) {
            emitter.emit('error', err)
          }).on('sql', function(sql) {
            emitter.emit('sql', sql)
          })
        })
      } else {
        attributes = self.QueryGenerator.attributesToSQL(attributeHashes)
        sql = self.QueryGenerator.createTableQuery(tableName, attributes, options)
 
        queryAndEmit.call(self, sql, 'createTable', options).success(function(results) {
          self.emit('createTable', null)
          emitter.emit('success', results)
        }).error(function(err) {
          self.emit('createTable', err)
          emitter.emit('error', err)
        }).on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
      }
    }).run()
  }
 
  QueryInterface.prototype.dropTable = function(tableName, options) {
    // if we're forcing we should be cascading unless explicitly stated otherwise
    options = options || {}
    options.cascade = options.cascade || options.force || false
 
    var sql  = this.QueryGenerator.dropTableQuery(tableName, options)
      , self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer()
 
      chainer.add(self, 'queryAndEmit', [sql, 'dropTable'], options)
 
      // Since postgres has a special case for enums, we should drop the related
      // enum type within the table and attribute
      Iif (self.sequelize.options.dialect === "postgres") {
        // Find the table that we're trying to drop
        daoTable = self.sequelize.daoFactoryManager.daos.filter(function(dao) {
          return dao.tableName === tableName
        })
 
        // Just in case if we're trying to drop a non-existing table
        daoTable = daoTable.length > 0 ? daoTable[0] : null
        if (!!daoTable) {
          var getTableName = (!options || !options.schema || options.schema === "public" ? '' : options.schema + '_') + tableName
 
          var keys = Object.keys(daoTable.rawAttributes)
            , keyLen = keys.length
            , i = 0
 
          for (i = 0; i < keyLen; i++) {
            if (daoTable.rawAttributes[keys[i]].type && daoTable.rawAttributes[keys[i]].type === "ENUM") {
              chainer.add(self.sequelize, 'query', [self.QueryGenerator.pgEnumDrop(getTableName, keys[i]), null, {logging: options.logging, raw: true}])
            }
          }
        }
      }
 
      chainer.runSerially().success(function(results) {
        emitter.emit('success', results[0])
        self.emit('dropTable', null)
      }).error(function(err) {
        emitter.emit('error', err)
        self.emit('dropTable', err)
      }).on('sql', function(sql) {
        emitter.emit('sql', sql)
      })
    }).run()
  }
 
  QueryInterface.prototype.dropAllTables = function() {
    var self = this
 
    Iif (this.sequelize.options.dialect === 'sqlite') {
      // sqlite needs some special treatment as it cannot drop a column
      return SQLiteQueryInterface.dropAllTables.call(this)
    } else {
      return new Utils.CustomEventEmitter(function(dropAllTablesEmitter) {
        var events  = []
          , chainer = new Utils.QueryChainer()
          , onError = function(err) {
              self.emit('dropAllTables', err)
              dropAllTablesEmitter.emit('error', err)
            }
 
        self.showAllTables().success(function(tableNames) {
          self.getForeignKeysForTables(tableNames).success(function(foreignKeys) {
 
            // add the foreign key removal query to the chainer
            Object.keys(foreignKeys).forEach(function(tableName) {
              foreignKeys[tableName].forEach(function(foreignKey) {
                var sql = self.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey)
                chainer.add(self.sequelize, 'query', [ sql ])
              })
            })
 
            // add the table removal query to the chainer
            tableNames.forEach(function(tableName) {
              chainer.add(self, 'dropTable', [ tableName, { cascade: true } ])
            })
 
            chainer
              .runSerially()
              .success(function() {
                self.emit('dropAllTables', null)
                dropAllTablesEmitter.emit('success', null)
              })
              .error(onError)
          }).error(onError)
        }).error(onError)
      }).run()
    }
  }
 
  QueryInterface.prototype.renameTable = function(before, after) {
    var sql = this.QueryGenerator.renameTableQuery(before, after)
    return queryAndEmit.call(this, sql, 'renameTable')
  }
 
  QueryInterface.prototype.showAllTables = function() {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var showTablesSql = self.QueryGenerator.showTablesQuery()
 
      self.sequelize.query(showTablesSql, null, { raw: true }).success(function(tableNames) {
        self.emit('showAllTables', null)
        emitter.emit('success', Utils._.flatten(tableNames))
      }).error(function(err) {
        self.emit('showAllTables', err)
        emitter.emit('error', err)
      })
    }).run()
  }
 
  QueryInterface.prototype.describeTable = function(tableName, options) {
    var self = this
      , schema = null
      , schemaDelimiter = null
 
    if (typeof options === "string") {
      schema = options
    }
    else if (typeof options === "object") {
      schema = options.schema || null
      schemaDelimiter = options.schemaDelimiter || null
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var sql;
 
      if (self.QueryGenerator.describeTableQuery) {
        sql = self.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter)
      } else {
        var table = self.QueryGenerator.quoteIdentifier(self.QueryGenerator.addSchema({tableName: tableName, options: {schema: schema, schemaDelimiter: schemaDelimiter}}), self.QueryGenerator.options.quoteIdentifiers)
        sql = 'DESCRIBE ' + table + ';'
      }
 
      self.sequelize.query(sql, null, { raw: true }).success(function(data) {
        emitter.emit('success', data)
      }).error(function(err) {
        emitter.emit('error', err)
      }).on('sql', function(sql) {
        emitter.emit('sql', sql)
      })
    }).run()
  }
 
  QueryInterface.prototype.addColumn = function(tableName, attributeName, dataTypeOrOptions) {
    var attributes = {}
 
    if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
      attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true }
    } else {
      attributes[attributeName] = dataTypeOrOptions
    }
 
    var options = this.QueryGenerator.attributesToSQL(attributes)
      , sql     = this.QueryGenerator.addColumnQuery(tableName, options)
 
    return queryAndEmit.call(this, sql, 'addColumn')
  }
 
  QueryInterface.prototype.removeColumn = function(tableName, attributeName) {
    if (this.sequelize.options.dialect === 'sqlite') {
      // sqlite needs some special treatment as it cannot drop a column
      return new Utils.CustomEventEmitter(function(emitter) {
        SQLiteQueryInterface.removeColumn.call(this, tableName, attributeName, emitter, queryAndEmit)
      }.bind(this)).run()
    } else {
      var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName)
      return queryAndEmit.call(this, sql, 'removeColumn')
    }
  }
 
  QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions) {
    var attributes = {}
 
    if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
      attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true }
    } else {
      attributes[attributeName] = dataTypeOrOptions
    }
 
    if (this.sequelize.options.dialect === 'sqlite') {
      // sqlite needs some special treatment as it cannot change a column
      return new Utils.CustomEventEmitter(function(emitter) {
        SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, emitter, queryAndEmit)
      }.bind(this)).run()
    } else {
      var options = this.QueryGenerator.attributesToSQL(attributes)
        , sql     = this.QueryGenerator.changeColumnQuery(tableName, options)
 
      return queryAndEmit.call(this, sql, 'changeColumn')
    }
  }
 
  QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter) {
    return new Utils.CustomEventEmitter(function(emitter) {
      this.describeTable(tableName).success(function(data) {
        data = data[attrNameBefore] || {}
 
        var options =  {}
 
        options[attrNameAfter] = {
          attribute:    attrNameAfter,
          type:         data.type,
          allowNull:    data.allowNull,
          defaultValue: data.defaultValue
        }
 
        if (this.sequelize.options.dialect === 'sqlite') {
          // sqlite needs some special treatment as it cannot rename a column
          SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, emitter, queryAndEmit)
        } else {
          var sql = this.QueryGenerator.renameColumnQuery(tableName,
            attrNameBefore,
            this.QueryGenerator.attributesToSQL(options)
          )
          queryAndEmit.call(this, sql, 'renameColumn', {}, emitter)
        }
      }.bind(this))
      .error(function(err) {
        this.emit('renameColumn', err)
        emitter.emit('error', err)
      }.bind(this))
    }.bind(this)).run()
  }
 
  QueryInterface.prototype.addIndex = function(tableName, attributes, options) {
    var sql = this.QueryGenerator.addIndexQuery(tableName, attributes, options)
    return queryAndEmit.call(this, sql, 'addIndex')
  }
 
  QueryInterface.prototype.showIndex = function(tableName, options) {
    var sql = this.QueryGenerator.showIndexQuery(tableName, options)
    return queryAndEmit.call(this, sql, 'showIndex')
  }
 
  QueryInterface.prototype.getForeignKeysForTables = function(tableNames) {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      if (tableNames.length === 0) {
        emitter.emit('success', {})
      } else {
        var chainer = new Utils.QueryChainer()
 
        tableNames.forEach(function(tableName) {
          var sql = self.QueryGenerator.getForeignKeysQuery(tableName, self.sequelize.config.database)
          chainer.add(self.sequelize, 'query', [sql])
        })
 
        chainer.runSerially().proxy(emitter, {
          skipEvents: ['success']
        }).success(function(results) {
          var result = {}
 
          tableNames.forEach(function(tableName, i) {
            result[tableName] = Utils._.compact(results[i]).map(function(r) { return r.constraint_name })
          })
 
          emitter.emit('success', result)
        })
      }
    }).run()
  }
 
  QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes) {
    var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes)
    return queryAndEmit.call(this, sql, "removeIndex")
  }
 
  QueryInterface.prototype.insert = function(dao, tableName, values, options) {
    var sql = this.QueryGenerator.insertQuery(tableName, values, dao.daoFactory.rawAttributes)
    return queryAndEmit.call(this, [sql, dao, options], 'insert', {
      success: function(obj) { obj.isNewRecord = false }
    })
  }
 
  QueryInterface.prototype.bulkInsert = function(tableName, records, options) {
    var sql = this.QueryGenerator.bulkInsertQuery(tableName, records)
    return queryAndEmit.call(this, [sql, null, options], 'bulkInsert')
  }
 
  QueryInterface.prototype.update = function(dao, tableName, values, identifier, options) {
    var self = this
      , restrict = false
      , sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, dao.daoFactory.rawAttributes)
 
    // Check for a restrict field
    Eif (!!dao.daoFactory && !!dao.daoFactory.associations) {
      var keys = Object.keys(dao.daoFactory.associations)
        , length = keys.length
 
      for (var i = 0; i < length; i++) {
        if (dao.daoFactory.associations[keys[i]].options && dao.daoFactory.associations[keys[i]].options.onUpdate && dao.daoFactory.associations[keys[i]].options.onUpdate === "restrict") {
          restrict = true
        }
      }
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer()
 
      chainer.add(self, 'queryAndEmit', [[sql, dao, options], 'delete'])
 
      chainer.runSerially()
      .success(function(results){
        emitter.query = { sql: sql }
        emitter.emit('success', results[0])
        emitter.emit('sql', sql)
      })
      .error(function(err) {
        emitter.query = { sql: sql }
        emitter.emit('error', err)
        emitter.emit('sql', sql)
      })
      .on('sql', function(sql) {
        emitter.emit('sql', sql)
      })
    }).run()
  }
 
  QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options) {
    var self = this
      , sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options)
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer()
 
      chainer.add(self, 'queryAndEmit', [[sql, null, options], 'bulkUpdate'])
 
      return chainer.runSerially()
      .success(function(results){
        emitter.query = { sql: sql }
        emitter.emit('sql', sql)
        emitter.emit('success', results[1])
      })
      .error(function(err) {
        emitter.query = { sql: sql }
        emitter.emit('sql', sql)
        emitter.emit('error', err)
      })
    }).run()
  }
 
  QueryInterface.prototype.delete = function(dao, tableName, identifier, options) {
    var self      = this
      , restrict  = false
      , cascades  = []
      , sql       = self.QueryGenerator.deleteQuery(tableName, identifier, null, dao.daoFactory)
 
    // Check for a restrict field
    Eif (!!dao.daoFactory && !!dao.daoFactory.associations) {
      var keys = Object.keys(dao.daoFactory.associations)
        , length = keys.length
 
      for (var i = 0; i < length; i++) {
        if (dao.daoFactory.associations[keys[i]].options && dao.daoFactory.associations[keys[i]].options.onDelete) {
          if (dao.daoFactory.associations[keys[i]].options.onDelete === "restrict") {
            restrict = true
          }
          else Iif (dao.daoFactory.associations[keys[i]].options.onDelete === "cascade" && dao.daoFactory.associations[keys[i]].options.useHooks === true) {
            cascades[cascades.length] = dao.daoFactory.associations[keys[i]].accessors.get
          }
        }
      }
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var tick = 0
      var iterate = function(err, i) {
        if (!!err || i >= cascades.length) {
          return run(err)
        }
 
        dao[cascades[i]]().success(function(tasks) {
          if (tasks === null || tasks.length < 1) {
            return run()
          }
 
          tasks = Array.isArray(tasks) ? tasks : [tasks]
 
          var ii = 0
          var next = function(err, ii) {
            if (!!err || ii >= tasks.length) {
              return iterate(err)
            }
 
            tasks[ii].destroy().error(function(err) {
              return iterate(err)
            })
            .success(function() {
              ii++
 
              if (ii >= tasks.length) {
                tick++
                return iterate(null, tick)
              }
 
              next(null, ii)
            })
          }
 
          next(null, ii)
        })
      }
 
      var run = function(err) {
        Iif (!!err) {
          return emitter.emit('error', err)
        }
 
        var chainer = new Utils.QueryChainer()
 
        chainer.add(self, 'queryAndEmit', [[sql, dao, options], 'delete'])
 
        chainer.runSerially()
        .success(function(results){
          emitter.query = { sql: sql }
          emitter.emit('sql', sql)
          emitter.emit('success', results[1])
        })
        .error(function(err) {
          emitter.query = { sql: sql }
          emitter.emit('sql', sql)
          emitter.emit('error', err)
        })
      }
 
      Iif (cascades.length > 0) {
        iterate(null, tick)
      } else {
        run()
      }
    }).run()
  }
 
  QueryInterface.prototype.bulkDelete = function(tableName, identifier, options) {
    var self = this
    var sql = self.QueryGenerator.deleteQuery(tableName, identifier, Utils._.defaults(options || {}, {limit: null}))
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer()
 
      chainer.add(self, 'queryAndEmit', [[sql, null, options], 'bulkDelete', options])
 
      chainer.runSerially()
      .success(function(results){
        emitter.query = { sql: sql }
        emitter.emit('sql', sql)
        emitter.emit('success', results[1])
      })
      .error(function(err) {
        emitter.query = { sql: sql }
        emitter.emit('sql', sql)
        emitter.emit('error', err)
      })
    }).run()
  }
 
  QueryInterface.prototype.select = function(factory, tableName, options, queryOptions) {
    options = options || {}
 
    // See if we need to merge options and factory.scopeObj
    // we're doing this on the QueryInterface level because it's a bridge between
    // sequelize and the databases
    if (Object.keys(factory.scopeObj).length > 0) {
      Eif (!!options) {
        Utils.injectScope.call(factory, options, true)
      }
 
      var scopeObj = buildScope.call(factory)
      Object.keys(scopeObj).forEach(function(method) {
        if (typeof scopeObj[method] === "number" || !Utils._.isEmpty(scopeObj[method])) {
          options[method] = scopeObj[method]
        }
      })
    }
 
    var sql = this.QueryGenerator.selectQuery(tableName, options, factory)
    queryOptions = Utils._.extend({}, queryOptions, { include: options.include, includeNames: options.includeNames, includeMap: options.includeMap })
 
    return queryAndEmit.call(this, [sql, factory, queryOptions], 'select')
  }
 
  QueryInterface.prototype.increment = function(dao, tableName, values, identifier, options) {
    var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes)
    return queryAndEmit.call(this, [sql, dao, options], 'increment')
  }
 
  QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelector) {
    var self = this
 
    if (attributeSelector === undefined) {
      throw new Error('Please pass an attribute selector!')
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var sql          = self.QueryGenerator.selectQuery(tableName, options)
        , queryOptions = Utils._.extend({ transaction: options.transaction }, { plain: true, raw: true, type: 'SELECT' })
        , query        = self.sequelize.query(sql, null, queryOptions)
 
      query
        .success(function(data) {
          var result = data ? data[attributeSelector] : null
 
          if (options && options.dataType) {
            var dataType = options.dataType;
 
            if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
              result = parseFloat(result);
            } else if (dataType === DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
              result = parseInt(result, 10);
            } else if (dataType === DataTypes.DATE) {
              result = new Date(result + 'Z');
            } else if (dataType === DataTypes.STRING) {
              // Nothing to do, result is already a string.
            }
          }
 
          self.emit('rawSelect', null)
          emitter.emit('success', result)
        })
        .error(function(err) {
          self.emit('rawSelect', err)
          emitter.emit('error', err)
        })
        .on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
    }).run()
  }
 
  QueryInterface.prototype.createTrigger = function(tableName, triggerName, timingType, fireOnArray,
      functionName, functionParams, optionsArray) {
    var  sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName
        , functionParams, optionsArray)
    if (sql){
      return queryAndEmit.call(this, sql, 'createTrigger')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('createTrigger', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  QueryInterface.prototype.dropTrigger = function(tableName, triggerName) {
    var  sql = this.QueryGenerator.dropTrigger(tableName, triggerName)
    if (sql){
      return queryAndEmit.call(this, sql, 'dropTrigger')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('dropTrigger', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName) {
    var  sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName)
    if (sql){
      return queryAndEmit.call(this, sql, 'renameTrigger')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('renameTrigger', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) {
    var  sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options)
    if (sql){
      return queryAndEmit.call(this, sql, 'createFunction')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('createFunction', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  QueryInterface.prototype.dropFunction = function(functionName, params) {
    var  sql = this.QueryGenerator.dropFunction(functionName, params)
    if (sql){
      return queryAndEmit.call(this, sql, 'dropFunction')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('dropFunction', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName) {
    var  sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName)
    if (sql){
      return queryAndEmit.call(this, sql, 'renameFunction')
    } else {
      return new Utils.CustomEventEmitter(function(emitter) {
        this.emit('renameFunction', null)
        emitter.emit('success')
      }).run()
    }
  }
 
  // Helper methods useful for querying
 
  /**
   * Escape an identifier (e.g. a table or attribute name). If force is true,
   * the identifier will be quoted even if the `quoteIdentifiers` option is
   * false.
   */
  QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
    return this.QueryGenerator.quoteIdentifier(identifier, force)
  }
 
  /**
   * Split an identifier into .-separated tokens and quote each part.
   * If force is true, the identifier will be quoted even if the
   * `quoteIdentifiers` option is false.
   */
  QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
    return this.QueryGenerator.quoteIdentifiers(identifiers, force)
  }
 
  /**
   * Escape a value (e.g. a string, number or date)
   */
  QueryInterface.prototype.escape = function(value) {
    return this.QueryGenerator.escape(value)
  }
 
  QueryInterface.prototype.setAutocommit = function(transaction, value) {
    Iif (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to set autocommit for a transaction without transaction object!')
    }
 
    var sql = this.QueryGenerator.setAutocommitQuery(value)
    return this.queryAndEmit([sql, null, { transaction: transaction }], 'setAutocommit')
  }
 
  QueryInterface.prototype.setIsolationLevel = function(transaction, value) {
    Iif (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to set isolation level for a transaction without transaction object!')
    }
 
    var sql = this.QueryGenerator.setIsolationLevelQuery(value)
    return this.queryAndEmit([sql, null, { transaction: transaction }], 'setIsolationLevel')
  }
 
  QueryInterface.prototype.startTransaction = function(transaction, options) {
    Iif (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to start a transaction without transaction object!')
    }
 
    options = Utils._.extend({
      transaction: transaction
    }, options || {})
 
    var sql = this.QueryGenerator.startTransactionQuery(options)
    return this.queryAndEmit([sql, null, options], 'startTransaction')
  }
 
  QueryInterface.prototype.commitTransaction = function(transaction, options) {
    if (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to commit a transaction without transaction object!')
    }
 
    options = Utils._.extend({
      transaction: transaction
    }, options || {})
 
    var sql = this.QueryGenerator.commitTransactionQuery(options)
    return this.queryAndEmit([sql, null, options], 'commitTransaction')
  }
 
  QueryInterface.prototype.rollbackTransaction = function(transaction, options) {
    Iif (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to rollback a transaction without transaction object!')
    }
 
    options = Utils._.extend({
      transaction: transaction
    }, options || {})
 
    var sql = this.QueryGenerator.rollbackTransactionQuery(options)
    return this.queryAndEmit([sql, null, options], 'rollbackTransaction')
  }
 
  // private
 
  var buildScope = function() {
    var smart
 
    // Use smartWhere to convert several {where} objects into a single where object
    smart = Utils.smartWhere(this.scopeObj.where || [], this.daoFactoryManager.sequelize.options.dialect)
    smart = Utils.compileSmartWhere.call(this, smart, this.daoFactoryManager.sequelize.options.dialect)
    return {limit: this.scopeObj.limit || null, offset: this.scopeObj.offset || null, where: smart, order: (this.scopeObj.order || []).join(', ')}
  }
 
  var queryAndEmit = QueryInterface.prototype.queryAndEmit = function(sqlOrQueryParams, methodName, options, emitter) {
    options = Utils._.extend({
      success:     function(){},
      error:       function(){},
      transaction: null,
      logging:     this.sequelize.options.logging
    }, options || {})
 
    var execQuery = function(emitter) {
      var query = null
 
      if (Array.isArray(sqlOrQueryParams)) {
        Iif (sqlOrQueryParams.length === 1) {
          sqlOrQueryParams.push(null)
        }
 
        Iif (sqlOrQueryParams.length === 2) {
          sqlOrQueryParams.push(typeof options === "object" ? options : {})
        }
 
        emitter.query = this.sequelize.query.apply(this.sequelize, sqlOrQueryParams)
      } else {
        emitter.query = this.sequelize.query(sqlOrQueryParams, null, options)
      }
 
      emitter
        .query
        .success(function(obj) {
          options.success && options.success(obj)
          this.emit(methodName, null)
          emitter.emit('success', obj)
        }.bind(this))
        .error(function(err) {
          options.error && options.error(err)
          this.emit(methodName, err)
          emitter.emit('error', err)
        }.bind(this))
        .on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
    }.bind(this)
 
    Iif (!!emitter) {
      execQuery(emitter)
    } else {
      return new Utils.CustomEventEmitter(execQuery).run()
    }
  }
 
  return QueryInterface
})()