Connection.php 31.2 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
/*
 * 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
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL;
romanb's avatar
romanb committed
21

22
use PDO, Closure, Exception,
23 24 25
    Doctrine\DBAL\Types\Type,
    Doctrine\DBAL\Driver\Connection as DriverConnection,
    Doctrine\Common\EventManager,
26
    Doctrine\DBAL\DBALException;
27 28

/**
29
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
30 31
 * events, transaction isolation levels, configuration, emulated transaction nesting,
 * lazy connecting and more.
32
 *
33 34 35 36 37 38 39 40 41
 * @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)
42
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
43
 */
44
class Connection implements DriverConnection
45
{
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
     */
    const TRANSACTION_READ_UNCOMMITTED = 1;
    
    /**
     * Constant for transaction isolation level READ COMMITTED.
     */
    const TRANSACTION_READ_COMMITTED = 2;
    
    /**
     * Constant for transaction isolation level REPEATABLE READ.
     */
    const TRANSACTION_REPEATABLE_READ = 3;
    
    /**
     * Constant for transaction isolation level SERIALIZABLE.
     */
    const TRANSACTION_SERIALIZABLE = 4;

romanb's avatar
romanb committed
66 67 68 69 70 71
    /**
     * The wrapped driver connection.
     *
     * @var Doctrine\DBAL\Driver\Connection
     */
    protected $_conn;
72

romanb's avatar
romanb committed
73 74 75 76
    /**
     * @var Doctrine\DBAL\Configuration
     */
    protected $_config;
77

romanb's avatar
romanb committed
78 79 80 81
    /**
     * @var Doctrine\Common\EventManager
     */
    protected $_eventManager;
82

romanb's avatar
romanb committed
83 84 85 86 87
    /**
     * Whether or not a connection has been established.
     *
     * @var boolean
     */
88
    private $_isConnected = false;
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103
    /**
     * The transaction nesting level.
     *
     * @var integer
     */
    private $_transactionNestingLevel = 0;

    /**
     * The currently active transaction isolation level.
     *
     * @var integer
     */
    private $_transactionIsolationLevel;

104 105 106 107 108 109
    /**
     * If nested transations should use savepoints
     *
     * @var integer
     */
    private $_nestTransactionsWithSavepoints;
Lukas Kahwe Smith's avatar
Lukas Kahwe Smith committed
110

romanb's avatar
romanb committed
111 112 113 114 115
    /**
     * The parameters used during creation of the Connection instance.
     *
     * @var array
     */
116
    private $_params = array();
117

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

romanb's avatar
romanb committed
126 127 128 129 130 131
    /**
     * The schema manager.
     *
     * @var Doctrine\DBAL\Schema\SchemaManager
     */
    protected $_schemaManager;
132

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

romanb's avatar
romanb committed
147 148 149 150 151 152 153 154 155 156 157 158 159
    /**
     * 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;
160

romanb's avatar
romanb committed
161 162 163 164
        if (isset($params['pdo'])) {
            $this->_conn = $params['pdo'];
            $this->_isConnected = true;
        }
165

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

romanb's avatar
romanb committed
175
        $this->_config = $config;
romanb's avatar
romanb committed
176
        $this->_eventManager = $eventManager;
177
        if ( ! isset($params['platform'])) {
178
            $this->_platform = $driver->getDatabasePlatform();
179
        } else if ($params['platform'] instanceof Platforms\AbstractPlatform) {
180 181 182 183
            $this->_platform = $params['platform'];
        } else {
            throw DBALException::invalidPlatformSpecified();
        }
184
        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
romanb's avatar
romanb committed
185
    }
romanb's avatar
romanb committed
186

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

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

    /**
     * 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.
     *
290 291
     * @return boolean TRUE if the connection was successfully established, FALSE if
     *                 the connection is already open.
romanb's avatar
romanb committed
292 293 294 295 296 297
     */
    public function connect()
    {
        if ($this->_isConnected) return false;

        $driverOptions = isset($this->_params['driverOptions']) ?
romanb's avatar
romanb committed
298 299
                $this->_params['driverOptions'] : array();
        $user = isset($this->_params['user']) ? $this->_params['user'] : null;
romanb's avatar
romanb committed
300
        $password = isset($this->_params['password']) ?
romanb's avatar
romanb committed
301 302 303
                $this->_params['password'] : null;

        $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
romanb's avatar
romanb committed
304 305
        $this->_isConnected = true;

306
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
307
            $eventArgs = new Event\ConnectionEventArgs($this);
308 309 310
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

romanb's avatar
romanb committed
311 312 313 314
        return true;
    }

    /**
315 316 317
     * Prepares and executes an SQL query and returns the first row of the result
     * as an associative array.
     * 
romanb's avatar
romanb committed
318 319 320 321
     * @param string $statement The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
322
    public function fetchAssoc($statement, array $params = array())
romanb's avatar
romanb committed
323
    {
324
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_ASSOC);
romanb's avatar
romanb committed
325 326 327
    }

    /**
328 329
     * Prepares and executes an SQL query and returns the first row of the result
     * as a numerically indexed array.
romanb's avatar
romanb committed
330 331 332 333 334 335 336
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchArray($statement, array $params = array())
    {
337
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_NUM);
romanb's avatar
romanb committed
338 339 340
    }

    /**
341 342 343
     * Prepares and executes an SQL query and returns the value of a single column
     * of the first row of the result.
     * 
romanb's avatar
romanb committed
344 345 346
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @param int $colnum               0-indexed column number to retrieve
347
     * @return mixed
romanb's avatar
romanb committed
348 349 350
     */
    public function fetchColumn($statement, array $params = array(), $colnum = 0)
    {
351
        return $this->executeQuery($statement, $params)->fetchColumn($colnum);
romanb's avatar
romanb committed
352 353 354 355 356 357 358 359 360 361 362 363
    }

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

364 365 366 367 368 369 370 371 372 373
    /**
     * Checks whether a transaction is currently active.
     * 
     * @return boolean TRUE if a transaction is currently active, FALSE otherwise.
     */
    public function isTransactionActive()
    {
        return $this->_transactionNestingLevel > 0;
    }

374 375
    /**
     * Executes an SQL DELETE statement on a table.
romanb's avatar
romanb committed
376
     *
377 378 379
     * @param string $table The name of the table on which to delete.
     * @param array $identifier The deletion criteria. An associateve array containing column-value pairs.
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
380 381 382 383
     */
    public function delete($tableName, array $identifier)
    {
        $this->connect();
384

romanb's avatar
romanb committed
385
        $criteria = array();
386 387 388

        foreach (array_keys($identifier) as $columnName) {
            $criteria[] = $columnName . ' = ?';
romanb's avatar
romanb committed
389 390
        }

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

393
        return $this->executeUpdate($query, array_values($identifier));
romanb's avatar
romanb committed
394 395 396 397 398 399 400 401 402 403
    }

    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
        unset($this->_conn);
404
        
romanb's avatar
romanb committed
405 406 407
        $this->_isConnected = false;
    }

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

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

