Query.php 51.6 KB
Newer Older
lsmith's avatar
lsmith committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
<?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>.
 */
Doctrine::autoload('Doctrine_Hydrate');
/**
 * 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>
 */
class Doctrine_Query extends Doctrine_Hydrate implements Countable {
    /**
     * @param array $subqueryAliases        the table aliases needed in some LIMIT subqueries
     */
    private $subqueryAliases  = array();
    /**
     * @param boolean $needsSubquery
     */
    private $needsSubquery    = false;
    /**
     * @param boolean $limitSubqueryUsed
     */
    private $limitSubqueryUsed = false;
zYne's avatar
zYne committed
46 47 48 49 50
    /**
     * @param boolean $isSubquery           whether or not this query object is a subquery of another 
     *                                      query object
     */
    private $isSubquery;
lsmith's avatar
lsmith committed
51 52 53 54 55 56

    private $tableStack;

    private $relationStack     = array();

    private $isDistinct        = false;
57
    
zYne's avatar
zYne committed
58 59
    protected $components      = array();
    
60
    private $neededTables      = array();
lsmith's avatar
lsmith committed
61 62 63 64
    /**
     * @var array $pendingFields
     */
    private $pendingFields     = array();
65

66

lsmith's avatar
lsmith committed
67 68 69 70 71 72 73 74 75 76 77

    /**
     * create
     * returns a new Doctrine_Query object
     *
     * @return Doctrine_Query
     */
    public static function create()
    {
        return new Doctrine_Query();
    }
zYne's avatar
zYne committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    /**
     * 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;
        }
lsmith's avatar
lsmith committed
96

zYne's avatar
zYne committed
97 98 99
        $this->isSubquery = (bool) $bool;
        return $this;
    }
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114
    /**
     * getAggregateAlias
     * 
     * @return string
     */
    public function getAggregateAlias($dqlAlias)
    {
        if(isset($this->aggregateMap[$dqlAlias])) {
            return $this->aggregateMap[$dqlAlias];
        }
        
        return null;
    }

lsmith's avatar
lsmith committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    public function getTableStack()
    {
        return $this->tableStack;
    }

    public function getRelationStack()
    {
        return $this->relationStack;
    }

    public function isDistinct($distinct = null)
    {
        if(isset($distinct))
            $this->isDistinct = (bool) $distinct;

        return $this->isDistinct;
    }

    public function processPendingFields($componentAlias)
    {
        $tableAlias = $this->getTableAlias($componentAlias);

zYne's avatar
zYne committed
137
        if ( ! isset($this->tables[$tableAlias]))
gnat's avatar
gnat committed
138
            throw new Doctrine_Query_Exception('Unknown component path '.$componentAlias);
lsmith's avatar
lsmith committed
139 140 141

        $table      = $this->tables[$tableAlias];

zYne's avatar
zYne committed
142
        if (isset($this->pendingFields[$componentAlias])) {
lsmith's avatar
lsmith committed
143 144
            $fields = $this->pendingFields[$componentAlias];

zYne's avatar
zYne committed
145
            if(in_array('*', $fields)) {
lsmith's avatar
lsmith committed
146
                $fields = $table->getColumnNames();
zYne's avatar
zYne committed
147 148 149 150 151 152 153
            } 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));
                }
            }
lsmith's avatar
lsmith committed
154
        }
zYne's avatar
zYne committed
155 156
        foreach ($fields as $name) {
            $name = $table->getColumnName($name);
157

lsmith's avatar
lsmith committed
158 159
            $this->parts["select"][] = $tableAlias . '.' .$name . ' AS ' . $tableAlias . '__' . $name;
        }
160 161
        
        $this->neededTables[] = $tableAlias;
lsmith's avatar
lsmith committed
162 163

    }
zYne's avatar
zYne committed
164 165 166 167 168 169 170
    /**
     * parseSelect
     * parses the query select part and
     * adds selected fields to pendingFields array
     *
     * @param string $dql
     */
