Connection.php 49.5 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 25
use function array_key_exists;
use function array_merge;
26
use function assert;
27 28 29 30 31
use function func_get_args;
use function implode;
use function is_int;
use function is_string;
use function key;
32 33

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

203
            $this->platform = $params['platform'];
204
            unset($this->params['platform']);
205 206
        }

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

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

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

219
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
220

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

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

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

244 245
    /**
     * Gets the hostname of the currently connected database.
246
     *
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 259 260
     * @return mixed
     */
    public function getPort()
    {
261
        return $this->params['port'] ?? null;
262
    }
263

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

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

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

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

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

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

        return $this->platform;
romanb's avatar
romanb committed
328
    }
329

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

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

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

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

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

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

romanb's avatar
romanb committed
368 369 370
        return true;
    }

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

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

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

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

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

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

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

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

                    throw $originalException;
                }

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

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

                return $serverVersion;
            }
451 452
        }

453 454 455 456 457 458 459 460 461 462
        return $this->getServerVersion();
    }

    /**
     * Returns the database server version if the underlying driver supports it.
     *
     * @return string|null
     */
    private function getServerVersion()
    {
463 464 465 466 467 468 469 470 471 472 473
        // Automatic platform version detection.
        if ($this->_conn instanceof ServerInfoAwareConnection &&
            ! $this->_conn->requiresQueryForServerVersion()
        ) {
            return $this->_conn->getServerVersion();
        }

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

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

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

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

        $this->commitAll();
517 518
    }

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

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

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

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

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

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

601
    /**
602
     * Gathers conditions for an update or delete call.
603
     *
604
     * @param mixed[] $identifiers Input array of columns to values
605 606
     *
     * @return string[][] a triplet with:
607
     *                    - the first key being the columns
608
     *                    - the second key being the values
609
     *                    - the third key being the conditions
610
     */
611
    private function gatherConditions(array $identifiers)
612
    {
613 614
        $columns    = [];
        $values     = [];
615
        $conditions = [];
616 617

        foreach ($identifiers as $columnName => $value) {
618
            if ($value === null) {
619
                $conditions[] = $this->getDatabasePlatform()->getIsNullExpression($columnName);
620 621 622
                continue;
            }

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

628
        return [$columns, $values, $conditions];
629 630
    }

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

651
        [$columns, $values, $conditions] = $this->gatherConditions($identifier);
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
    {
716
        $setColumns = [];
717 718
        $setValues  = [];
        $set        = [];
719

romanb's avatar
romanb committed
720
        foreach ($data as $columnName => $value) {
721
            $setColumns[] = $columnName;
722 723
            $setValues[]  = $value;
            $set[]        = $columnName . ' = ?';
romanb's avatar
romanb committed
724 725
        }

726 727 728
        [$conditionColumns, $conditionValues, $conditions] = $this->gatherConditions($identifier);
        $columns                                           = array_merge($setColumns, $conditionColumns);
        $values                                            = array_merge($setValues, $conditionValues);
729

730
        if (is_string(key($types))) {
731
            $types = $this->extractTypeValues($columns, $types);
732
        }
romanb's avatar
romanb committed
733

734
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
735
                . ' WHERE ' . implode(' AND ', $conditions);
romanb's avatar
romanb committed
736

737
        return $this->executeUpdate($sql, $values, $types);
romanb's avatar
romanb committed
738 739 740 741 742
    }

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

759
        $columns = [];
760 761
        $values  = [];
        $set     = [];
762 763

        foreach ($data as $columnName => $value) {
764
            $columns[] = $columnName;
765 766
            $values[]  = $value;
            $set[]     = '?';
767 768
        }

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

777
    /**
778
     * Extract ordered type list from an ordered column list and type map.
779
     *
780 781
     * @param string[]       $columnList
     * @param int[]|string[] $types
782
     *
783
     * @return int[]|string[]
784
     */
785
    private function extractTypeValues(array $columnList, array $types)
786
    {
787
        $typeValues = [];
788

789
        foreach ($columnList as $columnIndex => $columnName) {
790
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
791 792 793 794 795
        }

        return $typeValues;
    }

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

    /**
     * Quotes a given input parameter.
     *
818
     * @param mixed    $input The parameter to be quoted.
helsner's avatar
helsner committed
819
     * @param int|null $type  The type of the parameter.
Benjamin Morel's avatar
Benjamin Morel committed
820
     *
821
     * @return string The quoted parameter.
romanb's avatar
romanb committed
822 823 824
     */
    public function quote($input, $type = null)
    {
825
        $this->connect();
826

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

829
        return $this->_conn->quote($value, $bindingType);
romanb's avatar
romanb committed
830 831 832
    }

    /**
833
     * Prepares and executes an SQL query and returns the result as an associative array.
romanb's avatar
romanb committed
834
     *
835 836 837
     * @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
838
     *
839
     * @return mixed[]
romanb's avatar
romanb committed
840
     */
841
    public function fetchAll($sql, array $params = [], $types = [])
romanb's avatar
romanb committed
842
    {
root's avatar
root committed
843
        return $this->executeQuery($sql, $params, $types)->fetchAll();
romanb's avatar
romanb committed
844 845 846 847 848
    }

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

863
        $stmt->setFetchMode($this->defaultFetchMode);
864 865

        return $stmt;
romanb's avatar
romanb committed
866 867 868
    }

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