romanb's avatar
romanb committed
430
    /**
431
     * Executes an SQL UPDATE statement on a table.
romanb's avatar
romanb committed
432
     *
433 434 435
     * @param string $table The name of the table to update.
     * @param array $identifier The update criteria. An associative array containing column-value pairs.
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
436 437 438 439 440 441
     */
    public function update($tableName, array $data, array $identifier)
    {
        $this->connect();
        $set = array();
        foreach ($data as $columnName => $value) {
442
            $set[] = $columnName . ' = ?';
romanb's avatar
romanb committed
443 444 445 446
        }

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

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

451
        return $this->executeUpdate($sql, $params);
romanb's avatar
romanb committed
452 453 454 455 456
    }

    /**
     * Inserts a table row with specified data.
     *
457 458 459
     * @param string $table The name of the table to insert data into.
     * @param array $data An associative array containing column-value pairs.
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
460 461 462 463 464 465 466
     */
    public function insert($tableName, array $data)
    {
        $this->connect();

        // column names are specified as array keys
        $cols = array();
467
        $placeholders = array();
468
        
romanb's avatar
romanb committed
469
        foreach ($data as $columnName => $value) {
470
            $cols[] = $columnName;
471
            $placeholders[] = '?';
romanb's avatar
romanb committed
472 473
        }

474
        $query = 'INSERT INTO ' . $tableName
475
               . ' (' . implode(', ', $cols) . ')'
476
               . ' VALUES (' . implode(', ', $placeholders) . ')';
romanb's avatar
romanb committed
477

478
        return $this->executeUpdate($query, array_values($data));
romanb's avatar
romanb committed
479 480 481
    }

    /**
482
     * Sets the given charset on the current connection.
romanb's avatar
romanb committed
483
     *
484
     * @param string $charset The charset to set.
romanb's avatar
romanb committed
485 486 487
     */
    public function setCharset($charset)
    {
488
        $this->executeUpdate($this->_platform->getSetCharsetSQL($charset));
romanb's avatar
romanb committed
489 490 491 492 493 494 495 496
    }

    /**
     * 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.
     *
497 498
     * NOTE: Just because you CAN use quoted identifiers does not mean
     * you SHOULD use them. In general, they end up causing way more
romanb's avatar
romanb committed
499 500
     * problems than they solve.
     *
501 502
     * @param string $str The name to be quoted.
     * @return string The quoted name.
romanb's avatar
romanb committed
503 504 505
     */
    public function quoteIdentifier($str)
    {
506
        return $this->_platform->quoteIdentifier($str);
romanb's avatar
romanb committed
507 508 509 510 511
    }

    /**
     * Quotes a given input parameter.
     *
512 513 514
     * @param mixed $input Parameter to be quoted.
     * @param string $type Type of the parameter.
     * @return string The quoted parameter.
romanb's avatar
romanb committed
515 516 517
     */
    public function quote($input, $type = null)
    {
518 519
        $this->connect();
        
romanb's avatar
romanb committed
520 521 522 523
        return $this->_conn->quote($input, $type);
    }

    /**
524
     * Prepares and executes an SQL query and returns the result as an associative array.
romanb's avatar
romanb committed
525 526 527 528 529 530 531
     *
     * @param string $sql The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
    public function fetchAll($sql, array $params = array())
    {
532
        return $this->executeQuery($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
romanb's avatar
romanb committed
533 534 535 536 537
    }

    /**
     * Prepares an SQL statement.
     *
538
     * @param string $statement The SQL statement to prepare.
539
     * @return Doctrine\DBAL\Driver\Statement The prepared statement.
romanb's avatar
romanb committed
540 541 542 543
     */
    public function prepare($statement)
    {
        $this->connect();
544 545

        return new Statement($statement, $this);
romanb's avatar
romanb committed
546 547 548
    }

    /**
549
     * Executes an, optionally parameterized, SQL query.
romanb's avatar
romanb committed
550
     *
551 552 553 554 555 556 557
     * If the query is parameterized, a prepared statement is used.
     * If an SQLLogger is configured, the execution is logged.
     *
     * @param string $query The SQL query to execute.
     * @param array $params The parameters to bind to the query, if any.
     * @return Doctrine\DBAL\Driver\Statement The executed statement.
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
romanb's avatar
romanb committed
558
     */
