Query.php 43.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?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.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Query_Abstract');
22 23 24 25 26 27 28 29 30 31 32
/**
 * Doctrine_Query
 *
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
33
class Doctrine_Query extends Doctrine_Query_Abstract implements Countable
zYne's avatar
zYne committed
34
{
zYne's avatar
zYne committed
35 36 37 38 39 40 41 42 43
    const STATE_CLEAN  = 1;

    const STATE_DIRTY  = 2;

    const STATE_DIRECT = 3;

    const STATE_LOCKED = 4;


zYne's avatar
zYne committed
44
    protected $subqueryAliases   = array();
45 46 47
    /**
     * @param boolean $needsSubquery
     */
zYne's avatar
zYne committed
48
    protected $needsSubquery     = false;
49 50 51 52
    /**
     * @param boolean $isSubquery           whether or not this query object is a subquery of another 
     *                                      query object
     */
zYne's avatar
zYne committed
53
    protected $isSubquery;
zYne's avatar
zYne committed
54 55
    
    protected $isLimitSubqueryUsed = false;
zYne's avatar
zYne committed
56 57 58 59
    /**
     * @var array $_neededTableAliases      an array containing the needed table aliases
     */
    protected $_neededTables     = array();
60 61 62
    /**
     * @var array $pendingFields
     */
zYne's avatar
zYne committed
63
    protected $pendingFields     = array();
zYne's avatar
zYne committed
64 65 66 67
    /**
     * @var array $pendingSubqueries        SELECT part subqueries, these are called pending subqueries since
     *                                      they cannot be parsed directly (some queries might be correlated)
     */
zYne's avatar
zYne committed
68
    protected $pendingSubqueries = array();
zYne's avatar
zYne committed
69
    /**
zYne's avatar
zYne committed
70
     * @var array $_parsers                 an array of parser objects, each DQL query part has its own parser
zYne's avatar
zYne committed
71
     */
zYne's avatar
zYne committed
72
    protected $_parsers    = array();
zYne's avatar
zYne committed
73 74 75 76
    /**
     * @var array $_enumParams              an array containing the keys of the parameters that should be enumerated
     */
    protected $_enumParams = array();
zYne's avatar
zYne committed
77

zYne's avatar
zYne committed
78 79 80 81 82 83 84 85 86 87 88 89 90
    /**
     * @var array $_dqlParts                an array containing all DQL query parts
     */
    protected $_dqlParts   = array(
                            'select'    => array(),
                            'forUpdate' => false,
                            'from'      => array(),
                            'set'       => array(),
                            'join'      => array(),
                            'where'     => array(),
                            'groupby'   => array(),
                            'having'    => array(),
                            'orderby'   => array(),
91 92
                            'limit'     => array(),
                            'offset'    => array(),
zYne's avatar
zYne committed
93
                            );
94 95 96 97
    /**
     * @var array $_pendingJoinConditions    an array containing pending joins
     */
    protected $_pendingJoinConditions = array();
zYne's avatar
zYne committed
98 99
    
    protected $_state = Doctrine_Query::STATE_CLEAN;
100 101 102 103 104

    /**
     * create
     * returns a new Doctrine_Query object
     *
105
     * @param Doctrine_Connection $conn     optional connection parameter
106 107
     * @return Doctrine_Query
     */
108
    public static function create($conn = null)
109
    {
110 111
        return new Doctrine_Query($conn);
    }
zYne's avatar
zYne committed
112 113 114 115 116 117 118 119 120 121 122
    public function reset() 
    {
        $this->_enumParams = array();
        $this->_pendingJoinConditions = array();
        $this->pendingSubqueries = array();
        $this->pendingFields = array();
        $this->_neededTables = array();
        $this->subqueryAliases = array();
        $this->needsSubquery = false;
        $this->isLimitSubqueryUsed = false;
    }
123 124 125 126 127 128 129 130 131 132 133 134 135
    /**
     * setOption
     *
     * @param string $name      option name
     * @param string $value     option value
     * @return Doctrine_Query   this object
     */
    public function setOption($name, $value)
    {
        if ( ! isset($this->_options[$name])) {
            throw new Doctrine_Query_Exception('Unknown option ' . $name);
        }
        $this->_options[$name] = $value;
136
    }
137 138 139 140 141 142 143 144 145 146 147
    /**
     * addPendingJoinCondition
     *
     * @param string $componentAlias    component alias
     * @param string $joinCondition     dql join condition
     * @return Doctrine_Query           this object
     */
    public function addPendingJoinCondition($componentAlias, $joinCondition)
    {
        $this->_pendingJoins[$componentAlias] = $joinCondition;
    }
zYne's avatar
zYne committed
148 149 150 151 152 153 154 155 156
    /** 
     * addEnumParam
     * sets input parameter as an enumerated parameter
     *
     * @param string $key   the key of the input parameter
     * @return Doctrine_Query
     */
    public function addEnumParam($key, $table = null, $column = null)
    {
zYne's avatar
zYne committed
157
        $array = (isset($table) || isset($column)) ? array($table, $column) : array();
zYne's avatar
zYne committed
158

zYne's avatar
zYne committed
159 160
        if ($key === '?') {
            $this->_enumParams[] = $array;
zYne's avatar
zYne committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174
        } else {
            $this->_enumParams[$key] = $array;
        }
    }
    /**
     * getEnumParams
     * get all enumerated parameters
     *
     * @return array    all enumerated parameters
     */
    public function getEnumParams()
    {
        return $this->_enumParams;
    }
zYne's avatar
zYne committed
175 176 177 178 179 180 181 182 183
    /**
     * limitSubqueryUsed
     *
     * @return boolean
     */
    public function isLimitSubqueryUsed()
    {
        return $this->isLimitSubqueryUsed;
    }
