Connection.php 25.5 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 *  $Id: Connection.php 4933 2008-09-12 10:58:33Z romanb $
 *
 * 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.org>.
 */

22
#namespace Doctrine\DBAL;
romanb's avatar
romanb committed
23

24 25
#use Doctrine\Common\EventManager;
#use Doctrine\DBAL\Exceptions\ConnectionException;
26 27

/**
28
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
29 30
 * events, transaction isolation levels, configuration, emulated transaction nesting,
 * lazy connecting and more.
31
 *
romanb's avatar
romanb committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @since       1.0
 * @version     $Revision: 4933 $
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Lukas Smith <smith@pooteeweet.org> (MDB2 library)
 * @author      Roman Borschel <roman@code-factory.org>
 * @todo
 * 1) REPLICATION SUPPORT
 * Replication support should be tackled at this layer (DBAL).
 * There can be options that look like:
 *       'slaves' => array(
 *           'slave1' => array(
 *                user, pass etc.
 *           ),
 *           'slave2' => array(
 *                user, pass etc.
 *           )),
 *       'slaveConnectionResolver' => new MySlaveConnectionResolver(),
 *       'masters' => array(...),
 *       'masterConnectionResolver' => new MyMasterConnectionResolver()
52
 * 
53
 * Doctrine\DBAL could ship with a simple standard broker that uses a primitive
romanb's avatar
romanb committed
54
 * round-robin approach to distribution. User can provide its own brokers.
55
 */