559
    public function executeQuery($query, array $params = array(), $types = array())
romanb's avatar
romanb committed
560 561 562
    {
        $this->connect();

563 564
        $hasLogger = $this->_config->getSQLLogger() !== null;
        if ($hasLogger) {
565
            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
romanb's avatar
romanb committed
566
        }
567 568

        if ($params) {
romanb's avatar
romanb committed
569
            $stmt = $this->_conn->prepare($query);
570 571 572 573 574 575
            if ($types) {
                $this->_bindTypedValues($stmt, $params, $types);
                $stmt->execute();
            } else {
                $stmt->execute($params);
            }
romanb's avatar
romanb committed
576 577 578
        } else {
            $stmt = $this->_conn->query($query);
        }
579

580
        if ($hasLogger) {
581
            $this->_config->getSQLLogger()->stopQuery();
582 583
        }

romanb's avatar
romanb committed
584
        return $stmt;
romanb's avatar
romanb committed
585
    }
586

587
    /**
588 589
     * Executes an, optionally parameterized, SQL query and returns the result,
     * applying a given projection/transformation function on each row of the result.
590 591 592 593 594 595
     *
     * @param string $query The SQL query to execute.
     * @param array $params The parameters, if any.
     * @param Closure $mapper The transformation function that is applied on each row.
     *                        The function receives a single paramater, an array, that
     *                        represents a row of the result set.
596
     * @return mixed The projected result of the query.
597
     */
