Connection.php 49.4 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
     *
Benjamin Morel's avatar
Benjamin Morel committed
245
     * @return string|null
246 247 248
     */
    public function getHost()
    {
249
        return $this->params['host'] ?? null;
250
    }
251

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

262 263
    /**
     * Gets the username used by this connection.
264
     *
Benjamin Morel's avatar
Benjamin Morel committed
265
     * @return string|null
266 267 268
     */
    public function getUsername()
    {
269
        return $this->params['user'] ?? null;
270
    }
271

272 273
    /**
     * Gets the password used by this connection.
274
     *
Benjamin Morel's avatar
Benjamin Morel committed
275
     * @return string|null
276 277 278
     */
    public function getPassword()
    {
279
        return $this->params['password'] ?? null;
280
    }
romanb's avatar
romanb committed
281 282 283 284

    /**
     * Gets the DBAL driver instance.
     *
285
     * @return Driver
romanb's avatar
romanb committed
286 287 288 289 290 291 292 293 294
     */
    public function getDriver()
    {
        return $this->_driver;
    }

    /**
     * Gets the Configuration used by the Connection.
     *
295
     * @return Configuration
romanb's avatar
romanb committed
296 297 298 299 300 301 302 303 304
     */
    public function getConfiguration()
    {
        return $this->_config;
    }

    /**
     * Gets the EventManager used by the Connection.
     *
305
     * @return EventManager
romanb's avatar
romanb committed
306 307 308 309 310 311 312 313 314
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

    /**
     * Gets the DatabasePlatform for the connection.
     *
315
     * @return AbstractPlatform
316
     *
317
     * @throws DBALException
romanb's avatar
romanb committed
318 319 320
     */
    public function getDatabasePlatform()
    {
321
        if ($this->platform === null) {
322
            $this->detectDatabasePlatform();
323 324 325
        }

        return $this->platform;
romanb's avatar
romanb committed
326
    }
327

328 329 330
    /**
     * Gets the ExpressionBuilder for the connection.
     *
331
     * @return ExpressionBuilder
332 333 334 335 336
     */
    public function getExpressionBuilder()
    {
        return $this->_expr;
    }
337

romanb's avatar
romanb committed
338 339 340
    /**
     * Establishes the connection with the database.
     *
341 342
     * @return bool TRUE if the connection was successfully established, FALSE if
     *              the connection is already open.
romanb's avatar
romanb committed
343 344 345
     */
    public function connect()
    {
346
        if ($this->isConnected) {
347 348
            return false;
        }
romanb's avatar
romanb committed
349

350 351 352
        $driverOptions = $this->params['driverOptions'] ?? [];
        $user          = $this->params['user'] ?? null;
        $password      = $this->params['password'] ?? null;
romanb's avatar
romanb committed
353

354 355
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
        $this->isConnected = true;
romanb's avatar
romanb committed
356

357
        if ($this->autoCommit === false) {
358 359 360
            $this->beginTransaction();
        }

361
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
362
            $eventArgs = new Event\ConnectionEventArgs($this);
363 364 365
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

romanb's avatar
romanb committed
366 367 368
        return true;
    }

369 370 371 372 373
    /**
     * Detects and sets the database platform.
     *
     * Evaluates custom platform class and version in order to set the correct platform.
     *
374
     * @throws DBALException If an invalid platform was specified for this connection.
375 376 377
     */
    private function detectDatabasePlatform()
    {
378
        $version = $this->getDatabasePlatformVersion();
379

380 381 382
        if ($version !== null) {
            assert($this->_driver instanceof VersionAwarePlatformDriver);

383
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
384
        } else {
385
            $this->platform = $this->_driver->getDatabasePlatform();
386 387 388 389 390 391 392 393 394 395 396 397 398 399
        }

        $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
400
     *
401
     * @throws Exception
402 403 404 405
     */
    private function getDatabasePlatformVersion()
    {
        // Driver does not support version specific platforms.
406
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
407 408 409 410
            return null;
        }

        // Explicit platform version requested (supersedes auto-detection).
411 412
        if (isset($this->params['serverVersion'])) {
            return $this->params['serverVersion'];
413 414 415
        }

        // If not connected, we need to connect now to determine the platform version.
416
        if ($this->_conn === null) {
417 418
            try {
                $this->connect();
419
            } catch (Throwable $originalException) {
420
                if (empty($this->params['dbname'])) {
421 422 423 424 425
                    throw $originalException;
                }

                // The database to connect to might not yet exist.
                // Retry detection without database name connection parameter.
426 427
                $databaseName           = $this->params['dbname'];
                $this->params['dbname'] = null;
428 429 430

                try {
                    $this->connect();
431
                } catch (Throwable $fallbackException) {
432 433 434
                    // Either the platform does not support database-less connections
                    // or something else went wrong.
                    // Reset connection parameters and rethrow the original exception.
435
                    $this->params['dbname'] = $databaseName;
436 437 438 439 440

                    throw $originalException;
                }

                // Reset connection parameters.
441 442
                $this->params['dbname'] = $databaseName;
                $serverVersion          = $this->getServerVersion();
443 444 445 446 447 448

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

                return $serverVersion;
            }
449 450
        }

451 452 453 454 455 456 457 458 459 460
        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
461 462
        $connection = $this->getWrappedConnection();

463
        // Automatic platform version detection.
Sergei Morozov's avatar
Sergei Morozov committed
464 465
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
            return $connection->getServerVersion();
466 467 468 469 470 471
        }

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

