Query.php 43.6 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
    public function reset() 
    {
        $this->_pendingJoinConditions = array();
        $this->pendingSubqueries = array();
        $this->pendingFields = array();
        $this->_neededTables = array();
        $this->subqueryAliases = array();
        $this->needsSubquery = false;
        $this->isLimitSubqueryUsed = false;
    }
122 123 124 125 126 127 128 129 130 131 132 133 134
    /**
     * 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;
135
    }
136 137 138 139 140 141 142 143 144 145 146
    /**
     * 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
147 148 149 150 151 152 153 154 155
    /** 
     * 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
156
        $array = (isset($table) || isset($column)) ? array($table, $column) : array();
zYne's avatar
zYne committed
157

zYne's avatar
zYne committed
158 159
        if ($key === '?') {
            $this->_enumParams[] = $array;
zYne's avatar
zYne committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173
        } 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
174 175 176 177 178 179 180 181 182
    /**
     * limitSubqueryUsed
     *
     * @return boolean
     */
    public function isLimitSubqueryUsed()
    {
        return $this->isLimitSubqueryUsed;
    }
zYne's avatar
zYne committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    /**
     * 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;
    }
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
    /**
     * 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
225
     * @param string $dqlAlias      the dql alias of an aggregate value
226 227 228 229
     * @return string
     */
    public function getAggregateAlias($dqlAlias)
    {
zYne's avatar
zYne committed
230
        if (isset($this->aggregateMap[$dqlAlias])) {
231 232
            return $this->aggregateMap[$dqlAlias];
        }
zYne's avatar
zYne committed
233 234 235 236 237 238
        if ( ! empty($this->pendingAggregates)) {
            $this->processPendingAggregates();
            
            return $this->getAggregateAlias($dqlAlias);
        }
        throw new Doctrine_Query_Exception('Unknown aggregate alias ' . $dqlAlias);
239
    }
zYne's avatar
zYne committed
240 241 242 243 244 245 246 247
    /**
     * getParser
     * parser lazy-loader
     *
     * @throws Doctrine_Query_Exception     if unknown parser name given
     * @return Doctrine_Query_Part
     */
    public function getParser($name)
248
    {
zYne's avatar
zYne committed
249 250
        if ( ! isset($this->_parsers[$name])) {
            $class = 'Doctrine_Query_' . ucwords(strtolower($name));
251

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

zYne's avatar
zYne committed
258 259 260 261 262
            $this->_parsers[$name] = new $class($this);
        }
        
        return $this->_parsers[$name];
    }