598
    public function project($query, array $params, Closure $function)
599 600
    {
        $result = array();
601
        $stmt = $this->executeQuery($query, $params ?: array());
602

603
        while ($row = $stmt->fetch()) {
604
            $result[] = $function($row);
605
        }
606

607
        $stmt->closeCursor();
608

609 610
        return $result;
    }
romanb's avatar
romanb committed
611 612

    /**
613 614 615 616 617 618 619 620
     * Executes an SQL statement, returning a result set as a Statement object.
     * 
     * @param string $statement
     * @param integer $fetchType
     * @return Doctrine\DBAL\Driver\Statement
     */
    public function query()
    {
621 622
        $this->connect();

623 624 625 626 627 628 629 630 631 632 633 634 635 636
        $args = func_get_args();

        $logger = $this->getConfiguration()->getSQLLogger();
        if ($logger) {
            $logger->startQuery($args[0]);
        }

        $statement = call_user_func_array(array($this->_conn, 'query'), $args);

        if ($logger) {
            $logger->stopQuery();
        }

        return $statement;
637 638 639 640 641 642 643
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
     * 
     * This method supports PDO binding types as well as DBAL mapping types.
romanb's avatar
romanb committed
644
     *
645 646 647 648 649
     * @param string $query The SQL query.
     * @param array $params The query parameters.
     * @param array $types The parameter types.
     * @return integer The number of affected rows.
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
romanb's avatar
romanb committed
650
     */
651
    public function executeUpdate($query, array $params = array(), array $types = array())
romanb's avatar
romanb committed
652 653 654
    {
        $this->connect();

655 656
        $hasLogger = $this->_config->getSQLLogger() !== null;
        if ($hasLogger) {
657
            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
romanb's avatar
romanb committed
658 659
        }

660
        if ($params) {
romanb's avatar
romanb committed
661
            $stmt = $this->_conn->prepare($query);
662 663 664 665 666 667
            if ($types) {
                $this->_bindTypedValues($stmt, $params, $types);
                $stmt->execute();
            } else {
                $stmt->execute($params);
            }
romanb's avatar
romanb committed
668
            $result = $stmt->rowCount();
romanb's avatar
romanb committed
669
        } else {
romanb's avatar
romanb committed
670
            $result = $this->_conn->exec($query);
romanb's avatar
romanb committed
671
        }
672

673
        if ($hasLogger) {
674
            $this->_config->getSQLLogger()->stopQuery();
675 676
        }

romanb's avatar
romanb committed
677
        return $result;
romanb's avatar
romanb committed
678 679
    }

680 681 682 683 684 685 686 687 688 689 690 691
    /**
     * Execute an SQL statement and return the number of affected rows.
     * 
     * @param string $statement
     * @return integer The number of affected rows.
     */
    public function exec($statement)
    {
        $this->connect();
        return $this->_conn->exec($statement);
    }

692 693 694 695 696 697 698 699 700 701
    /**
     * Returns the current transaction nesting level.
     *
     * @return integer The nesting level. A value of 0 means there's no active transaction.
     */
    public function getTransactionNestingLevel()
    {
        return $this->_transactionNestingLevel;
    }

romanb's avatar
romanb committed
702
    /**
703
     * Fetch the SQLSTATE associated with the last database operation.
romanb's avatar
romanb committed
704
     *
705
     * @return integer The last error code.
romanb's avatar
romanb committed
706 707 708 709 710 711 712 713
     */
    public function errorCode()
    {
        $this->connect();
        return $this->_conn->errorCode();
    }

    /**
714
     * Fetch extended error information associated with the last database operation.
romanb's avatar
romanb committed
715
     *
716
     * @return array The last error information.
romanb's avatar
romanb committed
717 718 719 720 721 722 723 724 725 726 727 728
     */
    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,
729 730
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
romanb's avatar
romanb committed
731
     *
732 733
     * @param string $seqName Name of the sequence object from which the ID should be returned.
     * @return string A string representation of the last inserted ID.
romanb's avatar
romanb committed
734
     */
romanb's avatar
romanb committed
735 736 737 738 739
    public function lastInsertId($seqName = null)
    {
        $this->connect();
        return $this->_conn->lastInsertId($seqName);
    }
740

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    /**
     * Executes a function in a transaction.
     *
     * The function gets passed this Connection instance as an (optional) parameter.
     *
     * If an exception occurs during execution of the function or transaction commit,
     * the transaction is rolled back and the exception re-thrown.
     *
     * @param Closure $func The function to execute transactionally.
     */
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
            $func($this);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }
    }