472 473 474 475
    /**
     * Returns the current auto-commit mode for this connection.
     *
     * @see    setAutoCommit
476 477
     *
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
478
     */
479
    public function isAutoCommit()
480
    {
481
        return $this->autoCommit === true;
482 483 484 485 486 487 488 489 490 491 492 493
    }

    /**
     * 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.
     *
494
     * @see   isAutoCommit
495 496
     *
     * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
497 498 499
     */
    public function setAutoCommit($autoCommit)
    {
500
        $autoCommit = (bool) $autoCommit;
501 502 503 504 505 506 507 508 509

        // 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.
510
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
511
            return;
512
        }
513 514

        $this->commitAll();
515 516
    }

517
    /**
Benjamin Morel's avatar
Benjamin Morel committed
518
     * Sets the fetch mode.
519
     *
520
     * @param int $fetchMode
Benjamin Morel's avatar
Benjamin Morel committed
521 522
     *
     * @return void
523
     */
524
    public function setFetchMode($fetchMode)
525
    {
526
        $this->defaultFetchMode = $fetchMode;
527 528
    }

romanb's avatar
romanb committed
529
    /**
530 531
     * Prepares and executes an SQL query and returns the first row of the result
     * as an associative array.
532
     *
533 534 535
     * @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
536
     *
537
     * @return mixed[]|false False is returned if no rows are found.
538
     *
539
     * @throws DBALException
romanb's avatar
romanb committed
540
     */
541
    public function fetchAssoc($statement, array $params = [], array $types = [])
romanb's avatar
romanb committed
542
    {
543
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
romanb's avatar
romanb committed
544 545 546
    }

    /**
547 548
     * Prepares and executes an SQL query and returns the first row of the result
     * as a numerically indexed array.
romanb's avatar
romanb committed
549
     *
550 551 552
     * @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
553
     *
554
     * @return mixed[]|false False is returned if no rows are found.
romanb's avatar
romanb committed
555
     */
556
    public function fetchArray($statement, array $params = [], array $types = [])
romanb's avatar
romanb committed
557
    {
558
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
romanb's avatar
romanb committed
559 560 561
    }

    /**
562 563
     * Prepares and executes an SQL query and returns the value of a single column
     * of the first row of the result.
564
     *
565 566 567 568
     * @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
569
     *
570
     * @return mixed|false False is returned if no rows are found.
571
     *
572
     * @throws DBALException
romanb's avatar
romanb committed
573
     */
574
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
romanb's avatar
romanb committed
575
    {
576
        return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
romanb's avatar
romanb committed
577 578 579 580 581
    }

    /**
     * Whether an actual connection to the database is established.
     *
582
     * @return bool
romanb's avatar
romanb committed
583 584 585
     */
    public function isConnected()
    {
586
        return $this->isConnected;
romanb's avatar
romanb committed
587 588
    }

589 590
    /**
     * Checks whether a transaction is currently active.
591
     *
592
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
593 594 595
     */
    public function isTransactionActive()
    {
596
        return $this->transactionNestingLevel > 0;
597 598
    }

599
    /**
Sergei Morozov's avatar
Sergei Morozov committed
600
     * Adds identifier condition to the query components
601
     *
Sergei Morozov's avatar
Sergei Morozov committed
602 603 604 605
     * @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
606
     *
Sergei Morozov's avatar
Sergei Morozov committed
607
     * @throws DBALException
608
     */
Sergei Morozov's avatar
Sergei Morozov committed
609 610 611 612 613 614 615
    private function addIdentifierCondition(
        array $identifier,
        array &$columns,
        array &$values,
        array &$conditions
    ) : void {
        $platform = $this->getDatabasePlatform();
616

Sergei Morozov's avatar
Sergei Morozov committed
617
        foreach ($identifier as $columnName => $value) {
618
            if ($value === null) {
Sergei Morozov's avatar
Sergei Morozov committed
619
                $conditions[] = $platform->getIsNullExpression($columnName);
620 621 622
                continue;
            }

623 624
            $columns[]    = $columnName;
            $values[]     = $value;
625
            $conditions[] = $columnName . ' = ?';
626 627 628
        }
    }

