Connection.php 49.6 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2

3
namespace Doctrine\DBAL;
romanb's avatar
romanb committed
4

Benjamin Morel's avatar
Benjamin Morel committed
5 6 7 8
use Closure;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Cache\ArrayStatement;
use Doctrine\DBAL\Cache\CacheException;
9 10 11
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Cache\ResultCacheStatement;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12
use Doctrine\DBAL\Driver\PingableConnection;
13 14 15 16 17 18 19 20 21 22
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
use Doctrine\DBAL\Driver\Statement as DriverStatement;
use Doctrine\DBAL\Exception\InvalidArgumentException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Types\Type;
use Exception;
23
use Throwable;
24
use function array_key_exists;
25
use function assert;
26 27 28 29 30
use function func_get_args;
use function implode;
use function is_int;
use function is_string;
use function key;
31 32

/**
33
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
34 35
 * events, transaction isolation levels, configuration, emulated transaction nesting,
 * lazy connecting and more.
36
 */
37
class Connection implements DriverConnection
38
{
39 40
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
41 42
     *
     * @deprecated Use TransactionIsolationLevel::READ_UNCOMMITTED.
43
     */
44
    public const TRANSACTION_READ_UNCOMMITTED = TransactionIsolationLevel::READ_UNCOMMITTED;
45

46 47
    /**
     * Constant for transaction isolation level READ COMMITTED.
48 49
     *
     * @deprecated Use TransactionIsolationLevel::READ_COMMITTED.
50
     */
51
    public const TRANSACTION_READ_COMMITTED = TransactionIsolationLevel::READ_COMMITTED;
52

53 54
    /**
     * Constant for transaction isolation level REPEATABLE READ.
55 56
     *
     * @deprecated Use TransactionIsolationLevel::REPEATABLE_READ.
57
     */
58
    public const TRANSACTION_REPEATABLE_READ = TransactionIsolationLevel::REPEATABLE_READ;
59

60 61
    /**
     * Constant for transaction isolation level SERIALIZABLE.
62 63
     *
     * @deprecated Use TransactionIsolationLevel::SERIALIZABLE.
64
     */
65
    public const TRANSACTION_SERIALIZABLE = TransactionIsolationLevel::SERIALIZABLE;
66

67 68 69
    /**
     * Represents an array of ints to be expanded by Doctrine SQL parsing.
     */
Sergei Morozov's avatar
Sergei Morozov committed
70
    public const PARAM_INT_ARRAY = ParameterType::INTEGER + self::ARRAY_PARAM_OFFSET;
71

72 73 74
    /**
     * Represents an array of strings to be expanded by Doctrine SQL parsing.
     */
Sergei Morozov's avatar
Sergei Morozov committed
75
    public const PARAM_STR_ARRAY = ParameterType::STRING + self::ARRAY_PARAM_OFFSET;
76

77 78 79
    /**
     * Offset by which PARAM_* constants are detected as arrays of the param type.
     */
80
    public const ARRAY_PARAM_OFFSET = 100;
81

romanb's avatar
romanb committed
82 83 84
    /**
     * The wrapped driver connection.
     *
85
     * @var \Doctrine\DBAL\Driver\Connection|null
romanb's avatar
romanb committed
86 87
     */
    protected $_conn;
88

89
    /** @var Configuration */
romanb's avatar
romanb committed
90
    protected $_config;
91

92
    /** @var EventManager */
romanb's avatar
romanb committed
93
    protected $_eventManager;
94

95
    /** @var ExpressionBuilder */
96
    protected $_expr;
97

romanb's avatar
romanb committed
98 99 100
    /**
     * Whether or not a connection has been established.
     *
101
     * @var bool
romanb's avatar
romanb committed
102
     */
103
    private $isConnected = false;
104

105
    /**
106
     * The current auto-commit mode of this connection.
107
     *
108
     * @var bool
109 110 111
     */
    private $autoCommit = true;

112 113 114
    /**
     * The transaction nesting level.
     *
115
     * @var int
116
     */
117
    private $transactionNestingLevel = 0;
118 119 120 121

    /**
     * The currently active transaction isolation level.
     *
122
     * @var int
123
     */
124
    private $transactionIsolationLevel;
125

126
    /**
Benjamin Morel's avatar
Benjamin Morel committed
127
     * If nested transactions should use savepoints.
128
     *
129
     * @var bool
130
     */
131
    private $nestTransactionsWithSavepoints = false;
Lukas Kahwe Smith's avatar
Lukas Kahwe Smith committed
132

romanb's avatar
romanb committed
133 134 135
    /**
     * The parameters used during creation of the Connection instance.
     *
136
     * @var mixed[]
romanb's avatar
romanb committed
137
     */
138
    private $params = [];
139

romanb's avatar
romanb committed
140 141 142 143
    /**
     * The DatabasePlatform object that provides information about the
     * database platform used by the connection.
     *
144
     * @var AbstractPlatform
romanb's avatar
romanb committed
145
     */
146
    private $platform;
147

romanb's avatar
romanb committed
148 149 150
    /**
     * The schema manager.
     *
Sergei Morozov's avatar
Sergei Morozov committed
151
     * @var AbstractSchemaManager|null
romanb's avatar
romanb committed
152 153
     */
    protected $_schemaManager;
154

romanb's avatar
romanb committed
155
    /**
romanb's avatar
romanb committed
156 157
     * The used DBAL driver.
     *
158
     * @var Driver
romanb's avatar
romanb committed
159 160
     */
    protected $_driver;
161

162
    /**
163
     * Flag that indicates whether the current transaction is marked for rollback only.
164
     *
165
     * @var bool
166
     */
167
    private $isRollbackOnly = false;
168

169
    /** @var int */
170
    protected $defaultFetchMode = FetchMode::ASSOCIATIVE;
171

romanb's avatar
romanb committed
172 173 174
    /**
     * Initializes a new instance of the Connection class.
     *
175
     * @param mixed[]            $params       The connection parameters.
176 177 178
     * @param Driver             $driver       The driver to use.
     * @param Configuration|null $config       The configuration, optional.
     * @param EventManager|null  $eventManager The event manager, optional.
Benjamin Morel's avatar
Benjamin Morel committed
179
     *
180
     * @throws DBALException
romanb's avatar
romanb committed
181
     */
182 183 184 185 186 187
    public function __construct(
        array $params,
        Driver $driver,
        ?Configuration $config = null,
        ?EventManager $eventManager = null
    ) {
romanb's avatar
romanb committed
188
        $this->_driver = $driver;
189
        $this->params  = $params;
190

romanb's avatar
romanb committed
191
        if (isset($params['pdo'])) {
192 193 194
            $this->_conn       = $params['pdo'];
            $this->isConnected = true;
            unset($this->params['pdo']);
romanb's avatar
romanb committed
195
        }
196

197 198
        if (isset($params['platform'])) {
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199
                throw DBALException::invalidPlatformType($params['platform']);
200 201
            }

202
            $this->platform = $params['platform'];
203 204
        }

romanb's avatar
romanb committed
205
        // Create default config and event manager if none given
206
        if (! $config) {
romanb's avatar
romanb committed
207
            $config = new Configuration();
romanb's avatar
romanb committed
208
        }
209

210
        if (! $eventManager) {
romanb's avatar
romanb committed
211
            $eventManager = new EventManager();
romanb's avatar
romanb committed
212
        }
213

214
        $this->_config       = $config;
romanb's avatar
romanb committed
215
        $this->_eventManager = $eventManager;
216

217
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
218

219
        $this->autoCommit = $config->getAutoCommit();
romanb's avatar
romanb committed
220
    }