763 764 765 766
    /**
     * Set if nested transactions should use savepoints
     *
     * @param boolean
767
     * @return void
768 769 770
     */
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
    {
771 772 773 774
        if ($this->_transactionNestingLevel > 0) {
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
        }

775 776
        if (!$this->_platform->supportsSavepoints()) {
            throw ConnectionException::savepointsNotSupported();
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
        }

        $this->_nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
    }

    /**
     * Get if nested transactions should use savepoints
     *
     * @return boolean
     */
    public function getNestTransactionsWithSavepoints()
    {
        return $this->_nestTransactionsWithSavepoints;
    }

792 793 794 795 796 797
    /**
     * Returns the savepoint name to use for nested transactions are false if they are not supported
     * "savepointFormat" parameter is not set
     *
     * @return mixed a string with the savepoint name or false
     */
798 799 800
    protected function _getNestedTransactionSavePointName()
    {
        return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel;
801 802
    }

803 804 805 806 807 808 809 810 811
    /**
     * Starts a transaction by suspending auto-commit mode.
     *
     * @return void
     */
    public function beginTransaction()
    {
        $this->connect();

812 813 814
        ++$this->_transactionNestingLevel;

        if ($this->_transactionNestingLevel == 1) {
815
            $this->_conn->beginTransaction();
816 817
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
818 819 820 821 822 823 824 825 826 827 828 829 830
        }
    }

    /**
     * Commits the current transaction.
     *
     * @return void
     * @throws ConnectionException If the commit failed due to no active transaction or
     *                             because the transaction was marked for rollback only.
     */
    public function commit()
    {
        if ($this->_transactionNestingLevel == 0) {
831
            throw ConnectionException::noActiveTransaction();
832 833 834 835 836 837 838 839 840
        }
        if ($this->_isRollbackOnly) {
            throw ConnectionException::commitFailedRollbackOnly();
        }

        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            $this->_conn->commit();
841 842
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        }

        --$this->_transactionNestingLevel;
    }

    /**
     * Cancel any database changes done during the current transaction.
     *
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
     * eventlistener methods
     *
     * @throws ConnectionException If the rollback operation failed.
     */
    public function rollback()
    {
        if ($this->_transactionNestingLevel == 0) {
859
            throw ConnectionException::noActiveTransaction();
860 861 862 863 864 865 866 867
        }

        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            $this->_transactionNestingLevel = 0;
            $this->_conn->rollback();
            $this->_isRollbackOnly = false;
868 869 870
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
            --$this->_transactionNestingLevel;
871
        } else {
872
            $this->_isRollbackOnly = true;
873 874 875 876
            --$this->_transactionNestingLevel;
        }
    }

877 878 879 880 881 882 883
    /**
     * createSavepoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to set
     * @return void
     */
884
    public function createSavepoint($savepoint)
885
    {
886
        if (!$this->_platform->supportsSavepoints()) {
887
            throw ConnectionException::savepointsNotSupported();
888 889
        }

890
        $this->_conn->exec($this->_platform->createSavePoint($savepoint));
891 892 893 894 895 896 897 898 899
    }

    /**
     * releaseSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to release
     * @return void
     */
