Connection.php 31.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Configurable');
22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 61 62 63 64
/**
 * Doctrine_Connection
 *
 * @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>
 * @author      Lukas Smith <smith@pooteeweet.org> (MDB2 library)
 */
abstract class Doctrine_Connection extends Doctrine_Configurable implements Countable, IteratorAggregate
{
    /**
     * @var $dbh                                the database handler
     */
    protected $dbh;
    /**
     * @var array $tables                       an array containing all the initialized Doctrine_Table objects
     *                                          keys representing Doctrine_Table component names and values as Doctrine_Table objects
     */
    protected $tables           = array();
    /**
     * @var string $driverName                  the name of this connection driver
     */
    protected $driverName;
    /**
     * @var array $supported                    an array containing all features this driver supports,
     *                                          keys representing feature names and values as
     *                                          one of the following (true, false, 'emulated')
     */
    protected $supported        = array();
    /**
     * @var array $modules                      an array containing all modules
     *              transaction                 Doctrine_Transaction driver, handles savepoint and transaction isolation abstraction
     *
     *              expression                  Doctrine_Expression driver, handles expression abstraction
     *
     *              dataDict                    Doctrine_DataDict driver, handles datatype abstraction
     *
     *              export                      Doctrine_Export driver, handles db structure modification abstraction (contains
     *                                          methods such as alterTable, createConstraint etc.)
zYne's avatar
zYne committed
65 66 67
     *              import                      Doctrine_Import driver, handles db schema reading
     *
     *              sequence                    Doctrine_Sequence driver, handles sequential id generation and retrieval
68 69 70 71 72 73
     *
     * @see Doctrine_Connection::__get()
     * @see Doctrine_DataDict
     * @see Doctrine_Expression
     * @see Doctrine_Export
     * @see Doctrine_Transaction
zYne's avatar
zYne committed
74
     * @see Doctrine_Sequence
75 76 77 78 79
     */
    private $modules = array('transaction' => false,
                             'expression'  => false,
                             'dataDict'    => false,
                             'export'      => false,
zYne's avatar
zYne committed
80 81
                             'import'      => false,
                             'sequence'    => false,
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
                             'unitOfWork'  => false,
                             );
    /**
     * @var array $properties               an array of connection properties
     */
    protected $properties = array('sql_comments'        => array(array('start' => '--', 'end' => "\n", 'escape' => false),
                                                                 array('start' => '/*', 'end' => '*/', 'escape' => false)
                                                                 ),
                                  'identifier_quoting'  => array('start' => '"',
                                                                 'end' => '"',
                                                                 'escape' => '"'
                                                                 ),
                                  'string_quoting'      => array('start' => "'",
                                                                 'end' => "'",
                                                                 'escape' => false,
                                                                 'escape_pattern' => false
                                                                 ),
zYne's avatar
zYne committed
99 100
                                  'wildcards'           => array('%', '_'),
                                  'varchar_max_length'  => 255,
101
                                  );
zYne's avatar
zYne committed
102 103 104 105
    /**
     * @var array $serverInfo
     */
    protected $serverInfo = array();
106
    /**
fabien's avatar
fabien committed
107
     * @var array $availableDrivers         an array containing all availible drivers
108
     */
fabien's avatar
fabien committed
109
    private static $availableDrivers    = array(
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
                                        'Mysql',
                                        'Pgsql',
                                        'Oracle',
                                        'Informix',
                                        'Mssql',
                                        'Sqlite',
                                        'Firebird'
                                        );

    /**
     * the constructor
     *
     * @param Doctrine_Manager $manager                 the manager object
     * @param PDO|Doctrine_Adapter_Interface $adapter   database driver
     */
    public function __construct(Doctrine_Manager $manager, $adapter)
    {
        if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) {
            throw new Doctrine_Connection_Exception("First argument should be an instance of PDO or implement Doctrine_Adapter_Interface");
        }
        $this->dbh   = $adapter;

        //$this->modules['transaction']  = new Doctrine_Connection_Transaction($this);
        $this->modules['unitOfWork']   = new Doctrine_Connection_UnitOfWork($this);

        $this->setParent($manager);

