QueryBuilder.php 24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?php
/*
 *  $Id$
 *
 * 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
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM;

24
use Doctrine\ORM\Query\Expr;
25 26

/**
27 28
 * This class is responsible for building DQL query strings via an object oriented
 * PHP interface.
29
 *
30 31 32 33 34 35 36
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
37 38 39 40 41 42 43 44 45 46
 */
class QueryBuilder
{
    const SELECT = 0;
    const DELETE = 1;
    const UPDATE = 2;

    const STATE_DIRTY = 0;
    const STATE_CLEAN = 1;

47
    /**
48
     * @var EntityManager $em The EntityManager used by this QueryBuilder.
49
     */
50
    private $_em;
51 52

    /**
53
     * @var array $dqlParts The array of DQL parts collected.
54
     */
55
    private $_dqlParts = array(
56
        'select'  => array(),
jwage's avatar
jwage committed
57
        'from'    => array(),
58 59 60
        'join'    => array(),
        'set'     => array(),
        'where'   => null,
61
        'groupBy' => array(),
62
        'having'  => null,
63
        'orderBy' => array()
64
    );
65 66

    /**
67
     * @var integer The type of query this is. Can be select, update or delete.
68
     */
69
    private $_type = self::SELECT;
70 71

    /**
72
     * @var integer The state of the query object. Can be dirty or clean.
73
     */
74
    private $_state = self::STATE_CLEAN;
75 76

    /**
77
     * @var string The complete DQL string for this query.
78
     */
79
    private $_dql;
80
    
81
    /**
82
     * @var array The query parameters.
83
     */
84 85
    private $_params = array();
    
86
    /**
87
     * @var integer The index of the first result to retrieve.
88
     */
89 90 91 92 93 94
    private $_firstResult = null;
    
    /**
     * @var integer The maximum number of results to retrieve.
     */
    private $_maxResults = null;
95

96 97 98
    /**
     * Initializes a new <tt>QueryBuilder</tt> that uses the given <tt>EntityManager</tt>.
     * 
99
     * @param EntityManager $em The EntityManager to use.
100
     */
101
    public function __construct(EntityManager $em)
102
    {
103
        $this->_em = $em;
104 105
    }

106
    /**
107 108
     * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
     * Intended for convenient inline usage. Example:
109
     *
110 111 112 113 114 115
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where($qb->expr()->eq('u.id', 1));
     *
116
     * @return ExpressionBuilder
117 118 119
     */
    public function expr()
    {
120
        return $this->_em->getExpressionBuilder();
121 122
    }

123
    /**
124
     * Get the type of the currently built query.
125
     *
126
     * @return integer
127
     */
128 129 130 131 132
    public function getType()
    {
        return $this->_type;
    }

133
    /**
134
     * Get the associated EntityManager for this query builder.
135
     *
136
     * @return EntityManager
137
     */
138 139 140 141 142
    public function getEntityManager()
    {
        return $this->_em;
    }

143 144 145 146 147 148 149 150 151 152
    /**
     * Get the state of this query builder instance
     *
     *     [php]
     *     if ($qb->getState() == QueryBuilder::STATE_DIRTY) {
     *         echo 'Query builder is dirty';
     *     } else {
     *         echo 'Query builder is clean';
     *     }
     *
153
     * @return integer
154
     */
155 156 157 158 159
    public function getState()
    {
        return $this->_state;
    }

160 161 162 163 164 165 166 167 168
    /**
     * Get the complete DQL string for this query builder instance
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *     echo $qb->getDql(); // SELECT u FROM User u
     *
169
     * @return string The DQL string
170
     */
171 172
    public function getDql()
    {
173
        if ($this->_dql !== null && $this->_state === self::STATE_CLEAN) {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            return $this->_dql;
        }

        $dql = '';

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

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

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

194
        $this->_state = self::STATE_CLEAN;
195 196 197 198 199
        $this->_dql = $dql;

        return $dql;
    }

200
    /**
201
     * Constructs a Query instance from the current configuration of the builder.
202 203 204 205 206 207 208 209
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u');
     *     $q = $qb->getQuery();
     *     $results = $q->execute();
     *
210
     * @return Query
211
     */
212 213
    public function getQuery()
    {
214 215 216 217
        return $this->_em->createQuery($this->getDql())
                ->setParameters($this->_params)
                ->setFirstResult($this->_firstResult)
                ->setMaxResults($this->_maxResults);
218 219
    }

jwage's avatar
jwage committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    /**
     * Get the root alias for the query. This is the first entity alias involved
     * in the construction of the query
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u');
     *
     *     echo $qb->getRootAlias(); // u
     *
     * @return string $rootAlias
     */
    public function getRootAlias()
    {
        return $this->_dqlParts['from'][0]->getAlias();
    }

238 239 240
    /**
     * Sets a query parameter.
     *
241 242 243 244 245 246 247
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where('u.id = :user_id')
     *         ->setParameter(':user_id', 1);
     *
248 249
     * @param string|integer $key The parameter position or name.
     * @param mixed $value The parameter value.
250
     * @return QueryBuilder This QueryBuilder instance.
251 252 253
     */
    public function setParameter($key, $value)
    {
254
        $this->_params[$key] = $value;
255 256 257 258 259 260
        return $this;
    }
    