629 630
    /**
     * Executes an SQL DELETE statement on a table.
romanb's avatar
romanb committed
631
     *
632 633
     * Table expression and columns are not escaped and are not safe for user-input.
     *
634 635 636
     * @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
637
     *
638
     * @return int The number of affected rows.
639
     *
640
     * @throws DBALException
641
     * @throws InvalidArgumentException
642
     */
643
    public function delete($tableExpression, array $identifier, array $types = [])
644 645
    {
        if (empty($identifier)) {
646
            throw InvalidArgumentException::fromEmptyCriteria();
647 648
        }

Sergei Morozov's avatar
Sergei Morozov committed
649 650 651
        $columns = $values = $conditions = [];

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

653
        return $this->executeUpdate(
654 655 656
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
            $values,
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
657
        );
658 659
    }

romanb's avatar
romanb committed
660 661 662 663 664 665 666
    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
667
        $this->_conn = null;
668

669
        $this->isConnected = false;
romanb's avatar
romanb committed
670 671
    }

672 673 674
    /**
     * Sets the transaction isolation level.
     *
675
     * @param int $level The level to set.
Benjamin Morel's avatar
Benjamin Morel committed
676
     *
677
     * @return int
678 679 680
     */
    public function setTransactionIsolation($level)
    {
681
        $this->transactionIsolationLevel = $level;
682

683
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
684 685 686 687 688
    }

    /**
     * Gets the currently active transaction isolation level.
     *
689
     * @return int The current transaction isolation level.
690 691 692
     */
    public function getTransactionIsolation()
    {
693 694
        if ($this->transactionIsolationLevel === null) {
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
695 696
        }

697
        return $this->transactionIsolationLevel;
698 699
    }

romanb's avatar
romanb committed
700
    /**
701
     * Executes an SQL UPDATE statement on a table.
romanb's avatar
romanb committed
702
     *
703 704
     * Table expression and columns are not escaped and are not safe for user-input.
     *
705 706 707 708
     * @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
709
     *
710
     * @return int The number of affected rows.
711
     *
712
     * @throws DBALException
romanb's avatar
romanb committed
713
     */
714
    public function update($tableExpression, array $data, array $identifier, array $types = [])
romanb's avatar
romanb committed
715
    {
Sergei Morozov's avatar
Sergei Morozov committed
716
        $columns = $values = $conditions = $set = [];
717

romanb's avatar
romanb committed
718
        foreach ($data as $columnName => $value) {
Sergei Morozov's avatar
Sergei Morozov committed
719 720 721
            $columns[] = $columnName;
            $values[]  = $value;
            $set[]     = $columnName . ' = ?';
romanb's avatar
romanb committed
722 723
        }

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

726
        if (is_string(key($types))) {
727
            $types = $this->extractTypeValues($columns, $types);
728
        }
romanb's avatar
romanb committed
729

730
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
731
                . ' WHERE ' . implode(' AND ', $conditions);
romanb's avatar
romanb committed
732

733
        return $this->executeUpdate($sql, $values, $types);
romanb's avatar
romanb committed
734 735 736 737 738
    }

    /**
     * Inserts a table row with specified data.
     *
739 740
     * Table expression and columns are not escaped and are not safe for user-input.
     *
741 742 743
     * @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
744
     *
745
     * @return int The number of affected rows.
746
     *
747
     * @throws DBALException
romanb's avatar
romanb committed
748
     */
749
    public function insert($tableExpression, array $data, array $types = [])
romanb's avatar
romanb committed
750
    {
751
        if (empty($data)) {
752
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
753 754
        }

755
        $columns = [];
756 757
        $values  = [];
        $set     = [];
758 759

        foreach ($data as $columnName => $value) {
760
            $columns[] = $columnName;
761 762
            $values[]  = $value;
            $set[]     = '?';
763 764
        }

765
        return $this->executeUpdate(
766 767 768 769
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
            ' VALUES (' . implode(', ', $set) . ')',
            $values,
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
770
        );
romanb's avatar
romanb committed
771 772
    }

773
    /**
774
     * Extract ordered type list from an ordered column list and type map.
775
     *
Sergei Morozov's avatar
Sergei Morozov committed
776
     * @param int[]|string[] $columnList
777
     * @param int[]|string[] $types
778
     *
779
     * @return int[]|string[]
780
     */
781
    private function extractTypeValues(array $columnList, array $types)
782
    {
783
        $typeValues = [];
784

785
        foreach ($columnList as $columnIndex => $columnName) {
786
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
787 788 789 790 791
        }

        return $typeValues;
    }