        $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $this->getAttribute(Doctrine::ATTR_LISTENER)->onOpen($this);
    }
    /**
     * getName
     * returns the name of this driver
     *
     * @return string           the name of this driver
     */
    public function getName()
    {
        return $this->driverName;
    }
    /**
     * __get
     * lazy loads given module and returns it
     *
     * @see Doctrine_DataDict
     * @see Doctrine_Expression
     * @see Doctrine_Export
     * @see Doctrine_Transaction
     * @see Doctrine_Connection::$modules       all availible modules
     * @param string $name                      the name of the module to get
     * @throws Doctrine_Connection_Exception    if trying to get an unknown module
     * @return Doctrine_Connection_Module       connection module
     */
    public function __get($name)
    {
        if (isset($this->properties[$name]))
            return $this->properties[$name];

        if ( ! isset($this->modules[$name])) {
            throw new Doctrine_Connection_Exception('Unknown module / property ' . $name);
        }
        if ($this->modules[$name] === false) {
            switch ($name) {
                case 'unitOfWork':
                    $this->modules[$name] = new Doctrine_Connection_UnitOfWork($this);
                    break;
                default:
                    $class = 'Doctrine_' . ucwords($name) . '_' . $this->getName();
                    $this->modules[$name] = new $class($this);
                }
        }

        return $this->modules[$name];
    }
    /**
     * Quotes pattern (% and _) characters in a string)
     *
     * EXPERIMENTAL
     *
     * WARNING: this function is experimental and may change signature at
     * any time until labelled as non-experimental
     *
     * @param   string  the input string to quote
     *
     * @return  string  quoted string
     */
    public function escapePattern($text)
    {
        if ($this->string_quoting['escape_pattern']) {
            $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
            foreach ($this->wildcards as $wildcard) {
                $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
            }
        }
        return $text;
    }