lsmith's avatar
lsmith committed
171 172 173 174 175 176 177 178 179 180
    public function parseSelect($dql)
    {
        $refs = Doctrine_Query::bracketExplode($dql, ',');

        foreach($refs as $reference) {
            if(strpos($reference, '(') !== false) {
                $this->parseAggregateFunction2($reference);
            } else {

                $e = explode('.', $reference);
181
                if (count($e) > 2) {
lsmith's avatar
lsmith committed
182
                    $this->pendingFields[] = $reference;
183
                } else {
lsmith's avatar
lsmith committed
184
                    $this->pendingFields[$e[0]][] = $e[1];
185
                }
lsmith's avatar
lsmith committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199
            }
        }
    }
    public function parseAggregateFunction2($func)
    {
        $e    = Doctrine_Query::bracketExplode($func, ' ');
        $func = $e[0];

        $pos  = strpos($func, '(');
        $name = substr($func, 0, $pos);


        if(method_exists($this->conn->expression, $name)) {

zYne's avatar
zYne committed
200
            $argStr = substr($func, ($pos + 1), -1);
zYne's avatar
zYne committed
201
            $args   = explode(',', $argStr);
lsmith's avatar
lsmith committed
202

zYne's avatar
zYne committed
203
            $func   = call_user_func_array(array($this->conn->expression, $name), $args);
lsmith's avatar
lsmith committed
204

zYne's avatar
zYne committed
205 206 207 208 209 210 211 212
            if(substr($func, 0, 1) !== '(') {
                $pos  = strpos($func, '(');
                $name = substr($func, 0, $pos);
            } else {
                $name = $func;
            }

            $e2     = explode(' ', $args[0]);
lsmith's avatar
lsmith committed
213

zYne's avatar
zYne committed
214 215 216 217
            $distinct = '';
            if(count($e2) > 1) {
                if(strtoupper($e2[0]) == 'DISTINCT')
                    $distinct  = 'DISTINCT ';
lsmith's avatar
lsmith committed
218

zYne's avatar
zYne committed
219 220
                $args[0] = $e2[1];
            }
lsmith's avatar
lsmith committed
221 222 223



zYne's avatar
zYne committed
224 225 226
            $parts = explode('.', $args[0]);
            $owner = $parts[0];
            $alias = (isset($e[1])) ? $e[1] : $name;
lsmith's avatar
lsmith committed
227

zYne's avatar
zYne committed
228
            $e3    = explode('.', $alias);
lsmith's avatar
lsmith committed
229

zYne's avatar
zYne committed
230 231 232 233
            if(count($e3) > 1) {
                $alias = $e3[1];
                $owner = $e3[0];
            }
lsmith's avatar
lsmith committed
234

zYne's avatar
zYne committed
235 236 237 238 239
            // a function without parameters eg. RANDOM()
            if ($owner === '') {
                $owner = 0;
            }

zYne's avatar
zYne committed
240
            $this->pendingAggregates[$owner][] = array($name, $args, $distinct, $alias);
lsmith's avatar
lsmith committed
241
        } else {
zYne's avatar
zYne committed
242
            throw new Doctrine_Query_Exception('Unknown function '.$name);
lsmith's avatar
lsmith committed
243 244 245 246 247 248
        }
    }
    public function processPendingAggregates($componentAlias)
    {
        $tableAlias     = $this->getTableAlias($componentAlias);

zYne's avatar
zYne committed
249
        if ( ! isset($this->tables[$tableAlias])) {
gnat's avatar
gnat committed
250
            throw new Doctrine_Query_Exception('Unknown component path ' . $componentAlias);
zYne's avatar
zYne committed
251 252 253
        }
        
        $root       = current($this->tables);
lsmith's avatar
lsmith committed
254
        $table      = $this->tables[$tableAlias];
zYne's avatar
zYne committed
255 256 257 258 259 260 261 262 263 264 265
        $aggregates = array();

        if(isset($this->pendingAggregates[$componentAlias])) {
            $aggregates = $this->pendingAggregates[$componentAlias];
        }
        
        if ($root === $table) {
            if (isset($this->pendingAggregates[0])) {
                $aggregates += $this->pendingAggregates[0];
            }
        }
lsmith's avatar
lsmith committed
266

zYne's avatar
zYne committed
267
        foreach($aggregates as $parts) {
lsmith's avatar
lsmith committed
268 269 270 271 272 273 274 275
            list($name, $args, $distinct, $alias) = $parts;

            $arglist = array();
            foreach($args as $arg) {
                $e = explode('.', $arg);


                if(count($e) > 1) {
zYne's avatar
zYne committed
276
                    //$tableAlias = $this->getTableAlias($e[0]);
lsmith's avatar
lsmith committed
277 278
                    $table      = $this->tables[$tableAlias];

zYne's avatar
zYne committed
279 280
                    $e[1]       = $table->getColumnName($e[1]);

lsmith's avatar
lsmith committed
281 282 283 284 285 286 287 288 289 290
                    if( ! $table->hasColumn($e[1])) {
                        throw new Doctrine_Query_Exception('Unknown column ' . $e[1]);
                    }

                    $arglist[]  = $tableAlias . '.' . $e[1];
                } else {
                    $arglist[]  = $e[0];
                }
            }

291 292
            $sqlAlias = $tableAlias . '__' . count($this->aggregateMap);

zYne's avatar
zYne committed
293 294 295 296 297
            if(substr($name, 0, 1) !== '(') {
                $this->parts['select'][] = $name . '(' . $distinct . implode(', ', $arglist) . ') AS ' . $sqlAlias;
            } else {
                $this->parts['select'][] = $name . ' AS ' . $sqlAlias;
            }
298
            $this->aggregateMap[$alias] = $sqlAlias;
299
            $this->neededTables[] = $tableAlias;
lsmith's avatar
lsmith committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        }
    }
	/**
 	 * count
     *
     * @param array $params
	 * @return integer
     */
	public function count($params = array())
    {
		$this->remove('select');
		$join  = $this->join;
		$where = $this->where;
		$having = $this->having;
		$table  = reset($this->tables);

		$q  = 'SELECT COUNT(DISTINCT ' . $this->aliasHandler->getShortAlias($table->getTableName())
            . '.' . $table->getIdentifier()
            . ') FROM ' . $table->getTableName() . ' ' . $this->aliasHandler->getShortAlias($table->getTableName());

		foreach($join as $j) {
            $q .= ' '.implode(' ',$j);
		}
        $string = $this->applyInheritance();

        if( ! empty($where)) {
            $q .= ' WHERE ' . implode(' AND ', $where);
            if( ! empty($string))
                $q .= ' AND (' . $string . ')';
        } else {
            if( ! empty($string))
                $q .= ' WHERE (' . $string . ')';
        }
			
		if( ! empty($having))
			$q .= ' HAVING ' . implode(' AND ',$having);

        if( ! is_array($params))
            $params = array($params);

        $params = array_merge($this->params, $params);

zYne's avatar
zYne committed
342
		return (int) $this->getConnection()->fetchOne($q, $params);
lsmith's avatar
lsmith committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
	}
    /**
     * loadFields
     * loads fields for a given table and
     * constructs a little bit of sql for every field
     *
     * fields of the tables become: [tablename].[fieldname] as [tablename]__[fieldname]
     *
     * @access private
     * @param object Doctrine_Table $table          a Doctrine_Table object
     * @param integer $fetchmode                    fetchmode the table is using eg. Doctrine::FETCH_LAZY
     * @param array $names                          fields to be loaded (only used in lazy property loading)
     * @return void
     */
    protected function loadFields(Doctrine_Table $table, $fetchmode, array $names, $cpath)
    {
        $name = $table->getComponentName();

        switch($fetchmode):
            case Doctrine::FETCH_OFFSET:
                $this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT);
            case Doctrine::FETCH_IMMEDIATE:
zYne's avatar
zYne committed
365 366 367
                if( ! empty($names)) {
                    // only auto-add the primary key fields if this query object is not
                    // a subquery of another query object
lsmith's avatar
lsmith committed
368
                    $names = array_unique(array_merge($table->getPrimaryKeys(), $names));
zYne's avatar
zYne committed
369
                } else {
lsmith's avatar
lsmith committed
370
                    $names = $table->getColumnNames();
zYne's avatar
zYne committed
371
                }
lsmith's avatar
lsmith committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
            break;
            case Doctrine::FETCH_LAZY_OFFSET:
                $this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT);
            case Doctrine::FETCH_LAZY:
            case Doctrine::FETCH_BATCH:
                $names = array_unique(array_merge($table->getPrimaryKeys(), $names));
            break;
            default:
                throw new Doctrine_Exception("Unknown fetchmode.");
        endswitch;

        $component          = $table->getComponentName();
        $tablename          = $this->tableAliases[$cpath];

        $this->fetchModes[$tablename] = $fetchmode;

        $count = count($this->tables);

        foreach($names as $name) {
            if($count == 0) {
                $this->parts['select'][] = $tablename . '.' . $name;
            } else {
                $this->parts['select'][] = $tablename . '.' . $name . ' AS ' . $tablename . '__' . $name;
            }
        }
    }
    /**
     * addFrom
     *
     * @param strint $from
     * @return Doctrine_Query
     */
    public function addFrom($from)
    {
        $class = 'Doctrine_Query_From';
        $parser = new $class($this);
        $parser->parse($from);

        return $this;
    }
    /**
     * leftJoin
     *
     * @param strint $join
     * @return Doctrine_Query
     */
    public function leftJoin($join)
    {
        $class = 'Doctrine_Query_From';
        $parser = new $class($this);
        $parser->parse('LEFT JOIN ' . $join);

        return $this;
    }
    /**
     * innerJoin
     *
     * @param strint $join
     * @return Doctrine_Query
     */
    public function innerJoin($join)
    {
        $class = 'Doctrine_Query_From';
        $parser = new $class($this);
        $parser->parse('INNER JOIN ' . $join);

        return $this;
    }
    /**
     * addOrderBy
     *
     * @param strint $orderby
     * @return Doctrine_Query
     */
    public function addOrderBy($orderby)
    {
        $class = 'Doctrine_Query_Orderby';
        $parser = new $class($this);
        $this->parts['orderby'][] = $parser->parse($orderby);

        return $this;
    }
    /**
     * addWhere
     *
     * @param string $where
     * @param mixed $params
     */
    public function addWhere($where, $params = array())
    {
        $class  = 'Doctrine_Query_Where';
        $parser = new $class($this);
        $this->parts['where'][] = $parser->parse($where);

        if(is_array($params)) {
            $this->params = array_merge($this->params, $params);
        } else {
            $this->params[] = $params;
        }
    }
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    /**
     * addSelect
     *
     * @param string $select
     */
    public function addSelect($select)
    {
        $this->type = self::SELECT;
        
        $this->parseSelect($select);
        
        return $this;
    }
    /**
     * addHaving
     *
     * @param string $having
     */
    public function addHaving($having) 
    {
        $class = 'Doctrine_Query_Having';
        $parser = new $class($this);
gnat's avatar
gnat committed
494
        $this->parts['having'][] = $parser->parse($having);
495 496 497
        
        return $this;
    }
