Code coverage report for upstream/lib/dialects/abstract/query-generator.js

Statements: 58.4% (205 / 351)      Branches: 62.09% (172 / 277)      Functions: 42.65% (29 / 68)      Lines: 58.7% (199 / 339)     

All files » upstream/lib/dialects/abstract/ » query-generator.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 10491     1 1                                                                                                                                                                                                             262               262   262 262     262         262   262 862 862 862     862 36 36         826         262           262   262                                         76   76   76     76 76       76 173 173     76           76                                                                                                                                                                                                                                                                                                     15 6 9 1 8 8                                                                                                                                         2406     2406                                                                                       289   289                           289 74       289 189   189       189       189 9 8 8   9   180     189 4     189       289     289         289 19 24                   24   24                   24 24 104       24     24       24 2     8                                 2   2         2 2       2 2     2 2     2 2     2                                   22                 22 22     22 22   22                       24 5 5 3       24       19 21     21     21           289           289 289       289 224 224     224         289                   289 10   10     10         289     289 91     91         289           289     289   289                   12       12                   12                                       12                                           312     312 233 233 79 9 9       9     9 9 9 70 7 63 63     312       20   20 30     30     30 16   14 14     30 18       20                                 279 94     185 185   7       7 11 11 9 9         5           5 9 9 9 9       5 5                                                                                                       33   33 45 33               242   242     242 279     279         279     279 5   274       279 33 246 45   28 28   17 20 20         20 9 9   9   11 11         201     201     201       242               1       1      
var Utils = require("../../utils")
  , SqlString = require("../../sql-string")
 