romanb's avatar
romanb committed
221

222
    /**
romanb's avatar
romanb committed
223
     * Gets the parameters used during instantiation.
224
     *
225
     * @return mixed[]
226 227 228
     */
    public function getParams()
    {
229
        return $this->params;
230 231
    }

romanb's avatar
romanb committed
232
    /**
romanb's avatar
romanb committed
233
     * Gets the name of the database this Connection is connected to.
romanb's avatar
romanb committed
234
     *
Benjamin Morel's avatar
Benjamin Morel committed
235
     * @return string
romanb's avatar
romanb committed
236 237 238 239 240
     */
    public function getDatabase()
    {
        return $this->_driver->getDatabase($this);
    }
241

242 243
    /**
     * Gets the hostname of the currently connected database.
244
     *
245 246
     * @deprecated
     *
Benjamin Morel's avatar
Benjamin Morel committed
247
     * @return string|null
248 249 250
     */
    public function getHost()
    {
251
        return $this->params['host'] ?? null;
252
    }
253

254 255
    /**
     * Gets the port of the currently connected database.
256
     *
257 258
     * @deprecated
     *
259 260 261 262
     * @return mixed
     */
    public function getPort()
    {
263
        return $this->params['port'] ?? null;
264
    }
265

266 267
    /**
     * Gets the username used by this connection.
268
     *
269 270
     * @deprecated
     *
Benjamin Morel's avatar
Benjamin Morel committed
271
     * @return string|null
272 273 274
     */
    public function getUsername()
    {
275
        return $this->params['user'] ?? null;
276
    }
277

278 279
    /**
     * Gets the password used by this connection.
280
     *
281 282
     * @deprecated
     *
Benjamin Morel's avatar
Benjamin Morel committed
283
     * @return string|null
284 285 286
     */
    public function getPassword()
    {
287
        return $this->params['password'] ?? null;
288
    }
romanb's avatar
romanb committed
289 290 291 292

    /**
     * Gets the DBAL driver instance.
     *
293
     * @return Driver
romanb's avatar
romanb committed
294 295 296 297 298 299 300 301 302
     */
    public function getDriver()
    {
        return $this->_driver;
    }

    /**
     * Gets the Configuration used by the Connection.
     *
303
     * @return Configuration
romanb's avatar
romanb committed
304 305 306 307 308 309 310 311 312
     */
    public function getConfiguration()
    {
        return $this->_config;
    }

    /**
     * Gets the EventManager used by the Connection.
     *
313
     * @return EventManager
romanb's avatar
romanb committed
314 315 316 317 318 319 320 321 322
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

    /**
     * Gets the DatabasePlatform for the connection.
     *
323
     * @return AbstractPlatform
324
     *
325
     * @throws DBALException
romanb's avatar
romanb committed
326 327 328
     */
    public function getDatabasePlatform()
    {
329
        if ($this->platform === null) {
330
            $this->detectDatabasePlatform();
331 332 333
        }

        return $this->platform;
romanb's avatar
romanb committed
334
    }
335

336 337 338
    /**
     * Gets the ExpressionBuilder for the connection.
     *
339
     * @return ExpressionBuilder
340 341 342 343 344
     */
    public function getExpressionBuilder()
    {
        return $this->_expr;
    }
345

romanb's avatar
romanb committed
346 347 348
    /**
     * Establishes the connection with the database.
     *
349 350
     * @return bool TRUE if the connection was successfully established, FALSE if
     *              the connection is already open.
romanb's avatar
romanb committed
351 352 353
     */
    public function connect()
    {
354
        if ($this->isConnected) {
355 356
            return false;
        }
romanb's avatar
romanb committed
357

358 359 360
        $driverOptions = $this->params['driverOptions'] ?? [];
        $user          = $this->params['user'] ?? null;
        $password      = $this->params['password'] ?? null;
romanb's avatar
romanb committed
361

362 363
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
        $this->isConnected = true;
romanb's avatar
romanb committed
364

365 366
        $this->transactionNestingLevel = 0;

367
        if ($this->autoCommit === false) {
368 369 370
            $this->beginTransaction();
        }

371
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
372
            $eventArgs = new Event\ConnectionEventArgs($this);
373 374 375
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

romanb's avatar
romanb committed
376 377 378
        return true;
    }

379 380 381 382 383
    /**
     * Detects and sets the database platform.
     *
     * Evaluates custom platform class and version in order to set the correct platform.
     *
384
     * @throws DBALException If an invalid platform was specified for this connection.
385
     */
386
    private function detectDatabasePlatform() : void
387
    {
388
        $version = $this->getDatabasePlatformVersion();
389

390 391 392
        if ($version !== null) {
            assert($this->_driver instanceof VersionAwarePlatformDriver);

393
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
394
        } else {
395
            $this->platform = $this->_driver->getDatabasePlatform();
396 397 398 399 400 401 402 403 404 405 406 407 408 409
        }

        $this->platform->setEventManager($this->_eventManager);
    }

    /**
     * Returns the version of the related platform if applicable.
     *
     * Returns null if either the driver is not capable to create version
     * specific platform instances, no explicit server version was specified
     * or the underlying driver connection cannot determine the platform
     * version without having to query it (performance reasons).
     *
     * @return string|null
410
     *
411
     * @throws Exception
412 413 414 415
     */
    private function getDatabasePlatformVersion()
    {
        // Driver does not support version specific platforms.
416
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
417 418 419 420
            return null;
        }

        // Explicit platform version requested (supersedes auto-detection).
421 422
        if (isset($this->params['serverVersion'])) {
            return $this->params['serverVersion'];
423 424 425
        }

        // If not connected, we need to connect now to determine the platform version.
