Hydrate.php 36.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?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_Hydrate is a base class for Doctrine_RawSql and Doctrine_Query.
 * Its purpose is to populate object graphs.
25
 *
26 27 28 29 30 31 32 33 34
 *
 * @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>
 */
35
class Doctrine_Hydrate extends Doctrine_Object implements Serializable
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
{
    /**
     * QUERY TYPE CONSTANTS
     */

    /**
     * constant for SELECT queries
     */
    const SELECT = 0;
    /**
     * constant for DELETE queries
     */
    const DELETE = 1;
    /**
     * constant for UPDATE queries
     */
    const UPDATE = 2;
    /**
     * constant for INSERT queries
     */
    const INSERT = 3;
    /**
     * constant for CREATE queries
     */
    const CREATE = 4;
61 62 63 64 65 66 67 68
    /**
     * Constant for the array hydration mode.
     */
    const HYDRATE_ARRAY = 3;
    /**
     * Constant for the record (object) hydration mode.
     */
    const HYDRATE_RECORD = 2;
69

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    /**
     * @var array $params                       query input parameters
     */
    protected $_params      = array();
    /**
     * @var Doctrine_Connection $conn           Doctrine_Connection object
     */
    protected $_conn;
    /**
     * @var Doctrine_View $_view                Doctrine_View object, when set this object will use the
     *                                          the query given by the view object for object population
     */
    protected $_view;
    /**
     * @var array $_aliasMap                    two dimensional array containing the map for query aliases
     *      Main keys are component aliases
     *
     *          table               table object associated with given alias
     *
     *          relation            the relation object owned by the parent
     *
     *          parent              the alias of the parent
     *
     *          agg                 the aggregates of this component
     */
    protected $_aliasMap         = array();
    /**
     *
     */
    protected $pendingAggregates = array();
    /**
     * @var array $aggregateMap             an array containing all aggregate aliases, keys as dql aliases
     *                                      and values as sql aliases
     */
    protected $aggregateMap      = array();
    /**
     * @var array $_options                 an array of options
     */
    protected $_options    = array(
                            'fetchMode'      => Doctrine::FETCH_RECORD,
                            'parserCache'    => false,
                            'resultSetCache' => false,
                            );
zYne's avatar
zYne committed
113 114 115 116
    /**
     * @var string $_sql            cached SQL query
     */
    protected $_sql;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    /**
     * @var array $parts            SQL query string parts
     */
    protected $parts = array(
        'select'    => array(),
        'distinct'  => false,
        'forUpdate' => false,
        'from'      => array(),
        'set'       => array(),
        'join'      => array(),
        'where'     => array(),
        'groupby'   => array(),
        'having'    => array(),
        'orderby'   => array(),
        'limit'     => false,
        'offset'    => false,
        );
    /**
     * @var integer $type                   the query type
     *
     * @see Doctrine_Query::* constants
     */
    protected $type            = self::SELECT;
zYne's avatar
zYne committed
140 141 142
    /**
     * @var array
     */
143
    protected $_cache;
144 145 146 147
    /**
     * The current hydration mode.
     */
    protected $_hydrationMode = self::HYDRATE_RECORD;
zYne's avatar
zYne committed
148 149 150 151
    /**
     * @var boolean $_expireCache           a boolean value that indicates whether or not to force cache expiration
     */
    protected $_expireCache     = false;
152

zYne's avatar
zYne committed
153
    protected $_timeToLive;
154

zYne's avatar
zYne committed
155
    protected $_tableAliases    = array();
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    /**
     * @var array $_tableAliasSeeds         A simple array keys representing table aliases and values
     *                                      as table alias seeds. The seeds are used for generating short table
     *                                      aliases.
     */
    protected $_tableAliasSeeds = array();
    /**
     * constructor
     *
     * @param Doctrine_Connection|null $connection
     */
    public function __construct($connection = null)
    {
        if ( ! ($connection instanceof Doctrine_Connection)) {
            $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
        }
        $this->_conn = $connection;
    }
zYne's avatar
zYne committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    /**
     * getRootAlias
     * returns the alias of the the root component
     *
     * @return array
     */
    public function getRootAlias()
    {
        reset($this->_aliasMap);

        return key($this->_aliasMap);
    }
    /**
     * getRootDeclaration
     * returns the root declaration
     *
     * @return array
     */
    public function getRootDeclaration()
    {
        $map = reset($this->_aliasMap);

        return $map;
    }
zYne's avatar
zYne committed
198 199 200 201 202 203 204 205 206
    /**
     * getRoot
     * returns the root component for this object
     *
     * @return Doctrine_Table       root components table
     */
    public function getRoot()
    {
        $map = reset($this->_aliasMap);
207

zYne's avatar
zYne committed
208 209 210
        if ( ! isset($map['table'])) {
            throw new Doctrine_Hydrate_Exception('Root component not initialized.');
        }
211

zYne's avatar
zYne committed
212 213 214 215 216 217 218 219
        return $map['table'];
    }
    /**
     * getSql
     * return the sql associated with this object
     *
     * @return string   sql query string
     */
220 221 222 223
    public function getSql()
    {
        return $this->getQuery();
    }
zYne's avatar
zYne committed
224 225 226 227 228 229 230 231
    /**
     * useCache
     *
     * @param Doctrine_Cache_Interface|bool $driver      cache driver
     * @param integer $timeToLive                        how long the cache entry is valid
     * @return Doctrine_Hydrate         this object
     */
    public function useCache($driver = true, $timeToLive = null)
232
    {
233
        if ($driver !== null) {
zYne's avatar
zYne committed
234 235 236
            if ($driver !== true) {
                if ( ! ($driver instanceof Doctrine_Cache_Interface)) {
                    $msg = 'First argument should be instance of Doctrine_Cache_Interface or null.';
237

zYne's avatar
zYne committed
238 239 240
                    throw new Doctrine_Hydrate_Exception($msg);
                }
            }
241
        }
zYne's avatar
zYne committed
242 243
        $this->_cache = $driver;

zYne's avatar
zYne committed
244
        return $this->setCacheLifeSpan($timeToLive);
245
    }
zYne's avatar
zYne committed
246
    /**
zYne's avatar
zYne committed
247 248 249 250 251 252 253 254
     * expireCache
     *
     * @param boolean $expire       whether or not to force cache expiration
     * @return Doctrine_Hydrate     this object
     */
    public function expireCache($expire = true)
    {
        $this->_expireCache = true;
255

zYne's avatar
zYne committed
256 257 258 259
        return $this;
    }
    /**
     * setCacheLifeSpan
zYne's avatar
zYne committed
260 261 262 263
     *
     * @param integer $timeToLive   how long the cache entry is valid
     * @return Doctrine_Hydrate     this object
     */
zYne's avatar
zYne committed
264
    public function setCacheLifeSpan($timeToLive)
265
    {
266 267 268
        if ($timeToLive !== null) {
            $timeToLive = (int) $timeToLive;
        }
zYne's avatar
zYne committed
269
        $this->_timeToLive = $timeToLive;
270

zYne's avatar
zYne committed
271 272 273 274 275 276 277 278 279 280
        return $this;
    }
    /**
     * getCacheDriver
     * returns the cache driver associated with this object
     *
     * @return Doctrine_Cache_Interface|boolean|null    cache driver
     */
    public function getCacheDriver()
    {
281 282 283 284 285
        if ($this->_cache instanceof Doctrine_Cache_Interface) {
            return $this->_cache;
        } else {
            return $this->_conn->getCacheDriver();
        }
286
    }
287 288 289 290 291 292 293 294 295 296
    /**
     * Sets the fetchmode.
     *
     * @param integer $fetchmode  One of the Doctrine_Hydrate::HYDRATE_* constants.
     */
    public function setHydrationMode($hydrationMode)
    {
        $this->_hydrationMode = $hydrationMode;
        return $this;
    }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    /**
     * serialize
     * this method is automatically called when this Doctrine_Hydrate is serialized
     *
     * @return array    an array of serialized properties
     */
    public function serialize()
    {
        $vars = get_object_vars($this);

    }
    /**
     * unseralize
     * this method is automatically called everytime a Doctrine_Hydrate object is unserialized
     *
     * @param string $serialized                Doctrine_Record as serialized string
     * @return void
     */
    public function unserialize($serialized)
    {

    }
    /**
     * generateNewTableAlias
     * generates a new alias from given table alias
     *
     * @param string $tableAlias    table alias from which to generate the new alias from
     * @return string               the created table alias
     */
    public function generateNewTableAlias($tableAlias)
    {
        if (isset($this->_tableAliases[$tableAlias])) {
            // generate a new alias
            $name = substr($tableAlias, 0, 1);
            $i    = ((int) substr($tableAlias, 1));

            if ($i == 0) {
                $i = 1;
            }

            $newIndex  = ($this->_tableAliasSeeds[$name] + $i);

            return $name . $newIndex;
        }

gnat's avatar
gnat committed
342
        return $tableAlias;
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    }
    /**
     * hasTableAlias
     * whether or not this object has given tableAlias
     *
     * @param string $tableAlias    the table alias to be checked
     * @return boolean              true if this object has given alias, otherwise false
     */
    public function hasTableAlias($tableAlias)
    {
        return (isset($this->_tableAliases[$tableAlias]));
    }
    /**
     * getComponentAlias
     * get component alias associated with given table alias
     *
     * @param string $tableAlias    the table alias that identifies the component alias
     * @return string               component alias
     */
    public function getComponentAlias($tableAlias)
    {
        if ( ! isset($this->_tableAliases[$tableAlias])) {
            throw new Doctrine_Hydrate_Exception('Unknown table alias ' . $tableAlias);
        }
        return $this->_tableAliases[$tableAlias];
    }
    /**
     * getTableAliasSeed
     * returns the alias seed for given table alias
     *
     * @param string $tableAlias    table alias that identifies the alias seed
     * @return integer              table alias seed
     */
    public function getTableAliasSeed($tableAlias)
    {
        if ( ! isset($this->_tableAliasSeeds[$tableAlias])) {
            return 0;
        }
        return $this->_tableAliasSeeds[$tableAlias];
    }
    /**
     * generateTableAlias
     * generates a table alias from given table name and associates 
     * it with given component alias
     *
     * @param string $componentAlias    the component alias to be associated with generated table alias
     * @param string $tableName         the table name from which to generate the table alias
     * @return string                   the generated table alias
     */
    public function generateTableAlias($componentAlias, $tableName)
    {
        $char   = strtolower(substr($tableName, 0, 1));

        $alias  = $char;

        if ( ! isset($this->_tableAliasSeeds[$alias])) {
            $this->_tableAliasSeeds[$alias] = 1;
        }
zYne's avatar
zYne committed
401

402
        while (isset($this->_tableAliases[$alias])) {
zYne's avatar
zYne committed
403 404 405
            if ( ! isset($this->_tableAliasSeeds[$alias])) {
                $this->_tableAliasSeeds[$alias] = 1;
            }
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
            $alias = $char . ++$this->_tableAliasSeeds[$alias];
        }

        $this->_tableAliases[$alias] = $componentAlias;

        return $alias;
    }
    /**
     * getTableAliases
     * returns all table aliases
     *
     * @return array        table aliases as an array
     */
    public function getTableAliases()
    {
        return $this->_tableAliases;
    }
    /** 
     * addTableAlias
     * adds an alias for table and associates it with given component alias
     *
     * @param string $componentAlias    the alias for the query component associated with given tableAlias
     * @param string $tableAlias        the table alias to be added
     * @return Doctrine_Hydrate
     */
    public function addTableAlias($tableAlias, $componentAlias)
    {
        $this->_tableAliases[$tableAlias] = $componentAlias;
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 472 473 474 475 476
        return $this;
    }
    /**
     * getTableAlias
     * some database such as Oracle need the identifier lengths to be < ~30 chars
     * hence Doctrine creates as short identifier aliases as possible
     *
     * this method is used for the creation of short table aliases, its also
     * smart enough to check if an alias already exists for given component (componentAlias)
     *
     * @param string $componentAlias    the alias for the query component to search table alias for
     * @param string $tableName         the table name from which the table alias is being created
     * @return string                   the generated / fetched short alias
     */
    public function getTableAlias($componentAlias, $tableName = null)
    {
        $alias = array_search($componentAlias, $this->_tableAliases);

        if ($alias !== false) {
            return $alias;
        }

        if ($tableName === null) {
            throw new Doctrine_Hydrate_Exception("Couldn't get short alias for " . $componentAlias);
        }

        return $this->generateTableAlias($componentAlias, $tableName);
    }
    /**
     * addQueryPart
     * adds a query part in the query part array
     *
     * @param string $name          the name of the query part to be added
     * @param string $part          query part string
     * @throws Doctrine_Hydrate_Exception   if trying to add unknown query part
     * @return Doctrine_Hydrate     this object
     */
    public function addQueryPart($name, $part)
    {
        if ( ! isset($this->parts[$name])) {
            throw new Doctrine_Hydrate_Exception('Unknown query part ' . $name);
        }
zYne's avatar
zYne committed
477 478 479 480 481
        if (is_array($part)) {
            $this->parts[$name] = array_merge($this->parts[$name], $part);
        } else {
            $this->parts[$name][] = $part;
        }
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        return $this;
    }
    /**
     * setQueryPart
     * sets a query part in the query part array
     *
     * @param string $name          the name of the query part to be set
     * @param string $part          query part string
     * @throws Doctrine_Hydrate_Exception   if trying to set unknown query part
     * @return Doctrine_Hydrate     this object
     */
    public function getQueryPart($part)
    {
        if ( ! isset($this->parts[$part])) {
            throw new Doctrine_Hydrate_Exception('Unknown query part ' . $part);
        }

        return $this->parts[$part];
    }
    /**
     * removeQueryPart
     * removes a query part from the query part array
     *
     * @param string $name          the name of the query part to be removed
     * @throws Doctrine_Hydrate_Exception   if trying to remove unknown query part
     * @return Doctrine_Hydrate     this object
     */
    public function removeQueryPart($name)
    {
        if (isset($this->parts[$name])) {
            if ($name == 'limit' || $name == 'offset') {
                $this->parts[$name] = false;
            } else {
                $this->parts[$name] = array();
            }
        } else {
gnat's avatar
gnat committed
518
            throw new Doctrine_Hydrate_Exception('Unknown query part ' . $name);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        }
        return $this;
    }
    /**
     * setQueryPart
     * sets a query part in the query part array
     *
     * @param string $name          the name of the query part to be set
     * @param string $part          query part string
     * @throws Doctrine_Hydrate_Exception   if trying to set unknown query part
     * @return Doctrine_Hydrate     this object
     */
    public function setQueryPart($name, $part)
    {
        if ( ! isset($this->parts[$name])) {
            throw new Doctrine_Hydrate_Exception('Unknown query part ' . $name);
        }

        if ($name !== 'limit' && $name !== 'offset') {
zYne's avatar
zYne committed
538 539 540 541 542
            if (is_array($part)) {
                $this->parts[$name] = $part;
            } else {
                $this->parts[$name] = array($part);
            }
543 544 545
        } else {
            $this->parts[$name] = $part;
        }
zYne's avatar
zYne committed
546

547 548
        return $this;
    }
zYne's avatar
zYne committed
549 550 551 552 553 554 555 556 557 558 559
    /**
     * hasAliasDeclaration
     * whether or not this object has a declaration for given component alias
     *
     * @param string $componentAlias    the component alias the retrieve the declaration from
     * @return boolean
     */
    public function hasAliasDeclaration($componentAlias)
    {
        return isset($this->_aliasMap[$componentAlias]);
    }
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
    /**
     * getAliasDeclaration
     * get the declaration for given component alias
     *
     * @param string $componentAlias    the component alias the retrieve the declaration from
     * @return array                    the alias declaration
     */
    public function getAliasDeclaration($componentAlias)
    {
        if ( ! isset($this->_aliasMap[$componentAlias])) {
            throw new Doctrine_Hydrate_Exception('Unknown component alias ' . $componentAlias);
        }

        return $this->_aliasMap[$componentAlias];
    }
    /**
     * copyAliases
     * copy aliases from another Hydrate object
     *
     * this method is needed by DQL subqueries which need the aliases
     * of the parent query
     *
     * @param Doctrine_Hydrate $query   the query object from which the
     *                                  aliases are copied from
     * @return Doctrine_Hydrate         this object
     */
    public function copyAliases(Doctrine_Hydrate $query)
    {
        $this->_tableAliases = $query->_tableAliases;
zYne's avatar
zYne committed
589 590
        $this->_aliasMap     = $query->_aliasMap;
        $this->_tableAliasSeeds = $query->_tableAliasSeeds;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
        return $this;
    }
    /**
     * createSubquery
     * creates a subquery
     *
     * @return Doctrine_Hydrate
     */
    public function createSubquery()
    {
        $class = get_class($this);
        $obj   = new $class();

        // copy the aliases to the subquery
        $obj->copyAliases($this);

        // this prevents the 'id' being selected, re ticket #307
        $obj->isSubquery(true);

        return $obj;
    }
    /**
     * limitSubqueryUsed
     * whether or not limit subquery was used
     *
     * @return boolean
     */
    public function isLimitSubqueryUsed()
    {
        return false;
    }
    /**
     * clear
     * resets all the variables
     *
     * @return void
     */
    protected function clear()
    {
        $this->parts = array(
                    'select'    => array(),
                    'distinct'  => false,
                    'forUpdate' => false,
                    'from'      => array(),
                    'set'       => array(),
                    'join'      => array(),
                    'where'     => array(),
                    'groupby'   => array(),
                    'having'    => array(),
                    'orderby'   => array(),
                    'limit'     => false,
                    'offset'    => false,
                    );
        $this->inheritanceApplied = false;
    }
    /**
     * getConnection
     *
     * @return Doctrine_Connection
     */
    public function getConnection()
    {
        return $this->_conn;
    }
    /**
     * setView
     * sets a database view this query object uses
     * this method should only be called internally by doctrine
     *
     * @param Doctrine_View $view       database view
     * @return void
     */
    public function setView(Doctrine_View $view)
    {
        $this->_view = $view;
    }
    /**
     * getView
     * returns the view associated with this query object (if any)
     *
     * @return Doctrine_View        the view associated with this query object
     */
    public function getView()
    {
        return $this->_view;
    }
    /**
     * getParams
     *
     * @return array
     */
    public function getParams()
    {
        return $this->_params;
    }
    /**
     * setParams
     *
     * @param array $params
     */
    public function setParams(array $params = array()) {
        $this->_params = $params;
    }
    public function convertEnums($params)
    {
        return $params;
    }
    /**
     * setAliasMap
     * sets the whole component alias map
     *
     * @param array $map            alias map
     * @return Doctrine_Hydrate     this object
     */
    public function setAliasMap(array $map)
    {
        $this->_aliasMap = $map;

        return $this;
    }
    /**
     * getAliasMap
     * returns the component alias map
     *
     * @return array    component alias map
     */
    public function getAliasMap()
    {
        return $this->_aliasMap;
    }
zYne's avatar
zYne committed
721 722 723 724 725 726 727
    /**
     * getCachedForm
     * returns the cached form of this query for given resultSet
     *
     * @param array $resultSet
     * @return string           serialized string representation of this query
     */
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    public function getCachedForm(array $resultSet)
    {
        $map = '';

        foreach ($this->getAliasMap() as $k => $v) {
            if ( ! isset($v['parent'])) {
                $map[$k][] = $v['table']->getComponentName();
            } else {
                $map[$k][] = $v['parent'] . '.' . $v['relation']->getAlias();
            }
            if (isset($v['agg'])) {
                $map[$k][] = $v['agg'];
            }
        }

        return serialize(array($resultSet, $map, $this->getTableAliases()));
    }
745
    public function _execute($params)
746 747
    {
        $params = $this->_conn->convertBooleans(array_merge($this->_params, $params));
zYne's avatar
zYne committed
748

749 750 751 752 753 754
        if ( ! $this->_view) {
            $query = $this->getQuery($params);
        } else {
            $query = $this->_view->getSelectSql();
        }

zYne's avatar
zYne committed
755
        $params = $this->convertEnums($params);
zYne's avatar
zYne committed
756

757
        if ($this->isLimitSubqueryUsed() &&
758
            $this->_conn->getAttribute(Doctrine::ATTR_DRIVER_NAME) !== 'mysql') {
759 760 761 762 763 764 765 766

            $params = array_merge($params, $params);
        }

        if ($this->type !== self::SELECT) {
            return $this->_conn->exec($query, $params);
        }

zYne's avatar
zYne committed
767
        $stmt = $this->_conn->execute($query, $params);
768
        return $stmt;
769 770 771 772 773 774 775 776
    }
    /**
     * execute
     * executes the query and populates the data set
     *
     * @param string $params
     * @return Doctrine_Collection            the root collection
     */
777
    public function execute($params = array(), $hydrationMode = null)
778
    {
779 780 781
        if ($this->_cache) {
            $cacheDriver = $this->getCacheDriver();

782 783
            $dql  = $this->getDql();
            // calculate hash for dql query
zYne's avatar
zYne committed
784
            $hash = md5($dql . var_export($params, true));
785

zYne's avatar
zYne committed
786 787
            $cached = ($this->_expireCache) ? null : $cacheDriver->fetch($hash);

788 789 790

            if ($cached === null) {
                // cache miss
791 792
                $stmt = $this->_execute($params);
                $array = $this->parseData2($stmt, self::HYDRATE_ARRAY);
793 794

                $cached = $this->getCachedForm($array);
795

zYne's avatar
zYne committed
796
                $cacheDriver->save($hash, $cached, $this->_timeToLive);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
            } else {
                $cached = unserialize($cached);
                $this->_tableAliases = $cached[2];
                $array = $cached[0];

                $map   = array();
                foreach ($cached[1] as $k => $v) {
                    $e = explode('.', $v[0]);
                    if (count($e) === 1) {
                        $map[$k]['table'] = $this->_conn->getTable($e[0]);
                    } else {
                        $map[$k]['parent']   = $e[0];
                        $map[$k]['relation'] = $map[$e[0]]['table']->getRelation($e[1]);
                        $map[$k]['table']    = $map[$k]['relation']->getTable();
                    }
                    if (isset($v[1])) {
                        $map[$k]['agg'] = $v[1];
                    }
                }
                $this->_aliasMap = $map;
            }
        } else {
819
            $stmt = $this->_execute($params);
820

zYne's avatar
zYne committed
821 822 823 824
            if (is_integer($stmt)) {
                return $stmt;
            }

825
            $array = $this->parseData2($stmt, $hydrationMode);
826
        }
zYne's avatar
zYne committed
827
        return $array;
828
    }
zYne's avatar
zYne committed
829

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    /**
     * getType
     *
     * returns the type of this query object
     * by default the type is Doctrine_Hydrate::SELECT but if update() or delete()
     * are being called the type is Doctrine_Hydrate::UPDATE and Doctrine_Hydrate::DELETE,
     * respectively
     *
     * @see Doctrine_Hydrate::SELECT
     * @see Doctrine_Hydrate::UPDATE
     * @see Doctrine_Hydrate::DELETE
     *
     * @return integer      return the query type
     */
    public function getType()
    {
        return $this->type;
    }
    /**
     * applyInheritance
     * applies column aggregation inheritance to DQL / SQL query
     *
     * @return string
     */
    public function applyInheritance()
    {
        // get the inheritance maps
        $array = array();

        foreach ($this->_aliasMap as $componentAlias => $data) {
            $tableAlias = $this->getTableAlias($componentAlias);
            $array[$tableAlias][] = $data['table']->inheritanceMap;
        }

        // apply inheritance maps
        $str = '';
        $c = array();

        $index = 0;
        foreach ($array as $tableAlias => $maps) {
            $a = array();

            // don't use table aliases if the query isn't a select query
            if ($this->type !== Doctrine_Query::SELECT) {
                $tableAlias = '';
            } else {
                $tableAlias .= '.';
            }

            foreach ($maps as $map) {
                $b = array();
                foreach ($map as $field => $value) {
zYne's avatar
zYne committed
882 883
                    $identifier = $this->_conn->quoteIdentifier($tableAlias . $field);

884
                    if ($index > 0) {
zYne's avatar
zYne committed
885 886
                        $b[] = '(' . $identifier . ' = ' . $value
                             . ' OR ' . $identifier . ' IS NULL)';
887
                    } else {
zYne's avatar
zYne committed
888
                        $b[] = $identifier . ' = ' . $value;
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
                    }
                }

                if ( ! empty($b)) {
                    $a[] = implode(' AND ', $b);
                }
            }

            if ( ! empty($a)) {
                $c[] = implode(' AND ', $a);
            }
            $index++;
        }

        $str .= implode(' AND ', $c);

        return $str;
    }
907 908 909 910 911 912 913
    /**
     * fetchArray
     * Convenience method to execute using array fetching as hydration mode.
     *
     * @param string $params
     * @return array
     */
zYne's avatar
zYne committed
914
    public function fetchArray($params = array()) {
romanb's avatar
romanb committed
915
        return $this->execute($params, self::HYDRATE_ARRAY);
zYne's avatar
zYne committed
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
    /**
     * fetchOne
     * Convenience method to execute the query and return the first item
     * of the collection.
     *
     * @param string $params Parameters
     * @param int $hydrationMode Hydration mode
     * @return mixed Array or Doctrine_Collection or false if no result.
     */
    public function fetchOne($params = array(), $hydrationMode = null)
    {
        if (is_null($hydrationMode)) {
            $hydrationMode = $this->_hydrationMode;
        }

        $collection = $this->execute($params, $hydrationMode);

        switch ($hydrationMode) {
            case self::HYDRATE_RECORD:
                if (count($collection) > 0) {
                    return $collection->getFirst();
                }
            case self::HYDRATE_ARRAY:
                if (!empty($collection[0])) {
                    return $collection[0];
                }
        }

        return false;
    }
947 948 949 950
    /**
     * parseData
     * parses the data returned by statement object
     *
951 952 953 954 955 956
     * This is method defines the core of Doctrine object population algorithm
     * hence this method strives to be as fast as possible
     *
     * The key idea is the loop over the rowset only once doing all the needed operations
     * within this massive loop.
     *
957 958 959
     * @param mixed $stmt
     * @return array
     */
960
    public function parseData2($stmt, $hydrationMode)
961
    {
zYne's avatar
zYne committed
962

963 964 965
        $cache = array();
        $rootMap   = reset($this->_aliasMap);
        $rootAlias = key($this->_aliasMap);
zYne's avatar
zYne committed
966
        $componentName = $rootMap['table']->getComponentName();
967 968 969 970 971
        $index = 0;
        $incr  = true;
        $lastAlias = '';
        $currData  = array();

972 973 974
        if ($hydrationMode === null) {
            $hydrationMode = $this->_hydrationMode;
        }
975

976
        if ($hydrationMode === self::HYDRATE_ARRAY) {
zYne's avatar
zYne committed
977 978 979 980 981 982
            $driver = new Doctrine_Hydrate_Array();
        } else {
            $driver = new Doctrine_Hydrate_Record();
        }

        $array = $driver->getElementCollection($componentName);
983
        $identifiable = array();
984

zYne's avatar
zYne committed
985 986
        if ($stmt === false || $stmt === 0) {
            return $array;
zYne's avatar
zYne committed
987 988
        }

zYne's avatar
zYne committed
989
        while ($data = $stmt->fetch(Doctrine::FETCH_ASSOC)) {
zYne's avatar
zYne committed
990

zYne's avatar
zYne committed
991
            $parse = true;
992

993
            foreach ($data as $key => $value) {
zYne's avatar
zYne committed
994 995 996 997

                // The following little cache solution ensures that field aliases are
                // parsed only once. This increases speed on large result sets by an order
                // of magnitude.
998 999 1000
                if ( ! isset($cache[$key])) {
                    $e = explode('__', $key);
                    $cache[$key]['field'] = $field = strtolower(array_pop($e));
zYne's avatar
zYne committed
1001 1002
                    $cache[$key]['alias'] = $this->_tableAliases[strtolower(implode('__', $e))];
                }
1003 1004


zYne's avatar
zYne committed
1005 1006 1007
                $map   = $this->_aliasMap[$cache[$key]['alias']];
                $table = $map['table'];
                $alias = $cache[$key]['alias'];
zYne's avatar
zYne committed
1008
                $field = $cache[$key]['field'];
1009

zYne's avatar
zYne committed
1010 1011 1012 1013 1014
                if (isset($this->_aliasMap[$alias]['agg'][$field])) {
                    $field = $this->_aliasMap[$alias]['agg'][$field];
                }


zYne's avatar
zYne committed
1015 1016 1017 1018 1019
                $componentName  = $map['table']->getComponentName();
                if (isset($map['relation'])) {
                    $componentAlias = $map['relation']->getAlias();
                } else {
                    $componentAlias = $map['table']->getComponentName();
1020 1021 1022 1023 1024 1025
                }


                if ( ! isset($currData[$alias])) {
                    $currData[$alias] = array();
                }
1026

1027 1028
                if ( ! isset($prev[$alias])) {
                    $prev[$alias] = array();
zYne's avatar
zYne committed
1029 1030
                }

1031

1032 1033
                $skip = false;
                if (($alias !== $lastAlias || $parse) && ! empty($currData[$alias])) {
1034

1035
                    // component changed
zYne's avatar
zYne committed
1036 1037
                    $element = $driver->getElement($currData[$alias], $componentName);

1038
                    $oneToOne = false;
zYne's avatar
zYne committed
1039

1040 1041
                    if ($alias === $rootAlias) {
                        // dealing with root component
1042

1043 1044 1045 1046
                        $index = $driver->search($element, $array);
                        if ($index === false) {
                            $array[] = $element;
                        }
zYne's avatar
zYne committed
1047

1048 1049
                        $coll =& $array;
                    } else {
zYne's avatar
zYne committed
1050 1051
                        $parent   = $map['parent'];
                        $relation = $map['relation'];
1052

1053 1054 1055
                        if (!isset($prev[$parent])) {
                            break;
                        }
1056

1057 1058 1059 1060
                        // check the type of the relation
                        if ( ! $relation->isOneToOne()) {
                            // initialize the collection

zYne's avatar
zYne committed
1061
                            if ($driver->initRelated($prev[$parent], $componentAlias)) {
zYne's avatar
zYne committed
1062

1063 1064
                                // append element
                                if (isset($identifiable[$alias])) {
zYne's avatar
zYne committed
1065
                                    $index = $driver->search($element, $prev[$parent][$componentAlias]);
1066

1067
                                    if ($index === false) {
zYne's avatar
zYne committed
1068
                                        $prev[$parent][$componentAlias][] = $element;
1069
                                    }
zYne's avatar
zYne committed
1070
                                }
1071
                                // register collection for later snapshots
zYne's avatar
zYne committed
1072
                                $driver->registerCollection($prev[$parent][$componentAlias]);
1073
                            }
1074
                        } else {
1075 1076 1077 1078 1079 1080
                            if ( ! isset($identifiable[$alias])) {
                                $prev[$parent][$componentAlias] = $driver->getNullPointer();
                            } else {
                                $prev[$parent][$componentAlias] = $element;
                            }
                            $oneToOne = true;
1081
                        }
zYne's avatar
zYne committed
1082
                        $coll =& $prev[$parent][$componentAlias];
1083 1084
                    }

1085
                    $this->_setLastElement($prev, $coll, $index, $alias, $oneToOne);
1086

1087 1088
                    $currData[$alias] = array();
                    $identifiable[$alias] = null;
1089
                }
zYne's avatar
zYne committed
1090 1091 1092 1093



                $currData[$alias][$field] = $table->prepareValue($field, $value);
1094 1095 1096 1097
                $index = false;
                if ($value !== null) {
                    $identifiable[$alias] = true;
                }
1098
                $lastAlias = $alias;
zYne's avatar
zYne committed
1099
                $parse = false;
1100

zYne's avatar
zYne committed
1101
            }
1102
        }
1103

1104
        foreach ($currData as $alias => $data) {
1105 1106
            $table = $this->_aliasMap[$alias]['table'];
            $componentName = $table->getComponentName();
1107
            // component changed       
zYne's avatar
zYne committed
1108

1109
            $element = $driver->getElement($currData[$alias], $componentName);
1110

1111
            $oneToOne = false;
zYne's avatar
zYne committed
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
            if ($alias === $rootAlias) {
                // dealing with root component
                $index = $driver->search($element, $array);
                if ($index === false) {
                    $array[] = $element;
                }
                $coll =& $array;
            } else {
                $parent   = $this->_aliasMap[$alias]['parent'];
                $relation = $this->_aliasMap[$alias]['relation'];
                $componentAlias = $relation->getAlias();
1124

1125 1126 1127
                if (!isset($prev[$parent])) {
                    break;
                }
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

                // check the type of the relation
                if ( ! $relation->isOneToOne()) {
                    // initialize the collection

                    if ($driver->initRelated($prev[$parent], $componentAlias)) {

                        // append element
                        if (isset($identifiable[$alias])) {
                            $index = $driver->search($element, $prev[$parent][$componentAlias]);

                            if ($index === false) {
                                $prev[$parent][$componentAlias][] = $element;
1141 1142
                            }
                        }
1143 1144 1145 1146 1147 1148
                        // register collection for later snapshots
                        $driver->registerCollection($prev[$parent][$componentAlias]);
                    }
                } else {
                    if ( ! isset($identifiable[$alias])) {
                        $prev[$parent][$componentAlias] = $driver->getNullPointer();
1149
                    } else {
1150

1151 1152
                        $prev[$parent][$componentAlias] = $element;
                    }
1153
                    $oneToOne = true;
1154
                }
1155 1156 1157 1158
                $coll =& $prev[$parent][$componentAlias];
            }

            $this->_setLastElement($prev, $coll, $index, $alias, $oneToOne);
zYne's avatar
zYne committed
1159

1160
            $index = false;
zYne's avatar
zYne committed
1161
            $currData[$alias] = array();
1162
            unset($identifiable[$alias]);
1163 1164
        }

zYne's avatar
zYne committed
1165
        $driver->flush();
1166 1167

        $stmt->closeCursor();
1168 1169
        return $array;
    }
zYne's avatar
zYne committed
1170 1171 1172 1173 1174 1175 1176 1177 1178
    /**
     * _setLastElement
     *
     * sets the last element of given data array / collection
     * as previous element
     *
     * @param boolean|integer $index
     * @return void
     */
1179
    public function _setLastElement(&$prev, &$coll, $index, $alias, $oneToOne)
zYne's avatar
zYne committed
1180
    {
1181 1182 1183
        if ($coll === self::$_null) {
            return false;
        }
zYne's avatar
zYne committed
1184 1185 1186 1187 1188 1189 1190
        if ($index !== false) {
            $prev[$alias] =& $coll[$index];
        } else {
            // first check the count (we do not want to get the last element
            // of an empty collection/array)
            if (count($coll) > 0) {
                if (is_array($coll)) {
1191 1192 1193 1194 1195 1196
                    if ($oneToOne) {
                        $prev[$alias] =& $coll;
                    } else {
                        end($coll);
                        $prev[$alias] =& $coll[key($coll)];
                    }
zYne's avatar
zYne committed
1197 1198 1199
                } else {
                    $prev[$alias] = $coll->getLast();
                }
1200 1201 1202 1203
            } else {
                if (isset($prev[$alias])) {
                    unset($prev[$alias]);
                }
zYne's avatar
zYne committed
1204
            }
1205
        }
zYne's avatar
zYne committed
1206
    }
1207 1208 1209 1210 1211 1212 1213
    /**
     * @return string                   returns a string representation of this object
     */
    public function __toString()
    {
        return Doctrine_Lib::formatSql($this->getQuery());
    }
1214
}