romanb's avatar
romanb committed
792
    /**
Benjamin Morel's avatar
Benjamin Morel committed
793
     * Quotes a string so it can be safely used as a table or column name, even if
romanb's avatar
romanb committed
794 795 796 797
     * it is a reserved name.
     *
     * Delimiting style depends on the underlying database platform that is being used.
     *
798 799
     * 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
800 801
     * problems than they solve.
     *
802
     * @param string $str The name to be quoted.
Benjamin Morel's avatar
Benjamin Morel committed
803
     *
804
     * @return string The quoted name.
romanb's avatar
romanb committed
805 806 807
     */
    public function quoteIdentifier($str)
    {
808
        return $this->getDatabasePlatform()->quoteIdentifier($str);
romanb's avatar
romanb committed
809 810 811
    }

    /**
Sergei Morozov's avatar
Sergei Morozov committed
812
     * {@inheritDoc}
romanb's avatar
romanb committed
813 814 815
     */
    public function quote($input, $type = null)
    {
Sergei Morozov's avatar
Sergei Morozov committed
816
        $connection = $this->getWrappedConnection();
817

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

Sergei Morozov's avatar
Sergei Morozov committed
820
        return $connection->quote($value, $bindingType);
romanb's avatar
romanb committed
821 822 823
    }

    /**
824
     * Prepares and executes an SQL query and returns the result as an associative array.
romanb's avatar
romanb committed
825
     *
826 827 828
     * @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
829
     *
830
     * @return mixed[]
romanb's avatar
romanb committed
831
     */
832
    public function fetchAll($sql, array $params = [], $types = [])
romanb's avatar
romanb committed
833
    {
root's avatar
root committed
834
        return $this->executeQuery($sql, $params, $types)->fetchAll();
romanb's avatar
romanb committed
835 836 837 838 839
    }

    /**
     * Prepares an SQL statement.
     *
840
     * @param string $statement The SQL statement to prepare.
Benjamin Morel's avatar
Benjamin Morel committed
841
     *
842
     * @return DriverStatement The prepared statement.
Benjamin Morel's avatar
Benjamin Morel committed
843
     *
844
     * @throws DBALException
romanb's avatar
romanb committed
845 846 847
     */
    public function prepare($statement)
    {
848 849
        try {
            $stmt = new Statement($statement, $this);
850
        } catch (Throwable $ex) {
851
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
852 853
        }

854
        $stmt->setFetchMode($this->defaultFetchMode);
855 856

        return $stmt;
romanb's avatar
romanb committed
857 858 859
    }

    /**
Pascal Borreli's avatar
Pascal Borreli committed
860
     * Executes an, optionally parametrized, SQL query.
romanb's avatar
romanb committed
861
     *
Pascal Borreli's avatar
Pascal Borreli committed
862
     * If the query is parametrized, a prepared statement is used.
863 864
     * If an SQLLogger is configured, the execution is logged.
     *
865
     * @param string                 $query  The SQL query to execute.
866 867
     * @param mixed[]                $params The parameters to bind to the query, if any.
     * @param int[]|string[]         $types  The types the previous parameters are in.
868
     * @param QueryCacheProfile|null $qcp    The query cache profile, optional.
Benjamin Morel's avatar
Benjamin Morel committed
869
     *
870
     * @return ResultStatement The executed statement.
Benjamin Morel's avatar
Benjamin Morel committed
871
     *
872
     * @throws DBALException
romanb's avatar
romanb committed
873
     */
874
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
romanb's avatar
romanb committed
875
    {
876
        if ($qcp !== null) {
877
            return $this->executeCacheQuery($query, $params, $types, $qcp);
878 879
        }

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

882 883 884
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
885
        }
886

887 888
        try {
            if ($params) {
889
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
890

Sergei Morozov's avatar
Sergei Morozov committed
891
                $stmt = $connection->prepare($query);
892 893 894 895 896 897
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
898
            } else {
Sergei Morozov's avatar
Sergei Morozov committed
899
                $stmt = $connection->query($query);
900
            }
901
        } catch (Throwable $ex) {
902
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
903
        }
904

905
        $stmt->setFetchMode($this->defaultFetchMode);
906

907 908
        if ($logger) {
            $logger->stopQuery();
909 910
        }

romanb's avatar
romanb committed
911
        return $stmt;
romanb's avatar
romanb committed
912
    }
913

914
    /**
Benjamin Morel's avatar
Benjamin Morel committed
915 916
     * Executes a caching query.
     *
917
     * @param string            $query  The SQL query to execute.
918 919
     * @param mixed[]           $params The parameters to bind to the query, if any.
     * @param int[]|string[]    $types  The types the previous parameters are in.
920
     * @param QueryCacheProfile $qcp    The query cache profile.
921
     *
922
     * @return ResultStatement
Benjamin Morel's avatar
Benjamin Morel committed
923
     *
924
     * @throws CacheException
925 926 927
     */
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
    {
Sergei Morozov's avatar
Sergei Morozov committed
928 929 930
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();

        if ($resultCache === null) {
931 932 933
            throw CacheException::noResultDriverConfigured();
        }

934 935 936 937
        $connectionParams = $this->getParams();
        unset($connectionParams['platform']);

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

        // fetch the row pointers entry
940 941 942
        $data = $resultCache->fetch($cacheKey);

        if ($data !== false) {
943 944
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
            if (isset($data[$realKey])) {
945
                $stmt = new ArrayStatement($data[$realKey]);
Steve Müller's avatar
Steve Müller committed
946
            } elseif (array_key_exists($realKey, $data)) {
947
                $stmt = new ArrayStatement([]);
948 949
            }
        }
950

951
        if (! isset($stmt)) {
952 953 954
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
        }

955
        $stmt->setFetchMode($this->defaultFetchMode);
956 957

        return $stmt;
958 959
    }