900
    public function releaseSavepoint($savepoint)
901
    {
902
        if (!$this->_platform->supportsSavepoints()) {
903
            throw ConnectionException::savepointsNotSupported();
904 905
        }

906 907
        if ($this->_platform->supportsReleaseSavepoints()) {
            $this->_conn->exec($this->_platform->releaseSavePoint($savepoint));
908
        }
909 910 911 912 913 914 915 916 917
    }

    /**
     * rollbackSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to rollback to
     * @return void
     */
918
    public function rollbackSavepoint($savepoint)
919
    {
920
        if (!$this->_platform->supportsSavepoints()) {
921
            throw ConnectionException::savepointsNotSupported();
922 923
        }

924
        $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
925 926
    }

romanb's avatar
romanb committed
927 928 929 930 931 932 933 934
    /**
     * Gets the wrapped driver connection.
     *
     * @return Doctrine\DBAL\Driver\Connection
     */
    public function getWrappedConnection()
    {
        $this->connect();
935

romanb's avatar
romanb committed
936 937
        return $this->_conn;
    }
938

romanb's avatar
romanb committed
939 940 941 942
    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
943
     * @return Doctrine\DBAL\Schema\SchemaManager
romanb's avatar
romanb committed
944 945 946 947 948 949
     */
    public function getSchemaManager()
    {
        if ( ! $this->_schemaManager) {
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }
950

romanb's avatar
romanb committed
951 952
        return $this->_schemaManager;
    }
953

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
     * 
     * @throws ConnectionException 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 ConnectionException If no transaction is active.
     */
974
    public function isRollbackOnly()
975 976 977 978 979 980 981
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        return $this->_isRollbackOnly;
    }

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    /**
     * Converts a given value to its database representation according to the conversion
     * rules of a specific DBAL mapping type.
     * 
     * @param mixed $value The value to convert.
     * @param string $type The name of the DBAL mapping type.
     * @return mixed The converted value.
     */
    public function convertToDatabaseValue($value, $type)
    {
        return Type::getType($type)->convertToDatabaseValue($value, $this->_platform);
    }

    /**
     * Converts a given value to its PHP representation according to the conversion
     * rules of a specific DBAL mapping type.
     * 
     * @param mixed $value The value to convert.
     * @param string $type The name of the DBAL mapping type.
     * @return mixed The converted type.
     */
    public function convertToPHPValue($value, $type)
    {
        return Type::getType($type)->convertToPHPValue($value, $this->_platform);
    }

    /**
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
     * or DBAL mapping type, to a given statement.
     * 
1012
     * @param $stmt The statement to bind the values to.
1013 1014
     * @param array $params The map/list of named/positional parameters.
     * @param array $types The parameter types (PDO binding types or DBAL mapping types).
1015 1016
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
     *           raw PDOStatement instances.
1017
     */
1018
    private function _bindTypedValues($stmt, array $params, array $types)
1019 1020 1021 1022
    {
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
1023
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            $bindIndex = 1;
            foreach ($params as $position => $value) {
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
                    $type = $types[$typeIndex];
                    if (is_string($type)) {
                        $type = Type::getType($type);
                    }
                    if ($type instanceof Type) {
                        $value = $type->convertToDatabaseValue($value, $this->_platform);
                        $bindingType = $type->getBindingType();
                    } else {
                        $bindingType = $type; // PDO::PARAM_* constants
                    }
                    $stmt->bindValue($bindIndex, $value, $bindingType);
                } else {
                    $stmt->bindValue($bindIndex, $value);
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
                    $type = $types[$name];
                    if (is_string($type)) {
                        $type = Type::getType($type);
                    }
                    if ($type instanceof Type) {
                        $value = $type->convertToDatabaseValue($value, $this->_platform);
                        $bindingType = $type->getBindingType();
                    } else {
                        $bindingType = $type; // PDO::PARAM_* constants
                    }
                    $stmt->bindValue($name, $value, $bindingType);
                } else {
                    $stmt->bindValue($name, $value);
                }
            }
        }
    }
1065
}