    /**
     * Sets a collection of query parameters.
     *
261 262 263 264 265 266 267 268 269 270
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where('u.id = :user_id1 OR u.id = :user_id2')
     *         ->setParameters(array(
     *             ':user_id1' => 1,
     *             ':user_id2' => 2
     *         ));
     *
271
     * @param array $params
272
     * @return QueryBuilder This QueryBuilder instance.
273 274 275
     */
    public function setParameters(array $params)
    {
276
        $this->_params = $params;
277 278 279 280 281 282 283 284 285 286
        return $this;
    }

    /**
     * Get all defined parameters
     *
     * @return array Defined parameters
     */
    public function getParameters($params = array())
    {
287
        return $this->_params;
288 289 290 291 292 293 294 295 296 297
    }
    
    /**
     * Gets a query parameter.
     * 
     * @param mixed $key The key (index or name) of the bound parameter.
     * @return mixed The value of the bound parameter.
     */
    public function getParameter($key)
    {
298
        return isset($this->_params[$key]) ? $this->_params[$key] : null;
299
    }
300 301 302 303 304
    
    /**
     * Sets the position of the first result to retrieve (the "offset").
     *
     * @param integer $firstResult The first result to return.
305
     * @return QueryBuilder This QueryBuilder instance.
306 307 308
     */
    public function setFirstResult($firstResult)
    {
309
        $this->_firstResult = $firstResult;
310 311 312 313 314 315 316 317 318 319 320
        return $this;
    }
    
    /**
     * Gets the position of the first result the query object was set to retrieve (the "offset").
     * Returns NULL if {@link setFirstResult} was not applied to this query builder.
     * 
     * @return integer The position of the first result.
     */
    public function getFirstResult()
    {
321
        return $this->_firstResult;
322 323 324 325 326 327
    }
    
    /**
     * Sets the maximum number of results to retrieve (the "limit").
     * 
     * @param integer $maxResults
328
     * @return QueryBuilder This QueryBuilder instance.
329 330 331
     */
    public function setMaxResults($maxResults)
    {
332
        $this->_maxResults = $maxResults;
333 334 335 336 337 338 339 340 341 342 343
        return $this;
    }
    
    /**
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
     * Returns NULL if {@link setMaxResults} was not applied to this query builder.
     * 
     * @return integer Maximum number of results.
     */
    public function getMaxResults()
    {
344
        return $this->_maxResults;
345
    }
346 347 348 349 350 351 352

    /**
     * Add a single DQL query part to the array of parts
     *
     * @param string $dqlPartName 
     * @param string $dqlPart 
     * @param string $append 
353
     * @return QueryBuilder This QueryBuilder instance.
354 355 356
     */
    public function add($dqlPartName, $dqlPart, $append = false)
    {
357 358 359
        $isMultiple = is_array($this->_dqlParts[$dqlPartName]);
    
        if ($append && $isMultiple) {
360 361
            $this->_dqlParts[$dqlPartName][] = $dqlPart;
        } else {
362
            $this->_dqlParts[$dqlPartName] = ($isMultiple) ? array($dqlPart) : $dqlPart;
363 364 365 366 367 368 369
        }

        $this->_state = self::STATE_DIRTY;

        return $this;
    }

370
    /**
jwage's avatar
jwage committed
371
     * Set the SELECT statement
372 373 374 375 376 377 378 379
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u', 'p')
     *         ->from('User', 'u')
     *         ->leftJoin('u.Phonenumbers', 'p');
     *
     * @param mixed $select  String SELECT statement or SELECT Expr instance
380
     * @return QueryBuilder This QueryBuilder instance.
381
     */
382
    public function select($select = null)
383 384
    {
        $this->_type = self::SELECT;
385 386
        
        if (empty($select)) {
387 388
            return $this;
        }
389
        
390 391
        $selects = is_array($select) ? $select : func_get_args();

jwage's avatar
jwage committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405
        return $this->add('select', new Expr\Select($selects), false);
    }