960
    /**
Pascal Borreli's avatar
Pascal Borreli committed
961
     * Executes an, optionally parametrized, SQL query and returns the result,
962
     * applying a given projection/transformation function on each row of the result.
963
     *
964
     * @param string  $query    The SQL query to execute.
965
     * @param mixed[] $params   The parameters, if any.
966
     * @param Closure $function The transformation function that is applied on each row.
Benjamin Morel's avatar
Benjamin Morel committed
967 968 969
     *                           The function receives a single parameter, an array, that
     *                           represents a row of the result set.
     *
970
     * @return mixed[] The projected result of the query.
971
     */
972
    public function project($query, array $params, Closure $function)
973
    {
974
        $result = [];
975
        $stmt   = $this->executeQuery($query, $params);
976

977
        while ($row = $stmt->fetch()) {
978
            $result[] = $function($row);
979
        }
980

981
        $stmt->closeCursor();
982

983 984
        return $result;
    }
romanb's avatar
romanb committed
985 986

    /**
987
     * Executes an SQL statement, returning a result set as a Statement object.
988
     *
989
     * @return \Doctrine\DBAL\Driver\Statement
Benjamin Morel's avatar
Benjamin Morel committed
990
     *
991
     * @throws DBALException
992 993 994
     */
    public function query()
    {
Sergei Morozov's avatar
Sergei Morozov committed
995
        $connection = $this->getWrappedConnection();
996

997 998
        $args = func_get_args();

999
        $logger = $this->_config->getSQLLogger();
1000 1001 1002 1003
        if ($logger) {
            $logger->startQuery($args[0]);
        }

1004
        try {
Sergei Morozov's avatar
Sergei Morozov committed
1005
            $statement = $connection->query(...$args);
1006
        } catch (Throwable $ex) {
1007
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1008 1009
        }

1010
        $statement->setFetchMode($this->defaultFetchMode);
1011 1012 1013 1014 1015 1016

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

        return $statement;
1017 1018 1019 1020 1021
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
1022
     *
1023
     * This method supports PDO binding types as well as DBAL mapping types.
romanb's avatar
romanb committed
1024
     *
1025 1026 1027
     * @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
1028
     *
1029
     * @return int The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
1030
     *
1031
     * @throws DBALException
romanb's avatar
romanb committed
1032
     */
1033
    public function executeUpdate($query, array $params = [], array $types = [])
romanb's avatar
romanb committed
1034
    {
Sergei Morozov's avatar
Sergei Morozov committed
1035
        $connection = $this->getWrappedConnection();
romanb's avatar
romanb committed
1036

1037 1038 1039
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
1040 1041
        }

1042 1043
        try {
            if ($params) {
1044
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1045

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

1048 1049 1050 1051 1052 1053 1054
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
                $result = $stmt->rowCount();
1055
            } else {
Sergei Morozov's avatar
Sergei Morozov committed
1056
                $result = $connection->exec($query);
1057
            }
1058
        } catch (Throwable $ex) {
1059
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
1060
        }
1061

1062 1063
        if ($logger) {
            $logger->stopQuery();
1064 1065
        }

romanb's avatar
romanb committed
1066
        return $result;
romanb's avatar
romanb committed
1067 1068
    }

1069
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1070
     * Executes an SQL statement and return the number of affected rows.
1071
     *
1072
     * @param string $statement
Benjamin Morel's avatar
Benjamin Morel committed
1073
     *
1074
     * @return int The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
1075
     *
1076
     * @throws DBALException
1077 1078 1079
     */
    public function exec($statement)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1080
        $connection = $this->getWrappedConnection();
1081 1082 1083 1084 1085 1086

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

1087
        try {
Sergei Morozov's avatar
Sergei Morozov committed
1088
            $result = $connection->exec($statement);
1089
        } catch (Throwable $ex) {
1090
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1091
        }
1092 1093 1094 1095 1096 1097

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

        return $result;
1098 1099
    }

1100 1101 1102
    /**
     * Returns the current transaction nesting level.
     *
1103
     * @return int The nesting level. A value of 0 means there's no active transaction.
1104 1105 1106
     */
    public function getTransactionNestingLevel()
    {
1107
        return $this->transactionNestingLevel;
1108 1109
    }

