AbstractQuery.php 29.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php

/*
 *  $Id: Abstract.php 1393 2008-03-06 17:49:16Z guilhermeblanco $
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
20
 * <http://www.doctrine-project.org>.
21 22
 */

23 24
namespace Doctrine\ORM;

25
/**
26
 * Base class for Query and NativeQuery.
27 28
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
29
 * @link        www.doctrine-project.com
30 31 32 33
 * @since       1.0
 * @version     $Revision: 1393 $
 * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
34
 * @author      Roman Borschel <roman@code-factory.org>
35
 */
36
abstract class AbstractQuery
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
{
    /**
     * QUERY TYPE CONSTANTS
     */

    /**
     * Constant for SELECT queries.
     */
    const SELECT = 0;

    /**
     * Constant for DELETE queries.
     */
    const DELETE = 1;

    /**
     * Constant for UPDATE queries.
     */
    const UPDATE = 2;

    /**
     * @todo [TODO] Remove these ones (INSERT and CREATE)?
     */

    /**
     * Constant for INSERT queries.
     */
    //const INSERT = 3;

    /**
     * Constant for CREATE queries.
     */
    //const CREATE = 4;


    /**
     * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts.
     */
    const STATE_CLEAN  = 1;

    /**
     * A query object is in state DIRTY when it has DQL parts that have not yet been
     * parsed/processed. This is automatically defined as DIRTY when addDqlQueryPart
     * is called.
     */
    const STATE_DIRTY  = 2;

    /**
     * @todo [TODO] Remove these ones (DIRECT and LOCKED)?
     */

    /**
     * A query is in DIRECT state when ... ?
     */
    //const STATE_DIRECT = 3;

    /**
     * A query object is on LOCKED state when ... ?
     */
    //const STATE_LOCKED = 4;


    /**
     * @var integer $type Query type.
     *
102
     * @see Query::* constants
103 104 105 106 107 108 109 110 111 112
     */
    protected $_type = self::SELECT;

    /**
     * @var integer $_state   The current state of this query.
     */
    protected $_state = self::STATE_CLEAN;

    /**
     * @var array $params Parameters of this query.
113
     * @see Query::free that initializes this property
114 115 116 117 118
     */
    protected $_params = array();

    /**
     * @var array $_enumParams Array containing the keys of the parameters that should be enumerated.
119
     * @see Query::free that initializes this property
120 121 122 123 124
     */
    protected $_enumParams = array();

    /**
     * @var array $_dqlParts An array containing all DQL query parts.
125
     * @see Query::free that initializes this property
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
     */
    protected $_dqlParts = array();

    /**
     * @var string $_dql Cached DQL query.
     */
    protected $_dql = null;


    /**
     * Frees the resources used by the query object. It especially breaks a
     * cyclic reference between the query object and it's parsers. This enables
     * PHP's current GC to reclaim the memory.
     * This method can therefore be used to reduce memory usage when creating a lot
     * of query objects during a request.
     */
    public function free()
    {
        /**
         * @todo [TODO] What about "forUpdate" support? Remove it?
         */
        $this->_dqlParts = array(
            'select'    => array(),
            'distinct'  => false,
            'forUpdate' => false,
            'from'      => array(),
            'join'      => array(),
            'set'       => array(),
            'where'     => array(),
            'groupby'   => array(),
            'having'    => array(),
            'orderby'   => array(),
            'limit'     => array(),
            'offset'    => array(),
        );

        $this->_params = array(
            'join' => array(),
            'set' => array(),
            'where' => array(),
            'having' => array()
        );

        $this->_enumParams = array();

        $this->_dql = null;
        $this->_state = self::STATE_CLEAN;
    }


    /**
     * Defines a complete DQL
     *
     * @param string $dqlQuery DQL Query
     */
    public function setDql($dqlQuery)
    {
        $this->free();

        if ($dqlQuery !== null) {
            $this->_dql = $dqlQuery;

            $this->_state = self::STATE_DIRTY;
        }
    }


    /**
     * Returns the DQL query that is represented by this query object.
     *
     * @return string DQL query
     */
    public function getDql()
    {
        if ($this->_dql !== null) {
            return $this->_dql;
        }

        $dql = '';

        switch ($this->_type) {
            case self::DELETE:
                $dql = $this->_getDqlForDelete();
            break;

            case self::UPDATE:
                $dql = $this->_getDqlForUpdate();
            break;

            /**
             * @todo [TODO] Remove these ones (INSERT and CREATE)?
             */
            /*
            case self::INSERT:
            break;

            case self::CREATE:
            break;
            */

            case self::SELECT:
            default:
                $dql = $this->_getDqlForSelect();
            break;
        }

        return $dql;
    }


    /**
     * Builds the DQL of DELETE
     */
    protected function _getDqlForDelete()
    {
        /*
         * BNF:
         *
         * DeleteStatement = DeleteClause [WhereClause] [OrderByClause] [LimitClause] [OffsetClause]
         * DeleteClause    = "DELETE" "FROM" RangeVariableDeclaration
         * WhereClause     = "WHERE" ConditionalExpression
         * OrderByClause   = "ORDER" "BY" OrderByItem {"," OrderByItem}
         * LimitClause     = "LIMIT" integer
         * OffsetClause    = "OFFSET" integer
         *
         */
         return 'DELETE'
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' FROM ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('orderby', array('pre' => ' ORDER BY ', 'separator' => ', '))
              . $this->_getReducedDqlQueryPart('limit', array('pre' => ' LIMIT ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('offset', array('pre' => ' OFFSET ', 'separator' => ' '));
    }


    /**
     * Builds the DQL of UPDATE
     */
    protected function _getDqlForUpdate()
    {
        /*
         * BNF:
         *
         * UpdateStatement = UpdateClause [WhereClause] [OrderByClause] [LimitClause] [OffsetClause]
         * UpdateClause    = "UPDATE" RangeVariableDeclaration "SET" UpdateItem {"," UpdateItem}
         * WhereClause     = "WHERE" ConditionalExpression
         * OrderByClause   = "ORDER" "BY" OrderByItem {"," OrderByItem}
         * LimitClause     = "LIMIT" integer
         * OffsetClause    = "OFFSET" integer
         *
         */
         return 'UPDATE'
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' FROM ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' SET ', 'separator' => ', '))
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('orderby', array('pre' => ' ORDER BY ', 'separator' => ', '))
              . $this->_getReducedDqlQueryPart('limit', array('pre' => ' LIMIT ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('offset', array('pre' => ' OFFSET ', 'separator' => ' '));
    }


    /**
     * Builds the DQL of SELECT
     */
    protected function _getDqlForSelect()
    {
        /*
         * BNF:
         *
         * SelectStatement = [SelectClause] FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause] [LimitClause] [OffsetClause]
         * SelectClause    = "SELECT" ["ALL" | "DISTINCT"] SelectExpression {"," SelectExpression}
         * FromClause      = "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}
         * WhereClause     = "WHERE" ConditionalExpression
         * GroupByClause   = "GROUP" "BY" GroupByItem {"," GroupByItem}
         * HavingClause    = "HAVING" ConditionalExpression
         * OrderByClause   = "ORDER" "BY" OrderByItem {"," OrderByItem}
         * LimitClause     = "LIMIT" integer
         * OffsetClause    = "OFFSET" integer
         *
         */
         /**
          * @todo [TODO] What about "ALL" support?
          */
         return 'SELECT'
              . (($this->getDqlQueryPart('distinct') === true) ? ' DISTINCT' : '')
              . $this->_getReducedDqlQueryPart('select', array('pre' => ' ', 'separator' => ', ', 'empty' => ' *'))
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' FROM ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('groupby', array('pre' => ' GROUP BY ', 'separator' => ', '))
              . $this->_getReducedDqlQueryPart('having', array('pre' => ' HAVING ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('orderby', array('pre' => ' ORDER BY ', 'separator' => ', '))
              . $this->_getReducedDqlQueryPart('limit', array('pre' => ' LIMIT ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('offset', array('pre' => ' OFFSET ', 'separator' => ' '));
    }


    /**
     * @nodoc
     */
    protected function _getReducedDqlQueryPart($queryPartName, $options = array())
    {
        if (empty($this->_dqlParts[$queryPartName])) {
            return (isset($options['empty']) ? $options['empty'] : '');
        }

        $str  = (isset($options['pre']) ? $options['pre'] : '');
        $str .= implode($options['separator'], $this->getDqlQueryPart($queryPartName));
        $str .= (isset($options['post']) ? $options['post'] : '');

        return $str;
    }

    /**
     * Returns the type of this query object
     * By default the type is Doctrine_ORM_Query_Abstract::SELECT but if update() or delete()
     * are being called the type is Doctrine_ORM_Query_Abstract::UPDATE and Doctrine_ORM_Query_Abstract::DELETE,
     * respectively.
     *
     * @see Doctrine_ORM_Query_Abstract::SELECT
     * @see Doctrine_ORM_Query_Abstract::UPDATE
     * @see Doctrine_ORM_Query_Abstract::DELETE
     *
     * @return integer Return the query type
     */
    public function getType()
    {
        return $this->_type;
    }


    /**
     * Returns the state of this query object
     * By default the type is Doctrine_ORM_Query_Abstract::STATE_CLEAN but if it appears any unprocessed DQL
     * part, it is switched to Doctrine_ORM_Query_Abstract::STATE_DIRTY.
     *
     * @see Doctrine_ORM_Query_Abstract::STATE_CLEAN
     * @see Doctrine_ORM_Query_Abstract::STATE_DIRTY
     *
     * @return integer Return the query state
     */
    public function getState()
    {
        return $this->_state;
    }


    /**
     * Adds fields to the SELECT part of the query
     *
     * @param string $select Query SELECT part
     * @return Doctrine_ORM_Query
     */
    public function select($select = '', $override = false)
    {
        if ($select === '') {
            return $this;
        }

        return $this->_addDqlQueryPart('select', $select, ! $override);
    }


    /**
     * Makes the query SELECT DISTINCT.
     *
     * @param bool $flag Whether or not the SELECT is DISTINCT (default true).
     * @return Doctrine_ORM_Query
     */
    public function distinct($flag = true)
    {
        $this->_dqlParts['distinct'] = (bool) $flag;
        return $this;
    }


    /**
     * Makes the query SELECT FOR UPDATE.
     *
     * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
     * @return Doctrine_ORM_Query
     *
     * @todo [TODO] What about "forUpdate" support? Remove it?
     */
    public function forUpdate($flag = true)
    {
        return $this->_addDqlQueryPart('forUpdate', (bool) $flag);
    }


    /**
     * Sets the query type to DELETE
     *
     * @return Doctrine_ORM_Query
     */
    public function delete()
    {
        $this->_type = self::DELETE;
        return $this;
    }


    /**
     * Sets the UPDATE part of the query
     *
     * @param string $update Query UPDATE part
     * @return Doctrine_ORM_Query
     */
    public function update($update)
    {
        $this->_type = self::UPDATE;
        return $this->_addDqlQueryPart('from', $update);
    }


    /**
     * Sets the SET part of the query
     *
     * @param mixed $key UPDATE keys. Accepts either a string (requiring then $value or $params to be defined)
     *                   or an array of $key => $value pairs.
     * @param string $value UPDATE key value. Optional argument, but required if $key is a string.
     * @return Doctrine_ORM_Query
     */
    public function set($key, $value = null, $params = null)
    {
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                $this->set($k, '?', array($v));
            }

            return $this;
        } else {
            if ($params !== null) {
                if (is_array($params)) {
                    $this->_params['set'] = array_merge($this->_params['set'], $params);
                } else {
                    $this->_params['set'][] = $params;
                }
            }

            if ($value === null) {
466
                throw \Doctrine\Common\DoctrineException::updateMe( 'Cannot try to set \''.$key.'\' without a value.' );
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
            }

            return $this->_addDqlQueryPart('set', $key . ' = ' . $value, true);
        }
    }

    /**
     * Adds fields to the FROM part of the query
     *
     * @param string $from Query FROM part
     * @return Doctrine_ORM_Query
     */
    public function from($from, $override = false)
    {
        return $this->_addDqlQueryPart('from', $from, ! $override);
    }


    /**
     * Appends an INNER JOIN to the FROM part of the query
     *
     * @param string $join Query INNER JOIN
     * @param mixed $params Optional JOIN params (array of parameters or a simple scalar)
     * @return Doctrine_ORM_Query
     */
    public function innerJoin($join, $params = array())
    {
        if (is_array($params)) {
            $this->_params['join'] = array_merge($this->_params['join'], $params);
        } else {
            $this->_params['join'][] = $params;
        }

        return $this->_addDqlQueryPart('from', 'INNER JOIN ' . $join, true);
    }


    /**
     * Appends an INNER JOIN to the FROM part of the query
     *
     * @param string $join Query INNER JOIN
     * @param mixed $params Optional JOIN params (array of parameters or a simple scalar)
     * @return Doctrine_ORM_Query
     */
    public function join($join, $params = array())
    {
        return $this->innerJoin($join, $params);
    }


    /**
     * Appends a LEFT JOIN to the FROM part of the query
     *
     * @param string $join Query LEFT JOIN
     * @param mixed $params Optional JOIN params (array of parameters or a simple scalar)
     * @return Doctrine_ORM_Query
     */
    public function leftJoin($join, $params = array())
    {
        if (is_array($params)) {
            $this->_params['join'] = array_merge($this->_params['join'], $params);
        } else {
            $this->_params['join'][] = $params;
        }

        return $this->_addDqlQueryPart('from', 'LEFT JOIN ' . $join, true);
    }


    /**
     * Adds conditions to the WHERE part of the query
     *
     * @param string $where Query WHERE part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function where($where, $params = array(), $override = false)
    {
        if ($override) {
            $this->_params['where'] = array();
        }

        if (is_array($params)) {
            $this->_params['where'] = array_merge($this->_params['where'], $params);
        } else {
            $this->_params['where'][] = $params;
        }

        return $this->_addDqlQueryPart('where', $where, ! $override);
    }


    /**
     * Adds conditions to the WHERE part of the query
     *
     * @param string $where Query WHERE part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function andWhere($where, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'AND', true);
        }

        return $this->where($where, $params, $override);
    }


    /**
     * Adds conditions to the WHERE part of the query
     *
     * @param string $where Query WHERE part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function orWhere($where, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'OR', true);
        }

        return $this->where($where, $params, $override);
    }


    /**
     * Adds IN condition to the query WHERE part
     *
     * @param string $expr The operand of the IN
     * @param mixed $params An array of parameters or a simple scalar
     * @param boolean $not Whether or not to use NOT in front of IN
     * @return Doctrine_ORM_Query
     */
    public function whereIn($expr, $params = array(), $override = false, $not = false)
    {
        $params = (array) $params;

        // Must have at least one param, otherwise we'll get an empty IN () => invalid SQL
        if ( ! count($params)) {
            return $this;
        }

        list($sqlPart, $params) = $this->_processWhereInParams($params);

        $where = $expr . ($not === true ? ' NOT' : '') . ' IN (' . $sqlPart . ')';

        return $this->_returnWhereIn($where, $params, $override);
    }


    /**
     * Adds NOT IN condition to the query WHERE part
     *
     * @param string $expr The operand of the NOT IN
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function whereNotIn($expr, $params = array(), $override = false)
    {
        return $this->whereIn($expr, $params, $override, true);
    }


    /**
     * Adds IN condition to the query WHERE part
     *
     * @param string $expr The operand of the IN
     * @param mixed $params An array of parameters or a simple scalar
     * @param boolean $not Whether or not to use NOT in front of IN
     * @return Doctrine_ORM_Query
     */
    public function andWhereIn($expr, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'AND', true);
        }

        return $this->whereIn($expr, $params, $override);
    }


    /**
     * Adds NOT IN condition to the query WHERE part
     *
     * @param string $expr The operand of the NOT IN
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function andWhereNotIn($expr, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'AND', true);
        }

        return $this->whereIn($expr, $params, $override, true);
    }


    /**
     * Adds IN condition to the query WHERE part
     *
     * @param string $expr The operand of the IN
     * @param mixed $params An array of parameters or a simple scalar
     * @param boolean $not Whether or not to use NOT in front of IN
     * @return Doctrine_ORM_Query
     */
    public function orWhereIn($expr, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'OR', true);
        }

        return $this->whereIn($expr, $params, $override);
    }


    /**
     * Adds NOT IN condition to the query WHERE part
     *
     * @param string $expr The operand of the NOT IN
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function orWhereNotIn($expr, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('where')) > 0) {
            $this->_addDqlQueryPart('where', 'OR', true);
        }

        return $this->whereIn($expr, $params, $override, true);
    }


    /**
     * Adds fields to the GROUP BY part of the query
     *
     * @param string $groupby Query GROUP BY part
     * @return Doctrine_ORM_Query
     */
    public function groupBy($groupby, $override = false)
    {
        return $this->_addDqlQueryPart('groupby', $groupby, ! $override);
    }


    /**
     * Adds conditions to the HAVING part of the query
     *
     * @param string $having Query HAVING part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function having($having, $params = array(), $override = false)
    {
        if ($override) {
            $this->_params['having'] = array();
        }

        if (is_array($params)) {
            $this->_params['having'] = array_merge($this->_params['having'], $params);
        } else {
            $this->_params['having'][] = $params;
        }

        return $this->_addDqlQueryPart('having', $having, true);
    }


    /**
     * Adds conditions to the HAVING part of the query
     *
     * @param string $having Query HAVING part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function andHaving($having, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('having')) > 0) {
            $this->_addDqlQueryPart('having', 'AND', true);
        }

        return $this->having($having, $params, $override);
    }


    /**
     * Adds conditions to the HAVING part of the query
     *
     * @param string $having Query HAVING part
     * @param mixed $params An array of parameters or a simple scalar
     * @return Doctrine_ORM_Query
     */
    public function orHaving($having, $params = array(), $override = false)
    {
        if (count($this->getDqlQueryPart('having')) > 0) {
            $this->_addDqlQueryPart('having', 'OR', true);
        }

        return $this->having($having, $params, $override);
    }


    /**
     * Adds fields to the ORDER BY part of the query
     *
     * @param string $orderby Query ORDER BY part
     * @return Doctrine_ORM_Query
     */
    public function orderBy($orderby, $override = false)
    {
        return $this->_addDqlQueryPart('orderby', $orderby, ! $override);
    }


    /**
     * Sets the Query query limit
     *
     * @param integer $limit Limit to be used for limiting the query results
     * @return Doctrine_ORM_Query
     */
    public function limit($limit)
    {
        return $this->_addDqlQueryPart('limit', $limit);
    }


    /**
     * Sets the Query query offset
     *
     * @param integer $offset Offset to be used for paginating the query
     * @return Doctrine_ORM_Query
     */
    public function offset($offset)
    {
        return $this->_addDqlQueryPart('offset', $offset);
    }


    /**
     * Set enumerated parameters
     *
     * @param array $enumParams Enum parameters.
     */
    protected function _setEnumParams($enumParams = array())
    {
        $this->_enumParams = $enumParams;
    }


    /**
     * Get all enumerated parameters
     *
     * @return array All enumerated parameters
     */
    public function getEnumParams()
    {
        return $this->_enumParams;
    }


    /**
     * Convert ENUM parameters to their integer equivalents
     *
     * @param $params Parameters to be converted
     * @return array Converted parameters array
     */
    public function convertEnums($params)
    {
        foreach ($this->_enumParams as $key => $values) {
            if (isset($params[$key]) && ! empty($values)) {
                $params[$key] = $values[0]->enumIndex($values[1], $params[$key]);
            }
        }

        return $params;
    }


    /**
     * Get all defined parameters
     *
     * @return array Defined parameters
     */
    public function getParams($params = array())
    {
        return array_merge(
            $this->_params['join'],
            $this->_params['set'],
            $this->_params['where'],
            $this->_params['having'],
            $params
        );
    }


    /**
     * setParams
     *
     * @param array $params
     */
    public function setParams(array $params = array()) {
        $this->_params = $params;
    }


    /**
     * Method to check if a arbitrary piece of DQL exists
     *
     * @param string $dql Arbitrary piece of DQL to check for
     * @return boolean
     */
    public function contains($dql)
    {
      return stripos($this->getDql(), $dql) === false ? false : true;
    }


    /**
     * Retrieve a DQL part for internal purposes
     *
     * @param string $queryPartName  The name of the query part.
     * @return mixed Array related to query part or simple scalar
     */
    public function getDqlQueryPart($queryPartName)
    {
        if ( ! isset($this->_dqlParts[$queryPartName])) {
894
            throw \Doctrine\Common\DoctrineException::updateMe('Unknown DQL query part \'' . $queryPartName . '\'');
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
        }

        return $this->_dqlParts[$queryPartName];
    }


    /**
     * Adds a DQL part to the internal parts collection.
     *
     * @param string $queryPartName  The name of the query part.
     * @param string $queryPart      The actual query part to add.
     * @param boolean $append        Whether to append $queryPart to already existing
     *                               parts under the same $queryPartName. Defaults to FALSE
     *                               (previously added parts with the same name get overridden).
     * @return Doctrine_ORM_Query
     */
    protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false)
    {
        if ($append) {
            $this->_dqlParts[$queryPartName][] = $queryPart;
        } else {
            $this->_dqlParts[$queryPartName] = array($queryPart);
        }

        $this->_state = Doctrine_ORM_Query::STATE_DIRTY;
        return $this;
    }


    /**
     * Processes the WHERE IN () parameters and return an indexed array containing
     * the sqlPart to be placed in SQL statement and the new parameters (that will be
     * bound in SQL execution)
     *
     * @param array $params Parameters to be processed
     * @return array
     */
    protected function _processWhereInParams($params = array())
    {
        return array(
            // [0] => sqlPart
            implode(', ', array_map(array(&$this, '_processWhereInSqlPart'), $params)),
            // [1] => params
            array_filter($params, array(&$this, '_processWhereInParamItem')),
        );
    }


    /**
     * @nodoc
     */
    protected function _processWhereInSqlPart($value)
    {
        // [TODO] Add support to imbricated query (must deliver the hardest effort to Parser)
        return  ($value instanceof Doctrine_Expression) ? $value->getSql() : '?';
    }


    /**
     * @nodoc
     */
    protected function _processWhereInParamItem($value)
    {
        // [TODO] Add support to imbricated query (must deliver the hardest effort to Parser)
        return ( ! ($value instanceof Doctrine_Expression));
    }


    /**
     * Processes a WHERE IN () and build defined stuff to add in DQL
     *
     * @param string $where The WHERE clause to be added
     * @param array $params WHERE clause parameters
     * @param mixed $appender Where this clause may be not be appended, or appended 
     *                        (two possible values: AND or OR)
     * @return Doctrine_ORM_Query
     */
    protected function _returnWhereIn($where, $params = array(), $override = false)
    {
        // Parameters inclusion
        $this->_params['where'] = $override ? $params : array_merge($this->_params['where'], $params);

        // WHERE clause definition
        return $this->_addDqlQueryPart('where', $where, ! $override);
    }


    /**
     * Gets the SQL query that corresponds to this query object.
     * The returned SQL syntax depends on the connection driver that is used
     * by this query object at the time of this method call.
     *
     * @return string SQL query
     */
    abstract public function getSql();
    
    /**
     * Sets a query parameter.
     *
     * @param string|integer $key
     * @param mixed $value
     */
    public function setParameter($key, $value)
    {
        $this->_params[$key] = $value;
    }
    
    /**
     * Sets a collection of query parameters.
     *
     * @param array $params
     */
    public function setParameters(array $params)
    {
        foreach ($params as $key => $value) {
            $this->setParameter($key, $value);
        }
    }

}