lsmith's avatar
lsmith committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    /**
     * sets a query part
     *
     * @param string $name
     * @param array $args
     * @return void
     */
    public function __call($name, $args)
    {
        $name = strtolower($name);

        $method = 'parse' . ucwords($name);

        switch($name) {
            case 'select':
                $this->type = self::SELECT;

515
                if ( ! isset($args[0])) {
lsmith's avatar
lsmith committed
516
                    throw new Doctrine_Query_Exception('Empty select part');
517
                }
lsmith's avatar
lsmith committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
                $this->parseSelect($args[0]);
            break;
            case 'delete':
                $this->type = self::DELETE;
            break;
            case 'update':
                $this->type = self::UPDATE;
                $name       = 'from';
            case 'from':
                $this->parts['from']    = array();
                $this->parts['select']  = array();
                $this->parts['join']    = array();
                $this->joins            = array();
                $this->tables           = array();
                $this->fetchModes       = array();
                $this->tableIndexes     = array();
                $this->tableAliases     = array();
                $this->aliasHandler->clear();

                $class = "Doctrine_Query_".ucwords($name);
                $parser = new $class($this);

                $parser->parse($args[0]);
            break;
            case 'where':
                if(isset($args[1])) {
                    if(is_array($args[1])) {
                        $this->params = $args[1];
                    } else {
                        $this->params = array($args[1]);
                    }
                }
            case 'having':
            case 'orderby':
            case 'groupby':
                $class = "Doctrine_Query_".ucwords($name);
                $parser = new $class($this);

                $this->parts[$name] = array($parser->parse($args[0]));
            break;
            case 'limit':
            case 'offset':
                if($args[0] == null)
                    $args[0] = false;

                $this->parts[$name] = $args[0];
            break;
            default:
                $this->parts[$name] = array();
                $this->$method($args[0]);

            throw new Doctrine_Query_Exception("Unknown overload method");
        }


        return $this;
    }
    /**
     * returns a query part
     *
     * @param $name         query part name
     * @return mixed
     */
    public function get($name)
    {
        if( ! isset($this->parts[$name]))
            return false;

        return $this->parts[$name];
    }
    /**
     * set
     * sets a query SET part
     * this method should only be used with UPDATE queries
     *
     * @param $name             name of the field
     * @param $value            field value
     * @return Doctrine_Query
     */
    public function set($name, $value)
    {
        $class = new Doctrine_Query_Set($this);
        $this->parts['set'][] = $class->parse($name . ' = ' . $value);

        return $this;
    }
    /**
     * @return boolean
     */
    public function isLimitSubqueryUsed() {
        return $this->limitSubqueryUsed;
    }
    /**
     * getQueryBase
     * returns the base of the generated sql query
     * On mysql driver special strategy has to be used for DELETE statements
     *
     * @return string       the base of the generated sql query
     */
    public function getQueryBase()
    {
619
        switch ($this->type) {
lsmith's avatar
lsmith committed
620
            case self::DELETE:
621 622 623
            /**
                no longer needed? 

624
                if ($this->conn->getName() == 'Mysql') {
625
                    $q = 'DELETE '  . end($this->tableAliases) . ' FROM ';
626
                } else {
627
            */
lsmith's avatar
lsmith committed
628
                    $q = 'DELETE FROM ';
629
            //    }
lsmith's avatar
lsmith committed
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
            break;
            case self::UPDATE:
                $q = 'UPDATE ';
            break;
            case self::SELECT:
                $distinct = ($this->isDistinct()) ? 'DISTINCT ' : '';

                $q = 'SELECT '.$distinct.implode(', ', $this->parts['select']).' FROM ';
            break;
        }
        return $q;
    }
    /**
     * 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())
    {
        if(empty($this->parts["select"]) || empty($this->parts["from"]))
            return false;

        $needsSubQuery = false;
        $subquery = '';
        $k  = array_keys($this->tables);
        $table = $this->tables[$k[0]];

        if( ! empty($this->parts['limit']) && $this->needsSubquery && $table->getAttribute(Doctrine::ATTR_QUERY_LIMIT) == Doctrine::LIMIT_RECORDS) {
            $needsSubQuery = true;
            $this->limitSubqueryUsed = true;
        }

        // build the basic query

        $str = '';
        if($this->isDistinct())
            $str = 'DISTINCT ';

        $q = $this->getQueryBase();

        $q .= $this->parts['from'];
674 675 676 677 678 679 680 681
        /**
        var_dump($this->pendingFields);
        var_dump($this->subqueryAliases);  */
        //var_dump($this->parts['join']);

        foreach($this->parts['join'] as $parts) {
            foreach($parts as $part) {
                // preserve LEFT JOINs only if needed
lsmith's avatar
lsmith committed
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
                if(substr($part, 0,9) === 'LEFT JOIN') {
                    $e = explode(' ', $part);

                    $aliases = array_merge($this->subqueryAliases, 
                                array_keys($this->neededTables));


                    if( ! in_array($e[3], $aliases) &&
                        ! in_array($e[2], $aliases) &&

                        ! empty($this->pendingFields)) {
                        continue;
                    }

                }

                $e = explode(' ON ', $part);
                
                // we can always be sure that the first join condition exists
                $e2 = explode(' AND ', $e[1]);

                $part = $e[0] . ' ON '
                      . array_shift($e2);
                      
                if( ! empty($e2)) {
                    $parser = new Doctrine_Query_JoinCondition($this);
                    $part  .= ' AND ' . $parser->parse(implode(' AND ', $e2));
                }

                $q .= ' ' . $part;
            }
        }
        /**
lsmith's avatar
lsmith committed
716 717 718 719 720
        if( ! empty($this->parts['join'])) {
            foreach($this->parts['join'] as $part) {
                $q .= ' '.implode(' ', $part);
            }
        }
721
        */