426
        if ($this->_conn === null) {
427 428
            try {
                $this->connect();
429
            } catch (Throwable $originalException) {
430
                if (empty($this->params['dbname'])) {
431 432 433 434 435
                    throw $originalException;
                }

                // The database to connect to might not yet exist.
                // Retry detection without database name connection parameter.
436 437
                $databaseName           = $this->params['dbname'];
                $this->params['dbname'] = null;
438 439 440

                try {
                    $this->connect();
441
                } catch (Throwable $fallbackException) {
442 443 444
                    // Either the platform does not support database-less connections
                    // or something else went wrong.
                    // Reset connection parameters and rethrow the original exception.
445
                    $this->params['dbname'] = $databaseName;
446 447 448 449 450

                    throw $originalException;
                }

                // Reset connection parameters.
451 452
                $this->params['dbname'] = $databaseName;
                $serverVersion          = $this->getServerVersion();
453 454 455 456 457 458

                // Close "temporary" connection to allow connecting to the real database again.
                $this->close();

                return $serverVersion;
            }
459 460
        }

461 462 463 464 465 466 467 468 469 470
        return $this->getServerVersion();
    }

    /**
     * Returns the database server version if the underlying driver supports it.
     *
     * @return string|null
     */
    private function getServerVersion()
    {
Sergei Morozov's avatar
Sergei Morozov committed
471 472
        $connection = $this->getWrappedConnection();

473
        // Automatic platform version detection.
Sergei Morozov's avatar
Sergei Morozov committed
474 475
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
            return $connection->getServerVersion();
476 477 478 479 480 481
        }

        // Unable to detect platform version.
        return null;
    }

482 483 484 485
    /**
     * Returns the current auto-commit mode for this connection.
     *
     * @see    setAutoCommit
486 487
     *
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
488
     */
489
    public function isAutoCommit()
490
    {
491
        return $this->autoCommit === true;
492 493 494 495 496 497 498 499 500 501 502 503
    }

    /**
     * Sets auto-commit mode for this connection.
     *
     * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
     * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
     * the method commit or the method rollback. By default, new connections are in auto-commit mode.
     *
     * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
     * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
     *
504
     * @see   isAutoCommit
505 506
     *
     * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
507 508
     *
     * @return void
509 510 511
     */
    public function setAutoCommit($autoCommit)
    {
512
        $autoCommit = (bool) $autoCommit;
513 514 515 516 517 518 519 520 521

        // Mode not changed, no-op.
        if ($autoCommit === $this->autoCommit) {
            return;
        }

        $this->autoCommit = $autoCommit;

        // Commit all currently active transactions if any when switching auto-commit mode.
522
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
523
            return;
524
        }
525 526

        $this->commitAll();
527 528
    }

529
    /**
Benjamin Morel's avatar
Benjamin Morel committed
530
     * Sets the fetch mode.
531
     *
532
     * @param int $fetchMode
Benjamin Morel's avatar
Benjamin Morel committed
533 534
     *
     * @return void
535
     */
536
    public function setFetchMode($fetchMode)
537
    {
538
        $this->defaultFetchMode = $fetchMode;
539 540
    }

romanb's avatar
romanb committed
541
    /**
542 543
     * Prepares and executes an SQL query and returns the first row of the result
     * as an associative array.
544
     *
545 546 547
     * @param string         $statement The SQL query.
     * @param mixed[]        $params    The query parameters.
     * @param int[]|string[] $types     The query parameter types.
Benjamin Morel's avatar
Benjamin Morel committed
548
     *
549
     * @return mixed[]|false False is returned if no rows are found.
550
     *
551
     * @throws DBALException
romanb's avatar
romanb committed
552
     */
553
    public function fetchAssoc($statement, array $params = [], array $types = [])
romanb's avatar
romanb committed
554
    {
555
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
romanb's avatar
romanb committed
556 557 558
    }

    /**
559 560
     * Prepares and executes an SQL query and returns the first row of the result
     * as a numerically indexed array.
romanb's avatar
romanb committed
561
     *
562 563 564
     * @param string         $statement The SQL query to be executed.
     * @param mixed[]        $params    The prepared statement params.
     * @param int[]|string[] $types     The query parameter types.
Benjamin Morel's avatar
Benjamin Morel committed
565
     *
566
     * @return mixed[]|false False is returned if no rows are found.
romanb's avatar
romanb committed
567
     */
568
    public function fetchArray($statement, array $params = [], array $types = [])
romanb's avatar
romanb committed
569
    {
570
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
romanb's avatar
romanb committed
571 572 573
    }

    /**
574 575
     * Prepares and executes an SQL query and returns the value of a single column
     * of the first row of the result.
576
     *
577 578 579 580
     * @param string         $statement The SQL query to be executed.
     * @param mixed[]        $params    The prepared statement params.
     * @param int            $column    The 0-indexed column number to retrieve.
     * @param int[]|string[] $types     The query parameter types.
Benjamin Morel's avatar
Benjamin Morel committed
581
     *
582
     * @return mixed|false False is returned if no rows are found.
583
     *
584
     * @throws DBALException
romanb's avatar
romanb committed
585
     */
586
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
romanb's avatar
romanb committed
587
    {
588
        return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
romanb's avatar
romanb committed
589 590 591 592 593
    }

    /**
     * Whether an actual connection to the database is established.
     *
594
     * @return bool
romanb's avatar
romanb committed
595 596 597
     */
    public function isConnected()
    {
598
        return $this->isConnected;
romanb's avatar
romanb committed
599 600
    }

601 602
    /**
     * Checks whether a transaction is currently active.
603
     *
604
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
605 606 607
     */
    public function isTransactionActive()
    {
608
        return $this->transactionNestingLevel > 0;
609 610
    }

611
    /**
Sergei Morozov's avatar
Sergei Morozov committed
612
     * Adds identifier condition to the query components
613
     *
Sergei Morozov's avatar
Sergei Morozov committed
614 615 616 617
     * @param mixed[]  $identifier Map of key columns to their values
     * @param string[] $columns    Column names
     * @param mixed[]  $values     Column values
     * @param string[] $conditions Key conditions
618
     *
Sergei Morozov's avatar
Sergei Morozov committed
619
     * @throws DBALException
620
     */