    /**
     * Add to the SELECT statement
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->addSelect('p')
     *         ->from('User', 'u')
     *         ->leftJoin('u.Phonenumbers', 'p');
     *
     * @param mixed $select  String SELECT statement or SELECT Expr instance
406
     * @return QueryBuilder This QueryBuilder instance.
jwage's avatar
jwage committed
407 408 409 410
     */
    public function addSelect($select = null)
    {
        $this->_type = self::SELECT;
411 412 413
        
        if (empty($select)) {
            return $this;
jwage's avatar
jwage committed
414
        }
415 416
        
        $selects = is_array($select) ? $select : func_get_args();
jwage's avatar
jwage committed
417

418
        return $this->add('select', new Expr\Select($selects), true);
419 420
    }

421 422 423 424 425 426 427 428 429 430 431
    /**
     * Construct a DQL DELETE query
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->delete('User', 'u')
     *         ->where('u.id = :user_id');
     *         ->setParameter(':user_id', 1);
     *
     * @param string $delete    The model to delete 
     * @param string $alias     The alias of the model
432
     * @return QueryBuilder This QueryBuilder instance.
433
     */
434 435 436 437 438 439 440 441
    public function delete($delete = null, $alias = null)
    {
        $this->_type = self::DELETE;

        if ( ! $delete) {
            return $this;
        }

442
        return $this->add('from', new Expr\From($delete, $alias));
443 444
    }

445 446 447 448 449 450 451 452 453 454 455
    /**
     * Construct a DQL UPDATE query
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->update('User', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where('u.id = ?');
     *
     * @param string $update   The model to update
     * @param string $alias    The alias of the model
456
     * @return QueryBuilder This QueryBuilder instance.
457
     */
458 459 460 461 462 463 464 465
    public function update($update = null, $alias = null)
    {
        $this->_type = self::UPDATE;

        if ( ! $update) {
            return $this;
        }

466
        return $this->add('from', new Expr\From($update, $alias));
467 468
    }

469 470 471 472 473 474 475 476
    /**
     * Specify the FROM part when constructing a SELECT DQL query
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *
477 478 479
     * @param string $from   The class name.
     * @param string $alias  The alias of the class.
     * @return QueryBuilder This QueryBuilder instance.
480
     */
481
    public function from($from, $alias)
482
    {
jwage's avatar
jwage committed
483
        return $this->add('from', new Expr\From($from, $alias), true);
484
    }
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    
    /**
     * Add a INNER JOIN to an associated class.
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     *
     * @param string $join           The relationship to join
     * @param string $alias          The alias of the join
     * @param string $conditionType  The condition type constant. Either ON or WITH.
     * @param string $condition      The condition for the join
     * @return QueryBuilder This QueryBuilder instance.
     */
    public function join($join, $alias, $conditionType = null, $condition = null)
    {
        return $this->innerJoin($join, $alias, $conditionType, $condition);
    }
505 506