zYne's avatar
zYne committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    /**
     * convertBoolean
     * some drivers need the boolean values to be converted into integers
     * when using DQL API
     *
     * This method takes care of that conversion
     *
     * @param array $item
     * @return void
     */
    public function convertBooleans(array $items)
    {
        foreach ($items as $k => $item) {
            if (is_bool($item)) {
                $items[$k] = (int) $item;
            }
        }
        return $items;
    }
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 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
    /**
     * Quote a string so it can be safely used as a table or column name
     *
     * Delimiting style depends on which database driver is being used.
     *
     * NOTE: just because you CAN use delimited identifiers doesn't mean
     * you SHOULD use them.  In general, they end up causing way more
     * problems than they solve.
     *
     * Portability is broken by using the following characters inside
     * delimited identifiers:
     *   + backtick (<kbd>`</kbd>) -- due to MySQL
     *   + double quote (<kbd>"</kbd>) -- due to Oracle
     *   + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
     *
     * Delimited identifiers are known to generally work correctly under
     * the following drivers:
     *   + mssql
     *   + mysql
     *   + mysqli
     *   + oci8
     *   + pgsql
     *   + sqlite
     *
     * InterBase doesn't seem to be able to use delimited identifiers
     * via PHP 4.  They work fine under PHP 5.
     *
     * @param string $str           identifier name to be quoted
     * @param bool $checkOption     check the 'quote_identifier' option
     *
     * @return string               quoted identifier string
     */
    public function quoteIdentifier($str, $checkOption = true)
    {
        if ($checkOption && ! $this->getAttribute(Doctrine::ATTR_QUOTE_IDENTIFIER)) {
            return $str;
        }
        $str = str_replace($this->properties['identifier_quoting']['end'],
                           $this->properties['identifier_quoting']['escape'] .
                           $this->properties['identifier_quoting']['end'], $str);

        return $this->properties['identifier_quoting']['start']
               . $str . $this->properties['identifier_quoting']['end'];
    }
    /**
     * returns the manager that created this connection
     *
     * @return Doctrine_Manager
     */
    public function getManager()
    {
        return $this->getParent();
    }
    /**
     * returns the database handler of which this connection uses
     *
     * @return PDO              the database handler
     */
    public function getDbh()
    {
        return $this->dbh;
    }
    /**
     * converts given driver name
     *
     * @param
     */
    public function driverName($name)
    {
    }
    /**
     * supports
     *
     * @param string $feature   the name of the feature
     * @return boolean          whether or not this drivers supports given feature
     */
    public function supports($feature)
    {
        return (isset($this->supported[$feature])
            && ($this->supported[$feature] === 'emulated'
                || $this->supported[$feature]
            )
       );
    }
    /**
     * quote
     * quotes given input parameter
     *
     * @param mixed $input      parameter to be quoted
     * @param string $type
     * @return mixed
     */
    public function quote($input, $type = null)
    {
        if ($type == null) {
            $type = gettype($input);
        }
        switch ($type) {
            case 'integer':
            case 'enum':
            case 'boolean':
zYne's avatar
zYne committed
328 329 330 331
            case 'double':
            case 'float':
            case 'bool':
            case 'int':
332 333 334 335 336 337 338 339 340 341 342 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 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 472 473 474 475 476 477 478 479 480 481 482 483 484 485
                return $input;
            case 'array':
            case 'object':
                $input = serialize($input);
            case 'string':
            case 'char':
            case 'varchar':
            case 'text':
            case 'gzip':
            case 'blob':
            case 'clob':
                return $this->dbh->quote($input);
        }
    }
    /**
     * Removes any formatting in an sequence name using the 'seqname_format' option
     *
     * @param string $sqn string that containts name of a potential sequence
     * @return string name of the sequence with possible formatting removed
     */
    public function fixSequenceName($sqn)
    {
        $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)',  $this->getAttribute(Doctrine::ATTR_SEQNAME_FORMAT)).'$/i';
        $seqName    = preg_replace($seqPattern, '\\1', $sqn);

        if ($seqName && ! strcasecmp($sqn, $this->getSequenceName($seqName))) {
            return $seqName;
        }
        return $sqn;
    }
    /**
     * Removes any formatting in an index name using the 'idxname_format' option
     *
     * @param string $idx string that containts name of anl index
     * @return string name of the index with possible formatting removed
     */
    public function fixIndexName($idx)
    {
        $indexPattern   = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->getAttribute(Doctrine::ATTR_IDXNAME_FORMAT)).'$/i';
        $indexName      = preg_replace($indexPattern, '\\1', $idx);
        if ($indexName && ! strcasecmp($idx, $this->getIndexName($indexName))) {
            return $indexName;
        }
        return $idx;
    }
    /**
     * adds sequence name formatting to a sequence name
     *
     * @param string    name of the sequence
     * @return string   formatted sequence name
     */
    public function getSequenceName($sqn)
    {
        return sprintf($this->getAttribute(Doctrine::ATTR_SEQNAME_FORMAT),
            preg_replace('/[^a-z0-9_\$.]/i', '_', $sqn));
    }
    /**
     * adds index name formatting to a index name
     *
     * @param string    name of the index
     * @return string   formatted index name
     */
    public function getIndexName($idx)
    {
        return sprintf($this->getAttribute(Doctrine::ATTR_IDXNAME_FORMAT),
                preg_replace('/[^a-z0-9_\$]/i', '_', $idx));
    }

    /**
     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
     * query, except that if there is already a row in the table with the same
     * key field values, the REPLACE query just updates its values instead of
     * inserting a new row.
     *
     * The REPLACE type of query does not make part of the SQL standards. Since
     * practically only MySQL and SQLIte implement it natively, this type of
     * query isemulated through this method for other DBMS using standard types
     * of queries inside a transaction to assure the atomicity of the operation.
     *
     * @param                   string  name of the table on which the REPLACE query will
     *                          be executed.
     *
     * @param   array           an associative array that describes the fields and the
     *                          values that will be inserted or updated in the specified table. The
     *                          indexes of the array are the names of all the fields of the table.
     *
     *                          The values of the array are values to be assigned to the specified field.
     *
     * @param array $keys       an array containing all key fields (primary key fields
     *                          or unique index fields) for this table
     *
     *                          the uniqueness of a row will be determined according to
     *                          the provided key fields
     *
     *                          this method will fail if no key fields are specified
     *
     * @throws Doctrine_Connection_Exception        if this driver doesn't support replace
     * @throws Doctrine_Connection_Exception        if some of the key values was null
     * @throws Doctrine_Connection_Exception        if there were no key fields
     * @throws PDOException                         if something fails at PDO level
     * @return integer                              number of rows affected
     */
    public function replace($table, array $fields, array $keys)
    {
        //if ( ! $this->supports('replace'))
        //    throw new Doctrine_Connection_Exception('replace query is not supported');

        if (empty($keys)) {
            throw new Doctrine_Connection_Exception('Not specified which fields are keys');
        }
        $condition = $values = array();

        foreach ($fields as $name => $value) {
            $values[$name] = $value;

            if (in_array($name, $keys)) {
                if ($value === null)
                    throw new Doctrine_Connection_Exception('key value '.$name.' may not be null');

                $condition[]       = $name . ' = ?';
                $conditionValues[] = $value;
            }
        }

        $query          = 'DELETE FROM '. $table . ' WHERE ' . implode(' AND ', $condition);
        $affectedRows   = $this->exec($query);

        $this->insert($table, $values);

        $affectedRows++;


        return $affectedRows;
    }
    /**
     * Inserts a table row with specified data.
     *
     * @param string $table     The table to insert data into.
     * @param array $values     An associateve array containing column-value pairs.
     * @return boolean
     */
    public function insert($table, array $values = array()) {
        if (empty($values)) {
            return false;
        }
        // column names are specified as array keys
        $cols = array_keys($values);

        // build the statement
        $query = "INSERT INTO $table "
               . '(' . implode(', ', $cols) . ') '
               . 'VALUES (' . substr(str_repeat('?, ', count($values)), 0, -2) . ')';

        // prepare and execute the statement
486
        $this->execute($query, array_values($values));
487 488 489 490 491 492 493 494 495 496 497 498

        return true;
    }
    /**
     * Set the charset on the current connection
     *
     * @param string    charset
     *
     * @return void
     */
    public function setCharset($charset)
    {
zYne's avatar
zYne committed
499

500
    }