romanb's avatar
romanb committed
1110
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1111
     * Fetches the SQLSTATE associated with the last database operation.
romanb's avatar
romanb committed
1112
     *
1113
     * @return string|null The last error code.
romanb's avatar
romanb committed
1114 1115 1116
     */
    public function errorCode()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1117
        return $this->getWrappedConnection()->errorCode();
romanb's avatar
romanb committed
1118 1119 1120
    }

    /**
1121
     * {@inheritDoc}
romanb's avatar
romanb committed
1122 1123 1124
     */
    public function errorInfo()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1125
        return $this->getWrappedConnection()->errorInfo();
romanb's avatar
romanb committed
1126 1127 1128 1129 1130 1131 1132
    }

    /**
     * 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,
1133 1134
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
romanb's avatar
romanb committed
1135
     *
Benjamin Morel's avatar
Benjamin Morel committed
1136 1137
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
     *
1138
     * @return string A string representation of the last inserted ID.
romanb's avatar
romanb committed
1139
     */
romanb's avatar
romanb committed
1140 1141
    public function lastInsertId($seqName = null)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1142
        return $this->getWrappedConnection()->lastInsertId($seqName);
romanb's avatar
romanb committed
1143
    }
1144

1145 1146 1147 1148 1149 1150 1151 1152
    /**
     * 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.
     *
1153
     * @param Closure $func The function to execute transactionally.
Benjamin Morel's avatar
Benjamin Morel committed
1154
     *
1155
     * @return mixed The value returned by $func
Benjamin Morel's avatar
Benjamin Morel committed
1156
     *
1157 1158
     * @throws Exception
     * @throws Throwable
1159 1160 1161 1162 1163
     */
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
1164
            $res = $func($this);
1165
            $this->commit();
1166

1167
            return $res;
1168
        } catch (Exception $e) {
1169
            $this->rollBack();
1170 1171 1172
            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();
1173 1174 1175 1176
            throw $e;
        }
    }

1177
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1178
     * Sets if nested transactions should use savepoints.
1179
     *
1180
     * @param bool $nestTransactionsWithSavepoints
Benjamin Morel's avatar
Benjamin Morel committed
1181
     *
1182
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1183
     *
1184
     * @throws ConnectionException
1185 1186 1187
     */
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
    {
1188
        if ($this->transactionNestingLevel > 0) {
1189 1190 1191
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
        }

1192
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1193
            throw ConnectionException::savepointsNotSupported();
1194 1195
        }

1196
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1197 1198 1199
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1200
     * Gets if nested transactions should use savepoints.
1201
     *
1202
     * @return bool
1203 1204 1205
     */
    public function getNestTransactionsWithSavepoints()
    {
1206
        return $this->nestTransactionsWithSavepoints;
1207 1208
    }

1209 1210 1211 1212
    /**
     * 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
1213
     * @return mixed A string with the savepoint name or false.
1214
     */
1215 1216
    protected function _getNestedTransactionSavePointName()
    {
1217
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1218 1219
    }

1220
    /**
1221
     * {@inheritDoc}
1222 1223 1224
     */
    public function beginTransaction()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1225
        $connection = $this->getWrappedConnection();
1226

1227
        ++$this->transactionNestingLevel;
1228

1229 1230
        $logger = $this->_config->getSQLLogger();

1231
        if ($this->transactionNestingLevel === 1) {
1232 1233 1234
            if ($logger) {
                $logger->startQuery('"START TRANSACTION"');
            }
Sergei Morozov's avatar
Sergei Morozov committed
1235 1236 1237

            $connection->beginTransaction();

1238 1239 1240
            if ($logger) {
                $logger->stopQuery();
            }
1241
        } elseif ($this->nestTransactionsWithSavepoints) {
1242 1243 1244
            if ($logger) {
                $logger->startQuery('"SAVEPOINT"');
            }
1245
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1246 1247 1248
            if ($logger) {
                $logger->stopQuery();
            }
1249
        }
1250 1251

        return true;
