Connection.php 22.3 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2
/*
3
 *  $Id$
romanb's avatar
romanb committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
20 21
 */

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

24 25
use Doctrine\Common\EventManager,
    Doctrine\Common\DoctrineException;
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
 *
32 33 34 35 36 37 38 39 40
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision: 3938 $
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 * @author  Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author  Lukas Smith <smith@pooteeweet.org> (MDB2 library)
41
 */
42
class Connection
43
{
romanb's avatar
romanb committed
44 45 46 47
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
     */
    const TRANSACTION_READ_UNCOMMITTED = 1;
48
    
romanb's avatar
romanb committed
49 50 51 52
    /**
     * Constant for transaction isolation level READ COMMITTED.
     */
    const TRANSACTION_READ_COMMITTED = 2;
53
    
romanb's avatar
romanb committed
54 55 56 57
    /**
     * Constant for transaction isolation level REPEATABLE READ.
     */
    const TRANSACTION_REPEATABLE_READ = 3;
58
    
romanb's avatar
romanb committed
59 60 61 62
    /**
     * Constant for transaction isolation level SERIALIZABLE.
     */
    const TRANSACTION_SERIALIZABLE = 4;
63

64 65 66 67 68 69 70 71 72
    /**
     * Derived PDO constants
     */
    const FETCH_ASSOC       = 2;
    const FETCH_BOTH        = 4;
    const FETCH_COLUMN      = 7;
    const FETCH_NUM         = 3;
    const ATTR_AUTOCOMMIT   = 0;

romanb's avatar
romanb committed
73 74 75 76 77 78
    /**
     * The wrapped driver connection.
     *
     * @var Doctrine\DBAL\Driver\Connection
     */
    protected $_conn;
79

romanb's avatar
romanb committed
80 81 82 83 84 85
    /**
     * The Configuration.
     *
     * @var Doctrine\DBAL\Configuration
     */
    protected $_config;
86

romanb's avatar
romanb committed
87 88 89 90 91 92
    /**
     * The EventManager.
     *
     * @var Doctrine\Common\EventManager
     */
    protected $_eventManager;
93

romanb's avatar
romanb committed
94 95 96 97 98
    /**
     * Whether or not a connection has been established.
     *
     * @var boolean
     */
99
    private $_isConnected = false;
100

romanb's avatar
romanb committed
101 102 103 104 105
    /**
     * The transaction nesting level.
     *
     * @var integer
     */
106
    private $_transactionNestingLevel = 0;
romanb's avatar
romanb committed
107

romanb's avatar
romanb committed
108 109 110 111 112
    /**
     * The currently active transaction isolation level.
     *
     * @var integer
     */
113
    private $_transactionIsolationLevel;
114

romanb's avatar
romanb committed
115 116 117 118 119
    /**
     * The parameters used during creation of the Connection instance.
     *
     * @var array
     */
120
    private $_params = array();
121

romanb's avatar
romanb committed
122 123 124 125 126 127 128
    /**
     * The DatabasePlatform object that provides information about the
     * database platform used by the connection.
     *
     * @var Doctrine\DBAL\Platforms\AbstractPlatform
     */
    protected $_platform;
129

romanb's avatar
romanb committed
130 131 132 133 134 135
    /**
     * The schema manager.
     *
     * @var Doctrine\DBAL\Schema\SchemaManager
     */
    protected $_schemaManager;
136

romanb's avatar
romanb committed
137
    /**
romanb's avatar
romanb committed
138 139 140 141 142
     * The used DBAL driver.
     *
     * @var Doctrine\DBAL\Driver
     */
    protected $_driver;
143 144 145 146 147 148 149
    
    /**
     * Flag that indicates whether the current transaction is marked for rollback only.
     * 
     * @var boolean
     */
    private $_isRollbackOnly = false;
150

romanb's avatar
romanb committed
151 152 153 154 155 156 157 158 159 160 161 162 163
    /**
     * Initializes a new instance of the Connection class.
     *
     * @param array $params  The connection parameters.
     * @param Driver $driver
     * @param Configuration $config
     * @param EventManager $eventManager
     */
    public function __construct(array $params, Driver $driver, Configuration $config = null,
            EventManager $eventManager = null)
    {
        $this->_driver = $driver;
        $this->_params = $params;
164

romanb's avatar
romanb committed
165 166 167 168
        if (isset($params['pdo'])) {
            $this->_conn = $params['pdo'];
            $this->_isConnected = true;
        }
169

romanb's avatar
romanb committed
170 171 172
        // Create default config and event manager if none given
        if ( ! $config) {
            $config = new Configuration();
romanb's avatar
romanb committed
173
        }
174
        
romanb's avatar
romanb committed
175
        if ( ! $eventManager) {
romanb's avatar
romanb committed
176
            $eventManager = new EventManager();
romanb's avatar
romanb committed
177
        }
178

romanb's avatar
romanb committed
179
        $this->_config = $config;
romanb's avatar
romanb committed
180 181 182
        $this->_eventManager = $eventManager;
        $this->_platform = $driver->getDatabasePlatform();
        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
romanb's avatar
romanb committed
183
    }
romanb's avatar
romanb committed
184

185
    /**
romanb's avatar
romanb committed
186
     * Gets the parameters used during instantiation.
187 188 189 190 191 192 193 194
     *
     * @return array $params
     */
    public function getParams()
    {
        return $this->_params;
    }

romanb's avatar
romanb committed
195
    /**
romanb's avatar
romanb committed
196
     * Gets the name of the database this Connection is connected to.
romanb's avatar
romanb committed
197 198 199 200 201 202 203
     *
     * @return string $database
     */
    public function getDatabase()
    {
        return $this->_driver->getDatabase($this);
    }
204 205 206 207 208 209 210 211
    
    /**
     * Gets the hostname of the currently connected database.
     * 
     * @return string
     */
    public function getHost()
    {
jwage's avatar
jwage committed
212
        return isset($this->_params['host']) ? $this->_params['host'] : null;
213 214 215 216 217 218 219 220 221
    }
    
    /**
     * Gets the port of the currently connected database.
     * 
     * @return mixed
     */
    public function getPort()
    {
jwage's avatar
jwage committed
222
        return isset($this->_params['port']) ? $this->_params['port'] : null;
223 224 225 226 227 228 229 230 231
    }
    
    /**
     * Gets the username used by this connection.
     * 
     * @return string
     */
    public function getUsername()
    {
jwage's avatar
jwage committed
232
        return isset($this->_params['user']) ? $this->_params['user'] : null;
233 234 235 236 237 238 239 240 241
    }
    
    /**
     * Gets the password used by this connection.
     * 
     * @return string
     */
    public function getPassword()
    {
jwage's avatar
jwage committed
242
        return isset($this->_params['password']) ? $this->_params['password'] : null;
243
    }
romanb's avatar
romanb committed
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

    /**
     * Gets the DBAL driver instance.
     *
     * @return Doctrine\DBAL\Driver
     */
    public function getDriver()
    {
        return $this->_driver;
    }

    /**
     * Gets the Configuration used by the Connection.
     *
     * @return Doctrine\DBAL\Configuration
     */
    public function getConfiguration()
    {
        return $this->_config;
    }

    /**
     * Gets the EventManager used by the Connection.
     *
     * @return Doctrine\Common\EventManager
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

    /**
     * Gets the DatabasePlatform for the connection.
     *
     * @return Doctrine\DBAL\Platforms\AbstractPlatform
     */
    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']) ?
romanb's avatar
romanb committed
295 296
                $this->_params['driverOptions'] : array();
        $user = isset($this->_params['user']) ? $this->_params['user'] : null;
romanb's avatar
romanb committed
297
        $password = isset($this->_params['password']) ?
romanb's avatar
romanb committed
298 299 300
                $this->_params['password'] : null;

        $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
romanb's avatar
romanb committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314
        $this->_isConnected = true;

        return true;
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetch(PDO::FETCH_ASSOC).
     *
     * @param string $statement The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
    public function fetchRow($statement, array $params = array())
    {
315
        return $this->execute($statement, $params)->fetch(Connection::FETCH_ASSOC);
romanb's avatar
romanb committed
316 317 318 319 320 321 322 323 324 325 326
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetch(PDO::FETCH_NUM).
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchArray($statement, array $params = array())
    {
327
        return $this->execute($statement, $params)->fetch(Connection::FETCH_NUM);
romanb's avatar
romanb committed
328 329 330 331 332 333 334 335 336 337 338 339
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetchAll(PDO::FETCH_COLUMN, ...).
     *
     * @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)
    {
340
        return $this->execute($statement, $params)->fetchAll(Connection::FETCH_COLUMN, $colnum);
romanb's avatar
romanb committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    }

    /**
     * Whether an actual connection to the database is established.
     *
     * @return boolean
     */
    public function isConnected()
    {
        return $this->_isConnected;
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetchAll(PDO::FETCH_BOTH).
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchBoth($statement, array $params = array())
    {
362
        return $this->execute($statement, $params)->fetchAll(Connection::FETCH_BOTH);
romanb's avatar
romanb committed
363 364 365 366 367 368 369 370 371 372 373 374
    }

    /**
     * Deletes table row(s) matching the specified identifier.
     *
     * @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)
    {
        $this->connect();
375
        
romanb's avatar
romanb committed
376
        $criteria = array();
377
        
romanb's avatar
romanb committed
378
        foreach (array_keys($identifier) as $id) {
379
            $criteria[] = $id . ' = ?';
romanb's avatar
romanb committed
380 381
        }

382
        $query = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' AND ', $criteria);
romanb's avatar
romanb committed
383

384
        return $this->executeUpdate($query, array_values($identifier));
romanb's avatar
romanb committed
385 386 387 388 389 390 391 392 393 394
    }

    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
        unset($this->_conn);
395
        
romanb's avatar
romanb committed
396 397 398 399 400 401 402 403 404 405 406
        $this->_isConnected = false;
    }

    /**
     * Sets the transaction isolation level.
     *
     * @param integer $level The level to set.
     */
    public function setTransactionIsolation($level)
    {
        $this->_transactionIsolationLevel = $level;
407 408
        
        return $this->executeUpdate($this->_platform->getSetTransactionIsolationSql($level));
romanb's avatar
romanb committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    }

    /**
     * Gets the currently active transaction isolation level.
     *
     * @return integer The current transaction isolation level.
     */
    public function getTransactionIsolation()
    {
        return $this->_transactionIsolationLevel;
    }

    /**
     * Updates table row(s) with specified data
     *
     * @throws Doctrine\DBAL\ConnectionException    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)
    {
        $this->connect();
433
        
romanb's avatar
romanb committed
434 435 436 437 438
        if (empty($data)) {
            return false;
        }

        $set = array();
439
        
romanb's avatar
romanb committed
440
        foreach ($data as $columnName => $value) {
441
            $set[] = $columnName . ' = ?';
romanb's avatar
romanb committed
442 443 444 445
        }

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

446 447 448
        $sql  = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $set)
                . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
                . ' = ?';
romanb's avatar
romanb committed
449

450
        return $this->executeUpdate($sql, $params);
romanb's avatar
romanb committed
451 452 453 454 455 456 457 458 459 460 461 462 463
    }

    /**
     * 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)
    {
        $this->connect();
464
        
romanb's avatar
romanb committed
465 466 467 468 469 470 471
        if (empty($data)) {
            return false;
        }

        // column names are specified as array keys
        $cols = array();
        $a = array();
472
        
romanb's avatar
romanb committed
473
        foreach ($data as $columnName => $value) {
474
            $cols[] = $columnName;
romanb's avatar
romanb committed
475 476 477
            $a[] = '?';
        }

478
        $query = 'INSERT INTO ' . $tableName
479 480
               . ' (' . implode(', ', $cols) . ')'
               . ' VALUES (' . implode(', ', $a) . ')';
romanb's avatar
romanb committed
481

482
        return $this->executeUpdate($query, array_values($data));
romanb's avatar
romanb committed
483 484 485 486 487 488 489 490 491
    }

    /**
     * Set the charset on the current connection
     *
     * @param string    charset
     */
    public function setCharset($charset)
    {
492
        $this->executeUpdate($this->_platform->getSetCharsetSql($charset));
romanb's avatar
romanb committed
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    }

    /**
     * Quote a string so it can be safely used as a table or column name, even if
     * it is a reserved name.
     *
     * Delimiting style depends on the underlying database platform that 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.
     *
     * @param string $str           identifier name to be quoted
     * @return string               quoted identifier string
     */
    public function quoteIdentifier($str)
    {
510
        return $this->_platform->quoteIdentifier($str);
romanb's avatar
romanb committed
511 512 513 514 515 516 517 518 519 520 521
    }

    /**
     * Quotes a given input parameter.
     *
     * @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)
    {
522 523
        $this->connect();
        
romanb's avatar
romanb committed
524 525 526 527 528 529 530 531 532 533 534 535
        return $this->_conn->quote($input, $type);
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetchAll(PDO::FETCH_ASSOC).
     *
     * @param string $sql The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
    public function fetchAll($sql, array $params = array())
    {
536
        return $this->execute($sql, $params)->fetchAll(Connection::FETCH_ASSOC);
romanb's avatar
romanb committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    }

    /**
     * Convenience method for PDO::query("...") followed by $stmt->fetchColumn().
     *
     * @param string $statement The SQL query.
     * @param array $params The query parameters.
     * @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);
    }

    /**
     * Prepares an SQL statement.
     *
     * @param string $statement
     * @return Statement
     */
    public function prepare($statement)
    {
        $this->connect();
561
        
romanb's avatar
romanb committed
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
        return $this->_conn->prepare($statement);
    }

    /**
     * Queries the database with limit and offset added to the query and returns
     * a Statement object.
     *
     * @param string $query
     * @param integer $limit
     * @param integer $offset
     * @return Statement
     */
    public function select($query, $limit = 0, $offset = 0)
    {
        if ($limit > 0 || $offset > 0) {
            $query = $this->_platform->modifyLimitQuery($query, $limit, $offset);
        }
579
        
romanb's avatar
romanb committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
        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
     */
    public function execute($query, array $params = array())
    {
        $this->connect();

        if ($this->_config->getSqlLogger()) {
            $this->_config->getSqlLogger()->logSql($query, $params);
        }
romanb's avatar
romanb committed
597
        
romanb's avatar
romanb committed
598
        if ( ! empty($params)) {
romanb's avatar
romanb committed
599
            $stmt = $this->_conn->prepare($query);
romanb's avatar
romanb committed
600 601 602 603
            $stmt->execute($params);
        } else {
            $stmt = $this->_conn->query($query);
        }
604
        
romanb's avatar
romanb committed
605
        return $stmt;
romanb's avatar
romanb committed
606 607 608 609 610 611 612
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters.
     *
     * @param string $query     sql query
     * @param array $params     query parameters
613
     * @return integer
romanb's avatar
romanb committed
614
     */
615
    public function executeUpdate($query, array $params = array())
romanb's avatar
romanb committed
616 617 618 619 620 621 622 623
    {
        $this->connect();

        if ($this->_config->getSqlLogger()) {
            $this->_config->getSqlLogger()->logSql($query, $params);
        }

        if ( ! empty($params)) {
romanb's avatar
romanb committed
624
            $stmt = $this->_conn->prepare($query);
romanb's avatar
romanb committed
625
            $stmt->execute($params);
romanb's avatar
romanb committed
626
            $result = $stmt->rowCount();
romanb's avatar
romanb committed
627
        } else {
romanb's avatar
romanb committed
628
            $result = $this->_conn->exec($query);
romanb's avatar
romanb committed
629
        }
romanb's avatar
romanb committed
630 631
        
        return $result;
romanb's avatar
romanb committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    }

    /**
     * Returns the current transaction nesting level.
     *
     * @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();
652
        
romanb's avatar
romanb committed
653 654 655 656 657 658 659 660 661 662 663
        return $this->_conn->errorCode();
    }

    /**
     * Fetch extended error information associated with the last operation on the database handle
     *
     * @return array
     */
    public function errorInfo()
    {
        $this->connect();
664
        
romanb's avatar
romanb committed
665 666 667 668 669 670 671 672 673 674 675 676 677
        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.
     */
romanb's avatar
romanb committed
678 679 680
    public function lastInsertId($seqName = null)
    {
        $this->connect();
681
        
romanb's avatar
romanb committed
682 683
        return $this->_conn->lastInsertId($seqName);
    }
684

romanb's avatar
romanb committed
685
    /**
686
     * Start a transaction by suspending auto-commit mode.
romanb's avatar
romanb committed
687
     *
688
     * @return void
romanb's avatar
romanb committed
689 690 691 692
     */
    public function beginTransaction()
    {
        $this->connect();
693
        
romanb's avatar
romanb committed
694 695 696
        if ($this->_transactionNestingLevel == 0) {
            $this->_conn->beginTransaction();
        }
697
        
romanb's avatar
romanb committed
698 699
        ++$this->_transactionNestingLevel;
    }
700

romanb's avatar
romanb committed
701
    /**
702
     * Commits the current transaction.
romanb's avatar
romanb committed
703
     *
704
     * @return void
705 706
     * @throws ConnectionException If the commit failed due to no active transaction or
     *                             because the transaction was marked for rollback only.
romanb's avatar
romanb committed
707 708 709 710 711 712
     */
    public function commit()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::commitFailedNoActiveTransaction();
        }
713 714 715
        if ($this->_isRollbackOnly) {
            throw ConnectionException::commitFailedRollbackOnly();
        }
716

romanb's avatar
romanb committed
717
        $this->connect();
718

romanb's avatar
romanb committed
719 720 721
        if ($this->_transactionNestingLevel == 1) {
            $this->_conn->commit();
        }
722
        
romanb's avatar
romanb committed
723 724
        --$this->_transactionNestingLevel;
    }
725

romanb's avatar
romanb committed
726 727 728 729 730 731 732 733 734
    /**
     * 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
     *
735
     * @throws ConnectionException   If the rollback operation fails at database level.
romanb's avatar
romanb committed
736 737
     */
    public function rollback()
romanb's avatar
romanb committed
738
    {
romanb's avatar
romanb committed
739 740 741
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::rollbackFailedNoActiveTransaction();
        }
742

romanb's avatar
romanb committed
743
        $this->connect();
744

romanb's avatar
romanb committed
745 746 747
        if ($this->_transactionNestingLevel == 1) {
            $this->_transactionNestingLevel = 0;
            $this->_conn->rollback();
748
            $this->_isRollbackOnly = false;
749
        } else {
750
            $this->_isRollbackOnly = true;
751
            --$this->_transactionNestingLevel;
romanb's avatar
romanb committed
752 753
        }
    }
754

romanb's avatar
romanb committed
755 756 757 758 759 760 761 762
    /**
     * Gets the wrapped driver connection.
     *
     * @return Doctrine\DBAL\Driver\Connection
     */
    public function getWrappedConnection()
    {
        $this->connect();
763
        
romanb's avatar
romanb committed
764 765
        return $this->_conn;
    }
766

romanb's avatar
romanb committed
767 768 769 770 771 772 773 774 775 776 777
    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
     * @return Doctrine\DBAL\Schema\SchemaManager
     */
    public function getSchemaManager()
    {
        if ( ! $this->_schemaManager) {
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }
778
        
romanb's avatar
romanb committed
779 780
        return $this->_schemaManager;
    }
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
    
    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
     * 
     * @throws BadMethodCallException If no transaction is active.
     */
    public function setRollbackOnly()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        $this->_isRollbackOnly = true;
    }
    
    /**
     * Check whether the current transaction is marked for rollback only.
     * 
     * @return boolean
     * @throws BadMethodCallException If no transaction is active.
     */
    public function getRollbackOnly()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        return $this->_isRollbackOnly;
    }
809
}