romanb's avatar
romanb committed
889 890
        $this->connect();

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

896 897
        try {
            if ($params) {
898
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
899

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

914
        $stmt->setFetchMode($this->defaultFetchMode);
915

916 917
        if ($logger) {
            $logger->stopQuery();
918 919
        }

romanb's avatar
romanb committed
920
        return $stmt;
romanb's avatar
romanb committed
921
    }
922

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

942
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $this->getParams());
943 944

        // fetch the row pointers entry
945 946 947
        $data = $resultCache->fetch($cacheKey);

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

956
        if (! isset($stmt)) {
957 958 959
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
        }

960
        $stmt->setFetchMode($this->defaultFetchMode);
961 962

        return $stmt;
963 964
    }

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

982
        while ($row = $stmt->fetch()) {
983
            $result[] = $function($row);
984
        }
985

986
        $stmt->closeCursor();
987

988 989
        return $result;
    }
romanb's avatar
romanb committed
990 991

    /**
992
     * Executes an SQL statement, returning a result set as a Statement object.
993
     *
994
     * @return \Doctrine\DBAL\Driver\Statement
Benjamin Morel's avatar
Benjamin Morel committed
995
     *
996
     * @throws DBALException
997 998 999
     */
    public function query()
    {
1000 1001
        $this->connect();

1002 1003
        $args = func_get_args();

1004
        $logger = $this->_config->getSQLLogger();
1005 1006 1007 1008
        if ($logger) {
            $logger->startQuery($args[0]);
        }

1009
        try {
1010
            $statement = $this->_conn->query(...$args);
1011
        } catch (Throwable $ex) {
1012
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1013 1014
        }

1015
        $statement->setFetchMode($this->defaultFetchMode);
1016 1017 1018 1019 1020 1021

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

        return $statement;
1022 1023 1024 1025 1026
    }

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

1042 1043 1044
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
1045 1046
        }

1047 1048
        try {
            if ($params) {
1049
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1050

1051 1052 1053 1054 1055 1056 1057 1058
                $stmt = $this->_conn->prepare($query);
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
                $result = $stmt->rowCount();
1059
            } else {
1060
                $result = $this->_conn->exec($query);
1061
            }
1062
        } catch (Throwable $ex) {
1063
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
1064
        }
1065

1066 1067
        if ($logger) {
            $logger->stopQuery();
1068 1069
        }

romanb's avatar
romanb committed
1070
        return $result;
romanb's avatar
romanb committed
1071 1072
    }

1073
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1074
     * Executes an SQL statement and return the number of affected rows.
1075
     *
1076
     * @param string $statement
Benjamin Morel's avatar
Benjamin Morel committed
1077
     *
1078
     * @return int The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
1079
     *
1080
     * @throws DBALException
1081 1082 1083 1084
     */
    public function exec($statement)
    {
        $this->connect();
1085 1086 1087 1088 1089 1090

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

1091 1092
        try {
            $result = $this->_conn->exec($statement);
1093
        } catch (Throwable $ex) {
1094
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1095
        }
1096 1097 1098 1099 1100 1101

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

        return $result;
1102 1103
    }

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

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

romanb's avatar
romanb committed
1123 1124 1125 1126
        return $this->_conn->errorCode();
    }

    /**
1127
     * {@inheritDoc}
romanb's avatar
romanb committed
1128 1129 1130 1131
     */
    public function errorInfo()
    {
        $this->connect();
Benjamin Morel's avatar
Benjamin Morel committed
1132

romanb's avatar
romanb committed
1133 1134 1135 1136 1137 1138 1139 1140
        return $this->_conn->errorInfo();
    }

    /**
     * Returns the ID of the last inserted row, or the last value from a sequence object,
     * depending on the underlying driver.
     *
     * Note: This method may not return a meaningful or consistent result across different drivers,
1141 1142
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
romanb's avatar
romanb committed
1143
     *
Benjamin Morel's avatar
Benjamin Morel committed
1144 1145
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
     *
1146
     * @return string A string representation of the last inserted ID.
romanb's avatar
romanb committed
1147
     */
romanb's avatar
romanb committed
1148 1149 1150
    public function lastInsertId($seqName = null)
    {
        $this->connect();
Benjamin Morel's avatar
Benjamin Morel committed
1151

romanb's avatar
romanb committed
1152 1153
        return $this->_conn->lastInsertId($seqName);
    }
1154

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

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

1201
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1202
            throw ConnectionException::savepointsNotSupported();