263 264
    /**
     * parseQueryPart
zYne's avatar
zYne committed
265
     * parses given DQL query part
266 267 268 269 270 271 272 273 274
     *
     * @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
275 276 277 278 279
    {
        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
280

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

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

zYne's avatar
zYne committed
293 294 295 296 297 298 299 300 301 302 303 304 305
        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
306 307 308
        
        $this->_state = Doctrine_Query::STATE_DIRTY;

309
        return $this;
310
    }
zYne's avatar
zYne committed
311 312 313 314 315 316 317 318 319 320
    /**
     * 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
321 322
        $q = '';
        $q .= ( ! empty($this->_dqlParts['select']))?  'SELECT '    . implode(', ', $this->_dqlParts['select']) : '';
323 324 325 326 327 328 329
        $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
330 331 332
        
        return $q;
    }
zYne's avatar
zYne committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346
    /**
     * 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'];
347 348 349 350

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

zYne's avatar
zYne committed
351
            // check for wildcards
zYne's avatar
zYne committed
352
            if (in_array('*', $fields)) {
353 354 355 356 357 358 359 360 361 362 363 364
                $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
365
            $this->parts['select'][] = $tableAlias . '.' .$name . ' AS ' . $tableAlias . '__' . $name;
366 367 368 369 370 371 372 373 374 375 376 377 378 379
        }
        
        $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
380
        $refs = Doctrine_Tokenizer::bracketExplode($dql, ',');
381

382 383 384 385 386 387 388 389 390
        $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
391
        foreach ($refs as $reference) {
zYne's avatar
zYne committed
392
            $reference = trim($reference);
zYne's avatar
zYne committed
393 394 395 396 397
            if (strpos($reference, '(') !== false) {
                if (substr($reference, 0, 1) === '(') {
                    // subselect found in SELECT part
                    $this->parseSubselect($reference);
                } else {
zYne's avatar
zYne committed
398
                    $this->parseAggregateFunction($reference);
zYne's avatar
zYne committed
399
                }
400 401
            } else {

402

403 404 405 406 407 408 409 410 411
                $e = explode('.', $reference);
                if (count($e) > 2) {
                    $this->pendingFields[] = $reference;
                } else {
                    $this->pendingFields[$e[0]][] = $e[1];
                }
            }
        }
    }
zYne's avatar
zYne committed
412 413 414 415 416 417 418 419 420 421 422
    /** 
     * 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
423
        $e     = Doctrine_Tokenizer::bracketExplode($reference, ' ');
zYne's avatar
zYne committed
424 425 426 427 428 429 430 431 432 433 434 435 436
        $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
437 438 439 440 441
    /**
     * parseAggregateFunction
     * parses an aggregate function and returns the parsed form
     *
     * @see Doctrine_Expression
zYne's avatar
zYne committed
442
     * @param string $expr                  DQL aggregate function
zYne's avatar
zYne committed
443 444 445
     * @throws Doctrine_Query_Exception     if unknown aggregate function given
     * @return array                        parsed form of given function
     */
zYne's avatar
zYne committed
446
    public function parseAggregateFunction($expr, $nestedCall = false)
447
    {
zYne's avatar
zYne committed
448
        $e    = Doctrine_Tokenizer::bracketExplode($expr, ' ');
449 450 451
        $func = $e[0];

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

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

zYne's avatar
zYne committed
460 461 462 463 464 465 466
        $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
467
        try {
zYne's avatar
zYne committed
468
            $expr = call_user_func_array(array($this->_conn->expression, $name), $args);
zYne's avatar
zYne committed
469 470
        } catch(Doctrine_Expression_Exception $e) {
            throw new Doctrine_Query_Exception('Unknown function ' . $func . '.');
471
        }
zYne's avatar
zYne committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

        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;
494
    }