    /**
507
     * Add an INNER JOIN to an associated class.
508 509 510 511 512 513 514 515 516 517 518
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     *
     * @param string $join           The relationship to join
     * @param string $alias          The alias of the join
     * @param string $conditionType  The condition type constant. Either ON or WITH.
     * @param string $condition      The condition for the join
519
     * @return QueryBuilder This QueryBuilder instance.
520
     */
521
    public function innerJoin($join, $alias, $conditionType = null, $condition = null)
522
    {
523 524 525
        return $this->add('join', new Expr\Join(
            Expr\Join::INNER_JOIN, $join, $alias, $conditionType, $condition
        ), true);
526 527
    }

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    /**
     * Add a LEFT JOIN
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->leftJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     *
     * @param string $join           The relationship to join
     * @param string $alias          The alias of the join
     * @param string $conditionType  The condition type constant. Either ON or WITH.
     * @param string $condition      The condition for the join
     * @return QueryBuilder $qb
     */
543
    public function leftJoin($join, $alias, $conditionType = null, $condition = null)
544
    {
545 546 547 548 549
        return $this->add('join', new Expr\Join(
            Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition
        ), true);
    }

550 551 552 553 554 555 556 557 558 559 560 561 562
    /**
     * Add a SET statement for a DQL UPDATE query
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->update('User', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where('u.id = ?');
     *
     * @param string $key     The key/field to set
     * @param string $value   The value, expression, placeholder, etc. to use in the SET
     * @return QueryBuilder $qb
     */
563 564 565
    public function set($key, $value)
    {
        return $this->add('set', new Expr\Comparison($key, Expr\Comparison::EQ, $value), true);
566 567
    }

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    /**
     * Set and override any existing WHERE statements
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where('u.id = ?');
     *
     *     // You can optionally programatically build and/or expressions
     *     $qb = $em->createQueryBuilder();
     *
     *     $or = $qb->expr()->orx();
     *     $or->add($qb->expr()->eq('u.id', 1));
     *     $or->add($qb->expr()->eq('u.id', 2));
     *
     *     $qb->update('User', 'u')
     *         ->set('u.password', md5('password'))
     *         ->where($or);
     *
romanb's avatar
romanb committed
588 589
     * @param mixed $predicates The predicates.
     * @return QueryBuilder
590
     */
romanb's avatar
romanb committed
591
    public function where($predicates)
592
    {
romanb's avatar
romanb committed
593 594
        if ( ! (func_num_args() == 1 && ($predicates instanceof Expr\Andx || $predicates instanceof Expr\Orx))) {
            $predicates = new Expr\Andx(func_get_args());
595 596
        }
        
romanb's avatar
romanb committed
597
        return $this->add('where', $predicates);
598 599
    }

600 601 602 603 604 605 606 607 608 609 610 611 612 613
    /**
     * Add a new WHERE statement with an AND
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where('u.username LIKE ?')
     *         ->andWhere('u.is_active = 1');
     *
     * @param mixed $where The WHERE statement
     * @return QueryBuilder $qb
     * @see where()
     */
614 615
    public function andWhere($where)
    {
jwage's avatar
jwage committed
616
        $where = $this->getDqlPart('where');
617 618 619 620 621 622 623
        $args = func_get_args();
        
        if ($where instanceof Expr\Andx) {
            $where->addMultiple($args);
        } else { 
            array_unshift($args, $where);
            $where = new Expr\Andx($args);
624
        }
625
        
626
        return $this->add('where', $where, true);
627 628
    }

629 630 631 632 633 634 635 636 637 638 639 640 641 642
    /**
     * Add a new WHERE statement with an OR
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->where('u.id = 1')
     *         ->orWhere('u.id = 2');
     *
     * @param mixed $where The WHERE statement
     * @return QueryBuilder $qb
     * @see where()
     */
643 644
    public function orWhere($where)
    {
jwage's avatar
jwage committed
645
        $where = $this->getDqlPart('where');
646 647 648 649 650 651 652
        $args = func_get_args();
        
        if ($where instanceof Expr\Orx) {
            $where->addMultiple($args);
        } else {            
            array_unshift($args, $where);
            $where = new Expr\Orx($args);
653
        }
654
        
655
        return $this->add('where', $where, true);
656 657
    }

658 659 660 661 662 663 664 665 666 667 668 669
    /**
     * Set the GROUP BY clause
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->groupBy('u.id');
     *
     * @param string $groupBy  The GROUP BY clause
     * @return QueryBuilder $qb
     */
670 671
    public function groupBy($groupBy)
    {
672
        return $this->add('groupBy', new Expr\GroupBy(func_get_args()));
673 674
    }

675 676 677 678 679 680 681 682 683 684 685 686 687 688