Sergei Morozov's avatar
Sergei Morozov committed
621 622 623 624 625 626 627
    private function addIdentifierCondition(
        array $identifier,
        array &$columns,
        array &$values,
        array &$conditions
    ) : void {
        $platform = $this->getDatabasePlatform();
628

Sergei Morozov's avatar
Sergei Morozov committed
629
        foreach ($identifier as $columnName => $value) {
630
            if ($value === null) {
Sergei Morozov's avatar
Sergei Morozov committed
631
                $conditions[] = $platform->getIsNullExpression($columnName);
632 633 634
                continue;
            }

635 636
            $columns[]    = $columnName;
            $values[]     = $value;
637
            $conditions[] = $columnName . ' = ?';
638 639 640
        }
    }

641 642
    /**
     * Executes an SQL DELETE statement on a table.
romanb's avatar
romanb committed
643
     *
644 645
     * Table expression and columns are not escaped and are not safe for user-input.
     *
646 647 648
     * @param string         $tableExpression The expression of the table on which to delete.
     * @param mixed[]        $identifier      The deletion criteria. An associative array containing column-value pairs.
     * @param int[]|string[] $types           The types of identifiers.
Benjamin Morel's avatar
Benjamin Morel committed
649
     *
650
     * @return int The number of affected rows.
651
     *
652
     * @throws DBALException
653
     * @throws InvalidArgumentException
654
     */
655
    public function delete($tableExpression, array $identifier, array $types = [])
656 657
    {
        if (empty($identifier)) {
658
            throw InvalidArgumentException::fromEmptyCriteria();
659 660
        }

Sergei Morozov's avatar
Sergei Morozov committed
661 662 663
        $columns = $values = $conditions = [];

        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
664

665
        return $this->executeUpdate(
666 667 668
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
            $values,
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
669
        );
670 671
    }

romanb's avatar
romanb committed
672 673 674 675 676 677 678
    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
679
        $this->_conn = null;
680

681
        $this->isConnected = false;
romanb's avatar
romanb committed
682 683
    }

684 685 686
    /**
     * Sets the transaction isolation level.
     *
687
     * @param int $level The level to set.
Benjamin Morel's avatar
Benjamin Morel committed
688
     *
689
     * @return int
690 691 692
     */
    public function setTransactionIsolation($level)
    {
693
        $this->transactionIsolationLevel = $level;
694

695
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
696 697 698 699 700
    }

    /**
     * Gets the currently active transaction isolation level.
     *
701
     * @return int The current transaction isolation level.
702 703 704
     */
    public function getTransactionIsolation()
    {
705 706
        if ($this->transactionIsolationLevel === null) {
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
707 708
        }

709
        return $this->transactionIsolationLevel;
710 711
    }

romanb's avatar
romanb committed
712
    /**
713
     * Executes an SQL UPDATE statement on a table.
romanb's avatar
romanb committed
714
     *
715 716
     * Table expression and columns are not escaped and are not safe for user-input.
     *
717 718 719 720
     * @param string         $tableExpression The expression of the table to update quoted or unquoted.
     * @param mixed[]        $data            An associative array containing column-value pairs.
     * @param mixed[]        $identifier      The update criteria. An associative array containing column-value pairs.
     * @param int[]|string[] $types           Types of the merged $data and $identifier arrays in that order.
Benjamin Morel's avatar
Benjamin Morel committed
721
     *
722
     * @return int The number of affected rows.
723
     *
724
     * @throws DBALException
romanb's avatar
romanb committed
725
     */
726
    public function update($tableExpression, array $data, array $identifier, array $types = [])
romanb's avatar
romanb committed
727
    {
Sergei Morozov's avatar
Sergei Morozov committed
728
        $columns = $values = $conditions = $set = [];
729

romanb's avatar
romanb committed
730
        foreach ($data as $columnName => $value) {
Sergei Morozov's avatar
Sergei Morozov committed
731 732 733
            $columns[] = $columnName;
            $values[]  = $value;
            $set[]     = $columnName . ' = ?';
romanb's avatar
romanb committed
734 735
        }

Sergei Morozov's avatar
Sergei Morozov committed
736
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
737

738
        if (is_string(key($types))) {
739
            $types = $this->extractTypeValues($columns, $types);
740
        }
romanb's avatar
romanb committed
741

742
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
743
                . ' WHERE ' . implode(' AND ', $conditions);
romanb's avatar
romanb committed
744

745
        return $this->executeUpdate($sql, $values, $types);
romanb's avatar
romanb committed
746 747 748 749 750
    }

    /**
     * Inserts a table row with specified data.
     *
751 752
     * Table expression and columns are not escaped and are not safe for user-input.
     *
753 754 755
     * @param string         $tableExpression The expression of the table to insert data into, quoted or unquoted.
     * @param mixed[]        $data            An associative array containing column-value pairs.
     * @param int[]|string[] $types           Types of the inserted data.
Benjamin Morel's avatar
Benjamin Morel committed
756
     *
757
     * @return int The number of affected rows.
758
     *
759
     * @throws DBALException
romanb's avatar
romanb committed
760
     */
761
    public function insert($tableExpression, array $data, array $types = [])
romanb's avatar
romanb committed
762
    {
763
        if (empty($data)) {
764
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
765 766
        }

767
        $columns = [];
768 769
        $values  = [];
        $set     = [];
770 771

        foreach ($data as $columnName => $value) {
772
            $columns[] = $columnName;
773 774
            $values[]  = $value;
            $set[]     = '?';
775 776
        }

777
        return $this->executeUpdate(
778 779 780 781
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
            ' VALUES (' . implode(', ', $set) . ')',
            $values,
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
782
        );
romanb's avatar
romanb committed
783 784
    }

785
    /**
786
     * Extract ordered type list from an ordered column list and type map.
787
     *
Sergei Morozov's avatar
Sergei Morozov committed
788
     * @param int[]|string[] $columnList
789
     * @param int[]|string[] $types
790
     *
791
     * @return int[]|string[]
792
     */
793
    private function extractTypeValues(array $columnList, array $types)
794
    {
795
        $typeValues = [];
796

797
        foreach ($columnList as $columnIndex => $columnName) {
798
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
799 800 801 802 803
        }

        return $typeValues;
    }