zYne's avatar
zYne committed
495 496 497 498 499 500 501 502 503
    /**
     * 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
504 505
    public function processPendingSubqueries() 
    {
zYne's avatar
zYne committed
506
        foreach ($this->pendingSubqueries as $value) {
zYne's avatar
zYne committed
507 508 509 510
            list($dql, $alias) = $value;

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

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

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

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

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

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

zYne's avatar
zYne committed
538 539 540 541 542 543 544 545 546 547 548
            // 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);
549
                    }
zYne's avatar
zYne committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    
                    $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);
566 567
                }
            }
zYne's avatar
zYne committed
568 569 570 571 572 573

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

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

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

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

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

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

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

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

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

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

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

zYne's avatar
zYne committed
641
            }
642

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

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

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

652
            $this->parts['from'][$k] = $part;
653 654
        }
        return $q;
zYne's avatar
zYne committed
655 656 657 658 659 660 661 662 663 664 665 666 667
    }
    /**
     * 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
668 669 670 671 672 673 674 675 676 677 678 679 680
    }
    /**
     * 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()
    {

681 682 683 684 685 686 687 688 689 690 691
    }
    /**
     * 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
692 693 694 695
    	if ($this->_state !== self::STATE_DIRTY) {
    	   return $this->_sql;
    	}

zYne's avatar
zYne committed
696
    	$parts = $this->_dqlParts;
zYne's avatar
zYne committed
697

zYne's avatar
zYne committed
698
        // reset the state
zYne's avatar
zYne committed
699 700 701 702
        $this->_aliasMap = array();
        $this->pendingAggregates = array();
        $this->aggregateMap = array();
        
zYne's avatar
zYne committed
703
        $this->reset();   
zYne's avatar
zYne committed
704

zYne's avatar
zYne committed
705
        // parse the DQL parts
zYne's avatar
zYne committed
706
        foreach ($this->_dqlParts as $queryPartName => $queryParts) {
zYne's avatar
zYne committed
707 708 709
            
            $this->removeQueryPart($queryPartName);

zYne's avatar
zYne committed
710 711 712 713 714 715 716 717 718
            if (is_array($queryParts) && ! empty($queryParts)) {

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

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

                    if (isset($sql)) {
zYne's avatar
zYne committed
719
                        if ($queryPartName == 'limit' ||
zYne's avatar
zYne committed
720 721 722 723 724 725
                            $queryPartName == 'offset') {

                            $this->setQueryPart($queryPartName, $sql);
                        } else {
                            $this->addQueryPart($queryPartName, $sql);
                        }
726 727
                    }
                }
zYne's avatar
zYne committed
728
            }
729
        }
zYne's avatar
zYne committed
730 731
        $params = $this->convertEnums($params);

zYne's avatar
zYne committed
732 733 734 735 736 737 738
        $this->_state = self::STATE_DIRECT;

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

zYne's avatar
zYne committed
740
        if (empty($this->parts['from'])) {
741
            return false;
zYne's avatar
zYne committed
742
        }
743 744 745

        $needsSubQuery = false;
        $subquery = '';
zYne's avatar
zYne committed
746 747 748
        $map   = reset($this->_aliasMap);
        $table = $map['table'];
        $rootAlias = key($this->_aliasMap);
749

zYne's avatar
zYne committed
750
        if ( ! empty($this->parts['limit']) && $this->needsSubquery && $table->getAttribute(Doctrine::ATTR_QUERY_LIMIT) == Doctrine::LIMIT_RECORDS) {
zYne's avatar
zYne committed
751
            $this->isLimitSubqueryUsed = true;
752 753 754
            $needsSubQuery = true;
        }

zYne's avatar
zYne committed
755 756
        // process all pending SELECT part subqueries
        $this->processPendingSubqueries();
zYne's avatar
zYne committed
757
        $this->processPendingAggregates();
zYne's avatar
zYne committed
758

759 760
        // build the basic query

zYne's avatar
zYne committed
761 762 763 764
        $q  = $this->getQueryBase();
        $q .= $this->buildFromPart();

        if ( ! empty($this->parts['set'])) {
765 766 767 768
            $q .= ' SET ' . implode(', ', $this->parts['set']);
        }


zYne's avatar
zYne committed
769 770 771
        $string = $this->applyInheritance();
        
        // apply inheritance to WHERE part
zYne's avatar
zYne committed
772 773 774
        if ( ! empty($string)) {
            $this->parts['where'][] = '(' . $string . ')';
        }
775 776 777


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

zYne's avatar
zYne committed
780
            if ($needsSubQuery) {
781 782 783
                $subquery = $this->getLimitSubquery();


zYne's avatar
zYne committed
784
                switch (strtolower($this->_conn->getName())) {
785 786
                    case 'mysql':
                        // mysql doesn't support LIMIT in subqueries
zYne's avatar
zYne committed
787
                        $list     = $this->_conn->execute($subquery, $params)->fetchAll(Doctrine::FETCH_COLUMN);
788
                        $subquery = implode(', ', $list);
zYne's avatar
zYne committed
789
                        break;
790 791 792
                    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
793
                        break;
794 795
                }

zYne's avatar
zYne committed
796
                $field = $this->getTableAlias($rootAlias) . '.' . $table->getIdentifier();
797 798

                // only append the subquery if it actually contains something
zYne's avatar
zYne committed
799
                if ($subquery !== '') {
800
                    array_unshift($this->parts['where'], $field. ' IN (' . $subquery . ')');
zYne's avatar
zYne committed
801
                }
802 803 804 805 806

                $modifyLimit = false;
            }
        }

zYne's avatar
zYne committed
807 808 809 810
        $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'])  : '';
811

zYne's avatar
zYne committed
812 813
        if ($modifyLimit) {    

zYne's avatar
zYne committed
814
            $q = $this->_conn->modifyLimitQuery($q, $this->parts['limit'], $this->parts['offset']);
zYne's avatar
zYne committed
815
        }
816 817

        // return to the previous state
zYne's avatar
zYne committed
818
        if ( ! empty($string)) {
819
            array_pop($this->parts['where']);
zYne's avatar
zYne committed
820 821
        }
        if ($needsSubQuery) {
822
            array_shift($this->parts['where']);
zYne's avatar
zYne committed
823
        }
zYne's avatar
zYne committed
824
        $this->_sql = $q;
825

826 827 828
        return $q;
    }
    /**
zYne's avatar
zYne committed
829
     * getLimitSubquery
830 831 832 833 834 835 836 837 838 839
     * 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
840 841 842
        $map    = reset($this->_aliasMap);
        $table  = $map['table'];
        $componentAlias = key($this->_aliasMap);
843 844

        // get short alias
zYne's avatar
zYne committed
845
        $alias      = $this->getTableAlias($componentAlias);
846 847 848 849 850
        $primaryKey = $alias . '.' . $table->getIdentifier();

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

851
        if ($this->_conn->getAttribute(Doctrine::ATTR_DRIVER_NAME) == 'pgsql') {
852 853
            // pgsql needs the order by fields to be preserved in select clause

zYne's avatar
zYne committed
854
            foreach ($this->parts['orderby'] as $part) {
855 856 857
                $e = explode(' ', $part);

                // don't add primarykey column (its already in the select clause)
zYne's avatar
zYne committed
858
                if ($e[0] !== $primaryKey) {
859
                    $subquery .= ', ' . $e[0];
zYne's avatar
zYne committed
860
                }
861 862 863
            }
        }

zYne's avatar
zYne committed
864
        $subquery .= ' FROM';
865

866

zYne's avatar
zYne committed
867 868
        foreach ($this->parts['from'] as $part) {
            // preserve LEFT JOINs only if needed
zYne's avatar
zYne committed
869
            if (substr($part, 0, 9) === 'LEFT JOIN') {
zYne's avatar
zYne committed
870
                $e = explode(' ', $part);
871 872
                
                if (empty($this->parts['orderby']) && empty($this->parts['where'])) {
zYne's avatar
zYne committed
873
                    continue;
874 875
                }
            }
zYne's avatar
zYne committed
876 877

            $subquery .= ' ' . $part;
878 879 880 881 882 883
        }

        // 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
884 885

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

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

zYne's avatar
zYne committed
890
        $parts = Doctrine_Tokenizer::quoteExplode($subquery, ' ', "'", "'");
891 892 893 894 895 896

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

zYne's avatar
zYne committed
897
            if($this->hasTableAlias($part)) {
zYne's avatar
zYne committed
898
                $parts[$k] = $this->generateNewTableAlias($part);
899 900 901 902 903 904 905 906
            }

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

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

zYne's avatar
zYne committed
907
                $e[0] = substr($e[0], 0, $pos) . $this->generateNewTableAlias($trimmed);
908 909 910 911 912 913 914 915
                $parts[$k] = implode('.', $e);
            }
        }
        $subquery = implode(' ', $parts);

        return $subquery;
    }
    /**
zYne's avatar
zYne committed
916
     * tokenizeQuery
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
     * 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
934
    public function tokenizeQuery($query)
935
    {
zYne's avatar
zYne committed
936
        $e = Doctrine_Tokenizer::sqlExplode($query, ' ');
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

        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
986
        if ($clear) {
987
            $this->clear();
zYne's avatar
zYne committed
988
        }
989 990 991 992 993

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

zYne's avatar
zYne committed
994
        $parts = $this->tokenizeQuery($query);
995 996 997

        foreach($parts as $k => $part) {
            $part = implode(' ', $part);
zYne's avatar
zYne committed
998 999
            $k = strtolower($k);
            switch ($k) {
zYne's avatar
zYne committed
1000
                case 'create':
1001 1002
                    $this->type = self::CREATE;
                break;
zYne's avatar
zYne committed
1003
                case 'insert':
1004 1005
                    $this->type = self::INSERT;
                break;
zYne's avatar
zYne committed
1006
                case 'delete':
1007 1008
                    $this->type = self::DELETE;
                break;
zYne's avatar
zYne committed
1009
                case 'select':
1010
                    $this->type = self::SELECT;
zYne's avatar
zYne committed
1011
                    $this->parseQueryPart($k, $part);
1012
                break;
zYne's avatar
zYne committed
1013
                case 'update':
1014
                    $this->type = self::UPDATE;
zYne's avatar
zYne committed
1015
                    $k = 'from';
zYne's avatar
zYne committed
1016
                case 'from':
zYne's avatar
zYne committed
1017
                    $this->parseQueryPart($k, $part);
1018
                break;
zYne's avatar
zYne committed
1019
                case 'set':
zYne's avatar
zYne committed
1020
                    $this->parseQueryPart($k, $part, true);
1021
                break;
zYne's avatar
zYne committed
1022 1023
                case 'group':
                case 'order':
1024
                    $k .= 'by';
zYne's avatar
zYne committed
1025 1026 1027 1028
                case 'where':
                case 'having':
                case 'limit':
                case 'offset':
zYne's avatar
zYne committed
1029
                    $this->parseQueryPart($k, $part);
1030 1031 1032 1033 1034 1035
                break;
            }
        }

        return $this;
    }
zYne's avatar
zYne committed
1036
    public function load($path, $loadFields = true) 
1037 1038 1039 1040 1041
    {
        // parse custom join conditions
        $e = explode(' ON ', $path);
        
        $joinCondition = '';
zYne's avatar
zYne committed
1042 1043

        if (count($e) > 1) {
1044
            $joinCondition = $e[1];
1045 1046 1047
            $path = $e[0];
        }

zYne's avatar
zYne committed
1048 1049
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
1050 1051 1052

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

zYne's avatar
zYne committed
1053 1054 1055
        $fullPath = $tmp[0];
        $prevPath = '';
        $fullLength = strlen($fullPath);
1056

zYne's avatar
zYne committed
1057 1058
        if (isset($this->_aliasMap[$e[0]])) {
            $table = $this->_aliasMap[$e[0]]['table'];
1059

zYne's avatar
zYne committed
1060 1061
            $prevPath = $parent = array_shift($e);
        }
1062

zYne's avatar
zYne committed
1063 1064 1065
        foreach ($e as $key => $name) {
            // get length of the previous path
            $length = strlen($prevPath);
1066

zYne's avatar
zYne committed
1067 1068
            // build the current component path
            $prevPath = ($prevPath) ? $prevPath . '.' . $name : $name;
1069

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

zYne's avatar
zYne committed
1072 1073 1074 1075 1076 1077
            // 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
1078 1079 1080 1081 1082
            
            // if the current alias already exists, skip it
            if (isset($this->_aliasMap[$componentAlias])) {
                continue;
            }
1083

zYne's avatar
zYne committed
1084 1085
            if ( ! isset($table)) {
                // process the root of the path
1086

zYne's avatar
zYne committed
1087 1088 1089
                $table = $this->loadRoot($name, $componentAlias);
            } else {
                $join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN ';
1090

zYne's avatar
zYne committed
1091
                $relation = $table->getRelation($name);
zYne's avatar
zYne committed
1092 1093
                $table    = $relation->getTable();
                $this->_aliasMap[$componentAlias] = array('table'    => $table,
zYne's avatar
zYne committed
1094 1095 1096 1097 1098
                                                          'parent'   => $parent,
                                                          'relation' => $relation);
                if ( ! $relation->isOneToOne()) {
                   $this->needsSubquery = true;
                }
1099

zYne's avatar
zYne committed
1100 1101
                $localAlias   = $this->getTableAlias($parent, $table->getTableName());
                $foreignAlias = $this->getTableAlias($componentAlias, $relation->getTable()->getTableName());
zYne's avatar
zYne committed
1102 1103
                $localSql     = $this->_conn->quoteIdentifier($table->getTableName()) . ' ' . $localAlias;
                $foreignSql   = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) . ' ' . $foreignAlias;
1104

zYne's avatar
zYne committed
1105 1106 1107 1108 1109
                $map = $relation->getTable()->inheritanceMap;
  
                if ( ! $loadFields || ! empty($map) || $joinCondition) {
                    $this->subqueryAliases[] = $foreignAlias;
                }
1110

zYne's avatar
zYne committed
1111 1112 1113 1114 1115 1116 1117
                if ($relation instanceof Doctrine_Relation_Association) {
                    $asf = $relation->getAssociationFactory();
  
                    $assocTableName = $asf->getTableName();
  
                    if( ! $loadFields || ! empty($map) || $joinCondition) {
                        $this->subqueryAliases[] = $assocTableName;
1118 1119
                    }

zYne's avatar
zYne committed
1120 1121
                    $assocPath = $prevPath . '.' . $asf->getComponentName();
  
zYne's avatar
zYne committed
1122
                    $assocAlias = $this->getTableAlias($assocPath, $asf->getTableName());
1123

zYne's avatar
zYne committed
1124
                    $queryPart = $join . $assocTableName . ' ' . $assocAlias . ' ON ' . $localAlias  . '.'
1125 1126 1127 1128 1129 1130 1131
                                                               . $table->getIdentifier() . ' = '
                                                               . $assocAlias . '.' . $relation->getLocal();

                    if ($relation->isEqual()) {
                        $queryPart .= ' OR ' . $localAlias  . '.'
                                    . $table->getIdentifier() . ' = '
                                    . $assocAlias . '.' . $relation->getForeign();
1132 1133 1134

                    }

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

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                    $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();
1150 1151
                    }

zYne's avatar
zYne committed
1152
                } else {
1153

zYne's avatar
zYne committed
1154 1155
                    $queryPart = $join . $foreignSql
                                       . ' ON ' . $localAlias .  '.'
1156 1157 1158 1159 1160
                                       . $relation->getLocal() . ' = ' . $foreignAlias . '.' . $relation->getForeign();
                }
                $this->parts['from'][$componentAlias] = $queryPart;
                if ( ! empty($joinCondition)) {
                    $this->_pendingJoinConditions[$componentAlias] = $joinCondition;
1161
                }
zYne's avatar
zYne committed
1162 1163
            }
            if ($loadFields) {
zYne's avatar
zYne committed
1164
                                 
zYne's avatar
zYne committed
1165 1166 1167 1168 1169
                $restoreState = false;
                // load fields if necessary
                if ($loadFields && empty($this->pendingFields) 
                    && empty($this->pendingAggregates)
                    && empty($this->pendingSubqueries)) {
1170

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

zYne's avatar
zYne committed
1173 1174
                    $restoreState = true;
                }
1175

zYne's avatar
zYne committed
1176 1177
                if(isset($this->pendingFields[$componentAlias])) {
                    $this->processPendingFields($componentAlias);
1178
                }
zYne's avatar
zYne committed
1179
                /**
zYne's avatar
zYne committed
1180 1181 1182
                if(isset($this->pendingAggregates[$componentAlias]) || isset($this->pendingAggregates[0])) {
                    $this->processPendingAggregates($componentAlias);
                }
zYne's avatar
zYne committed
1183
                */