romanb's avatar
romanb committed
56
class Doctrine_DBAL_Connection
57
{
58 59 60
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
     */
61
    const TRANSACTION_READ_UNCOMMITTED = 1;
62 63 64
    /**
     * Constant for transaction isolation level READ COMMITTED.
     */
65
    const TRANSACTION_READ_COMMITTED = 2;
66 67 68
    /**
     * Constant for transaction isolation level REPEATABLE READ.
     */
69
    const TRANSACTION_REPEATABLE_READ = 3;
70 71 72
    /**
     * Constant for transaction isolation level SERIALIZABLE.
     */
73 74
    const TRANSACTION_SERIALIZABLE = 4;
    
romanb's avatar
romanb committed
75 76 77
    /**
     * The wrapped driver connection. 
     *
78
     * @var Doctrine\DBAL\Driver\Connection
romanb's avatar
romanb committed
79 80 81 82 83 84
     */
    protected $_conn;
    
    /**
     * The Configuration.
     *
85
     * @var Doctrine\DBAL\Configuration
romanb's avatar
romanb committed
86 87 88 89 90 91
     */
    protected $_config;
    
    /**
     * The EventManager.
     *
92
     * @var Doctrine\Common\EventManager
romanb's avatar
romanb committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
     */
    protected $_eventManager;
    
    /**
     * Whether or not a connection has been established.
     *
     * @var boolean               
     */
    protected $_isConnected = false;
    
    /**
     * The transaction nesting level.
     *
     * @var integer
     */
    protected $_transactionNestingLevel = 0;
    
    /**
     * The currently active transaction isolation level.
     *
     * @var integer
     */
    protected $_transactionIsolationLevel;
    
    /**
118
     * The parameters used during creation of the Connection instance.
romanb's avatar
romanb committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
     * 
     * @var array
     */
    protected $_params = array();
    
    /**
     * The query count. Represents the number of executed database queries by the connection.
     *
     * @var integer
     */
    protected $_queryCount = 0;
    
    /**
     * The DatabasePlatform object that provides information about the
     * database platform used by the connection.
     *
135
     * @var Doctrine\DBAL\Platforms\AbstractPlatform
romanb's avatar
romanb committed
136 137 138 139 140 141
     */
    protected $_platform;
    
    /**
     * The schema manager.
     *
142
     * @var Doctrine\DBAL\Schema\SchemaManager
romanb's avatar
romanb committed
143 144 145
     */
    protected $_schemaManager;
    
146 147 148
    /**
     * The used DBAL driver.
     *
149
     * @var Doctrine\DBAL\Driver
150 151 152
     */
    protected $_driver;
    
romanb's avatar
romanb committed
153
    /**
154
     * Initializes a new instance of the Connection class.
romanb's avatar
romanb committed
155 156 157 158
     *
     * @param array $params  The connection parameters.
     */
    public function __construct(array $params, Doctrine_DBAL_Driver $driver,
159
            Doctrine_DBAL_Configuration $config = null,
160
            Doctrine_Common_EventManager $eventManager = null)
romanb's avatar
romanb committed
161 162 163 164 165 166 167 168 169 170 171
    {
        $this->_driver = $driver;
        $this->_params = $params;
        
        if (isset($params['pdo'])) {
            $this->_conn = $params['pdo'];
            $this->_isConnected = true;
        }
        
        // Create default config and event manager if none given
        if ( ! $config) {
172
            $this->_config = new Doctrine_DBAL_Configuration();
romanb's avatar
romanb committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        }
        if ( ! $eventManager) {
            $this->_eventManager = new Doctrine_Common_EventManager();
        }

        $this->_platform = $driver->getDatabasePlatform();
        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
    }
    
    /**
     * Gets the Configuration used by the Connection.
     *
     * @return Configuration
     */
    public function getConfiguration()
    {
        return $this->_config;
    }
    
    /**
     * Gets the EventManager used by the Connection.
     *
195
     * @return Doctrine\Common\EventManager
romanb's avatar
romanb committed
196 197 198 199 200 201 202 203 204
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }
    
    /**
     * Gets the DatabasePlatform for the connection.
     *
205
     * @return Doctrine\DBAL\Platforms\AbstractPlatform
romanb's avatar
romanb committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }
    
    /**
     * Establishes the connection with the database.
     *
     * @return boolean
     */
    public function connect()
    {
        if ($this->_isConnected) {
            return false;
        }
        
        $driverOptions = isset($this->_params['driverOptions']) ?
                $this->_params['driverOptions'] : array();
        $user = isset($this->_params['user']) ?
                $this->_params['user'] : null;
        $password = isset($this->_params['password']) ?
                $this->_params['password'] : null;
229 230 231
        
        $this->_conn = $this->_driver->connect(
                $this->_params,
romanb's avatar
romanb committed
232 233 234 235 236 237 238 239 240 241 242
                $user,
                $password,
                $driverOptions
                );

        $this->_isConnected = true;

        return true;
    }
    
    /**
243
     * Whether an actual connection to the database is established.
romanb's avatar
romanb committed
244 245 246
     *
     * @return boolean
     */
247
    public function isConnected()
romanb's avatar
romanb committed
248
    {
249
        return $this->_isConnected;
romanb's avatar
romanb committed
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
    }

    /**
     * Deletes table row(s) matching the specified identifier.
     *
     * @throws Doctrine_Connection_Exception    if something went wrong at the database level
     * @param string $table         The table to delete data from
     * @param array $identifier     An associateve array containing identifier fieldname-value pairs.
     * @return integer              The number of affected rows
     */
    public function delete($tableName, array $identifier)
    {
        $criteria = array();
        foreach (array_keys($identifier) as $id) {
            $criteria[] = $this->quoteIdentifier($id) . ' = ?';
        }

        $query = 'DELETE FROM '
               . $this->quoteIdentifier($tableName)
               . ' WHERE ' . implode(' AND ', $criteria);

        return $this->exec($query, array_values($identifier));
    }

    /**
     * Updates table row(s) with specified data
     *
     * @throws Doctrine_Connection_Exception    if something went wrong at the database level
     * @param string $table     The table to insert data into
     * @param array $values     An associateve array containing column-value pairs.
     * @return mixed            boolean false if empty value array was given,
     *                          otherwise returns the number of affected rows
     */
    public function update($tableName, array $data, array $identifier)
    {
        if (empty($data)) {
            return false;
        }

        $set = array();
        foreach ($data as $columnName => $value) {
            if ($value instanceof Doctrine_Expression) {
                $set[] = $this->quoteIdentifier($columnName) . ' = ' . $value->getSql();
                unset($data[$columnName]);
            } else {
                $set[] = $this->quoteIdentifier($columnName) . ' = ?';
            }
        }

        $params = array_merge(array_values($data), array_values($identifier));

        $sql  = 'UPDATE ' . $this->quoteIdentifier($tableName)
              . ' SET ' . implode(', ', $set)
              . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
              . ' = ?';
305

romanb's avatar
romanb committed
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 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
        return $this->exec($sql, $params);
    }

    /**
     * Inserts a table row with specified data.
     *
     * @param string $table     The table to insert data into.
     * @param array $fields     An associateve array containing fieldname-value pairs.
     * @return mixed            boolean false if empty value array was given,
     *                          otherwise returns the number of affected rows
     */
    public function insert($tableName, array $data)
    {
        if (empty($data)) {
            return false;
        }

        // column names are specified as array keys
        $cols = array();
        // the query VALUES will contain either expressions (eg 'NOW()') or ?
        $a = array();
        foreach ($data as $columnName => $value) {
            $cols[] = $this->quoteIdentifier($columnName);
            if ($value instanceof Doctrine_Expression) {
                $a[] = $value->getSql();
                unset($data[$columnName]);
            } else {
                $a[] = '?';
            }
        }

        $query = 'INSERT INTO ' . $this->quoteIdentifier($tableName)
               . ' (' . implode(', ', $cols) . ') '
               . 'VALUES (';
        $query .= implode(', ', $a) . ')';

        return $this->exec($query, array_values($data));
    }

    /**
     * Set the charset on the current connection
     *
     * @param string    charset
     */
    public function setCharset($charset)
    {
        $this->exec($this->_platform->getSetCharsetSql($charset));
    }

    /**
     * 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
     *
     * @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)
    {
        return $this->_platform->quoteIdentifier($str);
    }

    /**
390
     * Quotes a given input parameter.
romanb's avatar
romanb committed
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 486 487
     *
     * @param mixed $input  Parameter to be quoted.
     * @param string $type  Type of the parameter.
     * @return string  The quoted parameter.
     */
    public function quote($input, $type = null)
    {
        return $this->_conn->quote($input, $type);
    }

    /**
     * fetchAll
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchAll($statement, array $params = array())
    {
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * 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
     */
    public function fetchOne($statement, array $params = array(), $colnum = 0)
    {
        return $this->execute($statement, $params)->fetchColumn($colnum);
    }

    /**
     * fetchRow
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchRow($statement, array $params = array())
    {
        return $this->execute($statement, $params)->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * fetchArray
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchArray($statement, array $params = array())
    {
        return $this->execute($statement, $params)->fetch(PDO::FETCH_NUM);
    }

    /**
     * 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
     */
    public function fetchColumn($statement, array $params = array(), $colnum = 0)
    {
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_COLUMN, $colnum);
    }

    /**
     * fetchAssoc
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchAssoc($statement, array $params = array())
    {
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * fetchBoth
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchBoth($statement, array $params = array())
    {
        return $this->execute($statement, $params)->fetchAll(PDO::FETCH_BOTH);
    }
    
    /**
488
     * Prepares an SQL statement.
romanb's avatar
romanb committed
489 490
     *
     * @param string $statement
491
     * @return Doctrine::DBAL::Statement
romanb's avatar
romanb committed
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 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
     */
    public function prepare($statement)
    {
        $this->connect();
        try {
            $stmt = $this->_conn->prepare($statement);
            return new Doctrine_DBAL_Statement($this, $stmt);
        } catch (PDOException $e) {
            $this->rethrowException($e, $this);
        }
    }
    
    /**
     * Queries the database with limit and offset
     * added to the query and returns a Doctrine_Connection_Statement object
     *
     * @param string $query
     * @param integer $limit
     * @param integer $offset
     * @return Doctrine_Connection_Statement
     */
    public function select($query, $limit = 0, $offset = 0)
    {
        if ($limit > 0 || $offset > 0) {
            $query = $this->_platform->modifyLimitQuery($query, $limit, $offset);
        }
        return $this->execute($query);
    }

    /**
     * Executes an SQL SELECT query with the given parameters.
     * 
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement|Doctrine_Adapter_Statement
     */
    public function execute($query, array $params = array())
    {
        $this->connect();
        try {
            if ( ! empty($params)) {
                $stmt = $this->prepare($query);
                $stmt->execute($params);
                return $stmt;
            } else {
                $stmt = $this->_conn->query($query);
                $this->_queryCount++;
                return $stmt;
            }
        } catch (PDOException $e) {
            $this->rethrowException($e, $this);
        }
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters.
     * 
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement|Doctrine_Adapter_Statement
     * @todo Rename to executeUpdate().
     */
    public function exec($query, array $params = array()) {
        $this->connect();
        try {
            if ( ! empty($params)) {
                $stmt = $this->prepare($query);
                $stmt->execute($params);
                return $stmt->rowCount();
            } else {
                $count = $this->_conn->exec($query);
                $this->_queryCount++;
                return $count;
            }
        } catch (PDOException $e) {
            $this->rethrowException($e, $this);
        }
    }

    /**
     * Wraps the given exception into a driver-specific exception and rethrows it.
     *
     * @throws Doctrine_Connection_Exception
     */
    public function rethrowException(Exception $e, $invoker)
    {
        throw $exc;
    }
    
    /**
     * Returns the number of queries executed by the connection.
     *
     * @return integer
     */
    public function getQueryCount()
    {
        return $this->_queryCount;
    }
    
    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
        $this->clear();
        unset($this->_conn);
        $this->_isConnected = false;
    }
    
    /**
     * Sets the transaction isolation level.
     *
     * @param integer $level The level to set.
     */
    public function setTransactionIsolation($level)
    {
        $this->_transactionIsolationLevel = $level;
613
        return $this->exec($this->_platform->getSetTransactionIsolationSql($level));
romanb's avatar
romanb committed
614 615 616 617 618 619 620 621 622 623 624 625 626
    }
    
    /**
     * Gets the currently active transaction isolation level.
     *
     * @return integer The current transaction isolation level.
     */
    public function getTransactionIsolation()
    {
        return $this->_transactionIsolationLevel;
    }

    /**
627
     * Returns the current transaction nesting level.
romanb's avatar
romanb committed
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
     *
     * @return integer  The nesting level. A value of 0 means theres no active transaction.
     */
    public function getTransactionNestingLevel()
    {
        return $this->_transactionNestingLevel;
    }
    
    /**
     * Fetch the SQLSTATE associated with the last operation on the database handle
     *
     * @return integer
     */
    public function errorCode()
    {
        $this->connect();
        return $this->_conn->errorCode();
    }

    /**
     * Fetch extended error information associated with the last operation on the database handle
     *
     * @return array
     */
    public function errorInfo()
    {
        $this->connect();
        return $this->_conn->errorInfo();
    }
    
    /**
     * Returns the ID of the last inserted row, or the last value from a sequence object,
     * depending on the underlying driver.
     *
     * Note: This method may not return a meaningful or consistent result across different drivers,
     * because the underlying database may not even support the notion of auto-increment fields or sequences.
     *
     * @param string $table     Name of the table into which a new row was inserted.
     * @param string $field     Name of the field into which a new row was inserted.
     */
    public function lastInsertId($seqName = null)
    {
        return $this->_conn->lastInsertId($seqName);
    }

    /**
     * Start a transaction or set a savepoint.
     *
     * if trying to set a savepoint and there is no active transaction
     * a new transaction is being started.
678 679
     * 
     * @return boolean
romanb's avatar
romanb committed
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
     */
    public function beginTransaction()
    {
        if ($this->_transactionNestingLevel == 0) {
            return $this->_conn->beginTransaction();
        }
        ++$this->_transactionNestingLevel;
        return true;
    }
    
    /**
     * Commits the database changes done during a transaction that is in
     * progress or release a savepoint. This function may only be called when
     * auto-committing is disabled, otherwise it will fail.
     *
695
     * @return boolean FALSE if commit couldn't be performed, TRUE otherwise
romanb's avatar
romanb committed
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 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 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 833 834 835 836 837 838 839 840 841 842 843
     */
    public function commit()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw new Doctrine_Exception("Commit failed. There is no active transaction.");
        }
        
        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            return $this->_conn->commit();
        }
        --$this->_transactionNestingLevel;
        
        return true;
    }

    /**
     * Cancel any database changes done during a transaction or since a specific
     * savepoint that is in progress. This function may only be called when
     * auto-committing is disabled, otherwise it will fail. Therefore, a new
     * transaction is implicitly started after canceling the pending changes.
     *
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
     * eventlistener methods
     *
     * @param string $savepoint                 Name of a savepoint to rollback to.
     * @throws Doctrine_Transaction_Exception   If the rollback operation fails at database level.
     * @return boolean                          FALSE if rollback couldn't be performed, TRUE otherwise.
     */
    public function rollback()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw new Doctrine_Exception("Rollback failed. There is no active transaction.");
        }
        
        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            $this->_transactionNestingLevel = 0;
            return $this->_conn->rollback();
            
        }
        --$this->_transactionNestingLevel;
        
        return true;
    }
    
    /**
     * 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
     */
    protected function _escapePattern($text)
    {
        return $text;
    }

    /**
     * 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
     */
    protected function _fixSequenceName($sqn)
    {
        $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)',  $this->conn->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
     */
    protected function _fixIndexName($idx)
    {
        $indexPattern   = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->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
     */
    protected function _getSequenceName($sqn)
    {
        return sprintf($this->conn->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
     */
    protected function _getIndexName($idx)
    {
        return sprintf($this->conn->getAttribute(Doctrine::ATTR_IDXNAME_FORMAT),
            preg_replace('/[^a-z0-9_\$]/i', '_', $idx));
    }

    /**
     * adds table name formatting to a table name
     *
     * @param string    name of the table
     * @return string   formatted table name
     */
    protected function _getTableName($table)
    {
        return $table;
        /*
        return sprintf($this->conn->getAttribute(Doctrine::ATTR_TBLNAME_FORMAT),
                $table);*/
    }

    /**
     * returns a string representation of this object
     * @return string
     */
    public function __toString()
    {
        return Doctrine_Lib::getConnectionAsString($this);
    }
    
    /**
     * Gets the wrapped driver connection.
     *
844
     * @return Doctrine\DBAL\Driver\Connection
romanb's avatar
romanb committed
845 846 847 848 849 850 851 852 853 854
     */
    public function getWrappedConnection()
    {
        return $this->_conn;
    }
    
    /**
     * Gets the SchemaManager that can be used to inspect or change the 
     * database schema through the connection.
     *
855
     * @return Doctrine\DBAL\Schema\SchemaManager
romanb's avatar
romanb committed
856 857 858 859
     */
    public function getSchemaManager()
    {
        if ( ! $this->_schemaManager) {
860
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
romanb's avatar
romanb committed
861 862 863 864
        }
        return $this->_schemaManager;
    }
}