501 502 503 504 505 506 507 508 509 510
    /**
     * Set the date/time format for the current connection
     *
     * @param string    time format
     *
     * @return void
     */
    public function setDateFormat($format = null)
    {
    }
511 512 513 514 515 516 517
    /**
     * fetchAll
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
zYne's avatar
zYne committed
518 519
    public function fetchAll($statement, array $params = array()) 
    {
zYne's avatar
zYne committed
520
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_ASSOC);
521 522 523 524 525 526 527 528 529
    }
    /**
     * fetchOne
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @param int $colnum               0-indexed column number to retrieve
     * @return mixed
     */
zYne's avatar
zYne committed
530 531
    public function fetchOne($statement, array $params = array(), $colnum = 0) 
    {
532 533 534 535 536 537 538 539 540
        return $this->execute($statement, $params)->fetchColumn($colnum);
    }
    /**
     * fetchRow
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
zYne's avatar
zYne committed
541 542
    public function fetchRow($statement, array $params = array()) 
    {
zYne's avatar
zYne committed
543
        return $this->execute($statement, $params)->fetch(PDO::FETCH_ASSOC);
544 545 546 547 548 549 550 551
    }
    /**
     * fetchArray
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
zYne's avatar
zYne committed
552 553
    public function fetchArray($statement, array $params = array()) 
    {
zYne's avatar
zYne committed
554
        return $this->execute($statement, $params)->fetch(PDO::FETCH_NUM);
555 556 557 558 559 560 561 562 563
    }
    /**
     * fetchColumn
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @param int $colnum               0-indexed column number to retrieve
     * @return array
     */
zYne's avatar
zYne committed
564 565
    public function fetchColumn($statement, array $params = array(), $colnum = 0) 
    {
zYne's avatar
zYne committed
566
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_COLUMN, $colnum);
567 568 569 570 571 572 573 574
    }
    /**
     * fetchAssoc
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
zYne's avatar
zYne committed
575 576
    public function fetchAssoc($statement, array $params = array()) 
    {
zYne's avatar
zYne committed
577
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_ASSOC);
578 579 580 581 582 583 584 585
    }
    /**
     * fetchBoth
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
zYne's avatar
zYne committed
586 587
    public function fetchBoth($statement, array $params = array()) 
    {
zYne's avatar
zYne committed
588
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_BOTH);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    }
    /**
     * query
     * queries the database using Doctrine Query Language
     * returns a collection of Doctrine_Record objects
     *
     * <code>
     * $users = $conn->query('SELECT u.* FROM User u');
     *
     * $users = $conn->query('SELECT u.* FROM User u WHERE u.name LIKE ?', array('someone'));
     * </code>
     *
     * @param string $query             DQL query
     * @param array $params             query parameters
     * @see Doctrine_Query
     * @return Doctrine_Collection      Collection of Doctrine_Record objects
     */