romanb's avatar
romanb committed
804
    /**
Benjamin Morel's avatar
Benjamin Morel committed
805
     * Quotes a string so it can be safely used as a table or column name, even if
romanb's avatar
romanb committed
806 807 808 809
     * it is a reserved name.
     *
     * Delimiting style depends on the underlying database platform that is being used.
     *
810 811
     * 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
812 813
     * problems than they solve.
     *
814
     * @param string $str The name to be quoted.
Benjamin Morel's avatar
Benjamin Morel committed
815
     *
816
     * @return string The quoted name.
romanb's avatar
romanb committed
817 818 819
     */
    public function quoteIdentifier($str)
    {
820
        return $this->getDatabasePlatform()->quoteIdentifier($str);
romanb's avatar
romanb committed
821 822 823
    }

    /**
Sergei Morozov's avatar
Sergei Morozov committed
824
     * {@inheritDoc}
romanb's avatar
romanb committed
825 826 827
     */
    public function quote($input, $type = null)
    {
Sergei Morozov's avatar
Sergei Morozov committed
828
        $connection = $this->getWrappedConnection();
829

830
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
831

Sergei Morozov's avatar
Sergei Morozov committed
832
        return $connection->quote($value, $bindingType);
romanb's avatar
romanb committed
833 834 835
    }

    /**
836
     * Prepares and executes an SQL query and returns the result as an associative array.
romanb's avatar
romanb committed
837
     *
838 839 840
     * @param string         $sql    The SQL query.
     * @param mixed[]        $params The query parameters.
     * @param int[]|string[] $types  The query parameter types.
Benjamin Morel's avatar
Benjamin Morel committed
841
     *
842
     * @return mixed[]
romanb's avatar
romanb committed
843
     */
844
    public function fetchAll($sql, array $params = [], $types = [])
romanb's avatar
romanb committed
845
    {
root's avatar
root committed
846
        return $this->executeQuery($sql, $params, $types)->fetchAll();
romanb's avatar
romanb committed
847 848 849 850 851
    }

    /**
     * Prepares an SQL statement.
     *
852
     * @param string $statement The SQL statement to prepare.
Benjamin Morel's avatar
Benjamin Morel committed
853
     *
854
     * @return DriverStatement The prepared statement.
Benjamin Morel's avatar
Benjamin Morel committed
855
     *
856
     * @throws DBALException
romanb's avatar
romanb committed
857 858 859
     */
    public function prepare($statement)
    {
860 861
        try {
            $stmt = new Statement($statement, $this);
862
        } catch (Throwable $ex) {
863
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
864 865
        }

866
        $stmt->setFetchMode($this->defaultFetchMode);
867 868

        return $stmt;
romanb's avatar
romanb committed
869 870 871
    }

    /**
Pascal Borreli's avatar
Pascal Borreli committed
872
     * Executes an, optionally parametrized, SQL query.
romanb's avatar
romanb committed
873
     *
Pascal Borreli's avatar
Pascal Borreli committed
874
     * If the query is parametrized, a prepared statement is used.
875 876
     * If an SQLLogger is configured, the execution is logged.
     *
877
     * @param string                 $query  The SQL query to execute.
878 879
     * @param mixed[]                $params The parameters to bind to the query, if any.
     * @param int[]|string[]         $types  The types the previous parameters are in.
880
     * @param QueryCacheProfile|null $qcp    The query cache profile, optional.
Benjamin Morel's avatar
Benjamin Morel committed
881
     *
882
     * @return ResultStatement The executed statement.
Benjamin Morel's avatar
Benjamin Morel committed
883
     *
884
     * @throws DBALException
romanb's avatar
romanb committed
885
     */
886
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
romanb's avatar
romanb committed
887
    {
888
        if ($qcp !== null) {
889
            return $this->executeCacheQuery($query, $params, $types, $qcp);
890 891
        }

Sergei Morozov's avatar
Sergei Morozov committed
892
        $connection = $this->getWrappedConnection();
romanb's avatar
romanb committed
893

894 895 896
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
897
        }
898

899 900
        try {
            if ($params) {
901
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
902

Sergei Morozov's avatar
Sergei Morozov committed
903
                $stmt = $connection->prepare($query);
904 905 906 907 908 909
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
910
            } else {
Sergei Morozov's avatar
Sergei Morozov committed
911
                $stmt = $connection->query($query);
912
            }
913
        } catch (Throwable $ex) {
914
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
915
        }
916

917
        $stmt->setFetchMode($this->defaultFetchMode);
918

919 920
        if ($logger) {
            $logger->stopQuery();
921 922
        }

romanb's avatar
romanb committed
923
        return $stmt;
romanb's avatar
romanb committed
924
    }
925

926
    /**
Benjamin Morel's avatar
Benjamin Morel committed
927 928
     * Executes a caching query.
     *
929
     * @param string            $query  The SQL query to execute.
930 931
     * @param mixed[]           $params The parameters to bind to the query, if any.
     * @param int[]|string[]    $types  The types the previous parameters are in.
932
     * @param QueryCacheProfile $qcp    The query cache profile.
933
     *
934
     * @return ResultStatement
Benjamin Morel's avatar
Benjamin Morel committed
935
     *
936
     * @throws CacheException
937 938 939
     */
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
    {
Sergei Morozov's avatar
Sergei Morozov committed
940 941 942
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();

        if ($resultCache === null) {
943 944 945
            throw CacheException::noResultDriverConfigured();
        }

946 947 948 949
        $connectionParams = $this->getParams();
        unset($connectionParams['platform']);

        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
950 951

        // fetch the row pointers entry
952 953 954
        $data = $resultCache->fetch($cacheKey);

        if ($data !== false) {
955 956
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
            if (isset($data[$realKey])) {
957
                $stmt = new ArrayStatement($data[$realKey]);
Steve Müller's avatar
Steve Müller committed
958
            } elseif (array_key_exists($realKey, $data)) {
959
                $stmt = new ArrayStatement([]);
960 961
            }
        }
962

963
        if (! isset($stmt)) {
964 965 966
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
        }

967
        $stmt->setFetchMode($this->defaultFetchMode);
968 969

        return $stmt;
970 971
    }

972
    /**
Pascal Borreli's avatar
Pascal Borreli committed
973
     * Executes an, optionally parametrized, SQL query and returns the result,
974
     * applying a given projection/transformation function on each row of the result.
975
     *
976
     * @param string  $query    The SQL query to execute.
977
     * @param mixed[] $params   The parameters, if any.
978
     * @param Closure $function The transformation function that is applied on each row.
Benjamin Morel's avatar
Benjamin Morel committed
979 980 981
     *                           The function receives a single parameter, an array, that
     *                           represents a row of the result set.
     *
982
     * @return mixed[] The projected result of the query.
983
     */
984
    public function project($query, array $params, Closure $function)
985
    {
986
        $result = [];
987
        $stmt   = $this->executeQuery($query, $params);
988

989
        while ($row = $stmt->fetch()) {
990
            $result[] = $function($row);
991
        }
992

993
        $stmt->closeCursor();
994

995 996
        return $result;
    }
romanb's avatar
romanb committed
997 998

    /**
999
     * Executes an SQL statement, returning a result set as a Statement object.
1000
     *
1001
     * @return \Doctrine\DBAL\Driver\Statement
Benjamin Morel's avatar
Benjamin Morel committed
1002
     *
1003
     * @throws DBALException
1004 1005 1006
     */
    public function query()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1007
        $connection = $this->getWrappedConnection();