1252 1253 1254
    }

    /**
1255
     * {@inheritDoc}
Benjamin Morel's avatar
Benjamin Morel committed
1256
     *
1257
     * @throws ConnectionException If the commit failed due to no active transaction or
Benjamin Morel's avatar
Benjamin Morel committed
1258
     *                                            because the transaction was marked for rollback only.
1259 1260 1261
     */
    public function commit()
    {
1262
        if ($this->transactionNestingLevel === 0) {
1263
            throw ConnectionException::noActiveTransaction();
1264
        }
1265
        if ($this->isRollbackOnly) {
1266 1267 1268
            throw ConnectionException::commitFailedRollbackOnly();
        }

1269 1270
        $result = true;

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

1273 1274
        $logger = $this->_config->getSQLLogger();

1275
        if ($this->transactionNestingLevel === 1) {
1276 1277 1278
            if ($logger) {
                $logger->startQuery('"COMMIT"');
            }
Sergei Morozov's avatar
Sergei Morozov committed
1279

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

1282 1283 1284
            if ($logger) {
                $logger->stopQuery();
            }
1285
        } elseif ($this->nestTransactionsWithSavepoints) {
1286 1287 1288
            if ($logger) {
                $logger->startQuery('"RELEASE SAVEPOINT"');
            }
1289
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1290 1291 1292
            if ($logger) {
                $logger->stopQuery();
            }
1293 1294
        }

1295
        --$this->transactionNestingLevel;
1296

1297
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1298
            return $result;
1299
        }
1300 1301

        $this->beginTransaction();
1302

1303
        return $result;
1304 1305 1306 1307 1308
    }

    /**
     * Commits all current nesting transactions.
     */
1309
    private function commitAll()
1310
    {
1311 1312
        while ($this->transactionNestingLevel !== 0) {
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1313 1314 1315 1316 1317 1318 1319 1320 1321
                // 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();
        }
1322 1323 1324
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1325
     * Cancels any database changes done during the current transaction.
1326
     *
1327
     * @throws ConnectionException If the rollback operation failed.
1328
     */
1329
    public function rollBack()
1330
    {
1331
        if ($this->transactionNestingLevel === 0) {
1332
            throw ConnectionException::noActiveTransaction();
1333 1334
        }

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

1337 1338
        $logger = $this->_config->getSQLLogger();

1339
        if ($this->transactionNestingLevel === 1) {
1340 1341 1342
            if ($logger) {
                $logger->startQuery('"ROLLBACK"');
            }
1343
            $this->transactionNestingLevel = 0;
Sergei Morozov's avatar
Sergei Morozov committed
1344
            $connection->rollBack();
1345
            $this->isRollbackOnly = false;
1346 1347 1348
            if ($logger) {
                $logger->stopQuery();
            }
1349

1350
            if ($this->autoCommit === false) {
1351 1352
                $this->beginTransaction();
            }
1353
        } elseif ($this->nestTransactionsWithSavepoints) {
1354 1355 1356
            if ($logger) {
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
            }
1357
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1358
            --$this->transactionNestingLevel;
1359 1360 1361
            if ($logger) {
                $logger->stopQuery();
            }
1362
        } else {
1363 1364
            $this->isRollbackOnly = true;
            --$this->transactionNestingLevel;
1365 1366 1367
        }
    }

1368
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1369 1370 1371
     * Creates a new savepoint.
     *
     * @param string $savepoint The name of the savepoint to create.
1372 1373
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1374
     *
1375
     * @throws ConnectionException
1376
     */
1377
    public function createSavepoint($savepoint)
1378
    {
1379
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1380
            throw ConnectionException::savepointsNotSupported();
1381 1382
        }

Sergei Morozov's avatar
Sergei Morozov committed
1383
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1384 1385 1386
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1387 1388 1389
     * Releases the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to release.
1390 1391
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1392
     *
1393
     * @throws ConnectionException
1394
     */
1395
    public function releaseSavepoint($savepoint)
1396
    {
1397
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1398
            throw ConnectionException::savepointsNotSupported();
1399 1400
        }

1401 1402
        if (! $this->platform->supportsReleaseSavepoints()) {
            return;
1403
        }
1404

Sergei Morozov's avatar
Sergei Morozov committed
1405
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1406 1407 1408
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1409 1410 1411
     * Rolls back to the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to rollback to.
1412 1413
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1414
     *
1415
     * @throws ConnectionException
1416
     */
1417
    public function rollbackSavepoint($savepoint)
1418
    {
1419
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1420
            throw ConnectionException::savepointsNotSupported();
1421 1422
        }

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

romanb's avatar
romanb committed
1426 1427 1428
    /**
     * Gets the wrapped driver connection.
     *
Sergei Morozov's avatar
Sergei Morozov committed
1429
     * @return DriverConnection
romanb's avatar
romanb committed
1430 1431 1432 1433
     */
    public function getWrappedConnection()
    {
        $this->connect();
1434

romanb's avatar
romanb committed
1435 1436
        return $this->_conn;
    }
1437

romanb's avatar
romanb committed
1438 1439 1440 1441
    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
1442
     * @return AbstractSchemaManager
romanb's avatar
romanb committed
1443 1444 1445
     */
    public function getSchemaManager()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1446
        if ($this->_schemaManager === null) {
romanb's avatar
romanb committed
1447 1448
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }
1449

romanb's avatar
romanb committed
1450 1451
        return $this->_schemaManager;
    }
1452

1453 1454 1455
    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
1456
     *
Benjamin Morel's avatar
Benjamin Morel committed
1457 1458
     * @return void
     *