    /**
     * Add to the existing GROUP BY clause
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->groupBy('u.last_login');
     *         ->addGroupBy('u.created_at')
     *
     * @param string $groupBy  The GROUP BY clause
     * @return QueryBuilder $qb
     */
689 690
    public function addGroupBy($groupBy)
    {
691
        return $this->add('groupBy', new Expr\GroupBy(func_get_args()), true);
692 693
    }

694 695 696 697 698 699
    /**
     * Set the HAVING clause
     *
     * @param mixed $having 
     * @return QueryBuilder $qb
     */
700 701
    public function having($having)
    {
702 703 704 705 706
        if ( ! (func_num_args() == 1 && ($having instanceof Expr\Andx || $having instanceof Expr\Orx))) {
            $having = new Expr\Andx(func_get_args());
        }
        
        return $this->add('having', $having);
707 708
    }

709 710 711 712 713 714
    /**
     * Add to the existing HAVING clause with an AND
     *
     * @param mixed $having 
     * @return QueryBuilder $qb
     */
715 716
    public function andHaving($having)
    {
jwage's avatar
jwage committed
717
        $having = $this->getDqlPart('having');
718 719 720 721 722 723 724
        $args = func_get_args();
        
        if ($having instanceof Expr\Andx) {
            $having->addMultiple($args);
        } else { 
            array_unshift($args, $having);
            $having = new Expr\Andx($args);
725
        }
726 727
        
        return $this->add('having', $having);
728 729
    }

730 731 732 733 734 735
    /**
     * Add to the existing HAVING clause with an OR
     *
     * @param mixed $having 
     * @return QueryBuilder $qb
     */
736 737
    public function orHaving($having)
    {
jwage's avatar
jwage committed
738
        $having = $this->getDqlPart('having');
739 740 741 742 743 744 745
        $args = func_get_args();
        
        if ($having instanceof Expr\Orx) {
            $having->addMultiple($args);
        } else { 
            array_unshift($args, $having);
            $having = new Expr\Orx($args);
746
        }
747 748
        
        return $this->add('having', $having);
749 750
    }

751 752 753 754 755 756 757
    /**
     * Set the ORDER BY clause
     *
     * @param string $sort    What to sort on
     * @param string $order   Optional: The order to sort the results.
     * @return QueryBuilder $qb
     */
758
    public function orderBy($sort, $order = null)
759
    {
760 761
        return $this->add('orderBy',  $sort instanceof Expr\OrderBy ? $sort
                : new Expr\OrderBy($sort, $order));
762 763
    }

764 765 766 767 768 769 770
    /**
     * Add to the existing ORDER BY clause
     *
     * @param string $sort    What to sort on
     * @param string $order   Optional: The order to sort the results.
     * @return QueryBuilder $qb
     */
771
    public function addOrderBy($sort, $order = null)
772
    {
773
        return $this->add('orderBy', new Expr\OrderBy($sort, $order), true);
774 775
    }

jwage's avatar
jwage committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    /**
     * Get a DQL part or parts by the part name
     *
     * @param string $queryPartName
     * @return mixed $queryPart
     */
    public function getDqlPart($queryPartName)
    {
        return $this->_dqlParts[$queryPartName];
    }

    /**
     * Get the full DQL parts array
     *
     * @return array $dqlParts
     */
    public function getDqlParts()
    {
        return $this->_dqlParts;
    }

797 798 799
    private function _getDqlForDelete()
    {
         return 'DELETE'
jwage's avatar
jwage committed
800
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' ', 'separator' => ', '))
801
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE '))
802
              . $this->_getReducedDqlQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
803 804 805 806 807
    }

    private function _getDqlForUpdate()
    {
         return 'UPDATE'
jwage's avatar
jwage committed
808
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' ', 'separator' => ', '))
809
              . $this->_getReducedDqlQueryPart('set', array('pre' => ' SET ', 'separator' => ', '))
810
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE '))
811
              . $this->_getReducedDqlQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
812 813 814 815
    }

    private function _getDqlForSelect()
    {
816
         return 'SELECT' 
817
              . $this->_getReducedDqlQueryPart('select', array('pre' => ' ', 'separator' => ', '))
jwage's avatar
jwage committed
818
              . $this->_getReducedDqlQueryPart('from', array('pre' => ' FROM ', 'separator' => ', '))
819 820
              . $this->_getReducedDqlQueryPart('join', array('pre' => ' ', 'separator' => ' '))
              . $this->_getReducedDqlQueryPart('where', array('pre' => ' WHERE '))
821
              . $this->_getReducedDqlQueryPart('groupBy', array('pre' => ' GROUP BY ', 'separator' => ', '))
822
              . $this->_getReducedDqlQueryPart('having', array('pre' => ' HAVING '))
823
              . $this->_getReducedDqlQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', '));
824 825 826 827
    }

    private function _getReducedDqlQueryPart($queryPartName, $options = array())
    {
jwage's avatar
jwage committed
828
        $queryPart = $this->getDqlPart($queryPartName);
829 830
        
        if (empty($queryPart)) {
831 832
            return (isset($options['empty']) ? $options['empty'] : '');
        }
833 834 835 836
        
        return (isset($options['pre']) ? $options['pre'] : '')
             . (is_array($queryPart) ? implode($options['separator'], $queryPart) : $queryPart)
             . (isset($options['post']) ? $options['post'] : '');
837 838
    }

839 840 841 842
    public function __toString()
    {
        return $this->getDql();
    }
jwage's avatar
jwage committed
843

844
    /*public function __clone()
jwage's avatar
jwage committed
845 846
    {
        $this->_q = clone $this->_q;
847
    }*/
848
}