lsmith's avatar
lsmith committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

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

        $string = $this->applyInheritance();

        if( ! empty($string))
            $this->parts['where'][] = '('.$string.')';



        $modifyLimit = true;
        if( ! empty($this->parts["limit"]) || ! empty($this->parts["offset"])) {

            if($needsSubQuery) {
                $subquery = $this->getLimitSubquery();


                switch(strtolower($this->conn->getName())) {
                    case 'mysql':
                        // mysql doesn't support LIMIT in subqueries
                        $params   = array_merge($this->params, $params);
                        $list     = $this->conn->execute($subquery, $params)->fetchAll(PDO::FETCH_COLUMN);
                        $subquery = implode(', ', $list);
                    break;
                    case 'pgsql':
                        // pgsql needs special nested LIMIT subquery
                        $subquery = 'SELECT doctrine_subquery_alias.' . $table->getIdentifier(). ' FROM (' . $subquery . ') AS doctrine_subquery_alias';
                    break;
                }

                $field    = $this->aliasHandler->getShortAlias($table->getTableName()) . '.' . $table->getIdentifier();

                // only append the subquery if it actually contains something
                if($subquery !== '')
                    array_unshift($this->parts['where'], $field. ' IN (' . $subquery . ')');

                $modifyLimit = false;
            }
        }

        $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']):'';

        if($modifyLimit)
            $q = $this->conn->modifyLimitQuery($q, $this->parts['limit'], $this->parts['offset']);

        // return to the previous state
        if( ! empty($string))
            array_pop($this->parts['where']);
        if($needsSubQuery)
            array_shift($this->parts['where']);

        return $q;
    }
    /**
     * 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()
    {
        $k          = array_keys($this->tables);
        $table      = $this->tables[$k[0]];

        // get short alias
        $alias      = $this->aliasHandler->getShortAlias($table->getTableName());
        $primaryKey = $alias . '.' . $table->getIdentifier();

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

        if($this->conn->getDBH()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
            // pgsql needs the order by fields to be preserved in select clause

            foreach($this->parts['orderby'] as $part) {
                $e = explode(' ', $part);

                // don't add primarykey column (its already in the select clause)
                if($e[0] !== $primaryKey)
                    $subquery .= ', ' . $e[0];
            }
        }

        $subquery .= ' FROM ' . $this->conn->quoteIdentifier($table->getTableName()) . ' ' . $alias;

        foreach($this->parts['join'] as $parts) {
            foreach($parts as $part) {
                // preserve LEFT JOINs only if needed
                if(substr($part,0,9) === 'LEFT JOIN') {
                    $e = explode(' ', $part);

                    if( ! in_array($e[3], $this->subqueryAliases) &&
                        ! in_array($e[2], $this->subqueryAliases)) {
                        continue;
                    }

                }

                $subquery .= ' '.$part;
            }
        }

        // all conditions must be preserved in subquery
833 834 835 836
        $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']) : '';
        $subquery .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(', ', $this->parts['orderby'])   : '';
lsmith's avatar
lsmith committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

        // add driver specific limit clause
        $subquery = $this->conn->modifyLimitQuery($subquery, $this->parts['limit'], $this->parts['offset']);

        $parts = self::quoteExplode($subquery, ' ', "'", "'");

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

            if($this->aliasHandler->hasAliasFor($part)) {
                $parts[$k] = $this->aliasHandler->generateNewAlias($part);
            }

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

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

                $e[0] = substr($e[0], 0, $pos) . $this->aliasHandler->generateNewAlias($trimmed);
                $parts[$k] = implode('.', $e);
            }
        }
        $subquery = implode(' ', $parts);

        return $subquery;
    }
    /**
     * query the database with DQL (Doctrine Query Language)
     *
     * @param string $query                 DQL query
     * @param array $params                 parameters
     */
    public function query($query,$params = array())
    {
        $this->parseQuery($query);

        if($this->aggregate) {
            $keys  = array_keys($this->tables);
            $query = $this->getQuery();
            $stmt  = $this->tables[$keys[0]]->getConnection()->select($query, $this->parts["limit"], $this->parts["offset"]);
            $data  = $stmt->fetch(PDO::FETCH_ASSOC);
            if(count($data) == 1) {
                return current($data);
            } else {
                return $data;
            }
        } else {
            return $this->execute($params);
        }
    }
    /**
     * splitQuery
     * 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
     */
    public function splitQuery($query)
    {
        $e = self::sqlExplode($query, ' ');

        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)
    {
        if($clear)
            $this->clear();

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

        $parts = $this->splitQuery($query);

        foreach($parts as $k => $part) {
zYne's avatar
zYne committed
971
            $part = implode(' ', $part);
lsmith's avatar
lsmith committed
972
            switch(strtoupper($k)) {
zYne's avatar
zYne committed
973 974 975 976 977 978
                case 'CREATE':
                    $this->type = self::CREATE;
                break;
                case 'INSERT':
                    $this->type = self::INSERT;
                break;
lsmith's avatar
lsmith committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
                case 'DELETE':
                    $this->type = self::DELETE;
                break;
                case 'SELECT':
                    $this->type = self::SELECT;
                    $this->parseSelect($part);
                break;
                case 'UPDATE':
                    $this->type = self::UPDATE;
                    $k = 'FROM';

                case 'FROM':
                    $class  = 'Doctrine_Query_' . ucwords(strtolower($k));
                    $parser = new $class($this);
                    $parser->parse($part);
                break;
                case 'SET':
                    $class  = 'Doctrine_Query_' . ucwords(strtolower($k));
                    $parser = new $class($this);
                    $this->parts['set'][] = $parser->parse($part);
                break;
                case 'GROUP':
                case 'ORDER':
                    $k .= 'by';
                case 'WHERE':
                case 'HAVING':
                    $class  = 'Doctrine_Query_' . ucwords(strtolower($k));
                    $parser = new $class($this);

                    $name = strtolower($k);
                    $this->parts[$name][] = $parser->parse($part);
                break;
                case 'LIMIT':
                    $this->parts['limit'] = trim($part);
                break;
                case 'OFFSET':
                    $this->parts['offset'] = trim($part);
                break;
            }
        }

        return $this;
    }
    /**
     * DQL ORDER BY PARSER
     * parses the order by part of the query string
     *
     * @param string $str
     * @return void
     */
    final public function parseOrderBy($str)
    {
        $parser = new Doctrine_Query_Part_Orderby($this);
        return $parser->parse($str);
    }
    /**
     * returns Doctrine::FETCH_* constant
     *
     * @param string $mode
     * @return integer
     */
    final public function parseFetchMode($mode)
    {
        switch(strtolower($mode)):
            case "i":
            case "immediate":
                $fetchmode = Doctrine::FETCH_IMMEDIATE;
            break;
            case "b":
            case "batch":
                $fetchmode = Doctrine::FETCH_BATCH;
            break;
            case "l":
            case "lazy":
                $fetchmode = Doctrine::FETCH_LAZY;
            break;
            case "o":
            case "offset":
                $fetchmode = Doctrine::FETCH_OFFSET;
            break;
            case "lo":
            case "lazyoffset":
                $fetchmode = Doctrine::FETCH_LAZYOFFSET;
            default:
                throw new Doctrine_Query_Exception("Unknown fetchmode '$mode'. The availible fetchmodes are 'i', 'b' and 'l'.");
        endswitch;
        return $fetchmode;
    }
    /**
     * trims brackets
     *
     * @param string $str
     * @param string $e1        the first bracket, usually '('
     * @param string $e2        the second bracket, usually ')'
     */
    public static function bracketTrim($str,$e1 = '(',$e2 = ')')
    {
        if(substr($str,0,1) == $e1 && substr($str,-1) == $e2)
            return substr($str,1,-1);
        else
            return $str;
    }
    /**
     * bracketExplode
     *
     * example:
     *
     * parameters:
     *      $str = (age < 20 AND age > 18) AND email LIKE 'John@example.com'
     *      $d = ' AND '
     *      $e1 = '('
     *      $e2 = ')'
     *
     * would return an array:
     *      array("(age < 20 AND age > 18)",
     *            "email LIKE 'John@example.com'")
     *
     * @param string $str
     * @param string $d         the delimeter which explodes the string
     * @param string $e1        the first bracket, usually '('
     * @param string $e2        the second bracket, usually ')'
     *
     */
    public static function bracketExplode($str, $d = ' ', $e1 = '(', $e2 = ')')
    {
        if(is_array($d)) {
            $a = preg_split('/('.implode('|', $d).')/', $str);
            $d = stripslashes($d[0]);
        } else
            $a = explode("$d",$str);

        $i = 0;
        $term = array();
        foreach($a as $key=>$val) {
            if (empty($term[$i])) {
                $term[$i] = trim($val);
                $s1 = substr_count($term[$i], "$e1");
                $s2 = substr_count($term[$i], "$e2");
                    if($s1 == $s2) $i++;
            } else {
                $term[$i] .= "$d".trim($val);
                $c1 = substr_count($term[$i], "$e1");
                $c2 = substr_count($term[$i], "$e2");
                    if($c1 == $c2) $i++;
            }
        }
        return $term;
    }
    /**
     * quoteExplode
     *
     * example:
     *
     * parameters:
     *      $str = email LIKE 'John@example.com'
     *      $d = ' AND '
     *
     * would return an array:
     *      array("email", "LIKE", "'John@example.com'")
     *
     * @param string $str
     * @param string $d         the delimeter which explodes the string
     */
    public static function quoteExplode($str, $d = ' ')
    {
        if(is_array($d)) {
            $a = preg_split('/('.implode('|', $d).')/', $str);
            $d = stripslashes($d[0]);
        } else
            $a = explode("$d",$str);

        $i = 0;
        $term = array();
        foreach($a as $key => $val) {
            if (empty($term[$i])) {
                $term[$i] = trim($val);

                if( ! (substr_count($term[$i], "'") & 1))
                    $i++;
            } else {
                $term[$i] .= "$d".trim($val);

                if( ! (substr_count($term[$i], "'") & 1))
                    $i++;
            }
        }
        return $term;
    }
    /**
     * sqlExplode
     *
     * explodes a string into array using custom brackets and
     * quote delimeters
     *
     *
     * example:
     *
     * parameters:
     *      $str = "(age < 20 AND age > 18) AND name LIKE 'John Doe'"
     *      $d   = ' '
     *      $e1  = '('
     *      $e2  = ')'
     *
     * would return an array:
     *      array('(age < 20 AND age > 18)',
     *            'name',
     *            'LIKE',
     *            'John Doe')
     *
     * @param string $str
     * @param string $d         the delimeter which explodes the string
     * @param string $e1        the first bracket, usually '('
     * @param string $e2        the second bracket, usually ')'
     *
     * @return array
     */
    public static function sqlExplode($str, $d = ' ', $e1 = '(', $e2 = ')')
    {
        if(is_array($d)) {
            $str = preg_split('/('.implode('|', $d).')/', $str);
            $d = stripslashes($d[0]);
        } else
            $str = explode("$d",$str);

        $i = 0;
        $term = array();
        foreach($str as $key => $val) {
            if (empty($term[$i])) {
                $term[$i] = trim($val);

                $s1 = substr_count($term[$i],"$e1");
                $s2 = substr_count($term[$i],"$e2");

1212
                if (substr($term[$i],0,1) == "(") {
lsmith's avatar
lsmith committed
1213 1214 1215 1216
                    if($s1 == $s2) {
                        $i++;
                    }
                } else {
1217 1218
                    if ( ! (substr_count($term[$i], "'") & 1) &&
                         ! (substr_count($term[$i], "\"") & 1) &&
gnat's avatar
gnat committed
1219
                         ! (substr_count($term[$i], "�") & 1)
1220
                       ) { $i++; }
lsmith's avatar
lsmith committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
                }
            } else {
                $term[$i] .= "$d".trim($val);
                $c1 = substr_count($term[$i],"$e1");
                $c2 = substr_count($term[$i],"$e2");

                if(substr($term[$i],0,1) == "(") {
                    if($c1 == $c2) {
                        $i++;
                    }
                } else {
1232 1233
                    if ( ! (substr_count($term[$i], "'") & 1) &&
                         ! (substr_count($term[$i], "\"") & 1) &&
gnat's avatar
gnat committed
1234
                         ! (substr_count($term[$i], "�") & 1)
1235
                       ) { $i++; }
lsmith's avatar
lsmith committed
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
                }
            }
        }
        return $term;
    }
    /**
     * generateAlias
     *
     * @param string $tableName
     * @return string
     */
    public function generateAlias($tableName)
    {
        if(isset($this->tableIndexes[$tableName])) {
            return $tableName.++$this->tableIndexes[$tableName];
        } else {
            $this->tableIndexes[$tableName] = 1;
            return $tableName;
        }
    }

    /**
     * loads a component
     *
     * @param string $path              the path of the loadable component
     * @param integer $fetchmode        optional fetchmode, if not set the components default fetchmode will be used
     * @throws Doctrine_Query_Exception
     * @return Doctrine_Table
     */
    final public function load($path, $loadFields = true)
    {
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
                
        // parse custom join conditions
        $e = explode(' ON ', $path);
        
        $joinCondition = '';
        if(count($e) > 1) {
            $joinCondition = ' AND ' . $e[1];
            $path = $e[0];
        }

lsmith's avatar
lsmith committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
        $tmp            = explode(' ',$path);
        $componentAlias = (count($tmp) > 1) ? end($tmp) : false;

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


        if(isset($this->compAliases[$e[0]])) {
            $end      = substr($tmp[0], strlen($e[0]));
            $path     = $this->compAliases[$e[0]] . $end;
            $e        = preg_split("/[.:]/", $path, -1);
        } else {
            $path     = $tmp[0];
        }



        $index = 0;
        $currPath = '';
        $this->tableStack = array();

        foreach($e as $key => $fullname) {
            try {
                $e2    = preg_split("/[-(]/",$fullname);
                $name  = $e2[0];

                $currPath .= '.' . $name;

                if($key == 0) {
                    $currPath = substr($currPath,1);

                    $this->conn = Doctrine_Manager::getInstance()
                                  ->getConnectionForComponent($name);

                    $table = $this->conn->getTable($name);


                    $tname = $this->aliasHandler->getShortAlias($table->getTableName());

                    if( ! isset($this->tableAliases[$currPath])) {
                        $this->tableIndexes[$tname] = 1;
zYne's avatar
zYne committed
1317
                    }  
lsmith's avatar
lsmith committed
1318

zYne's avatar
zYne committed
1319 1320 1321 1322 1323
                    $this->parts['from'] = $this->conn->quoteIdentifier($table->getTableName());
                    
                    if ($this->type === self::SELECT) {
                         $this->parts['from'] .= ' ' . $tname;
                    }
lsmith's avatar
lsmith committed
1324 1325 1326 1327 1328 1329 1330 1331 1332

                    $this->tableAliases[$currPath] = $tname;

                    $tableName = $tname;

                } else {

                    $index += strlen($e[($key - 1)]) + 1;
                    // the mark here is either '.' or ':'
1333
                    $mark  = substr($path, ($index - 1), 1);
lsmith's avatar
lsmith committed
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

                    if(isset($this->tableAliases[$prevPath])) {
                        $tname = $this->tableAliases[$prevPath];
                    } else {
                        $tname = $this->aliasHandler->getShortAlias($table->getTableName());
                    }

                    $fk       = $table->getRelation($name);
                    $name     = $fk->getTable()->getComponentName();
                    $original = $fk->getTable()->getTableName();



1347
                    if (isset($this->tableAliases[$currPath])) {
lsmith's avatar
lsmith committed
1348
                        $tname2 = $this->tableAliases[$currPath];
1349
                    } else {
lsmith's avatar
lsmith committed
1350
                        $tname2 = $this->aliasHandler->generateShortAlias($original);
1351
                    }
lsmith's avatar
lsmith committed
1352 1353 1354

                    $aliasString = $this->conn->quoteIdentifier($original) . ' ' . $tname2;

1355
                    switch ($mark) {
lsmith's avatar
lsmith committed
1356 1357 1358 1359 1360 1361 1362
                        case ':':
                            $join = 'INNER JOIN ';
                        break;
                        case '.':
                            $join = 'LEFT JOIN ';
                        break;
                        default:
1363
                            throw new Doctrine_Query_Exception("Unknown operator '$mark'");
lsmith's avatar
lsmith committed
1364 1365 1366 1367 1368 1369
                    }

                    if( ! $fk->isOneToOne()) {
                       $this->needsSubquery = true;
                    }

zYne's avatar
zYne committed
1370 1371 1372 1373

                    $map = $fk->getTable()->inheritanceMap;

                    if( ! $loadFields || ! empty($map) || $joinCondition) {
lsmith's avatar
lsmith committed
1374 1375 1376
                        $this->subqueryAliases[] = $tname2;
                    }

1377

zYne's avatar
zYne committed
1378
                    if ($fk instanceof Doctrine_Relation_Association) {
lsmith's avatar
lsmith committed
1379 1380 1381 1382
                        $asf = $fk->getAssociationFactory();

                        $assocTableName = $asf->getTableName();

zYne's avatar
zYne committed
1383
                        if( ! $loadFields || ! empty($map) || $joinCondition) {
lsmith's avatar
lsmith committed
1384 1385
                            $this->subqueryAliases[] = $assocTableName;
                        }
1386 1387 1388 1389 1390 1391 1392 1393 1394
                        
                        $assocPath = $prevPath . '.' . $asf->getComponentName();

                        if (isset($this->tableAliases[$assocPath])) {
                            $assocAlias = $this->tableAliases[$assocPath];
                        } else {
                            $assocAlias = $this->aliasHandler->generateShortAlias($assocTableName);
                        }

zYne's avatar
zYne committed
1395
                        $this->parts['join'][$tname][$assocTableName] = $join . $assocTableName . ' ' . $assocAlias . ' ON ' . $tname  . '.'
lsmith's avatar
lsmith committed
1396
                                                                      . $table->getIdentifier() . ' = '
1397
                                                                      . $assocAlias . '.' . $fk->getLocal();
zYne's avatar
zYne committed
1398 1399 1400 1401 1402
                                                                      
                        if ($fk instanceof Doctrine_Relation_Association_Self) {
                            $this->parts['join'][$tname][$assocTableName] .= ' OR ' . $tname  . '.' . $table->getIdentifier() . ' = '
                                                                           . $assocAlias . '.' . $fk->getForeign();
                        }
lsmith's avatar
lsmith committed
1403

1404
                        $this->parts['join'][$tname][$tname2]         = $join . $aliasString    . ' ON ' . $tname2 . '.'
lsmith's avatar
lsmith committed
1405
                                                                      . $fk->getTable()->getIdentifier() . ' = '
1406
                                                                      . $assocAlias . '.' . $fk->getForeign()
1407
                                                                      . $joinCondition;
lsmith's avatar
lsmith committed
1408

zYne's avatar
zYne committed
1409 1410 1411 1412 1413
                        if ($fk instanceof Doctrine_Relation_Association_Self) {
                            $this->parts['join'][$tname][$tname2] .= ' OR ' . $tname2  . '.' . $table->getIdentifier() . ' = '
                                                                           . $assocAlias . '.' . $fk->getLocal();
                        }

lsmith's avatar
lsmith committed
1414
                    } else {
1415
                        $this->parts['join'][$tname][$tname2]         = $join . $aliasString
lsmith's avatar
lsmith committed
1416
                                                                      . ' ON ' . $tname .  '.'
1417 1418
                                                                      . $fk->getLocal() . ' = ' . $tname2 . '.' . $fk->getForeign()
                                                                      . $joinCondition;
lsmith's avatar
lsmith committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
                    }


                    $this->joins[$tname2] = $prevTable;


                    $table = $fk->getTable();

                    $this->tableAliases[$currPath] = $tname2;

                    $tableName = $tname2;

                    $this->relationStack[] = $fk;
                }

                $this->components[$currPath] = $table;

                $this->tableStack[] = $table;

                if( ! isset($this->tables[$tableName])) {
                    $this->tables[$tableName] = $table;

1441
                    if ($loadFields) {
lsmith's avatar
lsmith committed
1442 1443 1444

                        $skip = false;

1445 1446
                        if ( ! empty($this->pendingFields) ||
                             ! empty($this->pendingAggregates)) {
lsmith's avatar
lsmith committed
1447
                            $skip = true;
1448
                        }
lsmith's avatar
lsmith committed
1449

1450
                        if ($componentAlias) {
lsmith's avatar
lsmith committed
1451 1452 1453 1454 1455 1456
                            $this->compAliases[$componentAlias] = $currPath;

                            if(isset($this->pendingFields[$componentAlias])) {
                                $this->processPendingFields($componentAlias);
                                $skip = true;
                            }
zYne's avatar
zYne committed
1457 1458 1459
                            if(isset($this->pendingAggregates[$componentAlias]) ||
                              (current($this->tables) === $table && isset($this->pendingAggregates[0]))
                               ) {
lsmith's avatar
lsmith committed
1460 1461 1462 1463 1464
                                $this->processPendingAggregates($componentAlias);
                                $skip = true;
                            }
                        }

1465
                        if ( ! $skip) {
lsmith's avatar
lsmith committed
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
                            $this->parseFields($fullname, $tableName, $e2, $currPath);
                        }
                    }
                }


                $prevPath  = $currPath;
                $prevTable = $tableName;
            } catch(Exception $e) {
                throw new Doctrine_Query_Exception($e->__toString());
            }
        }

        if($componentAlias !== false) {
            $this->compAliases[$componentAlias] = $currPath;
        }

        return $table;
    }
    /**
     * parseFields
     *
     * @param string $fullName
     * @param string $tableName
     * @param array $exploded
     * @param string $currPath
     * @return void
     */
    final public function parseFields($fullName, $tableName, array $exploded, $currPath)
    {
        $table = $this->tables[$tableName];

        $fields = array();

        if(strpos($fullName, '-') === false) {
            $fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE);

            if(isset($exploded[1])) {
                if(count($exploded) > 2) {
                    $fields = $this->parseAggregateValues($fullName, $tableName, $exploded, $currPath);
                } elseif(count($exploded) == 2) {
                    $fields = explode(',',substr($exploded[1],0,-1));
                }
            }
        } else {
            if(isset($exploded[1])) {
                $fetchmode = $this->parseFetchMode($exploded[1]);
            } else
                $fetchmode = $table->getAttribute(Doctrine::ATTR_FETCHMODE);

            if(isset($exploded[2])) {
                if(substr_count($exploded[2], ')') > 1) {

                } else {
                    $fields = explode(',', substr($exploded[2],0,-1));
                }
            }

        }
        if( ! $this->aggregate)
            $this->loadFields($table, $fetchmode, $fields, $currPath);
    }
    /**
     * parseAggregateFunction
     *
     * @param string $func
     * @param string $reference
     * @return string
     */
    public function parseAggregateFunction($func,$reference)
    {
        $pos = strpos($func, '(');

        if($pos !== false) {
            $funcs  = array();

            $name   = substr($func, 0, $pos);
            $func   = substr($func, ($pos + 1), -1);
            $params = Doctrine_Query::bracketExplode($func, ',', '(', ')');

            foreach($params as $k => $param) {
                $params[$k] = $this->parseAggregateFunction($param,$reference);
            }

            $funcs = $name . '(' . implode(', ', $params). ')';

            return $funcs;

        } else {
            if( ! is_numeric($func)) {

                $func = $this->getTableAlias($reference).'.'.$func;

                return $func;
            } else {

                return $func;
            }
        }
    }
    /**
     * parseAggregateValues
     */
    public function parseAggregateValues($fullName, $tableName, array $exploded, $currPath)
    {
        $this->aggregate = true;
        $pos    = strpos($fullName, '(');
        $name   = substr($fullName, 0, $pos);
        $string = substr($fullName, ($pos + 1), -1);

        $exploded     = Doctrine_Query::bracketExplode($string, ',');
        foreach($exploded as $k => $value) {
            $func         = $this->parseAggregateFunction($value, $currPath);
            $exploded[$k] = $func;

            $this->parts['select'][] = $exploded[$k];
        }
    }
}