module.exports = (function() {
  var QueryGenerator = {
    addSchema: function(opts) {
      throwMethodUndefined('addSchema')
    },
 
    /*
      Returns a query for creating a table.
      Parameters:
        - tableName: Name of the new table.
        - attributes: An object with containing attribute-attributeType-pairs.
                      Attributes should have the format:
                      {attributeName: type, attr2: type2}
                      --> e.g. {title: 'VARCHAR(255)'}
        - options: An object with options.
                   Defaults: { engine: 'InnoDB', charset: null }
    */
    createTableQuery: function(tableName, attributes, options) {
      throwMethodUndefined('createTableQuery')
    },
 
    /*
      Returns a query for dropping a table.
    */
    dropTableQuery: function(tableName, options) {
      throwMethodUndefined('dropTableQuery')
    },
 
    /*
      Returns a rename table query.
      Parameters:
        - originalTableName: Name of the table before execution.
        - futureTableName: Name of the table after execution.
    */
    renameTableQuery: function(before, after) {
      var query = "ALTER TABLE <%= before %> RENAME TO <%= after %>;"
      return Utils._.template(query)({
        before: this.quoteTable(before),
        after: this.quoteTable(after)
      })
    },
 
    /*
      Returns a query, which gets all available table names in the database.
    */
    showTablesQuery: function() {
      throwMethodUndefined('showTablesQuery')
    },
 
    /*
      Returns a query, which adds an attribute to an existing table.
      Parameters:
        - tableName: Name of the existing table.
        - attributes: A hash with attribute-attributeOptions-pairs.
          - key: attributeName
          - value: A hash with attribute specific options:
            - type: DataType
            - defaultValue: A String with the default value
            - allowNull: Boolean
    */
    addColumnQuery: function(tableName, attributes) {
      throwMethodUndefined('addColumnQuery')
    },
 
    /*
      Returns a query, which removes an attribute from an existing table.
      Parameters:
        - tableName: Name of the existing table
        - attributeName: Name of the obsolete attribute.
    */
    removeColumnQuery: function(tableName, attributeName) {
      throwMethodUndefined('removeColumnQuery')
    },
 
    /*
      Returns a query, which modifies an existing attribute from a table.
      Parameters:
        - tableName: Name of the existing table.
        - attributes: A hash with attribute-attributeOptions-pairs.
          - key: attributeName
          - value: A hash with attribute specific options:
            - type: DataType
            - defaultValue: A String with the default value
            - allowNull: Boolean
    */
    changeColumnQuery: function(tableName, attributes) {
      throwMethodUndefined('changeColumnQuery')
    },
 
    /*
      Returns a query, which renames an existing attribute.
      Parameters:
        - tableName: Name of an existing table.
        - attrNameBefore: The name of the attribute, which shall be renamed.
        - attrNameAfter: The name of the attribute, after renaming.
    */
    renameColumnQuery: function(tableName, attrNameBefore, attrNameAfter) {
      throwMethodUndefined('renameColumnQuery')
    },
 
    /*
      Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
    */
    insertQuery: function(table, valueHash, modelAttributes) {
      var query
        , valueQuery          = "INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>)"
        , emptyQuery          = "INSERT INTO <%= table %>"
        , fields              = []
        , values              = []
        , key
        , value
 
      Iif (this._dialect.supports['DEFAULT VALUES']) {
        emptyQuery += " DEFAULT VALUES"
      } else Eif (this._dialect.supports['VALUES ()']) {
        emptyQuery += " VALUES ()"
      }
 
      Iif (this._dialect.supports['RETURNING']) {
        valueQuery += " RETURNING *"
        emptyQuery += " RETURNING *"
      }
 
      valueHash = Utils.removeNullValuesFromHash(valueHash, this.options.omitNull)
 
      for (key in valueHash) {
        Eif (valueHash.hasOwnProperty(key)) {
          value = valueHash[key]
          fields.push(this.quoteIdentifier(key))
 
          // SERIALS' can't be NULL in postgresql, use DEFAULT where supported
          if (modelAttributes && modelAttributes[key] && modelAttributes[key].autoIncrement === true && !value) {
            Eif (this._dialect.supports['DEFAULT']) {
              values.push('DEFAULT')
            } else {
              values.push(this.escape(null))
            }
          } else {
            values.push(this.escape(value, (modelAttributes && modelAttributes[key]) || undefined))
          }
        }
      }
 
      var replacements  = {
        table:      this.quoteTable(table),
        attributes: fields.join(","),
        values:     values.join(",")
      }
 
      query = (replacements.attributes.length ? valueQuery : emptyQuery) + ";"
 
      return Utils._.template(query)(replacements)
    },
    /*
      Returns an insert into command for multiple values.
      Parameters: table name + list of hashes of attribute-value-pairs.
    */
    bulkInsertQuery: function(tableName, attrValueHashes) {
      throwMethodUndefined('bulkInsertQuery')
    },
 
    /*
      Returns an update query.
      Parameters:
        - tableName -> Name of the table
        - values -> A hash with attribute-value-pairs
        - where -> A hash with conditions (e.g. {name: 'foo'})
                   OR an ID as integer
                   OR a string with conditions (e.g. 'name="foo"').
                   If you use a string, you have to escape it on your own.
    */
    updateQuery: function(tableName, attrValueHash, where, options, attributes) {
      options = options || {}
 
      attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull, options)
 
      var query
        , values = []
 
      query = "UPDATE <%= table %> SET <%= values %> WHERE <%= where %>"
      Iif (this._dialect.supports['RETURNING'] && (options.returning || options.returning === undefined)) {
        query += " RETURNING *"
      }
 
      for (var key in attrValueHash) {
        var value = attrValueHash[key]
        values.push(this.quoteIdentifier(key) + "=" + this.escape(value, (!!attributes && !!attributes[key] ? attributes[key] : undefined)))
      }
 
      var replacements = {
        table:  this.quoteTable(tableName),
        values: values.join(","),
        where:  this.getWhereConditions(where)
      }
 
      return Utils._.template(query)(replacements)
    },
 
    /*
      Returns a deletion query.
      Parameters:
        - tableName -> Name of the table
        - where -> A hash with conditions (e.g. {name: 'foo'})
                   OR an ID as integer
                   OR a string with conditions (e.g. 'name="foo"').
                   If you use a string, you have to escape it on your own.
      Options:
        - limit -> Maximaum count of lines to delete
        - truncate -> boolean - whether to use an 'optimized' mechanism (i.e. TRUNCATE) if available,
                                note that this should not be the default behaviour because TRUNCATE does not
                                always play nicely (e.g. InnoDB tables with FK constraints)
                                (@see http://dev.mysql.com/doc/refman/5.6/en/truncate-table.html).
                                Note that truncate must ignore limit and where
    */
    deleteQuery: function(tableName, where, options) {
      throwMethodUndefined('deleteQuery')
    },
 
    /*
      Returns a bulk deletion query.
      Parameters:
        - tableName -> Name of the table
        - where -> A hash with conditions (e.g. {name: 'foo'})
                   OR an ID as integer
                   OR a string with conditions (e.g. 'name="foo"').
                   If you use a string, you have to escape it on your own.
    */
    bulkDeleteQuery: function(tableName, where, options) {
      throwMethodUndefined('bulkDeleteQuery')
    },
 
    /*
      Returns an update query.
      Parameters:
        - tableName -> Name of the table
        - values -> A hash with attribute-value-pairs
        - where -> A hash with conditions (e.g. {name: 'foo'})
                   OR an ID as integer
                   OR a string with conditions (e.g. 'name="foo"').
                   If you use a string, you have to escape it on your own.
    */
    incrementQuery: function(tableName, attrValueHash, where, options) {
      attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull)
 
      var query
        , values = []
 
      query = "UPDATE <%= table %> SET <%= values %> WHERE <%= where %>"
      if (this._dialect.supports['RETURNING']) {
        query += " RETURNING *"
      }
 
      for (var key in attrValueHash) {
        var value = attrValueHash[key]
        values.push(this.quoteIdentifier(key) + "=" + this.quoteIdentifier(key) + " + " + this.escape(value))
      }
 
      options = options || {}
      for (var key in options) {
        var value = options[key];
        values.push(this.quoteIdentifier(key) + "=" + this.escape(value))
      }
 
      var replacements = {
        table:  this.quoteIdentifiers(tableName),
        values: values.join(","),
        where:  this.getWhereConditions(where)
      }
 
      return Utils._.template(query)(replacements)
    },
 
    /*
      Returns an add index query.
      Parameters:
        - tableName -> Name of an existing table.
        - attributes:
            An array of attributes as string or as hash.
            If the attribute is a hash, it must have the following content:
              - attribute: The name of the attribute/column
              - length: An integer. Optional
              - order: 'ASC' or 'DESC'. Optional
        - options:
          - indicesType: UNIQUE|FULLTEXT|SPATIAL
          - indexName: The name of the index. Default is <tableName>_<attrName1>_<attrName2>
          - parser
    */
    addIndexQuery: function(tableName, attributes, options) {
      throwMethodUndefined('addIndexQuery')
    },
 
    /*
      Returns an show index query.
      Parameters:
        - tableName: Name of an existing table.
        - options:
          - database: Name of the database.
    */
    showIndexQuery: function(tableName, options) {
      throwMethodUndefined('showIndexQuery')
    },
 
    /*
      Returns a remove index query.
      Parameters:
        - tableName: Name of an existing table.
        - indexNameOrAttributes: The name of the index as string or an array of attribute names.
    */
    removeIndexQuery: function(tableName, indexNameOrAttributes) {
      throwMethodUndefined('removeIndexQuery')
    },
 
    /*
      This method transforms an array of attribute hashes into equivalent
      sql attribute definition.
    */
    attributesToSQL: function(attributes) {
      throwMethodUndefined('attributesToSQL')
    },
 
    /*
      Returns all auto increment fields of a factory.
    */
    findAutoIncrementField: function(factory) {
      throwMethodUndefined('findAutoIncrementField')
    },
 
    /*
      Quote an object based on its type. This is a more general version of quoteIdentifiers
      Strings: should proxy to quoteIdentifiers
      Arrays: First argument should be qouted, second argument should be append without quoting
      Objects:
        * If raw is set, that value should be returned verbatim, without quoting
        * If fn is set, the string should start with the value of fn, starting paren, followed by
          the values of cols (which is assumed to be an array), quoted and joined with ', ',
          unless they are themselves objects
        * If direction is set, should be prepended
 
      Currently this function is only used for ordering / grouping columns, but it could
      potentially also be used for other places where we want to be able to call SQL functions (e.g. as default values)
    */
    quote: function(obj, force) {
      if (Utils._.isString(obj)) {
        return this.quoteIdentifiers(obj, force)
      } else if (Array.isArray(obj)) {
        return this.quote(obj[0], force) + ' ' + obj[1]
      } else Eif (obj instanceof Utils.fn || obj instanceof Utils.col || obj instanceof Utils.literal || obj instanceof Utils.cast) {
        return obj.toString(this)
      } else if (Utils._.isObject(obj) && 'raw' in obj) {
        return obj.raw
      } else {
        throw new Error('Unknown structure passed to order / group: ' + JSON.stringify(obj))
      }
    },
 
    /*
     Create a trigger
     */
    createTrigger: function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams,
        optionsArray) {
      throwMethodUndefined('createTrigger')
    },
 
    /*
     Drop a trigger
     */
    dropTrigger: function(tableName, triggerName) {
      throwMethodUndefined('dropTrigger')
    },
 
    /*
     Rename a trigger
     */
    renameTrigger: function(tableName, oldTriggerName, newTriggerName) {
      throwMethodUndefined('renameTrigger')
    },
 
    /*
     Create a function
     */
    createFunction: function(functionName, params, returnType, language, body, options) {
      throwMethodUndefined('createFunction')
    },
 
    /*
     Drop a function
     */
    dropFunction: function(functionName, params) {
      throwMethodUndefined('dropFunction')
    },
 
    /*
     Rename a function
     */
    renameFunction: function(oldFunctionName, params, newFunctionName) {
      throwMethodUndefined('renameFunction')
    },
 
    /*
      Escape an identifier (e.g. a table or attribute name)
    */
    quoteIdentifier: function(identifier, force) {
      throwMethodUndefined('quoteIdentifier')
    },
 
    /*
      Split an identifier into .-separated tokens and quote each part
    */
    quoteIdentifiers: function(identifiers, force) {
      throwMethodUndefined('quoteIdentifiers')
    },
 
    /*
      Escape a value (e.g. a string, number or date)
    */
    escape: function(value, field) {
      Iif (value instanceof Utils.fn || value instanceof Utils.col || value instanceof Utils.literal || value instanceof Utils.cast) {
        return value.toString(this)
      } else {
        return SqlString.escape(value, false, null, this.dialect, field)
      }
    },
 
    /**
     * Generates an SQL query that returns all foreign keys of a table.
     *
     * @param  {String} tableName  The name of the table.
     * @param  {String} schemaName The name of the schema.
     * @return {String}            The generated sql query.
     */
    getForeignKeysQuery: function(tableName, schemaName) {
      throwMethodUndefined('getForeignKeysQuery')
    },
 
    /**
     * Generates an SQL query that removes a foreign key from a table.
     *
     * @param  {String} tableName  The name of the table.
     * @param  {String} foreignKey The name of the foreign key constraint.
     * @return {String}            The generated sql query.
     */
    dropForeignKeyQuery: function(tableName, foreignKey) {
      throwMethodUndefined('dropForeignKeyQuery')
    },
 
 
    /*
      Returns a query for selecting elements in the table <tableName>.
      Options:
        - attributes -> An array of attributes (e.g. ['name', 'birthday']). Default: *
        - where -> A hash with conditions (e.g. {name: 'foo'})
                   OR an ID as integer
                   OR a string with conditions (e.g. 'name="foo"').
                   If you use a string, you have to escape it on your own.
        - order -> e.g. 'id DESC'
        - group
        - limit -> The maximum count you want to get.
        - offset -> An offset value to start from. Only useable with limit!
    */
 
    selectQuery: function(tableName, options, factory) {
      // Enter and change at your own peril -- Mick Hansen
 
      options       = options || {}
 
      var table               = null
        , self                = this
        , query
        , limit               = options.limit
        , mainQueryItems      = []
        , mainAttributes      = options.attributes
        , mainJoinQueries     = []
        // We'll use a subquery if there's a limit, if we have hasMany associations and if any of them are filtered
        , subQuery            = limit && options && options.hasIncludeWhere && options.hasIncludeRequired && options.hasMultiAssociation
        , subQueryItems       = []
        , subQueryAttributes  = null
        , subJoinQueries      = []
 
      // Escape table
      options.table = table = !Array.isArray(tableName) ? this.quoteIdentifiers(tableName) : tableName.map(function(t) {
        return this.quoteIdentifiers(t)
      }.bind(this)).join(", ")
 
      // Escape attributes
      mainAttributes = mainAttributes && mainAttributes.map(function(attr){
        var addTable = true
 
        Iif (attr instanceof Utils.literal) {
          return attr.toString(this)
        }
 
        Iif (attr instanceof Utils.fn || attr instanceof Utils.col) {
          return self.quote(attr)
        }
 
        if(Array.isArray(attr) && attr.length == 2) {
          if (attr[0] instanceof Utils.fn || attr[0] instanceof Utils.col) {
            attr[0] = self.quote(attr[0])
            addTable = false
          }
          attr = [attr[0], this.quoteIdentifier(attr[1])].join(' as ')
        } else {
          attr = attr.indexOf(Utils.TICK_CHAR) < 0 && attr.indexOf('"') < 0 ? this.quoteIdentifiers(attr) : attr
        }
 
        if (options.include && attr.indexOf('.') === -1 && addTable) {
          attr = this.quoteIdentifier(options.table) + '.' + attr
        }
 
        return attr
      }.bind(this))
 
      // If no attributes specified, use *
      mainAttributes = mainAttributes || (options.include ? [options.table+'.*'] : ['*'])
 
      // If subquery, we ad the mainAttributes to the subQuery and set the mainAttributes to select * from subquery
      Iif (subQuery) {
        subQueryAttributes = mainAttributes
        mainAttributes = [options.table+'.*']
      }
 
      if (options.include) {
        var generateJoinQuery = function(include, parentTable) {
          var table         = include.daoFactory.tableName
            , as            = include.as
            , joinQueryItem = ""
            , attributes
            , association   = include.association
            , through       = include.through
            , joinType      = include.required ? ' INNER JOIN ' : ' LEFT OUTER JOIN '
            , includeWhere  = {}
            , whereOptions  = Utils._.clone(options)
 
          if (tableName !== parentTable) as = parentTable+'.'+include.as
 
          Iif (include.where) {
            for (var key in include.where) {
              if (include.where.hasOwnProperty(key)) {
                includeWhere[self.quoteIdentifier(as)+'.'+self.quoteIdentifiers(key)] = include.where[key]
              }
            }
            whereOptions.keysEscaped = true
          }
 
          // includeIgnoreAttributes is used by aggregate functions
          Eif (options.includeIgnoreAttributes !== false) {
            attributes  = include.attributes.map(function(attr) {
              return self.quoteIdentifier(as) + "." + self.quoteIdentifier(attr) + " AS " + self.quoteIdentifier(as + "." + attr)
            })
 
            // If not many to many, and we're doing a subquery, add attributes to the subquery
            Iif (!include.association.isMultiAssociation && subQuery && (include.hasIncludeRequired || include.required)) {
              subQueryAttributes = subQueryAttributes.concat(attributes)
            } else {
              mainAttributes = mainAttributes.concat(attributes)
            }
          }
 
          if (through) {
            var throughTable      = through.daoFactory.tableName
              , throughAs         = as + "." + through.as
              , throughAttributes = through.attributes.map(function(attr) {
                return self.quoteIdentifier(throughAs) + "." + self.quoteIdentifier(attr) + " AS " + self.quoteIdentifier(throughAs + "." + attr)
              })
              , primaryKeysSource = Object.keys(association.source.primaryKeys)
              , tableSource       = parentTable
              , identSource       = association.identifier
              , attrSource        = ((!association.source.hasPrimaryKeys || primaryKeysSource.length !== 1) ? 'id' : primaryKeysSource[0])
              , where
 
              , primaryKeysTarget = Object.keys(association.target.primaryKeys)
              , tableTarget       = as
              , identTarget       = association.foreignIdentifier
              , attrTarget        = ((!include.association.target.hasPrimaryKeys || primaryKeysTarget.length !== 1) ? 'id' : primaryKeysTarget[0])
 
              , sourceJoinOn
              , targetJoinOn
              , targetWhere
 
            Eif (options.includeIgnoreAttributes !== false) {
              // Through includes are always hasMany, so we need to add the attributes to the mainAttributes no matter what (Real join will never be executed in subquery)
              mainAttributes = mainAttributes.concat(throughAttributes)
            }
 
            // Filter statement for left side of through
            // Used by both join and subquery where
            sourceJoinOn = self.quoteIdentifier(tableSource) + "." + self.quoteIdentifier(attrSource) + " = "
              sourceJoinOn += self.quoteIdentifier(throughAs) + "." + self.quoteIdentifier(identSource)
 
            // Filter statement for right side of through
            // Used by both join and subquery where
            targetJoinOn = self.quoteIdentifier(tableTarget) + "." + self.quoteIdentifier(attrTarget) + " = "
              targetJoinOn += self.quoteIdentifier(throughAs) + "." + self.quoteIdentifier(identTarget)
 
            // Generate join SQL for left side of through
            joinQueryItem += joinType + self.quoteIdentifier(throughTable) + " AS " + self.quoteIdentifier(throughAs) + " ON "
              joinQueryItem += sourceJoinOn
 
            // Generate join SQL for right side of through
            joinQueryItem += joinType + self.quoteIdentifier(table) + " AS " + self.quoteIdentifier(as) + " ON "
              joinQueryItem += targetJoinOn
 
 
            Iif (include.where) {
              targetWhere = self.hashToWhereConditions(includeWhere, include.daoFactory, whereOptions)
              joinQueryItem += " AND "+ targetWhere
              if (subQuery) {
                if (!options.where) options.where = {}
 
                // Creating the as-is where for the subQuery, checks that the required association exists
                var _where = "(";
                  _where += "SELECT "+self.quoteIdentifier(identSource)+" FROM " + self.quoteIdentifier(throughTable) + " AS " + self.quoteIdentifier(throughAs);
                  _where += joinType + self.quoteIdentifier(table) + " AS " + self.quoteIdentifier(as) + " ON "+targetJoinOn;
                  _where += " WHERE " + sourceJoinOn + " AND " + targetWhere + " LIMIT 1"
                _where += ")";
                _where += " IS NOT NULL"
 
                options.where["__"+throughAs] = self.sequelize.asIs(_where)
              }
            }
          } else {
            var primaryKeysLeft = ((association.associationType === 'BelongsTo') ? Object.keys(association.target.primaryKeys) : Object.keys(include.association.source.primaryKeys))
              , tableLeft       = ((association.associationType === 'BelongsTo') ? as : parentTable)
              , attrLeft        = ((primaryKeysLeft.length !== 1) ? 'id' : primaryKeysLeft[0])
              , tableRight      = ((association.associationType === 'BelongsTo') ? parentTable : as)
              , attrRight       = association.identifier
              , where
 
            // Filter statement
            // Used by both join and subquery where
            where = self.quoteIdentifier(tableLeft) + "." + self.quoteIdentifier(attrLeft) + " = "
            where += self.quoteIdentifier(tableRight) + "." + self.quoteIdentifier(attrRight)
 
            // Generate join SQL
            joinQueryItem += joinType + self.quoteIdentifier(table) + " AS " + self.quoteIdentifier(as) + " ON "
              joinQueryItem += where
 
            Iif (include.where) {
              joinQueryItem += " AND "+self.hashToWhereConditions(includeWhere, include.daoFactory, whereOptions)
 
              // If its a multi association we need to add a where query to the main where (executed in the subquery)
              if (subQuery && association.isMultiAssociation) {
                if (!options.where) options.where = {}
                // Creating the as-is where for the subQuery, checks that the required association exists
                options.where["__"+as] = self.sequelize.asIs("(SELECT "+self.quoteIdentifier(attrRight)+" FROM " + self.quoteIdentifier(tableRight) + " WHERE " + where + " LIMIT 1) IS NOT NULL")
              }
            }
          }
 
          if (include.include) {
            include.include.forEach(function(childInclude) {
              if (childInclude._pseudo) return
              joinQueryItem += generateJoinQuery(childInclude, as)
            }.bind(this))
          }
 
          return joinQueryItem
        }
 
        // Loop through includes and generate subqueries
        options.include.forEach(function(include) {
          var joinQueryItem = generateJoinQuery(include, tableName)
 
          // If not many to many, and we're doing a subquery, add joinQuery to subQueries
          Iif (!include.association.isMultiAssociation && (subQuery && (include.hasIncludeWhere || include.where))) {
            subJoinQueries.push(joinQueryItem)
          } else {
            mainJoinQueries.push(joinQueryItem)
          }
        }.bind(this))
      }
 
      // If using subQuery select defined subQuery attributes and join subJoinQueries
      Iif (subQuery) {
        subQueryItems.push("SELECT " + subQueryAttributes.join(', ') + " FROM " + options.table)
        subQueryItems.push(subJoinQueries.join(''))
 
      // Else do it the reguar way
      } else {
        mainQueryItems.push("SELECT " + mainAttributes.join(', ') + " FROM " + options.table)
        mainQueryItems.push(mainJoinQueries.join(''))
      }
 
      // Add WHERE to sub or main query
      if (options.hasOwnProperty('where')) {
        options.where = this.getWhereConditions(options.where, tableName, factory, options)
        Iif (subQuery) {
          subQueryItems.push(" WHERE " + options.where)
        } else {
          mainQueryItems.push(" WHERE " + options.where)
        }
      }
 
      // Add GROUP BY to sub or main query
      Iif (options.group) {
        options.group = Array.isArray(options.group) ? options.group.map(function (t) { return this.quote(t) }.bind(this)).join(', ') : options.group
        if (subQuery) {
          subQueryItems.push(" GROUP BY " + options.group)
        } else {
          mainQueryItems.push(" GROUP BY " + options.group)
        }
      }
 
      // Add ORDER to sub or main query
      if (options.order) {
        options.order = Array.isArray(options.order) ? options.order.map(function (t) { return this.quote(t) }.bind(this)).join(', ') : options.order
 
        Iif (subQuery) {
          subQueryItems.push(" ORDER BY " + options.order)
        } else {
          mainQueryItems.push(" ORDER BY " + options.order)
        }
      }
 
 
      var limitOrder = this.addLimitAndOffset(options, query)
 
      // Add LIMIT, OFFSET to sub or main query
      if (limitOrder) {
        Iif (subQuery) {
          subQueryItems.push(limitOrder)
        } else {
          mainQueryItems.push(limitOrder)
        }
      }
 
      // If using subQuery, select attributes from wrapped subQuery and join out join tables
      Iif (subQuery) {
        query = "SELECT " + mainAttributes.join(', ') + " FROM ("
          query += subQueryItems.join('')
        query += ") AS "+options.table
        query += mainJoinQueries.join('')
      } else {
        query = mainQueryItems.join('')
      }
 
      query += ";";
 
      return query
    },
 
    /**
     * Returns a query that starts a transaction.
     *
     * @param  {Boolean} value A boolean that states whether autocommit shall be done or not.
     * @return {String}        The generated sql query.
     */
    setAutocommitQuery: function(value) {
      return "SET autocommit = " + (!!value ? 1 : 0) + ";"
    },
 
    setIsolationLevelQuery: function(value) {
      return "SET SESSION TRANSACTION ISOLATION LEVEL " + value + ";"
    },
 
    /**
     * Returns a query that starts a transaction.
     *
     * @param  {Object} options An object with options.
     * @return {String}         The generated sql query.
     */
    startTransactionQuery: function(options) {
      return "START TRANSACTION;"
    },
 
    /**
     * Returns a query that commits a transaction.
     *
     * @param  {Object} options An object with options.
     * @return {String}         The generated sql query.
     */
    commitTransactionQuery: function(options) {
      return "COMMIT;"
    },
 
    /**
     * Returns a query that rollbacks a transaction.
     *
     * @param  {Object} options An object with options.
     * @return {String}         The generated sql query.
     */
    rollbackTransactionQuery: function(options) {
      return "ROLLBACK;"
    },
 
    addLimitAndOffset: function(options, query){
      query = query || ""
 
      if (options.offset && !options.limit) {
        query += " LIMIT " + options.offset + ", " + 10000000000000;
      } else if (options.limit && !(options.include && (options.limit === 1))) {
        if (options.offset) {
          query += " LIMIT " + options.offset + ", " + options.limit
        } else {
          query += " LIMIT " + options.limit
        }
      }
      return query;
    },
 
    /*
      Takes something and transforms it into values of a where condition.
    */
    getWhereConditions: function(smth, tableName, factory, options) {
      var result = null
        , where = {}
 
      if (Utils.isHash(smth)) {
        smth   = Utils.prependTableNameToHash(tableName, smth)
        result = this.hashToWhereConditions(smth, factory, options)
      } else if (typeof smth === 'number') {
        var primaryKeys = !!factory ? Object.keys(factory.primaryKeys) : []
        Iif (primaryKeys.length > 0) {
          // Since we're just a number, assume only the first key
          primaryKeys = primaryKeys[0]
        } else {
          primaryKeys = 'id'
        }
 
        where[primaryKeys] = smth
        smth   = Utils.prependTableNameToHash(tableName, where)
        result = this.hashToWhereConditions(smth)
      } else if (typeof smth === "string") {
        result = smth
      } else Eif (Array.isArray(smth)) {
        result = Utils.format(smth, this.dialect)
      }
 
      return result ? result : '1=1'
    },
 
    findAssociation: function(attribute, dao){
      var associationToReturn;
 
      Object.keys(dao.associations).forEach(function(key){
        Iif(!dao.associations[key]) return;
 
 
        var association = dao.associations[key]
          , associationName
 
        if (association.associationType === 'BelongsTo') {
          associationName = Utils.singularize(association.associationAccessor[0].toLowerCase() + association.associationAccessor.slice(1));
        } else {
          associationName = association.accessors.get.replace('get', '')
          associationName = associationName[0].toLowerCase() + associationName.slice(1);
        }
 
        if(associationName === attribute){
          associationToReturn = association;
        }
      });
 
      return associationToReturn;
    },
 
    getAssociationFilterDAO: function(filterStr, dao){
      var associationParts = filterStr.split('.')
        , self = this
 
      associationParts.pop()
 
      associationParts.forEach(function (attribute) {
        dao = self.findAssociation(attribute, dao).target;
      });
 
      return dao;
    },
 
    isAssociationFilter: function(filterStr, dao, options){
      if(!dao){
        return false;
      }
 
      var pattern = /^[a-z][a-zA-Z0-9]+(\.[a-z][a-zA-Z0-9]+)+$/;
      if (!pattern.test(filterStr)) return false;
 
      var associationParts = filterStr.split('.')
        , attributePart = associationParts.pop()
        , self = this
 
      return associationParts.every(function (attribute) {
        var association = self.findAssociation(attribute, dao);
        if (!association) return false;
        dao = association.target;
        return !!dao;
      }) && dao.rawAttributes.hasOwnProperty(attributePart);
    },
 
    getAssociationFilterColumn: function(filterStr, dao, options){
      var associationParts = filterStr.split('.')
        , attributePart = associationParts.pop()
        , self = this
        , association
        , keyParts = []
 
      associationParts.forEach(function (attribute) {
        association = self.findAssociation(attribute, dao)
        dao = association.target;
        Eif (options.include) {
          keyParts.push(association.as || association.options.as || dao.tableName)
        }
      })
 
      Eif (options.include) {
        return this.quoteIdentifier(keyParts.join('.')) + '.' +  this.quote(attributePart);
      }
      return this.quoteIdentifiers(dao.tableName + '.' +  attributePart);
    },
 
    getConditionalJoins: function(options, originalDao){
      var joins = ''
        , self = this
        , joinedTables = {}
 
      if (Utils.isHash(options.where)) {
        Object.keys(options.where).forEach(function(filterStr){
          var associationParts = filterStr.split('.')
            , attributePart = associationParts.pop()
            , dao = originalDao
 
          if (self.isAssociationFilter(filterStr, dao, options)) {
            associationParts.forEach(function (attribute) {
              var association = self.findAssociation(attribute, dao);
 
              if(!joinedTables[association.target.tableName]){
                joinedTables[association.target.tableName] = true;
 
                if(association.associationType === 'BelongsTo'){
                  joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName)
                  joins += ' ON ' + self.quoteIdentifiers(association.source.tableName + '.' + association.identifier)
                  joins += ' = ' + self.quoteIdentifiers(association.target.tableName + '.' + association.target.autoIncrementField)
                } else if (Object(association.through) === association.through) {
                  joinedTables[association.through.tableName] = true;
                  joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.through.tableName)
                  joins += ' ON ' + self.quoteIdentifiers(association.source.tableName + '.' + association.source.autoIncrementField)
                  joins += ' = ' + self.quoteIdentifiers(association.through.tableName + '.' + association.identifier)
 
                  joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName)
                  joins += ' ON ' + self.quoteIdentifiers(association.through.tableName + '.' + association.foreignIdentifier)
                  joins += ' = ' + self.quoteIdentifiers(association.target.tableName + '.' + association.target.autoIncrementField)
                } else {
                  joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName)
                  joins += ' ON ' + self.quoteIdentifiers(association.source.tableName + '.' + association.source.autoIncrementField)
                  joins += ' = ' + self.quoteIdentifiers(association.target.tableName + '.' + association.identifier)
                }
              }
              dao = association.target;
            });
          }
        });
      }
 
      return joins;
    },
 
    arrayValue: function(value, key, _key){
        var _value = null;
 
        Iif (value.length === 0) { value = [null] }
        _value = "(" + value.map(function(v) { return this.escape(v) }.bind(this)).join(',') + ")"
        return [_key, _value].join(" IN ")
    },
 
    /*
      Takes a hash and transforms it into a mysql where condition: {key: value, key2: value2} ==> key=value AND key2=value2
      The values are transformed by the relevant datatype.
    */
    hashToWhereConditions: function(hash, dao, options) {
      var result = []
 
      options = options || {}
 
      // Closures are nice
      Utils._.each(hash, function (value, key) {
        var _key
          , _value = null
 
        Iif (value instanceof Utils.asIs) {
          result.push(value.toString(this))
          return
        }
 
        Iif (options.keysEscaped) {
          _key = key
        } else {
          if(this.isAssociationFilter(key, dao, options)){
            _key = key = this.getAssociationFilterColumn(key, dao, options);
          } else {
            _key = this.quoteIdentifiers(key)
          }
        }
 
        if (Array.isArray(value)) {
          result.push(this.arrayValue(value, key, _key, dao))
        } else if ((value) && (typeof value == 'object') && !(value instanceof Date) && !Buffer.isBuffer(value)) {
          if (!!value.join) {
            //using as sentinel for join column => value
            _value = this.quoteIdentifiers(value.join)
            result.push([_key, _value].join("="))
          } else {
            for (var logic in value) {
              var logicResult = Utils.getWhereLogic(logic, hash[key][logic]);
              Iif (logic === "IN" || logic === "NOT IN") {
                var values = Array.isArray(where[i][ii]) ? where[i][ii] : [where[i][ii]]
                _where[_where.length] = i + ' ' + logic + ' (' + values.map(function(){ return '?' }).join(',') + ')'
                _whereArgs = _whereArgs.concat(values)
              }
              else if (logicResult === "BETWEEN" || logicResult === "NOT BETWEEN") {
                _value = this.escape(value[logic][0])
                var _value2 = this.escape(value[logic][1])
 
                result.push(' (' + _key + ' ' + logicResult + ' ' + _value + ' AND ' + _value2 + ') ')
              } else {
                _value = this.escape(value[logic])
                result.push([_key, _value].join(' ' + logicResult + ' '))
              }
            }
          }
        } else {
          Iif (typeof value === 'boolean') {
            _value = this.booleanValue(value);
          } else {
            _value = this.escape(value)
          }
 
          result.push((_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("="))
        }
      }.bind(this))
 
      return result.join(" AND ")
    },
 
    booleanValue: function(value){
      return value;
    }
  }
 
  var throwMethodUndefined = function(methodName) {
    throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.')
  }
 
  return QueryGenerator
})()