1184

zYne's avatar
zYne committed
1185 1186 1187 1188
                if ($restoreState) {
                    $this->pendingFields = array();
                    $this->pendingAggregates = array();
                }
1189
            }
zYne's avatar
zYne committed
1190
            $parent = $prevPath;
1191
        }
zYne's avatar
zYne committed
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
        return end($this->_aliasMap);
    }
    /**
     * loadRoot
     *
     * @param string $name
     * @param string $componentAlias
     */
    public function loadRoot($name, $componentAlias)
    {
zYne's avatar
zYne committed
1202
        // get the connection for the component
zYne's avatar
zYne committed
1203
        $this->_conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
1204 1205
                      ->getConnectionForComponent($name);

zYne's avatar
zYne committed
1206
        $table = $this->_conn->getTable($name);
zYne's avatar
zYne committed
1207
        $tableName = $table->getTableName();
1208

zYne's avatar
zYne committed
1209
        // get the short alias for this table
zYne's avatar
zYne committed
1210
        $tableAlias = $this->getTableAlias($componentAlias, $tableName);
zYne's avatar
zYne committed
1211
        // quote table name
zYne's avatar
zYne committed
1212
        $queryPart = $this->_conn->quoteIdentifier($tableName);
zYne's avatar
zYne committed
1213 1214 1215

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

zYne's avatar
zYne committed
1218 1219 1220 1221
        $this->parts['from'][] = $queryPart;
        $this->tableAliases[$tableAlias]  = $componentAlias;
        $this->_aliasMap[$componentAlias] = array('table' => $table);
        
1222 1223
        return $table;
    }