zYne's avatar
zYne committed
606 607
    public function query($query, array $params = array()) 
    {
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
        $parser = new Doctrine_Query($this);

        return $parser->query($query, $params);
    }
    /**
     * query
     * queries the database using Doctrine Query Language and returns
     * the first record found
     *
     * <code>
     * $user = $conn->queryOne('SELECT u.* FROM User u WHERE u.id = ?', array(1));
     *
     * $user = $conn->queryOne('SELECT u.* FROM User u WHERE u.name LIKE ? AND u.password = ?',
     *         array('someone', 'password')
     *         );
     * </code>
     *
     * @param string $query             DQL query
     * @param array $params             query parameters
     * @see Doctrine_Query
     * @return Doctrine_Record|false    Doctrine_Record object on success,
     *                                  boolean false on failure
     */
zYne's avatar
zYne committed
631 632
    public function queryOne($query, array $params = array()) 
    {
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
        $parser = new Doctrine_Query($this);

        $coll = $parser->query($query, $params);
        if ( ! $coll->contains(0)) {
            return false;
        }
        return $coll[0];
    }
    /**
     * queries the database with limit and offset
     * added to the query and returns a PDOStatement object
     *
     * @param string $query
     * @param integer $limit
     * @param integer $offset
     * @return PDOStatement
     */
    public function select($query,$limit = 0,$offset = 0)
    {
        if ($limit > 0 || $offset > 0) {
            $query = $this->modifyLimitQuery($query, $limit, $offset);
        }
        return $this->dbh->query($query);
    }
zYne's avatar
zYne committed
657 658 659 660 661 662 663 664 665 666 667 668
    /**
     * standaloneQuery
     *
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement|Doctrine_Adapter_Statement
     */
    public function standaloneQuery($query, $params = array())
    {
        return $this->execute($query, $params);
    }
669 670 671 672 673 674 675
    /**
     * execute
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement|Doctrine_Adapter_Statement
     */
zYne's avatar
zYne committed
676 677
    public function execute($query, array $params = array()) 
    {
678 679 680 681 682 683 684 685 686 687
        try {
            if ( ! empty($params)) {
                $stmt = $this->dbh->prepare($query);
                $stmt->execute($params);
                return $stmt;
            } else {
                return $this->dbh->query($query);
            }
        } catch(Doctrine_Adapter_Exception $e) {
        } catch(PDOException $e) { }
zYne's avatar
zYne committed
688

689 690 691 692 693 694 695 696 697 698 699 700 701 702
        $this->rethrowException($e);
    }
    /**
     * exec
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement|Doctrine_Adapter_Statement
     */
    public function exec($query, array $params = array()) {
        try {
            if ( ! empty($params)) {
                $stmt = $this->dbh->prepare($query);
                $stmt->execute($params);
zYne's avatar
zYne committed
703
                return $stmt->rowCount();
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
            } else {
                return $this->dbh->exec($query);
            }
        } catch(Doctrine_Adapter_Exception $e) {
        } catch(PDOException $e) { }

        $this->rethrowException($e);
    }
    /**
     * rethrowException
     *
     * @throws Doctrine_Connection_Exception
     */
    private function rethrowException(Exception $e)
    {
        $name = 'Doctrine_Connection_' . $this->driverName . '_Exception';

        $exc  = new $name($e->getMessage(), (int) $e->getCode());
        if ( ! is_array($e->errorInfo)) {
            $e->errorInfo = array(null, null, null, null);
        }
        $exc->processErrorInfo($e->errorInfo);

        throw $exc;
    }
    /**
     * hasTable
     * whether or not this connection has table $name initialized
     *
     * @param mixed $name
     * @return boolean
     */
    public function hasTable($name)
    {
        return isset($this->tables[$name]);
    }
    /**
     * returns a table object for given component name
     *
     * @param string $name              component name
     * @return object Doctrine_Table
     */
zYne's avatar
zYne committed
746
    public function getTable($name, $allowExport = true)