1008

1009 1010
        $args = func_get_args();

1011
        $logger = $this->_config->getSQLLogger();
1012 1013 1014 1015
        if ($logger) {
            $logger->startQuery($args[0]);
        }

1016
        try {
Sergei Morozov's avatar
Sergei Morozov committed
1017
            $statement = $connection->query(...$args);
1018
        } catch (Throwable $ex) {
1019
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1020 1021
        }

1022
        $statement->setFetchMode($this->defaultFetchMode);
1023 1024 1025 1026 1027 1028

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

        return $statement;
1029 1030 1031 1032 1033
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
1034
     *
1035
     * This method supports PDO binding types as well as DBAL mapping types.
romanb's avatar
romanb committed
1036
     *
1037 1038 1039
     * @param string         $query  The SQL query.
     * @param mixed[]        $params The query parameters.
     * @param int[]|string[] $types  The parameter types.
Benjamin Morel's avatar
Benjamin Morel committed
1040
     *
1041
     * @return int The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
1042
     *
1043
     * @throws DBALException
romanb's avatar
romanb committed
1044
     */
1045
    public function executeUpdate($query, array $params = [], array $types = [])
romanb's avatar
romanb committed
1046
    {
Sergei Morozov's avatar
Sergei Morozov committed
1047
        $connection = $this->getWrappedConnection();
romanb's avatar
romanb committed
1048

1049 1050 1051
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
1052 1053
        }

1054 1055
        try {
            if ($params) {
1056
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1057

Sergei Morozov's avatar
Sergei Morozov committed
1058 1059
                $stmt = $connection->prepare($query);

1060 1061 1062 1063 1064 1065 1066
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
                $result = $stmt->rowCount();
1067
            } else {
Sergei Morozov's avatar
Sergei Morozov committed
1068
                $result = $connection->exec($query);
1069
            }
1070
        } catch (Throwable $ex) {
1071
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
1072
        }
1073

1074 1075
        if ($logger) {
            $logger->stopQuery();
1076 1077
        }

romanb's avatar
romanb committed
1078
        return $result;
romanb's avatar
romanb committed
1079 1080
    }

1081
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1082
     * Executes an SQL statement and return the number of affected rows.
1083
     *
1084
     * @param string $statement
Benjamin Morel's avatar
Benjamin Morel committed
1085
     *
1086
     * @return int The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
1087
     *
1088
     * @throws DBALException
1089 1090 1091
     */
    public function exec($statement)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1092
        $connection = $this->getWrappedConnection();
1093 1094 1095 1096 1097 1098

        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($statement);
        }

1099
        try {
Sergei Morozov's avatar
Sergei Morozov committed
1100
            $result = $connection->exec($statement);
1101
        } catch (Throwable $ex) {
1102
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1103
        }
1104 1105 1106 1107 1108 1109

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

        return $result;
1110 1111
    }

1112 1113 1114
    /**
     * Returns the current transaction nesting level.
     *
1115
     * @return int The nesting level. A value of 0 means there's no active transaction.
1116 1117 1118
     */
    public function getTransactionNestingLevel()
    {
1119
        return $this->transactionNestingLevel;
1120 1121
    }

romanb's avatar
romanb committed
1122
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1123
     * Fetches the SQLSTATE associated with the last database operation.
romanb's avatar
romanb committed
1124
     *
1125
     * @return string|null The last error code.
romanb's avatar
romanb committed
1126 1127 1128
     */
    public function errorCode()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1129
        return $this->getWrappedConnection()->errorCode();
romanb's avatar
romanb committed
1130 1131 1132
    }

    /**
1133
     * {@inheritDoc}
romanb's avatar
romanb committed
1134 1135 1136
     */
    public function errorInfo()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1137
        return $this->getWrappedConnection()->errorInfo();
romanb's avatar
romanb committed
1138 1139 1140 1141 1142 1143 1144
    }

    /**
     * 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,
1145 1146
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
romanb's avatar
romanb committed
1147
     *
Benjamin Morel's avatar
Benjamin Morel committed
1148 1149
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
     *
1150
     * @return string A string representation of the last inserted ID.
romanb's avatar
romanb committed
1151
     */
romanb's avatar
romanb committed
1152 1153
    public function lastInsertId($seqName = null)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1154
        return $this->getWrappedConnection()->lastInsertId($seqName);
romanb's avatar
romanb committed
1155
    }
1156

1157 1158 1159 1160 1161 1162 1163 1164
    /**
     * 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.
     *
1165
     * @param Closure $func The function to execute transactionally.
Benjamin Morel's avatar
Benjamin Morel committed
1166
     *
1167
     * @return mixed The value returned by $func
Benjamin Morel's avatar
Benjamin Morel committed
1168
     *
1169 1170
     * @throws Exception
     * @throws Throwable
1171 1172 1173 1174 1175
     */
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
1176
            $res = $func($this);
1177
            $this->commit();
1178

1179
            return $res;
1180
        } catch (Exception $e) {
1181
            $this->rollBack();
1182 1183 1184
            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();
1185 1186 1187 1188
            throw $e;
        }
    }

1189
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1190
     * Sets if nested transactions should use savepoints.
1191
     *
1192
     * @param bool $nestTransactionsWithSavepoints
Benjamin Morel's avatar
Benjamin Morel committed
1193
     *
1194
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1195
     *
1196
     * @throws ConnectionException
1197 1198 1199
     */
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
    {
1200
        if ($this->transactionNestingLevel > 0) {
1201 1202 1203
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
        }

1204
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1205
            throw ConnectionException::savepointsNotSupported();
1206 1207
        }

1208
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1209 1210 1211
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1212
     * Gets if nested transactions should use savepoints.
1213
     *
1214
     * @return bool
1215 1216 1217
     */
    public function getNestTransactionsWithSavepoints()
    {
1218
        return $this->nestTransactionsWithSavepoints;
1219 1220
    }

1221 1222 1223 1224
    /**
     * Returns the savepoint name to use for nested transactions are false if they are not supported
     * "savepointFormat" parameter is not set
     *
Benjamin Morel's avatar
Benjamin Morel committed
1225
     * @return mixed A string with the savepoint name or false.
1226
     */
1227 1228
    protected function _getNestedTransactionSavePointName()
    {
1229
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1230 1231
    }

1232
    /**
1233
     * {@inheritDoc}
1234 1235 1236
     */
    public function beginTransaction()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1237
        $connection = $this->getWrappedConnection();
1238

1239
        ++$this->transactionNestingLevel;