zYne's avatar
zYne committed
1224 1225 1226 1227 1228
    /**
      * count
      * fetches the count of the query
      *
      * This method executes the main query without all the
zYne's avatar
zYne committed
1229
     * selected fields, ORDER BY part, LIMIT part and OFFSET part.
1230
     *
zYne's avatar
zYne committed
1231 1232 1233 1234 1235 1236
     * Example:
     * Main query: 
     *      SELECT u.*, p.phonenumber FROM User u
     *          LEFT JOIN u.Phonenumber p 
     *          WHERE p.phonenumber = '123 123' LIMIT 10
     *
1237
     * The modified DQL query:
zYne's avatar
zYne committed
1238 1239 1240 1241 1242
     *      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
1243
     * @return integer             the count of this query
1244
     */
zYne's avatar
zYne committed
1245
    public function count($params = array())
1246
    {
zYne's avatar
zYne committed
1247 1248 1249 1250 1251 1252 1253 1254 1255
        $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
1256 1257

        // build the query base
zYne's avatar
zYne committed
1258
        $q  = 'SELECT COUNT(DISTINCT ' . $this->getTableAlias($componentAlias)
zYne's avatar
zYne committed
1259 1260
            . '.' . $table->getIdentifier()
            . ') FROM ' . $this->buildFromPart();
1261

zYne's avatar
zYne committed
1262 1263
        // append column aggregation inheritance (if needed)
        $string = $this->applyInheritance();
1264

zYne's avatar
zYne committed
1265 1266 1267 1268 1269
        if ( ! empty($string)) {
            $where[] = $string;
        }
        // append conditions
        $q .= ( ! empty($where)) ?  ' WHERE '  . implode(' AND ', $where) : '';
zYne's avatar
zYne committed
1270
        $q .= ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having): '';
1271

zYne's avatar
zYne committed
1272 1273 1274 1275
        if ( ! is_array($params)) {
            $params = array($params);
        }
        // append parameters
zYne's avatar
zYne committed
1276
        $params = array_merge($this->_params, $params);
1277

zYne's avatar
zYne committed
1278 1279
        return (int) $this->getConnection()->fetchOne($q, $params);
    }
1280

zYne's avatar
zYne committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    /**
     * 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);
1293

zYne's avatar
zYne committed
1294 1295
        return $this->execute($params);
    }
1296
}