1459
     * @throws ConnectionException If no transaction is active.
1460 1461 1462
     */
    public function setRollbackOnly()
    {
1463
        if ($this->transactionNestingLevel === 0) {
1464 1465
            throw ConnectionException::noActiveTransaction();
        }
1466
        $this->isRollbackOnly = true;
1467 1468 1469
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1470
     * Checks whether the current transaction is marked for rollback only.
1471
     *
1472
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
1473
     *
1474
     * @throws ConnectionException If no transaction is active.
1475
     */
1476
    public function isRollbackOnly()
1477
    {
1478
        if ($this->transactionNestingLevel === 0) {
1479 1480
            throw ConnectionException::noActiveTransaction();
        }
Benjamin Morel's avatar
Benjamin Morel committed
1481

1482
        return $this->isRollbackOnly;
1483 1484
    }

1485 1486 1487
    /**
     * Converts a given value to its database representation according to the conversion
     * rules of a specific DBAL mapping type.
1488
     *
Benjamin Morel's avatar
Benjamin Morel committed
1489 1490 1491
     * @param mixed  $value The value to convert.
     * @param string $type  The name of the DBAL mapping type.
     *
1492 1493 1494 1495
     * @return mixed The converted value.
     */
    public function convertToDatabaseValue($value, $type)
    {
1496
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1497 1498 1499 1500 1501
    }

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

    /**
     * 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.
1516
     *
1517 1518 1519
     * @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
1520
     * @param \Doctrine\DBAL\Driver\Statement $stmt   The statement to bind the values to.
1521 1522
     * @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
1523 1524
     *
     * @return void
1525
     */
1526
    private function _bindTypedValues($stmt, array $params, array $types)
1527 1528 1529 1530
    {
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
1531
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1532
            $bindIndex  = 1;
1533
            foreach ($params as $value) {
1534 1535
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
1536 1537
                    $type                  = $types[$typeIndex];
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
                    $stmt->bindValue($bindIndex, $value, $bindingType);
                } else {
                    $stmt->bindValue($bindIndex, $value);
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
1548 1549
                    $type                  = $types[$name];
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1550 1551 1552 1553 1554 1555 1556
                    $stmt->bindValue($name, $value, $bindingType);
                } else {
                    $stmt->bindValue($name, $value);
                }
            }
        }
    }
1557 1558 1559 1560

    /**
     * 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
1561 1562
     * @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
1563
     *
1564
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1565 1566 1567 1568 1569 1570 1571
     */
    private function getBindingInfo($value, $type)
    {
        if (is_string($type)) {
            $type = Type::getType($type);
        }
        if ($type instanceof Type) {
1572
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1573 1574
            $bindingType = $type->getBindingType();
        } else {
1575
            $bindingType = $type;
1576
        }
Benjamin Morel's avatar
Benjamin Morel committed
1577

1578
        return [$value, $bindingType];
1579 1580
    }

1581 1582 1583 1584 1585 1586
    /**
     * 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.
     *
1587 1588
     * @param mixed[]        $params
     * @param int[]|string[] $types
1589
     *
1590
     * @return mixed[]
1591 1592 1593
     */
    public function resolveParams(array $params, array $types)
    {
1594
        $resolvedParams = [];
1595 1596 1597 1598 1599

        // 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;
1600
            $bindIndex  = 1;
1601 1602 1603
            foreach ($params as $value) {
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
1604 1605
                    $type                       = $types[$typeIndex];
                    [$value]                    = $this->getBindingInfo($value, $type);
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
                    $resolvedParams[$bindIndex] = $value;
                } else {
                    $resolvedParams[$bindIndex] = $value;
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
1616 1617
                    $type                  = $types[$name];
                    [$value]               = $this->getBindingInfo($value, $type);
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
                    $resolvedParams[$name] = $value;
                } else {
                    $resolvedParams[$name] = $value;
                }
            }
        }

        return $resolvedParams;
    }

1628
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1629
     * Creates a new instance of a SQL query builder.
1630
     *
1631
     * @return QueryBuilder
1632 1633 1634 1635 1636
     */
    public function createQueryBuilder()
    {
        return new Query\QueryBuilder($this);
    }
1637 1638

    /**
1639 1640 1641 1642 1643 1644
     * 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:
     *
1645 1646
     * @return bool
     *
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
     * @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.
1658 1659 1660
     */
    public function ping()
    {
Sergei Morozov's avatar
Sergei Morozov committed
1661
        $connection = $this->getWrappedConnection();
1662

Sergei Morozov's avatar
Sergei Morozov committed
1663 1664
        if ($connection instanceof PingableConnection) {
            return $connection->ping();
1665 1666 1667
        }

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

1670 1671
            return true;
        } catch (DBALException $e) {
1672
            return false;
1673
        }
1674
    }
1675
}