1203 1204
        }

1205
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1206 1207 1208
    }

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

1218 1219 1220 1221
    /**
     * 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
1222
     * @return mixed A string with the savepoint name or false.
1223
     */
1224 1225
    protected function _getNestedTransactionSavePointName()
    {
1226
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1227 1228
    }

1229 1230 1231 1232 1233 1234 1235 1236 1237
    /**
     * Starts a transaction by suspending auto-commit mode.
     *
     * @return void
     */
    public function beginTransaction()
    {
        $this->connect();

1238
        ++$this->transactionNestingLevel;
1239

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

1242
        if ($this->transactionNestingLevel === 1) {
1243 1244 1245
            if ($logger) {
                $logger->startQuery('"START TRANSACTION"');
            }
1246
            $this->_conn->beginTransaction();
1247 1248 1249
            if ($logger) {
                $logger->stopQuery();
            }
1250
        } elseif ($this->nestTransactionsWithSavepoints) {
1251 1252 1253
            if ($logger) {
                $logger->startQuery('"SAVEPOINT"');
            }
1254
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1255 1256 1257
            if ($logger) {
                $logger->stopQuery();
            }
1258 1259 1260 1261 1262 1263 1264
        }
    }

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

        $this->connect();

1280 1281
        $logger = $this->_config->getSQLLogger();

1282
        if ($this->transactionNestingLevel === 1) {
1283 1284 1285
            if ($logger) {
                $logger->startQuery('"COMMIT"');
            }
1286
            $this->_conn->commit();
1287 1288 1289
            if ($logger) {
                $logger->stopQuery();
            }
1290
        } elseif ($this->nestTransactionsWithSavepoints) {
1291 1292 1293
            if ($logger) {
                $logger->startQuery('"RELEASE SAVEPOINT"');
            }
1294
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1295 1296 1297
            if ($logger) {
                $logger->stopQuery();
            }
1298 1299
        }

1300
        --$this->transactionNestingLevel;
1301

1302
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1303
            return;
1304
        }
1305 1306

        $this->beginTransaction();
1307 1308 1309 1310 1311
    }

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

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

        $this->connect();

1340 1341
        $logger = $this->_config->getSQLLogger();

1342
        if ($this->transactionNestingLevel === 1) {
1343 1344 1345
            if ($logger) {
                $logger->startQuery('"ROLLBACK"');
            }
1346
            $this->transactionNestingLevel = 0;
1347
            $this->_conn->rollBack();
1348
            $this->isRollbackOnly = false;
1349 1350 1351
            if ($logger) {
                $logger->stopQuery();
            }
1352

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

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

1386
        $this->_conn->exec($this->platform->createSavePoint($savepoint));
1387 1388 1389
    }

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

1404 1405
        if (! $this->platform->supportsReleaseSavepoints()) {
            return;
1406
        }
1407 1408

        $this->_conn->exec($this->platform->releaseSavePoint($savepoint));
1409 1410 1411
    }

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

1426
        $this->_conn->exec($this->platform->rollbackSavePoint($savepoint));
1427 1428
    }

romanb's avatar
romanb committed
1429 1430 1431
    /**
     * Gets the wrapped driver connection.
     *
1432
     * @return \Doctrine\DBAL\Driver\Connection
romanb's avatar
romanb committed
1433 1434 1435 1436
     */
    public function getWrappedConnection()
    {
        $this->connect();
1437

romanb's avatar
romanb committed
1438 1439
        return $this->_conn;
    }
1440

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

romanb's avatar
romanb committed
1453 1454
        return $this->_schemaManager;
    }
1455

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

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

1485
        return $this->isRollbackOnly;
1486 1487
    }

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

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

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

    /**
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
     *
1564 1565
     * @param mixed      $value The value to bind.
     * @param int|string $type  The type to bind (PDO or DBAL).
Benjamin Morel's avatar
Benjamin Morel committed
1566
     *
1567
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1568 1569 1570 1571 1572 1573 1574
     */
    private function getBindingInfo($value, $type)
    {
        if (is_string($type)) {
            $type = Type::getType($type);
        }
        if ($type instanceof Type) {
1575
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1576 1577
            $bindingType = $type->getBindingType();
        } else {
1578
            $bindingType = $type;
1579
        }
Benjamin Morel's avatar
Benjamin Morel committed
1580

1581
        return [$value, $bindingType];
1582 1583
    }

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

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

        return $resolvedParams;
    }

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

    /**
1642 1643 1644 1645 1646 1647
     * 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:
     *
1648 1649
     * @return bool
     *
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
     * @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.
1661 1662 1663
     */
    public function ping()
    {
1664
        $this->connect();
1665

1666 1667 1668 1669 1670
        if ($this->_conn instanceof PingableConnection) {
            return $this->_conn->ping();
        }

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

1673 1674
            return true;
        } catch (DBALException $e) {
1675
            return false;
1676
        }
1677
    }
1678
}