1240

1241 1242
        $logger = $this->_config->getSQLLogger();

1243
        if ($this->transactionNestingLevel === 1) {
1244 1245 1246
            if ($logger) {
                $logger->startQuery('"START TRANSACTION"');
            }
Sergei Morozov's avatar
Sergei Morozov committed
1247 1248 1249

            $connection->beginTransaction();

1250 1251 1252
            if ($logger) {
                $logger->stopQuery();
            }
1253
        } elseif ($this->nestTransactionsWithSavepoints) {
1254 1255 1256
            if ($logger) {
                $logger->startQuery('"SAVEPOINT"');
            }
1257
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1258 1259 1260
            if ($logger) {
                $logger->stopQuery();
            }
1261
        }
1262 1263

        return true;
1264 1265 1266
    }

    /**
1267
     * {@inheritDoc}
Benjamin Morel's avatar
Benjamin Morel committed
1268
     *
1269
     * @throws ConnectionException If the commit failed due to no active transaction or
Benjamin Morel's avatar
Benjamin Morel committed
1270
     *                                            because the transaction was marked for rollback only.
1271 1272 1273
     */
    public function commit()
    {
1274
        if ($this->transactionNestingLevel === 0) {
1275
            throw ConnectionException::noActiveTransaction();
1276
        }
1277
        if ($this->isRollbackOnly) {
1278 1279 1280
            throw ConnectionException::commitFailedRollbackOnly();
        }

1281 1282
        $result = true;

Sergei Morozov's avatar
Sergei Morozov committed
1283
        $connection = $this->getWrappedConnection();
1284

1285 1286
        $logger = $this->_config->getSQLLogger();

1287
        if ($this->transactionNestingLevel === 1) {
1288 1289 1290
            if ($logger) {
                $logger->startQuery('"COMMIT"');
            }
Sergei Morozov's avatar
Sergei Morozov committed
1291

1292
            $result = $connection->commit();
Sergei Morozov's avatar
Sergei Morozov committed
1293

1294 1295 1296
            if ($logger) {
                $logger->stopQuery();
            }
1297
        } elseif ($this->nestTransactionsWithSavepoints) {
1298 1299 1300
            if ($logger) {
                $logger->startQuery('"RELEASE SAVEPOINT"');
            }
1301
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1302 1303 1304
            if ($logger) {
                $logger->stopQuery();
            }
1305 1306
        }

1307
        --$this->transactionNestingLevel;
1308

1309
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1310
            return $result;
1311
        }
1312 1313

        $this->beginTransaction();
1314

1315
        return $result;
1316 1317 1318 1319 1320
    }

    /**
     * Commits all current nesting transactions.
     */
1321
    private function commitAll() : void
1322
    {
1323 1324
        while ($this->transactionNestingLevel !== 0) {
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1325 1326 1327 1328 1329 1330 1331 1332 1333
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
                $this->commit();

                return;
            }

            $this->commit();
        }
1334 1335 1336
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1337
     * Cancels any database changes done during the current transaction.
1338
     *
1339 1340
     * @return bool
     *
1341
     * @throws ConnectionException If the rollback operation failed.
1342
     */
1343
    public function rollBack()
1344
    {
1345
        if ($this->transactionNestingLevel === 0) {
1346
            throw ConnectionException::noActiveTransaction();
1347 1348
        }

Sergei Morozov's avatar
Sergei Morozov committed
1349
        $connection = $this->getWrappedConnection();
1350

1351 1352
        $logger = $this->_config->getSQLLogger();

1353
        if ($this->transactionNestingLevel === 1) {
1354 1355 1356
            if ($logger) {
                $logger->startQuery('"ROLLBACK"');
            }
1357
            $this->transactionNestingLevel = 0;
Sergei Morozov's avatar
Sergei Morozov committed
1358
            $connection->rollBack();
1359
            $this->isRollbackOnly = false;
1360 1361 1362
            if ($logger) {
                $logger->stopQuery();
            }
1363

1364
            if ($this->autoCommit === false) {
1365 1366
                $this->beginTransaction();
            }
1367
        } elseif ($this->nestTransactionsWithSavepoints) {
1368 1369 1370
            if ($logger) {
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
            }
1371
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1372
            --$this->transactionNestingLevel;
1373 1374 1375
            if ($logger) {
                $logger->stopQuery();
            }
1376
        } else {
1377 1378
            $this->isRollbackOnly = true;
            --$this->transactionNestingLevel;
1379
        }
1380 1381

        return true;
1382 1383
    }

1384
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1385 1386 1387
     * Creates a new savepoint.
     *
     * @param string $savepoint The name of the savepoint to create.
1388 1389
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1390
     *
1391
     * @throws ConnectionException
1392
     */
1393
    public function createSavepoint($savepoint)
1394
    {
1395
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1396
            throw ConnectionException::savepointsNotSupported();
1397 1398
        }

Sergei Morozov's avatar
Sergei Morozov committed
1399
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1400 1401 1402
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1403 1404 1405
     * Releases the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to release.
1406 1407
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1408
     *
1409
     * @throws ConnectionException
1410
     */
1411
    public function releaseSavepoint($savepoint)
1412
    {
1413
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1414
            throw ConnectionException::savepointsNotSupported();
1415 1416
        }

1417 1418
        if (! $this->platform->supportsReleaseSavepoints()) {
            return;
1419
        }
1420

Sergei Morozov's avatar
Sergei Morozov committed
1421
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1422 1423 1424
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1425 1426 1427
     * Rolls back to the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to rollback to.
1428 1429
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1430
     *
1431
     * @throws ConnectionException
1432
     */
1433
    public function rollbackSavepoint($savepoint)
1434
    {
1435
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1436
            throw ConnectionException::savepointsNotSupported();
1437 1438
        }

Sergei Morozov's avatar
Sergei Morozov committed
1439
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1440 1441
    }

romanb's avatar
romanb committed
1442 1443 1444
    /**
     * Gets the wrapped driver connection.
     *
Sergei Morozov's avatar
Sergei Morozov committed
1445
     * @return DriverConnection
romanb's avatar
romanb committed
1446 1447 1448 1449
     */
    public function getWrappedConnection()
    {
        $this->connect();
1450

romanb's avatar
romanb committed
1451 1452
        return $this->_conn;
    }
1453

romanb's avatar
romanb committed
1454 1455 1456 1457
    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
1458
     * @return AbstractSchemaManager
romanb's avatar
romanb committed
1459 1460 1461
     */
    public function getSchemaManager()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1462
        if ($this->_schemaManager === null) {
romanb's avatar
romanb committed
1463 1464
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }
1465