747 748 749 750
    {
        if (isset($this->tables[$name])) {
            return $this->tables[$name];
        }
zYne's avatar
zYne committed
751
        $class = $name . 'Table';
752

zYne's avatar
zYne committed
753 754
        if (class_exists($class) && in_array('Doctrine_Table', class_parents($class))) {
            $table = new $class($name, $this, $allowExport);
755
        } else {
zYne's avatar
zYne committed
756
            $table = new Doctrine_Table($name, $this, $allowExport);
757
        }
zYne's avatar
zYne committed
758 759 760 761
        
        $this->tables[$name] = $table;
        
        return $table;
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 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 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
    }
    /**
     * returns an array of all initialized tables
     *
     * @return array
     */
    public function getTables()
    {
        return $this->tables;
    }
    /**
     * returns an iterator that iterators through all
     * initialized table objects
     *
     * <code>
     * foreach ($conn as $index => $table) {
     *      print $table;  // get a string representation of each table object
     * }
     * </code>
     *
     * @return ArrayIterator        SPL ArrayIterator object
     */
    public function getIterator()
    {
        return new ArrayIterator($this->tables);
    }
    /**
     * returns the count of initialized table objects
     *
     * @return integer
     */
    public function count()
    {
        return count($this->tables);
    }
    /**
     * addTable
     * adds a Doctrine_Table object into connection registry
     *
     * @param $objTable             a Doctrine_Table object to be added into registry
     * @return boolean
     */
    public function addTable(Doctrine_Table $objTable)
    {
        $name = $objTable->getComponentName();

        if (isset($this->tables[$name])) {
            return false;
        }
        $this->tables[$name] = $objTable;
        return true;
    }
    /**
     * create
     * creates a record
     *
     * create                       creates a record
     * @param string $name          component name
     * @return Doctrine_Record      Doctrine_Record object
     */
    public function create($name)
    {
        return $this->getTable($name)->create();
    }
    /**
     * flush
     * saves all the records from all tables
     * this operation is isolated using a transaction
     *
     * @throws PDOException         if something went wrong at database level
     * @return void
     */
    public function flush()
    {
        $this->beginTransaction();
        $this->unitOfWork->saveAll();
        $this->commit();
    }
    /**
     * clear
     * clears all repositories
     *
     * @return void
     */
    public function clear()
    {
        foreach ($this->tables as $k => $table) {
            $table->getRepository()->evictAll();
            $table->clear();
        }
    }
    /**
     * evictTables
     * evicts all tables
     *
     * @return void
     */
    public function evictTables()
    {
        $this->tables = array();
    }
    /**
     * close
     * closes the connection
     *
     * @return void
     */
    public function close()
    {
        $this->getAttribute(Doctrine::ATTR_LISTENER)->onPreClose($this);

        $this->clear();

        $this->getAttribute(Doctrine::ATTR_LISTENER)->onClose($this);
    }
    /**
     * get the current transaction nesting level
     *
     * @return integer
     */
    public function getTransactionLevel()
    {
        return $this->transaction->getTransactionLevel();
    }
    /**
     * beginTransaction
     * starts a new transaction
     *
     * this method can be listened by onPreBeginTransaction and onBeginTransaction
     * listener methods
     *
     * @return void
     */
    public function beginTransaction()
    {
        $this->transaction->beginTransaction();
    }
    /**
     * commits the current transaction
     * if lockmode is optimistic this method starts a transaction
     * and commits it instantly
     *
     * @return void
     */
    public function commit()
    {
        $this->transaction->commit();
    }
    /**
     * rollback
     * rolls back all transactions
     *
     * this method also listens to onPreTransactionRollback and onTransactionRollback
     * eventlisteners
     *
     * @return void
     */
    public function rollback()
    {
        $this->transaction->rollback();
    }
    /**
     * saves the given record
     *
     * @param Doctrine_Record $record
     * @return void
     */
    public function save(Doctrine_Record $record)
    {
        $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($record);

zYne's avatar
zYne committed
933
        switch ($record->state()) {
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
            case Doctrine_Record::STATE_TDIRTY:
                $this->unitOfWork->insert($record);
                break;
            case Doctrine_Record::STATE_DIRTY:
            case Doctrine_Record::STATE_PROXY:
                $this->unitOfWork->update($record);
                break;
            case Doctrine_Record::STATE_CLEAN:
            case Doctrine_Record::STATE_TCLEAN:
                // do nothing
                break;
        };

        $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onSave($record);
    }
    /**
     * deletes this data access object and all the related composites
     * this operation is isolated by a transaction
     *
     * this event can be listened by the onPreDelete and onDelete listeners
     *
     * @return boolean      true on success, false on failure
     */
    public function delete(Doctrine_Record $record)
    {
        if ( ! $record->exists()) {
            return false;
        }
        $this->beginTransaction();

        $record->getTable()->getListener()->onPreDelete($record);

        $this->unitOfWork->deleteComposites($record);

        $this->transaction->addDelete($record);

        $record->getTable()->getListener()->onDelete($record);

        $this->commit();

        return true;
    }
    /**
     * returns a string representation of this object
     * @return string
     */
    public function __toString()
    {
        return Doctrine_Lib::getConnectionAsString($this);
    }
}