zYne's avatar
zYne committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    /**
     * convertEnums
     * convert enum parameters to their integer equivalents
     *
     * @return array    converted parameter array
     */
    public function convertEnums($params) 
    {
        foreach ($this->_enumParams as $key => $values) {
            if (isset($params[$key])) {
                if ( ! empty($values)) {
                    $params[$key] = $values[0]->enumIndex($values[1], $params[$key]);
                }
            }
        }
        return $params;
    }
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
    /**
     * isSubquery
     * if $bool parameter is set this method sets the value of
     * Doctrine_Query::$isSubquery. If this value is set to true
     * the query object will not load the primary key fields of the selected
     * components.
     *
     * If null is given as the first parameter this method retrieves the current
     * value of Doctrine_Query::$isSubquery.
     *
     * @param boolean $bool     whether or not this query acts as a subquery
     * @return Doctrine_Query|bool
     */
    public function isSubquery($bool = null)
    {
        if ($bool === null) {
            return $this->isSubquery;
        }

        $this->isSubquery = (bool) $bool;
        return $this;
    }
    /**
     * getAggregateAlias
     * 
zYne's avatar
zYne committed
226
     * @param string $dqlAlias      the dql alias of an aggregate value
227 228 229 230
     * @return string
     */
    public function getAggregateAlias($dqlAlias)
    {
zYne's avatar
zYne committed
231
        if (isset($this->aggregateMap[$dqlAlias])) {
232 233
            return $this->aggregateMap[$dqlAlias];
        }
zYne's avatar
zYne committed
234 235 236 237 238 239
        if ( ! empty($this->pendingAggregates)) {
            $this->processPendingAggregates();
            
            return $this->getAggregateAlias($dqlAlias);
        }
        throw new Doctrine_Query_Exception('Unknown aggregate alias ' . $dqlAlias);
240
    }
zYne's avatar
zYne committed
241 242 243 244 245 246 247 248
    /**
     * getParser
     * parser lazy-loader
     *
     * @throws Doctrine_Query_Exception     if unknown parser name given
     * @return Doctrine_Query_Part
     */
    public function getParser($name)
249
    {
zYne's avatar
zYne committed
250 251
        if ( ! isset($this->_parsers[$name])) {
            $class = 'Doctrine_Query_' . ucwords(strtolower($name));
252

zYne's avatar
zYne committed
253 254 255 256 257
            Doctrine::autoload($class);
            
            if ( ! class_exists($class)) {
                throw new Doctrine_Query_Exception('Unknown parser ' . $name);
            }
258

zYne's avatar
zYne committed
259 260 261 262 263
            $this->_parsers[$name] = new $class($this);
        }
        
        return $this->_parsers[$name];
    }
264 265
    /**
     * parseQueryPart
zYne's avatar
zYne committed
266
     * parses given DQL query part
267 268 269 270 271 272 273 274 275
     *
     * @param string $queryPartName     the name of the query part
     * @param string $queryPart         query part to be parsed
     * @param boolean $append           whether or not to append the query part to its stack
     *                                  if false is given, this method will overwrite 
     *                                  the given query part stack with $queryPart
     * @return Doctrine_Query           this object
     */
    public function parseQueryPart($queryPartName, $queryPart, $append = false) 
zYne's avatar
zYne committed
276 277 278 279 280
    {
        if ($this->_state === self::STATE_LOCKED) {
            throw new Doctrine_Query_Exception('This query object is locked. No query parts can be manipulated.');
        }

zYne's avatar
zYne committed
281

zYne's avatar
zYne committed
282 283
        // sanity check
        if ($queryPart === '' || $queryPart === null) {
zYne's avatar
zYne committed
284
            throw new Doctrine_Query_Exception('Empty ' . $queryPartName . ' part given.');
zYne's avatar
zYne committed
285
        }
zYne's avatar
zYne committed
286

zYne's avatar
zYne committed
287
        // add query part to the dql part array
zYne's avatar
zYne committed
288 289 290
        if ($append) {
            $this->_dqlParts[$queryPartName][] = $queryPart;
        } else {
291
            $this->_dqlParts[$queryPartName] = array($queryPart);
zYne's avatar
zYne committed
292 293
        }

zYne's avatar
zYne committed
294 295 296 297 298 299 300 301 302 303 304 305 306
        if ($this->_state === self::STATE_DIRECT) {
            $parser = $this->getParser($queryPartName);

            $sql = $parser->parse($queryPart);

            if (isset($sql)) {
                if ($append) {
                    $this->addQueryPart($queryPartName, $sql);
                } else {
                    $this->setQueryPart($queryPartName, $sql);
                }
            }                                   	
        }
zYne's avatar
zYne committed
307
           
308
        return $this;
309
    }