romanb's avatar
romanb committed
1466 1467
        return $this->_schemaManager;
    }
1468

1469 1470 1471
    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
1472
     *
Benjamin Morel's avatar
Benjamin Morel committed
1473 1474
     * @return void
     *
1475
     * @throws ConnectionException If no transaction is active.
1476 1477 1478
     */
    public function setRollbackOnly()
    {
1479
        if ($this->transactionNestingLevel === 0) {
1480 1481
            throw ConnectionException::noActiveTransaction();
        }
1482
        $this->isRollbackOnly = true;
1483 1484 1485
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1486
     * Checks whether the current transaction is marked for rollback only.
1487
     *
1488
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
1489
     *
1490
     * @throws ConnectionException If no transaction is active.
1491
     */
1492
    public function isRollbackOnly()
1493
    {
1494
        if ($this->transactionNestingLevel === 0) {
1495 1496
            throw ConnectionException::noActiveTransaction();
        }
Benjamin Morel's avatar
Benjamin Morel committed
1497

1498
        return $this->isRollbackOnly;
1499 1500
    }

1501 1502 1503
    /**
     * Converts a given value to its database representation according to the conversion
     * rules of a specific DBAL mapping type.
1504
     *
Benjamin Morel's avatar
Benjamin Morel committed
1505 1506 1507
     * @param mixed  $value The value to convert.
     * @param string $type  The name of the DBAL mapping type.
     *
1508 1509 1510 1511
     * @return mixed The converted value.
     */
    public function convertToDatabaseValue($value, $type)
    {
1512
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1513 1514 1515 1516 1517
    }

    /**
     * Converts a given value to its PHP representation according to the conversion
     * rules of a specific DBAL mapping type.
1518
     *
Benjamin Morel's avatar
Benjamin Morel committed
1519 1520 1521
     * @param mixed  $value The value to convert.
     * @param string $type  The name of the DBAL mapping type.
     *
1522 1523 1524 1525
     * @return mixed The converted type.
     */
    public function convertToPHPValue($value, $type)
    {
1526
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1527 1528 1529 1530 1531
    }

    /**
     * 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.
1532
     *
1533 1534 1535
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
     *           raw PDOStatement instances.
     *
Benjamin Morel's avatar
Benjamin Morel committed
1536
     * @param \Doctrine\DBAL\Driver\Statement $stmt   The statement to bind the values to.
1537 1538
     * @param mixed[]                         $params The map/list of named/positional parameters.
     * @param int[]|string[]                  $types  The parameter types (PDO binding types or DBAL mapping types).
Benjamin Morel's avatar
Benjamin Morel committed
1539 1540
     *
     * @return void
1541
     */
1542
    private function _bindTypedValues($stmt, array $params, array $types)
1543 1544 1545 1546
    {
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
1547
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1548
            $bindIndex  = 1;
1549
            foreach ($params as $value) {
1550 1551
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
1552 1553
                    $type                  = $types[$typeIndex];
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
                    $stmt->bindValue($bindIndex, $value, $bindingType);
                } else {
                    $stmt->bindValue($bindIndex, $value);
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
1564 1565
                    $type                  = $types[$name];
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1566 1567 1568 1569 1570 1571 1572
                    $stmt->bindValue($name, $value, $bindingType);
                } else {
                    $stmt->bindValue($name, $value);
                }
            }
        }
    }
1573 1574 1575 1576

    /**
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
     *
Sergei Morozov's avatar
Sergei Morozov committed
1577 1578
     * @param mixed           $value The value to bind.
     * @param int|string|null $type  The type to bind (PDO or DBAL).
Benjamin Morel's avatar
Benjamin Morel committed
1579
     *
1580
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1581 1582 1583 1584 1585 1586 1587
     */
    private function getBindingInfo($value, $type)
    {
        if (is_string($type)) {
            $type = Type::getType($type);
        }
        if ($type instanceof Type) {
1588
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1589 1590
            $bindingType = $type->getBindingType();
        } else {
1591
            $bindingType = $type;
1592
        }
Benjamin Morel's avatar
Benjamin Morel committed
1593

1594
        return [$value, $bindingType];
1595 1596
    }

1597 1598 1599 1600 1601 1602
    /**
     * Resolves the parameters to a format which can be displayed.
     *
     * @internal This is a purely internal method. If you rely on this method, you are advised to
     *           copy/paste the code as this method may change, or be removed without prior notice.
     *
1603 1604
     * @param mixed[]        $params
     * @param int[]|string[] $types
1605
     *
1606
     * @return mixed[]
1607 1608 1609
     */
    public function resolveParams(array $params, array $types)
    {
1610
        $resolvedParams = [];
1611 1612 1613 1614 1615

        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1616
            $bindIndex  = 1;
1617 1618 1619
            foreach ($params as $value) {
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
1620 1621
                    $type                       = $types[$typeIndex];
                    [$value]                    = $this->getBindingInfo($value, $type);
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
                    $resolvedParams[$bindIndex] = $value;
                } else {
                    $resolvedParams[$bindIndex] = $value;
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
1632 1633
                    $type                  = $types[$name];
                    [$value]               = $this->getBindingInfo($value, $type);
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
                    $resolvedParams[$name] = $value;
                } else {
                    $resolvedParams[$name] = $value;
                }
            }
        }

        return $resolvedParams;
    }

1644
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1645
     * Creates a new instance of a SQL query builder.
1646
     *
1647
     * @return QueryBuilder
1648 1649 1650 1651 1652
     */
    public function createQueryBuilder()
    {
        return new Query\QueryBuilder($this);
    }
1653 1654

    /**
1655 1656 1657 1658 1659 1660
     * Ping the server
     *
     * When the server is not available the method returns FALSE.
     * It is responsibility of the developer to handle this case
     * and abort the request or reconnect manually:
     *
1661 1662
     * @return bool
     *
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
     * @example
     *
     *   if ($conn->ping() === false) {
     *      $conn->close();
     *      $conn->connect();
     *   }
     *
     * It is undefined if the underlying driver attempts to reconnect
     * or disconnect when the connection is not available anymore
     * as long it returns TRUE when a reconnect succeeded and
     * FALSE when the connection was dropped.
1674 1675 1676
     */
    public function ping()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1677
        $connection = $this->getWrappedConnection();
1678

Sergei Morozov's avatar
Sergei Morozov committed
1679 1680
        if ($connection instanceof PingableConnection) {
            return $connection->ping();
1681 1682 1683
        }

        try {
1684
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
till's avatar
till committed
1685

1686 1687
            return true;
        } catch (DBALException $e) {
1688
            return false;
1689
        }
1690
    }
1691
}