zYne's avatar
zYne committed
310 311 312 313 314 315 316 317 318 319
    /**
     * getDql
     * returns the DQL query associated with this object
     *
     * the query is built from $_dqlParts
     *
     * @return string   the DQL query
     */
    public function getDql()
    {
zYne's avatar
zYne committed
320 321
        $q = '';
        $q .= ( ! empty($this->_dqlParts['select']))?  'SELECT '    . implode(', ', $this->_dqlParts['select']) : '';
322 323 324 325 326 327 328
        $q .= ( ! empty($this->_dqlParts['from']))?    ' FROM '     . implode(' ', $this->_dqlParts['from']) : '';
        $q .= ( ! empty($this->_dqlParts['where']))?   ' WHERE '    . implode(' AND ', $this->_dqlParts['where']) : '';
        $q .= ( ! empty($this->_dqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_dqlParts['groupby']) : '';
        $q .= ( ! empty($this->_dqlParts['having']))?  ' HAVING '   . implode(' AND ', $this->_dqlParts['having']) : '';
        $q .= ( ! empty($this->_dqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_dqlParts['orderby']) : '';
        $q .= ( ! empty($this->_dqlParts['limit']))?   ' LIMIT '    . implode(' ', $this->_dqlParts['limit']) : '';
        $q .= ( ! empty($this->_dqlParts['offset']))?  ' OFFSET '   . implode(' ', $this->_dqlParts['offset']) : '';
zYne's avatar
zYne committed
329 330 331
        
        return $q;
    }
zYne's avatar
zYne committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345
    /**
     * processPendingFields
     * the fields in SELECT clause cannot be parsed until the components
     * in FROM clause are parsed, hence this method is called everytime a 
     * specific component is being parsed.
     *
     * @throws Doctrine_Query_Exception     if unknown component alias has been given
     * @param string $componentAlias        the alias of the component
     * @return void
     */
    public function processPendingFields($componentAlias)
    {
        $tableAlias = $this->getTableAlias($componentAlias);
        $table      = $this->_aliasMap[$componentAlias]['table'];
346 347 348 349

        if (isset($this->pendingFields[$componentAlias])) {
            $fields = $this->pendingFields[$componentAlias];

zYne's avatar
zYne committed
350
            // check for wildcards
zYne's avatar
zYne committed
351
            if (in_array('*', $fields)) {
352 353 354 355 356 357 358 359 360 361 362 363
                $fields = $table->getColumnNames();
            } else {
                // only auto-add the primary key fields if this query object is not 
                // a subquery of another query object
                if ( ! $this->isSubquery) {
                    $fields = array_unique(array_merge($table->getPrimaryKeys(), $fields));
                }
            }
        }
        foreach ($fields as $name) {
            $name = $table->getColumnName($name);

zYne's avatar
zYne committed
364
            $this->parts['select'][] = $tableAlias . '.' .$name . ' AS ' . $tableAlias . '__' . $name;
365 366 367 368 369 370 371 372 373 374 375 376 377 378
        }
        
        $this->neededTables[] = $tableAlias;

    }
    /**
     * parseSelect
     * parses the query select part and
     * adds selected fields to pendingFields array
     *
     * @param string $dql
     */
    public function parseSelect($dql)
    {
zYne's avatar
zYne committed
379
        $refs = Doctrine_Tokenizer::bracketExplode($dql, ',');
380

381 382 383 384 385 386 387 388 389
        $pos   = strpos(trim($refs[0]), ' ');
        $first = substr($refs[0], 0, $pos);
        
        if ($first === 'DISTINCT') {
            $this->parts['distinct'] = true;
            
            $refs[0] = substr($refs[0], ++$pos);
        }

zYne's avatar
zYne committed
390
        foreach ($refs as $reference) {
zYne's avatar
zYne committed
391
            $reference = trim($reference);
zYne's avatar
zYne committed
392 393 394 395 396
            if (strpos($reference, '(') !== false) {
                if (substr($reference, 0, 1) === '(') {
                    // subselect found in SELECT part
                    $this->parseSubselect($reference);
                } else {
zYne's avatar
zYne committed
397
                    $this->parseAggregateFunction($reference);
zYne's avatar
zYne committed
398
                }
399 400
            } else {

401

402 403 404 405 406 407 408 409 410
                $e = explode('.', $reference);
                if (count($e) > 2) {
                    $this->pendingFields[] = $reference;
                } else {
                    $this->pendingFields[$e[0]][] = $e[1];
                }
            }
        }
    }
zYne's avatar
zYne committed
411 412 413 414 415 416 417 418 419 420 421
    /** 
     * parseSubselect
     *
     * parses the subquery found in DQL SELECT part and adds the
     * parsed form into $pendingSubqueries stack
     *
     * @param string $reference
     * @return void
     */
    public function parseSubselect($reference) 
    {
zYne's avatar
zYne committed
422
        $e     = Doctrine_Tokenizer::bracketExplode($reference, ' ');
zYne's avatar
zYne committed
423 424 425 426 427 428 429 430 431 432 433 434 435
        $alias = $e[1];

        if (count($e) > 2) {
            if (strtoupper($e[1]) !== 'AS') {
                throw new Doctrine_Query_Exception('Syntax error near: ' . $reference);
            }
            $alias = $e[2];
        }
        
        $subquery = substr($e[0], 1, -1);
        
        $this->pendingSubqueries[] = array($subquery, $alias);
    }
zYne's avatar
zYne committed
436 437 438 439 440
    /**
     * parseAggregateFunction
     * parses an aggregate function and returns the parsed form
     *
     * @see Doctrine_Expression
zYne's avatar
zYne committed
441
     * @param string $expr                  DQL aggregate function
zYne's avatar
zYne committed
442 443 444
     * @throws Doctrine_Query_Exception     if unknown aggregate function given
     * @return array                        parsed form of given function
     */
zYne's avatar
zYne committed
445
    public function parseAggregateFunction($expr, $nestedCall = false)
446
    {
zYne's avatar
zYne committed
447
        $e    = Doctrine_Tokenizer::bracketExplode($expr, ' ');
448 449 450
        $func = $e[0];

        $pos  = strpos($func, '(');
zYne's avatar
zYne committed
451 452 453 454 455 456 457
        if ($pos === false) {
            return $expr;
        }

        // get the name of the function
        $name   = substr($func, 0, $pos);
        $argStr = substr($func, ($pos + 1), -1);
458

zYne's avatar
zYne committed
459 460 461 462 463 464 465
        $args   = array();
        // parse args
        foreach (Doctrine_Tokenizer::bracketExplode($argStr, ',') as $expr) {
           $args[] = $this->parseAggregateFunction($expr, true);
        }

        // convert DQL function to its RDBMS specific equivalent
zYne's avatar
zYne committed
466
        try {
zYne's avatar
zYne committed
467
            $expr = call_user_func_array(array($this->_conn->expression, $name), $args);
zYne's avatar
zYne committed
468 469
        } catch(Doctrine_Expression_Exception $e) {
            throw new Doctrine_Query_Exception('Unknown function ' . $func . '.');
470
        }
zYne's avatar
zYne committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

        if ( ! $nestedCall) {
            // try to find all component references
            preg_match_all("/[a-z0-9_]+\.[a-z0-9_]+[\.[a-z0-9]+]*/i", $argStr, $m);

            if (isset($e[1])) {
                if (strtoupper($e[1]) === 'AS') {
                    if ( ! isset($e[2])) {
                        throw new Doctrine_Query_Exception('Missing aggregate function alias.');
                    }
                    $alias = $e[2];
                } else {
                    $alias = $e[1];
                }
            } else {
                $alias = substr($expr, 0, strpos($expr, '('));
            }

            $this->pendingAggregates[] = array($expr, $m[0], $alias);
        }

        return $expr;
493
    }
zYne's avatar
zYne committed
494 495 496 497 498 499 500 501 502
    /**
     * processPendingSubqueries
     * processes pending subqueries
     *
     * subqueries can only be processed when the query is fully constructed
     * since some subqueries may be correlated
     *
     * @return void
     */
zYne's avatar
zYne committed
503 504
    public function processPendingSubqueries() 
    {
zYne's avatar
zYne committed
505
        foreach ($this->pendingSubqueries as $value) {
zYne's avatar
zYne committed
506 507 508 509
            list($dql, $alias) = $value;

            $sql = $this->createSubquery()->parseQuery($dql, false)->getQuery();

zYne's avatar
zYne committed
510 511 512
            reset($this->_aliasMap);
            $componentAlias = key($this->_aliasMap);
            $tableAlias = $this->getTableAlias($componentAlias);
zYne's avatar
zYne committed
513 514

            $sqlAlias = $tableAlias . '__' . count($this->aggregateMap);
zYne's avatar
zYne committed
515

zYne's avatar
zYne committed
516
            $this->parts['select'][] = '(' . $sql . ') AS ' . $sqlAlias;
zYne's avatar
zYne committed
517

zYne's avatar
zYne committed
518
            $this->aggregateMap[$alias] = $sqlAlias;
zYne's avatar
zYne committed
519
            $this->_aliasMap[$componentAlias]['agg'][] = $alias;
zYne's avatar
zYne committed
520
        }
zYne's avatar
zYne committed
521
        $this->pendingSubqueries = array();
zYne's avatar
zYne committed
522
    }
zYne's avatar
zYne committed
523 524 525 526 527 528
    /** 
     * processPendingAggregates
     * processes pending aggregate values for given component alias
     *
     * @return void
     */
zYne's avatar
zYne committed
529
    public function processPendingAggregates()
530
    {
zYne's avatar
zYne committed
531
        // iterate trhough all aggregates
zYne's avatar
zYne committed
532 533
        foreach ($this->pendingAggregates as $aggregate) {
            list ($expression, $components, $alias) = $aggregate;
534

zYne's avatar
zYne committed
535
            $tableAliases = array();
536

zYne's avatar
zYne committed
537 538 539 540 541 542 543 544 545 546 547
            // iterate through the component references within the aggregate function
            if ( ! empty ($components)) {
                foreach ($components as $component) {
                    $e = explode('.', $component);
    
                    $field = array_pop($e);
                    $componentAlias = implode('.', $e);
    
                    // check the existence of the component alias
                    if ( ! isset($this->_aliasMap[$componentAlias])) {
                        throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
548
                    }
zYne's avatar
zYne committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    
                    $table = $this->_aliasMap[$componentAlias]['table'];
    
                    $field = $table->getColumnName($field);
    
                    // check column existence
                    if ( ! $table->hasColumn($field)) {
                        throw new Doctrine_Query_Exception('Unknown column ' . $field);
                    }
    
                    $tableAlias = $this->getTableAlias($componentAlias);
    
                    $tableAliases[$tableAlias] = true;
    
                    // build sql expression
                    $expression = str_replace($component, $tableAlias . '.' . $field, $expression);
565 566
                }
            }
zYne's avatar
zYne committed
567 568 569 570 571 572

            if (count($tableAliases) !== 1) {
                $componentAlias = reset($this->tableAliases);
                $tableAlias = key($this->tableAliases);
            }

zYne's avatar
zYne committed
573 574
            $index    = count($this->aggregateMap);
            $sqlAlias = $tableAlias . '__' . $index;
575

zYne's avatar
zYne committed
576 577
            $this->parts['select'][] = $expression . ' AS ' . $sqlAlias;

578
            $this->aggregateMap[$alias] = $sqlAlias;
zYne's avatar
zYne committed
579

zYne's avatar
zYne committed
580 581
            $this->_aliasMap[$componentAlias]['agg'][$index] = $alias;

582 583
            $this->neededTables[] = $tableAlias;
        }
zYne's avatar
zYne committed
584 585
        // reset the state
        $this->pendingAggregates = array();
586 587
    }
    /**
zYne's avatar
zYne committed
588 589 590
     * getQueryBase
     * returns the base of the generated sql query
     * On mysql driver special strategy has to be used for DELETE statements
591
     *
zYne's avatar
zYne committed
592
     * @return string       the base of the generated sql query
593
     */
zYne's avatar
zYne committed
594
    public function getQueryBase()
595
    {
zYne's avatar
zYne committed
596 597 598
        switch ($this->type) {
            case self::DELETE:
                $q = 'DELETE FROM ';
599
            break;
zYne's avatar
zYne committed
600 601
            case self::UPDATE:
                $q = 'UPDATE ';
602
            break;
zYne's avatar
zYne committed
603
            case self::SELECT:
604
                $distinct = ($this->parts['distinct']) ? 'DISTINCT ' : '';
605

zYne's avatar
zYne committed
606 607
                $q = 'SELECT ' . $distinct . implode(', ', $this->parts['select']) . ' FROM ';
            break;
608
        }
zYne's avatar
zYne committed
609
        return $q;
610 611
    }
    /**
zYne's avatar
zYne committed
612
     * buildFromPart
zYne's avatar
zYne committed
613
     * builds the from part of the query and returns it
614
     *
zYne's avatar
zYne committed
615
     * @return string   the query sql from part
616
     */
zYne's avatar
zYne committed
617
    public function buildFromPart()
618
    {
zYne's avatar
zYne committed
619
        $q = '';
zYne's avatar
zYne committed
620 621 622 623 624 625
        foreach ($this->parts['from'] as $k => $part) {
            if ($k === 0) {
                $q .= $part;
                continue;
            }
            // preserve LEFT JOINs only if needed
626

zYne's avatar
zYne committed
627 628
            if (substr($part, 0, 9) === 'LEFT JOIN') {
                $e = explode(' ', $part);
629

zYne's avatar
zYne committed
630 631
                $aliases = array_merge($this->subqueryAliases,
                            array_keys($this->neededTables));
632

zYne's avatar
zYne committed
633 634
                if( ! in_array($e[3], $aliases) &&
                    ! in_array($e[2], $aliases) &&
635

zYne's avatar
zYne committed
636 637
                    ! empty($this->pendingFields)) {
                    continue;
638
                }
639

zYne's avatar
zYne committed
640
            }
641

642
            if (isset($this->_pendingJoinConditions[$k])) {
zYne's avatar
zYne committed
643
                $parser = new Doctrine_Query_JoinCondition($this);
644 645 646
                $part  .= ' AND ' . $parser->parse($this->_pendingJoinConditions[$k]);

                unset($this->_pendingJoinConditions[$k]);
zYne's avatar
zYne committed
647
            }
648

zYne's avatar
zYne committed
649
            $q .= ' ' . $part;
zYne's avatar
zYne committed
650

651
            $this->parts['from'][$k] = $part;
652 653
        }
        return $q;
zYne's avatar
zYne committed
654 655 656 657 658 659 660 661 662 663 664 665 666
    }
    /**
     * preQuery
     *
     * Empty template method to provide Query subclasses with the possibility
     * to hook into the query building procedure, doing any custom / specialized
     * query building procedures that are neccessary.
     *
     * @return void
     */
    public function preQuery()
    {

zYne's avatar
zYne committed
667 668 669 670 671 672 673 674 675 676 677 678 679
    }
    /**
     * postQuery
     *
     * Empty template method to provide Query subclasses with the possibility
     * to hook into the query building procedure, doing any custom / specialized
     * post query procedures (for example logging) that are neccessary.
     *
     * @return void
     */
    public function postQuery()
    {

680 681 682 683 684 685 686 687 688 689 690
    }
    /**
     * builds the sql query from the given parameters and applies things such as
     * column aggregation inheritance and limit subqueries if needed
     *
     * @param array $params             an array of prepared statement params (needed only in mysql driver
     *                                  when limit subquery algorithm is used)
     * @return string                   the built sql query
     */
    public function getQuery($params = array())
    {
zYne's avatar
zYne committed
691
    	$parts = $this->_dqlParts;
zYne's avatar
zYne committed
692

zYne's avatar
zYne committed
693
        // reset the state
zYne's avatar
zYne committed
694 695 696 697
        $this->_aliasMap = array();
        $this->pendingAggregates = array();
        $this->aggregateMap = array();
        
zYne's avatar
zYne committed
698
        $this->reset();   
zYne's avatar
zYne committed
699

zYne's avatar
zYne committed
700
        // parse the DQL parts
zYne's avatar
zYne committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        foreach ($this->_dqlParts as $queryPartName => $queryParts) {
            $this->parts[$queryPartName] = array();
            if (is_array($queryParts) && ! empty($queryParts)) {

                foreach ($queryParts as $queryPart) {
                    $parser = $this->getParser($queryPartName);
                                      

                    $sql = $parser->parse($queryPart);

                    if (isset($sql)) {
                        if ($queryPartName == 'limit' || 
                            $queryPartName == 'offset') {

                            $this->setQueryPart($queryPartName, $sql);
                        } else {
                            $this->addQueryPart($queryPartName, $sql);
                        }
719 720
                    }
                }
zYne's avatar
zYne committed
721
            }
722
        }
zYne's avatar
zYne committed
723 724 725 726 727 728 729
        $this->_state = self::STATE_DIRECT;

        // invoke the preQuery hook
        $this->preQuery();        
        $this->_state = self::STATE_CLEAN;
        
        $this->_dqlParts = $parts;
zYne's avatar
zYne committed
730

zYne's avatar
zYne committed
731
        if (empty($this->parts['from'])) {
732
            return false;
zYne's avatar
zYne committed
733
        }
734 735 736

        $needsSubQuery = false;
        $subquery = '';
zYne's avatar
zYne committed
737 738 739
        $map   = reset($this->_aliasMap);
        $table = $map['table'];
        $rootAlias = key($this->_aliasMap);
740

zYne's avatar
zYne committed
741
        if ( ! empty($this->parts['limit']) && $this->needsSubquery && $table->getAttribute(Doctrine::ATTR_QUERY_LIMIT) == Doctrine::LIMIT_RECORDS) {
zYne's avatar
zYne committed
742
            $this->isLimitSubqueryUsed = true;
743 744 745
            $needsSubQuery = true;
        }

zYne's avatar
zYne committed
746 747
        // process all pending SELECT part subqueries
        $this->processPendingSubqueries();
zYne's avatar
zYne committed
748
        $this->processPendingAggregates();
zYne's avatar
zYne committed
749

750 751
        // build the basic query

zYne's avatar
zYne committed
752 753 754 755
        $q  = $this->getQueryBase();
        $q .= $this->buildFromPart();

        if ( ! empty($this->parts['set'])) {
756 757 758 759
            $q .= ' SET ' . implode(', ', $this->parts['set']);
        }


zYne's avatar
zYne committed
760 761 762
        $string = $this->applyInheritance();
        
        // apply inheritance to WHERE part
zYne's avatar
zYne committed
763 764 765
        if ( ! empty($string)) {
            $this->parts['where'][] = '(' . $string . ')';
        }
766 767 768


        $modifyLimit = true;
zYne's avatar
zYne committed
769
        if ( ! empty($this->parts['limit']) || ! empty($this->parts['offset'])) {
770

zYne's avatar
zYne committed
771
            if ($needsSubQuery) {
772 773 774
                $subquery = $this->getLimitSubquery();


zYne's avatar
zYne committed
775
                switch (strtolower($this->_conn->getName())) {
776 777
                    case 'mysql':
                        // mysql doesn't support LIMIT in subqueries
zYne's avatar
zYne committed
778
                        $list     = $this->_conn->execute($subquery, $params)->fetchAll(Doctrine::FETCH_COLUMN);
779
                        $subquery = implode(', ', $list);
zYne's avatar
zYne committed
780
                        break;
781 782 783
                    case 'pgsql':
                        // pgsql needs special nested LIMIT subquery
                        $subquery = 'SELECT doctrine_subquery_alias.' . $table->getIdentifier(). ' FROM (' . $subquery . ') AS doctrine_subquery_alias';
zYne's avatar
zYne committed
784
                        break;
785 786
                }

zYne's avatar
zYne committed
787
                $field = $this->getTableAlias($rootAlias) . '.' . $table->getIdentifier();
788 789

                // only append the subquery if it actually contains something
zYne's avatar
zYne committed
790
                if ($subquery !== '') {
791
                    array_unshift($this->parts['where'], $field. ' IN (' . $subquery . ')');
zYne's avatar
zYne committed
792
                }
793 794 795 796 797

                $modifyLimit = false;
            }
        }

zYne's avatar
zYne committed
798 799 800 801
        $q .= ( ! empty($this->parts['where']))?   ' WHERE '    . implode(' AND ', $this->parts['where']) : '';
        $q .= ( ! empty($this->parts['groupby']))? ' GROUP BY ' . implode(', ', $this->parts['groupby'])  : '';
        $q .= ( ! empty($this->parts['having']))?  ' HAVING '   . implode(' AND ', $this->parts['having']): '';
        $q .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(', ', $this->parts['orderby'])  : '';
802

zYne's avatar
zYne committed
803
        if ($modifyLimit) {
zYne's avatar
zYne committed
804
            $q = $this->_conn->modifyLimitQuery($q, $this->parts['limit'], $this->parts['offset']);
zYne's avatar
zYne committed
805
        }
806 807

        // return to the previous state
zYne's avatar
zYne committed
808
        if ( ! empty($string)) {
809
            array_pop($this->parts['where']);
zYne's avatar
zYne committed
810 811
        }
        if ($needsSubQuery) {
812
            array_shift($this->parts['where']);
zYne's avatar
zYne committed
813
        }
814

815 816 817
        return $q;
    }
    /**
zYne's avatar
zYne committed
818
     * getLimitSubquery
819 820 821 822 823 824 825 826 827 828
     * this is method is used by the record limit algorithm
     *
     * when fetching one-to-many, many-to-many associated data with LIMIT clause
     * an additional subquery is needed for limiting the number of returned records instead
     * of limiting the number of sql result set rows
     *
     * @return string       the limit subquery
     */
    public function getLimitSubquery()
    {
zYne's avatar
zYne committed
829 830 831
        $map    = reset($this->_aliasMap);
        $table  = $map['table'];
        $componentAlias = key($this->_aliasMap);
832 833

        // get short alias
zYne's avatar
zYne committed
834
        $alias      = $this->getTableAlias($componentAlias);
835 836 837 838 839
        $primaryKey = $alias . '.' . $table->getIdentifier();

        // initialize the base of the subquery
        $subquery   = 'SELECT DISTINCT ' . $primaryKey;

zYne's avatar
zYne committed
840
        if ($this->_conn->getDBH()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
841 842
            // pgsql needs the order by fields to be preserved in select clause

zYne's avatar
zYne committed
843
            foreach ($this->parts['orderby'] as $part) {
844 845 846
                $e = explode(' ', $part);

                // don't add primarykey column (its already in the select clause)
zYne's avatar
zYne committed
847
                if ($e[0] !== $primaryKey) {
848
                    $subquery .= ', ' . $e[0];
zYne's avatar
zYne committed
849
                }
850 851 852
            }
        }

zYne's avatar
zYne committed
853
        $subquery .= ' FROM';
854

855

zYne's avatar
zYne committed
856 857
        foreach ($this->parts['from'] as $part) {
            // preserve LEFT JOINs only if needed
zYne's avatar
zYne committed
858
            if (substr($part, 0, 9) === 'LEFT JOIN') {
zYne's avatar
zYne committed
859
                $e = explode(' ', $part);
860 861
                
                if (empty($this->parts['orderby']) && empty($this->parts['where'])) {
zYne's avatar
zYne committed
862
                    continue;
863 864
                }
            }
zYne's avatar
zYne committed
865 866

            $subquery .= ' ' . $part;
867 868 869 870 871 872
        }

        // all conditions must be preserved in subquery
        $subquery .= ( ! empty($this->parts['where']))?   ' WHERE '    . implode(' AND ', $this->parts['where'])  : '';
        $subquery .= ( ! empty($this->parts['groupby']))? ' GROUP BY ' . implode(', ', $this->parts['groupby'])   : '';
        $subquery .= ( ! empty($this->parts['having']))?  ' HAVING '   . implode(' AND ', $this->parts['having']) : '';
zYne's avatar
zYne committed
873 874

        $subquery .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(', ', $this->parts['orderby'])   : '';
875 876

        // add driver specific limit clause
zYne's avatar
zYne committed
877
        $subquery = $this->_conn->modifyLimitQuery($subquery, $this->parts['limit'], $this->parts['offset']);
878

zYne's avatar
zYne committed
879
        $parts = Doctrine_Tokenizer::quoteExplode($subquery, ' ', "'", "'");
880 881 882 883 884 885

        foreach($parts as $k => $part) {
            if(strpos($part, "'") !== false) {
                continue;
            }

zYne's avatar
zYne committed
886
            if($this->hasTableAlias($part)) {
zYne's avatar
zYne committed
887
                $parts[$k] = $this->generateNewTableAlias($part);
888 889 890 891 892 893 894 895
            }

            if(strpos($part, '.') !== false) {
                $e = explode('.', $part);

                $trimmed = ltrim($e[0], '( ');
                $pos     = strpos($e[0], $trimmed);

zYne's avatar
zYne committed
896
                $e[0] = substr($e[0], 0, $pos) . $this->generateNewTableAlias($trimmed);
897 898 899 900 901 902 903 904
                $parts[$k] = implode('.', $e);
            }
        }
        $subquery = implode(' ', $parts);

        return $subquery;
    }
    /**
zYne's avatar
zYne committed
905
     * tokenizeQuery
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
     * splits the given dql query into an array where keys
     * represent different query part names and values are
     * arrays splitted using sqlExplode method
     *
     * example:
     *
     * parameter:
     *      $query = "SELECT u.* FROM User u WHERE u.name LIKE ?"
     * returns:
     *      array('select' => array('u.*'),
     *            'from'   => array('User', 'u'),
     *            'where'  => array('u.name', 'LIKE', '?'))
     *
     * @param string $query                 DQL query
     * @throws Doctrine_Query_Exception     if some generic parsing error occurs
     * @return array                        an array containing the query string parts
     */
zYne's avatar
zYne committed
923
    public function tokenizeQuery($query)
924
    {
zYne's avatar
zYne committed
925
        $e = Doctrine_Tokenizer::sqlExplode($query, ' ');
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

        foreach($e as $k=>$part) {
            $part = trim($part);
            switch(strtolower($part)) {
                case 'delete':
                case 'update':
                case 'select':
                case 'set':
                case 'from':
                case 'where':
                case 'limit':
                case 'offset':
                case 'having':
                    $p = $part;
                    $parts[$part] = array();
                break;
                case 'order':
                case 'group':
                    $i = ($k + 1);
                    if(isset($e[$i]) && strtolower($e[$i]) === "by") {
                        $p = $part;
                        $parts[$part] = array();
                    } else
                        $parts[$p][] = $part;
                break;
                case "by":
                    continue;
                default:
                    if( ! isset($p))
                        throw new Doctrine_Query_Exception("Couldn't parse query.");

                    $parts[$p][] = $part;
            }
        }
        return $parts;
    }
    /**
     * DQL PARSER
     * parses a DQL query
     * first splits the query in parts and then uses individual
     * parsers for each part
     *
     * @param string $query                 DQL query
     * @param boolean $clear                whether or not to clear the aliases
     * @throws Doctrine_Query_Exception     if some generic parsing error occurs
     * @return Doctrine_Query
     */
    public function parseQuery($query, $clear = true)
    {
zYne's avatar
zYne committed
975
        if ($clear) {
976
            $this->clear();
zYne's avatar
zYne committed
977
        }
978 979 980 981 982

        $query = trim($query);
        $query = str_replace("\n", ' ', $query);
        $query = str_replace("\r", ' ', $query);

zYne's avatar
zYne committed
983
        $parts = $this->tokenizeQuery($query);
984 985 986

        foreach($parts as $k => $part) {
            $part = implode(' ', $part);
zYne's avatar
zYne committed
987 988
            $k = strtolower($k);
            switch ($k) {
zYne's avatar
zYne committed
989
                case 'create':
990 991
                    $this->type = self::CREATE;
                break;
zYne's avatar
zYne committed
992
                case 'insert':
993 994
                    $this->type = self::INSERT;
                break;
zYne's avatar
zYne committed
995
                case 'delete':
996 997
                    $this->type = self::DELETE;
                break;
zYne's avatar
zYne committed
998
                case 'select':
999
                    $this->type = self::SELECT;
zYne's avatar
zYne committed
1000
                    $this->parseQueryPart($k, $part);
1001
                break;
zYne's avatar
zYne committed
1002
                case 'update':
1003
                    $this->type = self::UPDATE;
zYne's avatar
zYne committed
1004
                    $k = 'from';
zYne's avatar
zYne committed
1005
                case 'from':
zYne's avatar
zYne committed
1006
                    $this->parseQueryPart($k, $part);
1007
                break;
zYne's avatar
zYne committed
1008
                case 'set':
zYne's avatar
zYne committed
1009
                    $this->parseQueryPart($k, $part, true);
1010
                break;
zYne's avatar
zYne committed
1011 1012
                case 'group':
                case 'order':
1013
                    $k .= 'by';
zYne's avatar
zYne committed
1014 1015 1016 1017
                case 'where':
                case 'having':
                case 'limit':
                case 'offset':
zYne's avatar
zYne committed
1018
                    $this->parseQueryPart($k, $part);
1019 1020 1021 1022 1023 1024
                break;
            }
        }

        return $this;
    }
zYne's avatar
zYne committed
1025
    public function load($path, $loadFields = true) 
1026 1027 1028 1029 1030
    {
        // parse custom join conditions
        $e = explode(' ON ', $path);
        
        $joinCondition = '';
zYne's avatar
zYne committed
1031 1032

        if (count($e) > 1) {
1033
            $joinCondition = $e[1];
1034 1035 1036
            $path = $e[0];
        }

zYne's avatar
zYne committed
1037 1038
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
1039 1040 1041

        $e = preg_split("/[.:]/", $tmp[0], -1);

zYne's avatar
zYne committed
1042 1043 1044
        $fullPath = $tmp[0];
        $prevPath = '';
        $fullLength = strlen($fullPath);
1045

zYne's avatar
zYne committed
1046 1047
        if (isset($this->_aliasMap[$e[0]])) {
            $table = $this->_aliasMap[$e[0]]['table'];
1048

zYne's avatar
zYne committed
1049 1050
            $prevPath = $parent = array_shift($e);
        }
1051

zYne's avatar
zYne committed
1052 1053 1054
        foreach ($e as $key => $name) {
            // get length of the previous path
            $length = strlen($prevPath);
1055

zYne's avatar
zYne committed
1056 1057
            // build the current component path
            $prevPath = ($prevPath) ? $prevPath . '.' . $name : $name;
1058

zYne's avatar
zYne committed
1059
            $delimeter = substr($fullPath, $length, 1);
1060

zYne's avatar
zYne committed
1061 1062 1063 1064 1065 1066
            // if an alias is not given use the current path as an alias identifier
            if (strlen($prevPath) === $fullLength && isset($originalAlias)) {
                $componentAlias = $originalAlias;
            } else {
                $componentAlias = $prevPath;
            }
zYne's avatar
zYne committed
1067 1068 1069 1070 1071
            
            // if the current alias already exists, skip it
            if (isset($this->_aliasMap[$componentAlias])) {
                continue;
            }
1072

zYne's avatar
zYne committed
1073 1074
            if ( ! isset($table)) {
                // process the root of the path
1075

zYne's avatar
zYne committed
1076 1077 1078
                $table = $this->loadRoot($name, $componentAlias);
            } else {
                $join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN ';
1079

zYne's avatar
zYne committed
1080
                $relation = $table->getRelation($name);
zYne's avatar
zYne committed
1081 1082
                $table    = $relation->getTable();
                $this->_aliasMap[$componentAlias] = array('table'    => $table,
zYne's avatar
zYne committed
1083 1084 1085 1086 1087
                                                          'parent'   => $parent,
                                                          'relation' => $relation);
                if ( ! $relation->isOneToOne()) {
                   $this->needsSubquery = true;
                }
1088

zYne's avatar
zYne committed
1089 1090
                $localAlias   = $this->getTableAlias($parent, $table->getTableName());
                $foreignAlias = $this->getTableAlias($componentAlias, $relation->getTable()->getTableName());
zYne's avatar
zYne committed
1091 1092
                $localSql     = $this->_conn->quoteIdentifier($table->getTableName()) . ' ' . $localAlias;
                $foreignSql   = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) . ' ' . $foreignAlias;
1093

zYne's avatar
zYne committed
1094 1095 1096 1097 1098
                $map = $relation->getTable()->inheritanceMap;
  
                if ( ! $loadFields || ! empty($map) || $joinCondition) {
                    $this->subqueryAliases[] = $foreignAlias;
                }
1099

zYne's avatar
zYne committed
1100 1101 1102 1103 1104 1105 1106
                if ($relation instanceof Doctrine_Relation_Association) {
                    $asf = $relation->getAssociationFactory();
  
                    $assocTableName = $asf->getTableName();
  
                    if( ! $loadFields || ! empty($map) || $joinCondition) {
                        $this->subqueryAliases[] = $assocTableName;
1107 1108
                    }

zYne's avatar
zYne committed
1109 1110
                    $assocPath = $prevPath . '.' . $asf->getComponentName();
  
zYne's avatar
zYne committed
1111
                    $assocAlias = $this->getTableAlias($assocPath, $asf->getTableName());
1112

zYne's avatar
zYne committed
1113
                    $queryPart = $join . $assocTableName . ' ' . $assocAlias . ' ON ' . $localAlias  . '.'
1114 1115 1116 1117 1118 1119 1120
                                                               . $table->getIdentifier() . ' = '
                                                               . $assocAlias . '.' . $relation->getLocal();

                    if ($relation->isEqual()) {
                        $queryPart .= ' OR ' . $localAlias  . '.'
                                    . $table->getIdentifier() . ' = '
                                    . $assocAlias . '.' . $relation->getForeign();
1121 1122 1123

                    }

zYne's avatar
zYne committed
1124
                    $this->parts['from'][] = $queryPart;
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
                    $queryPart = $join . $foreignSql . ' ON ';
                    if ($relation->isEqual()) {
                        $queryPart .= '(';
                    } 
                    $queryPart .= $foreignAlias . '.'
                                . $relation->getTable()->getIdentifier() . ' = '
                                . $assocAlias . '.' . $relation->getForeign();

                    if ($relation->isEqual()) {
                        $queryPart .= ' OR '  . $foreignAlias   . '.' . $table->getIdentifier()
                                    . ' = '   . $assocAlias     . '.' . $relation->getLocal()
                                    . ') AND ' . $foreignAlias   . '.' . $table->getIdentifier()
                                    . ' != '  . $localAlias     . '.' . $table->getIdentifier();
1139 1140
                    }

zYne's avatar
zYne committed
1141
                } else {
1142

zYne's avatar
zYne committed
1143 1144
                    $queryPart = $join . $foreignSql
                                       . ' ON ' . $localAlias .  '.'
1145 1146 1147 1148 1149
                                       . $relation->getLocal() . ' = ' . $foreignAlias . '.' . $relation->getForeign();
                }
                $this->parts['from'][$componentAlias] = $queryPart;
                if ( ! empty($joinCondition)) {
                    $this->_pendingJoinConditions[$componentAlias] = $joinCondition;
1150
                }
zYne's avatar
zYne committed
1151 1152
            }
            if ($loadFields) {
zYne's avatar
zYne committed
1153
                                 
zYne's avatar
zYne committed
1154 1155 1156 1157 1158
                $restoreState = false;
                // load fields if necessary
                if ($loadFields && empty($this->pendingFields) 
                    && empty($this->pendingAggregates)
                    && empty($this->pendingSubqueries)) {
1159

zYne's avatar
zYne committed
1160
                    $this->pendingFields[$componentAlias] = array('*');
1161

zYne's avatar
zYne committed
1162 1163
                    $restoreState = true;
                }
1164

zYne's avatar
zYne committed
1165 1166
                if(isset($this->pendingFields[$componentAlias])) {
                    $this->processPendingFields($componentAlias);
1167
                }
zYne's avatar
zYne committed
1168
                /**
zYne's avatar
zYne committed
1169 1170 1171
                if(isset($this->pendingAggregates[$componentAlias]) || isset($this->pendingAggregates[0])) {
                    $this->processPendingAggregates($componentAlias);
                }
zYne's avatar
zYne committed
1172
                */
1173

zYne's avatar
zYne committed
1174 1175 1176 1177
                if ($restoreState) {
                    $this->pendingFields = array();
                    $this->pendingAggregates = array();
                }
1178
            }
zYne's avatar
zYne committed
1179
            $parent = $prevPath;
1180
        }
zYne's avatar
zYne committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        return end($this->_aliasMap);
    }
    /**
     * loadRoot
     *
     * @param string $name
     * @param string $componentAlias
     */
    public function loadRoot($name, $componentAlias)
    {
zYne's avatar
zYne committed
1191
        // get the connection for the component
zYne's avatar
zYne committed
1192
        $this->_conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
1193 1194
                      ->getConnectionForComponent($name);

zYne's avatar
zYne committed
1195
        $table = $this->_conn->getTable($name);
zYne's avatar
zYne committed
1196
        $tableName = $table->getTableName();
1197

zYne's avatar
zYne committed
1198
        // get the short alias for this table
zYne's avatar
zYne committed
1199
        $tableAlias = $this->getTableAlias($componentAlias, $tableName);
zYne's avatar
zYne committed
1200
        // quote table name
zYne's avatar
zYne committed
1201
        $queryPart = $this->_conn->quoteIdentifier($tableName);
zYne's avatar
zYne committed
1202 1203 1204

        if ($this->type === self::SELECT) {
            $queryPart .= ' ' . $tableAlias;
1205 1206
        }

zYne's avatar
zYne committed
1207 1208 1209 1210
        $this->parts['from'][] = $queryPart;
        $this->tableAliases[$tableAlias]  = $componentAlias;
        $this->_aliasMap[$componentAlias] = array('table' => $table);
        
1211 1212
        return $table;
    }
zYne's avatar
zYne committed
1213 1214 1215 1216 1217
    /**
      * count
      * fetches the count of the query
      *
      * This method executes the main query without all the
zYne's avatar
zYne committed
1218
     * selected fields, ORDER BY part, LIMIT part and OFFSET part.
1219
     *
zYne's avatar
zYne committed
1220 1221 1222 1223 1224 1225
     * Example:
     * Main query: 
     *      SELECT u.*, p.phonenumber FROM User u
     *          LEFT JOIN u.Phonenumber p 
     *          WHERE p.phonenumber = '123 123' LIMIT 10
     *
1226
     * The modified DQL query:
zYne's avatar
zYne committed
1227 1228 1229 1230 1231
     *      SELECT COUNT(DISTINCT u.id) FROM User u
     *          LEFT JOIN u.Phonenumber p
     *          WHERE p.phonenumber = '123 123'
     *
     * @param array $params        an array of prepared statement parameters
zYne's avatar
zYne committed
1232
     * @return integer             the count of this query
1233
     */
zYne's avatar
zYne committed
1234
    public function count($params = array())
1235
    {
zYne's avatar
zYne committed
1236 1237 1238 1239 1240 1241 1242 1243 1244
        $this->getQuery();

        // initialize temporary variables
        $where  = $this->parts['where'];
        $having = $this->parts['having'];
        $map    = reset($this->_aliasMap);
        $componentAlias = key($this->_aliasMap);
        $table = $map['table'];

zYne's avatar
zYne committed
1245 1246

        // build the query base
zYne's avatar
zYne committed
1247
        $q  = 'SELECT COUNT(DISTINCT ' . $this->getTableAlias($componentAlias)
zYne's avatar
zYne committed
1248 1249
            . '.' . $table->getIdentifier()
            . ') FROM ' . $this->buildFromPart();
1250

zYne's avatar
zYne committed
1251 1252
        // append column aggregation inheritance (if needed)
        $string = $this->applyInheritance();
1253

zYne's avatar
zYne committed
1254 1255 1256 1257 1258
        if ( ! empty($string)) {
            $where[] = $string;
        }
        // append conditions
        $q .= ( ! empty($where)) ?  ' WHERE '  . implode(' AND ', $where) : '';
zYne's avatar
zYne committed
1259
        $q .= ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having): '';
1260

zYne's avatar
zYne committed
1261 1262 1263 1264
        if ( ! is_array($params)) {
            $params = array($params);
        }
        // append parameters
zYne's avatar
zYne committed
1265
        $params = array_merge($this->_params, $params);
1266

zYne's avatar
zYne committed
1267 1268
        return (int) $this->getConnection()->fetchOne($q, $params);
    }
1269

zYne's avatar
zYne committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    /**
     * query
     * query the database with DQL (Doctrine Query Language)
     *
     * @param string $query     DQL query
     * @param array $params     prepared statement parameters
     * @see Doctrine::FETCH_* constants
     * @return mixed
     */
    public function query($query, $params = array())
    {
        $this->parseQuery($query);
1282

zYne's avatar
zYne committed
1283 1284
        return $this->execute($params);
    }
1285
}