Failed Conditions
Push — master ( 01c22b...e42c1f )
by Marco
79:13 queued 10s
created

Connection::rollBack()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 32
ccs 14
cts 14
cp 1
rs 9.2568
c 0
b 0
f 0
cc 5
nc 7
nop 0
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL;
6
7
use Closure;
8
use Doctrine\Common\EventManager;
9
use Doctrine\DBAL\Cache\ArrayStatement;
10
use Doctrine\DBAL\Cache\CacheException;
11
use Doctrine\DBAL\Cache\Exception\NoResultDriverConfigured;
12
use Doctrine\DBAL\Cache\QueryCacheProfile;
13
use Doctrine\DBAL\Cache\ResultCacheStatement;
14
use Doctrine\DBAL\Driver\Connection as DriverConnection;
15
use Doctrine\DBAL\Driver\DriverException;
16
use Doctrine\DBAL\Driver\PingableConnection;
17
use Doctrine\DBAL\Driver\ResultStatement;
18
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
19
use Doctrine\DBAL\Driver\Statement as DriverStatement;
20
use Doctrine\DBAL\Exception\CommitFailedRollbackOnly;
21
use Doctrine\DBAL\Exception\EmptyCriteriaNotAllowed;
22
use Doctrine\DBAL\Exception\InvalidArgumentException;
23
use Doctrine\DBAL\Exception\InvalidPlatformType;
24
use Doctrine\DBAL\Exception\MayNotAlterNestedTransactionWithSavepointsInTransaction;
25
use Doctrine\DBAL\Exception\NoActiveTransaction;
26
use Doctrine\DBAL\Exception\SavepointsNotSupported;
27
use Doctrine\DBAL\Platforms\AbstractPlatform;
28
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
29
use Doctrine\DBAL\Query\QueryBuilder;
30
use Doctrine\DBAL\Schema\AbstractSchemaManager;
31
use Doctrine\DBAL\Types\Type;
32
use Exception;
33
use Throwable;
34
use function array_key_exists;
35
use function assert;
36
use function implode;
37
use function is_int;
38
use function is_string;
39
use function key;
40
41
/**
42
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
43
 * events, transaction isolation levels, configuration, emulated transaction nesting,
44
 * lazy connecting and more.
45
 */
46
class Connection implements DriverConnection
47
{
48
    /**
49
     * Represents an array of ints to be expanded by Doctrine SQL parsing.
50
     */
51
    public const PARAM_INT_ARRAY = ParameterType::INTEGER + self::ARRAY_PARAM_OFFSET;
52
53
    /**
54
     * Represents an array of strings to be expanded by Doctrine SQL parsing.
55
     */
56
    public const PARAM_STR_ARRAY = ParameterType::STRING + self::ARRAY_PARAM_OFFSET;
57
58
    /**
59
     * Offset by which PARAM_* constants are detected as arrays of the param type.
60
     */
61
    public const ARRAY_PARAM_OFFSET = 100;
62
63
    /**
64
     * The wrapped driver connection.
65
     *
66
     * @var \Doctrine\DBAL\Driver\Connection|null
67
     */
68
    protected $_conn;
69
70
    /** @var Configuration */
71
    protected $_config;
72
73
    /** @var EventManager */
74
    protected $_eventManager;
75
76
    /** @var ExpressionBuilder */
77
    protected $_expr;
78
79
    /**
80
     * Whether or not a connection has been established.
81
     *
82
     * @var bool
83
     */
84
    private $isConnected = false;
85
86
    /**
87
     * The current auto-commit mode of this connection.
88
     *
89
     * @var bool
90
     */
91
    private $autoCommit = true;
92
93
    /**
94
     * The transaction nesting level.
95
     *
96
     * @var int
97
     */
98
    private $transactionNestingLevel = 0;
99
100
    /**
101
     * The currently active transaction isolation level.
102
     *
103
     * @var int
104
     */
105
    private $transactionIsolationLevel;
106
107
    /**
108
     * If nested transactions should use savepoints.
109
     *
110
     * @var bool
111
     */
112
    private $nestTransactionsWithSavepoints = false;
113
114
    /**
115
     * The parameters used during creation of the Connection instance.
116
     *
117
     * @var array<string, mixed>
118
     */
119
    private $params = [];
120
121
    /**
122
     * The DatabasePlatform object that provides information about the
123
     * database platform used by the connection.
124
     *
125
     * @var AbstractPlatform
126
     */
127
    private $platform;
128
129
    /**
130
     * The schema manager.
131
     *
132
     * @var AbstractSchemaManager|null
133
     */
134
    protected $_schemaManager;
135
136
    /**
137
     * The used DBAL driver.
138
     *
139
     * @var Driver
140
     */
141
    protected $_driver;
142
143
    /**
144
     * Flag that indicates whether the current transaction is marked for rollback only.
145
     *
146
     * @var bool
147
     */
148
    private $isRollbackOnly = false;
149
150
    /** @var int */
151
    protected $defaultFetchMode = FetchMode::ASSOCIATIVE;
152
153
    /**
154
     * Initializes a new instance of the Connection class.
155
     *
156
     * @param array<string, mixed> $params       The connection parameters.
157
     * @param Driver               $driver       The driver to use.
158
     * @param Configuration|null   $config       The configuration, optional.
159
     * @param EventManager|null    $eventManager The event manager, optional.
160
     *
161
     * @throws DBALException
162
     */
163
    public function __construct(
164
        array $params,
165
        Driver $driver,
166
        ?Configuration $config = null,
167
        ?EventManager $eventManager = null
168
    ) {
169
        $this->_driver = $driver;
170
        $this->params  = $params;
171
172
        if (isset($params['platform'])) {
173
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
174
                throw InvalidPlatformType::new($params['platform']);
175
            }
176
177
            $this->platform = $params['platform'];
178
        }
179
180
        // Create default config and event manager if none given
181
        if (! $config) {
182 9351
            $config = new Configuration();
183
        }
184
185
        if (! $eventManager) {
186
            $eventManager = new EventManager();
187
        }
188 9351
189 9351
        $this->_config       = $config;
190
        $this->_eventManager = $eventManager;
191 9351
192 8358
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
193 8358
194 8358
        $this->autoCommit = $config->getAutoCommit();
195
    }
196
197 9351
    /**
198 8539
     * Gets the parameters used during instantiation.
199 8084
     *
200
     * @return array<string, mixed>
201
     */
202 8537
    public function getParams() : array
203
    {
204
        return $this->params;
205
    }
206 9351
207 8948
    /**
208
     * Gets the name of the currently selected database.
209
     *
210 9351
     * @return string|null The name of the database or NULL if a database is not selected.
211 8696
     *                     The platforms which don't support the concept of a database (e.g. embedded databases)
212
     *                     must always return a string as an indicator of an implicitly selected database.
213
     *
214 9351
     * @throws DBALException
215 9351
     */
216
    public function getDatabase() : ?string
217 9351
    {
218
        $platform = $this->getDatabasePlatform();
219 9351
        $query    = $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
220 9351
        $database = $this->query($query)->fetchColumn();
221
222
        assert(is_string($database) || $database === null);
223
224
        return $database;
225
    }
226
227 8576
    /**
228
     * Gets the DBAL driver instance.
229 8576
     */
230
    public function getDriver() : Driver
231
    {
232
        return $this->_driver;
233
    }
234
235
    /**
236
     * Gets the Configuration used by the Connection.
237 7993
     */
238
    public function getConfiguration() : Configuration
239 7993
    {
240
        return $this->_config;
241
    }
242
243
    /**
244
     * Gets the EventManager used by the Connection.
245
     */
246
    public function getEventManager() : EventManager
247
    {
248
        return $this->_eventManager;
249 8959
    }
250
251 8959
    /**
252
     * Gets the DatabasePlatform for the connection.
253
     *
254
     * @throws DBALException
255
     */
256
    public function getDatabasePlatform() : AbstractPlatform
257
    {
258
        if ($this->platform === null) {
259
            $this->detectDatabasePlatform();
260
        }
261 2
262
        return $this->platform;
263 2
    }
264
265
    /**
266
     * Gets the ExpressionBuilder for the connection.
267
     */
268
    public function getExpressionBuilder() : ExpressionBuilder
269
    {
270
        return $this->_expr;
271
    }
272
273 655
    /**
274
     * Establishes the connection with the database.
275 655
     *
276
     * @throws DriverException
277
     */
278
    public function connect() : void
279
    {
280
        if ($this->isConnected) {
281
            return;
282
        }
283
284
        $driverOptions = $this->params['driverOptions'] ?? [];
285 2
        $user          = $this->params['user'] ?? '';
286
        $password      = $this->params['password'] ?? '';
287 2
288
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
289
        $this->isConnected = true;
290
291
        $this->transactionNestingLevel = 0;
292
293
        if ($this->autoCommit === false) {
294
            $this->beginTransaction();
295 9047
        }
296
297 9047
        if (! $this->_eventManager->hasListeners(Events::postConnect)) {
298
            return;
299
        }
300
301
        $eventArgs = new Event\ConnectionEventArgs($this);
302
        $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
303
    }
304
305 9597
    /**
306
     * Detects and sets the database platform.
307 9597
     *
308
     * Evaluates custom platform class and version in order to set the correct platform.
309
     *
310
     * @throws DBALException If an invalid platform was specified for this connection.
311
     */
312
    private function detectDatabasePlatform() : void
313
    {
314
        $version = $this->getDatabasePlatformVersion();
315 6960
316
        if ($version !== null) {
317 6960
            assert($this->_driver instanceof VersionAwarePlatformDriver);
318
319
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
320
        } else {
321
            $this->platform = $this->_driver->getDatabasePlatform();
322
        }
323
324
        $this->platform->setEventManager($this->_eventManager);
325
    }
326
327 9331
    /**
328
     * Returns the version of the related platform if applicable.
329 9331
     *
330 8944
     * Returns null if either the driver is not capable to create version
331
     * specific platform instances, no explicit server version was specified
332
     * or the underlying driver connection cannot determine the platform
333 9329
     * version without having to query it (performance reasons).
334
     *
335
     * @throws Exception
336
     */
337
    private function getDatabasePlatformVersion() : ?string
338
    {
339
        // Driver does not support version specific platforms.
340
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
341
            return null;
342
        }
343
344
        // Explicit platform version requested (supersedes auto-detection).
345
        if (isset($this->params['serverVersion'])) {
346
            return $this->params['serverVersion'];
347
        }
348
349
        // If not connected, we need to connect now to determine the platform version.
350
        if ($this->_conn === null) {
351
            try {
352 9540
                $this->connect();
353
            } catch (Throwable $originalException) {
354 9540
                if (empty($this->params['dbname'])) {
355 9243
                    throw $originalException;
356
                }
357
358 9005
                // The database to connect to might not yet exist.
359 9005
                // Retry detection without database name connection parameter.
360 9005
                $databaseName           = $this->params['dbname'];
361
                $this->params['dbname'] = null;
362 9005
363 8997
                try {
364
                    $this->connect();
365 8997
                } catch (Throwable $fallbackException) {
366
                    // Either the platform does not support database-less connections
367 8997
                    // or something else went wrong.
368 8638
                    // Reset connection parameters and rethrow the original exception.
369
                    $this->params['dbname'] = $databaseName;
370
371 8997
                    throw $originalException;
372 8961
                }
373 8961
374
                // Reset connection parameters.
375
                $this->params['dbname'] = $databaseName;
376 8997
                $serverVersion          = $this->getServerVersion();
377
378
                // Close "temporary" connection to allow connecting to the real database again.
379
                $this->close();
380
381
                return $serverVersion;
382
            }
383
        }
384
385
        return $this->getServerVersion();
386 8944
    }
387
388 8944
    /**
389
     * Returns the database server version if the underlying driver supports it.
390 8942
     */
391 8159
    private function getServerVersion() : ?string
392
    {
393 8159
        $connection = $this->getWrappedConnection();
394
395 8940
        // Automatic platform version detection.
396
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
397
            return $connection->getServerVersion();
398 8942
        }
399 8942
400
        // Unable to detect platform version.
401
        return null;
402
    }
403
404
    /**
405
     * Returns the current auto-commit mode for this connection.
406
     *
407
     * @see    setAutoCommit
408
     *
409
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
410
     */
411
    public function isAutoCommit() : bool
412
    {
413 8944
        return $this->autoCommit;
414
    }
415
416 8944
    /**
417 8940
     * Sets auto-commit mode for this connection.
418
     *
419
     * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
420
     * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
421 8161
     * the method commit or the method rollback. By default, new connections are in auto-commit mode.
422
     *
423
     * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
424
     * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
425
     *
426 8161
     * @see isAutoCommit
427
     *
428 8161
     * @throws ConnectionException
429 8059
     * @throws DriverException
430 8059
     */
431
    public function setAutoCommit(bool $autoCommit) : void
432
    {
433
        // Mode not changed, no-op.
434
        if ($autoCommit === $this->autoCommit) {
435
            return;
436 8059
        }
437 8059
438
        $this->autoCommit = $autoCommit;
439
440 8059
        // Commit all currently active transactions if any when switching auto-commit mode.
441 8059
        if (! $this->isConnected || $this->transactionNestingLevel === 0) {
442
            return;
443
        }
444
445 8059
        $this->commitAll();
446
    }
447 8059
448
    /**
449
     * Sets the fetch mode.
450
     */
451 6487
    public function setFetchMode(int $fetchMode) : void
452 6487
    {
453
        $this->defaultFetchMode = $fetchMode;
454
    }
455 6487
456
    /**
457 6487
     * Prepares and executes an SQL query and returns the first row of the result
458
     * as an associative array.
459
     *
460
     * @param string                                           $query  The SQL query.
461 8159
     * @param array<int, mixed>|array<string, mixed>           $params The prepared statement params.
462
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
463
     *
464
     * @return array<string, mixed>|false False is returned if no rows are found.
465
     *
466
     * @throws DBALException
467
     */
468
    public function fetchAssoc(string $query, array $params = [], array $types = [])
469 8159
    {
470
        return $this->executeQuery($query, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
471 8159
    }
472
473
    /**
474 8159
     * Prepares and executes an SQL query and returns the first row of the result
475 8159
     * as a numerically indexed array.
476
     *
477
     * @param string                                           $query  The SQL query to be executed.
478
     * @param array<int, mixed>|array<string, mixed>           $params The prepared statement params.
479
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
480
     *
481
     * @return array<int, mixed>|false False is returned if no rows are found.
482
     *
483
     * @throws DBALException
484
     */
485
    public function fetchArray(string $query, array $params = [], array $types = [])
486
    {
487
        return $this->executeQuery($query, $params, $types)->fetch(FetchMode::NUMERIC);
488
    }
489 8686
490
    /**
491 8686
     * Prepares and executes an SQL query and returns the value of a single column
492
     * of the first row of the result.
493
     *
494
     * @param string                                           $query  The SQL query to be executed.
495
     * @param array<int, mixed>|array<string, mixed>           $params The prepared statement params.
496
     * @param int                                              $column The 0-indexed column number to retrieve.
497
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
498
     *
499
     * @return mixed|false False is returned if no rows are found.
500
     *
501
     * @throws DBALException
502
     */
503
    public function fetchColumn(string $query, array $params = [], int $column = 0, array $types = [])
504
    {
505
        return $this->executeQuery($query, $params, $types)->fetchColumn($column);
506
    }
507
508 8667
    /**
509
     * Whether an actual connection to the database is established.
510 8667
     */
511
    public function isConnected() : bool
512
    {
513 8667
        return $this->isConnected;
514 8659
    }
515
516
    /**
517 8667
     * Checks whether a transaction is currently active.
518
     *
519
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
520 8667
     */
521 8665
    public function isTransactionActive() : bool
522
    {
523
        return $this->transactionNestingLevel > 0;
524 8534
    }
525 8534
526
    /**
527
     * Adds identifier condition to the query components
528
     *
529
     * @param array<string, mixed> $identifier Map of key columns to their values
530
     * @param array<int, string>   $columns    Column names
531
     * @param array<int, mixed>    $values     Column values
532
     * @param array<int, string>   $conditions Key conditions
533
     *
534 4319
     * @throws DBALException
535
     */
536 4319
    private function addIdentifierCondition(
537 4319
        array $identifier,
538
        array &$columns,
539
        array &$values,
540
        array &$conditions
541
    ) : void {
542
        $platform = $this->getDatabasePlatform();
543
544
        foreach ($identifier as $columnName => $value) {
545
            if ($value === null) {
546
                $conditions[] = $platform->getIsNullExpression($columnName);
547
                continue;
548
            }
549
550
            $columns[]    = $columnName;
551 8573
            $values[]     = $value;
552
            $conditions[] = $columnName . ' = ?';
553 8573
        }
554
    }
555
556
    /**
557
     * Executes an SQL DELETE statement on a table.
558
     *
559
     * Table expression and columns are not escaped and are not safe for user-input.
560
     *
561
     * @param string                                           $table      The SQL expression of the table on which to delete.
562
     * @param array<string, mixed>                             $identifier The deletion criteria. An associative array containing column-value pairs.
563
     * @param array<int, int|string>|array<string, int|string> $types      The query parameter types.
564
     *
565
     * @return int The number of affected rows.
566 6547
     *
567
     * @throws DBALException
568 6547
     * @throws InvalidArgumentException
569
     */
570
    public function delete(string $table, array $identifier, array $types = []) : int
571
    {
572
        if (empty($identifier)) {
573
            throw EmptyCriteriaNotAllowed::new();
574
        }
575
576
        $columns = $values = $conditions = [];
577
578
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
579
580
        return $this->executeUpdate(
581
            'DELETE FROM ' . $table . ' WHERE ' . implode(' AND ', $conditions),
582
            $values,
583
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
584 8480
        );
585
    }
586 8480
587
    /**
588
     * Closes the connection.
589
     */
590
    public function close() : void
591
    {
592
        $this->_conn = null;
593
594 9088
        $this->isConnected = false;
595
    }
596 9088
597
    /**
598
     * Sets the transaction isolation level.
599
     *
600
     * @param int $level The level to set.
601
     */
602
    public function setTransactionIsolation(int $level) : void
603
    {
604 9670
        $this->transactionIsolationLevel = $level;
605
606 9670
        $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
607
    }
608
609
    /**
610
     * Gets the currently active transaction isolation level.
611
     *
612
     * @return int The current transaction isolation level.
613
     */
614
    public function getTransactionIsolation() : int
615
    {
616
        if ($this->transactionIsolationLevel === null) {
617
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
618
        }
619 8511
620
        return $this->transactionIsolationLevel;
621
    }
622
623
    /**
624
     * Executes an SQL UPDATE statement on a table.
625 8511
     *
626
     * Table expression and columns are not escaped and are not safe for user-input.
627 8511
     *
628 8511
     * @param string                                           $table      The SQL expression of the table to update quoted or unquoted.
629 8465
     * @param array<string, mixed>                             $data       An associative array containing column-value pairs.
630 8465
     * @param array<string, mixed>                             $identifier The update criteria. An associative array containing column-value pairs.
631
     * @param array<int, int|string>|array<string, int|string> $types      The query parameter types.
632
     *
633 8507
     * @return int The number of affected rows.
634 8507
     *
635 8507
     * @throws DBALException
636
     */
637 8511
    public function update(string $table, array $data, array $identifier, array $types = []) : int
638
    {
639
        $columns = $values = $conditions = $set = [];
640
641
        foreach ($data as $columnName => $value) {
642
            $columns[] = $columnName;
643
            $values[]  = $value;
644
            $set[]     = $columnName . ' = ?';
645
        }
646
647
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
648
649
        if (is_string(key($types))) {
650
            $types = $this->extractTypeValues($columns, $types);
651
        }
652
653 8446
        $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set)
654
                . ' WHERE ' . implode(' AND ', $conditions);
655 8446
656 8309
        return $this->executeUpdate($sql, $values, $types);
657
    }
658
659 8444
    /**
660
     * Inserts a table row with specified data.
661 8444
     *
662
     * Table expression and columns are not escaped and are not safe for user-input.
663 8444
     *
664 8444
     * @param string                                           $table The SQL expression of the table to insert data into, quoted or unquoted.
665 12
     * @param array<string, mixed>                             $data  An associative array containing column-value pairs.
666 8444
     * @param array<int, int|string>|array<string, int|string> $types The query parameter types.
667
     *
668
     * @return int The number of affected rows.
669
     *
670
     * @throws DBALException
671
     */
672
    public function insert(string $table, array $data, array $types = []) : int
673
    {
674
        if (empty($data)) {
675 7997
            return $this->executeUpdate('INSERT INTO ' . $table . ' () VALUES ()');
676
        }
677 7997
678
        $columns = [];
679 7997
        $values  = [];
680 7997
        $set     = [];
681
682
        foreach ($data as $columnName => $value) {
683
            $columns[] = $columnName;
684
            $values[]  = $value;
685
            $set[]     = '?';
686
        }
687
688
        return $this->executeUpdate(
689
            'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' .
690
            ' VALUES (' . implode(', ', $set) . ')',
691
            $values,
692
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
693
        );
694
    }
695
696
    /**
697
     * Extract ordered type list from an ordered column list and type map.
698
     *
699
     * @param array<int, string>     $columnList
700
     * @param array<int, int|string> $types      The query parameter types.
701
     *
702
     * @return array<int, int>|array<int, string>
703
     */
704
    private function extractTypeValues(array $columnList, array $types)
705
    {
706
        $typeValues = [];
707
708
        foreach ($columnList as $columnName) {
709
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
710
        }
711
712
        return $typeValues;
713
    }
714
715
    /**
716
     * Quotes a string so it can be safely used as a table or column name, even if
717
     * it is a reserved name.
718
     *
719
     * Delimiting style depends on the underlying database platform that is being used.
720
     *
721
     * NOTE: Just because you CAN use quoted identifiers does not mean
722
     * you SHOULD use them. In general, they end up causing way more
723
     * problems than they solve.
724 8499
     *
725
     * @param string $identifier The identifier to be quoted.
726 8499
     *
727
     * @return string The quoted identifier.
728 8499
     */
729 8499
    public function quoteIdentifier(string $identifier) : string
730 8499
    {
731 8499
        return $this->getDatabasePlatform()->quoteIdentifier($identifier);
732
    }
733
734 8499
    /**
735
     * {@inheritDoc}
736 8499
     */
737 8492
    public function quote(string $input) : string
738
    {
739
        return $this->getWrappedConnection()->quote($input);
740 8499
    }
741 8499
742
    /**
743 8499
     * Prepares and executes an SQL query and returns the result as an associative array.
744
     *
745
     * @param string                                           $query  The SQL query.
746
     * @param array<int, mixed>|array<string, mixed>           $params The query parameters.
747
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
748
     *
749
     * @return array<int, mixed>
750
     */
751
    public function fetchAll(string $query, array $params = [], array $types = []) : array
752
    {
753
        return $this->executeQuery($query, $params, $types)->fetchAll();
754
    }
755
756
    /**
757
     * Prepares an SQL statement.
758
     *
759 8664
     * @param string $sql The SQL statement to prepare.
760
     *
761 8664
     * @throws DBALException
762 8509
     */
763
    public function prepare(string $sql) : DriverStatement
764
    {
765 8412
        try {
766 8412
            $stmt = new Statement($sql, $this);
767 8412
        } catch (Throwable $ex) {
768
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
769 8412
        }
770 8412
771 8412
        $stmt->setFetchMode($this->defaultFetchMode);
772 8412
773
        return $stmt;
774
    }
775 8412
776 8412
    /**
777 8412
     * Executes an, optionally parametrized, SQL query.
778 155
     *
779 8412
     * If the query is parametrized, a prepared statement is used.
780
     * If an SQLLogger is configured, the execution is logged.
781
     *
782
     * @param string                                           $query  The SQL query to execute.
783
     * @param array<int, mixed>|array<string, mixed>           $params The parameters to bind to the query, if any.
784
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
785
     * @param QueryCacheProfile|null                           $qcp    The query cache profile, optional.
786
     *
787
     * @return ResultStatement The executed statement.
788
     *
789
     * @throws DBALException
790
     */
791 8500
    public function executeQuery(string $query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) : ResultStatement
792
    {
793 8500
        if ($qcp !== null) {
794
            return $this->executeCacheQuery($query, $params, $types, $qcp);
795 8500
        }
796 8500
797
        $connection = $this->getWrappedConnection();
798
799 8500
        $logger = $this->_config->getSQLLogger();
800
        $logger->startQuery($query, $params, $types);
801
802
        try {
803
            if ($params) {
804
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
805
806
                $stmt = $connection->prepare($query);
807
                if ($types) {
808
                    $this->_bindTypedValues($stmt, $params, $types);
809
                    $stmt->execute();
810
                } else {
811
                    $stmt->execute($params);
812
                }
813
            } else {
814
                $stmt = $connection->query($query);
815
            }
816 6775
        } catch (Throwable $ex) {
817
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
818 6775
        }
819
820
        $stmt->setFetchMode($this->defaultFetchMode);
821
822
        $logger->stopQuery();
823
824 7079
        return $stmt;
825
    }
826 7079
827
    /**
828 7079
     * Executes a caching query.
829
     *
830 7079
     * @param string                                           $query  The SQL query to execute.
831
     * @param array<int, mixed>|array<string, mixed>           $params The parameters to bind to the query, if any.
832
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
833
     * @param QueryCacheProfile                                $qcp    The query cache profile.
834
     *
835
     * @throws CacheException
836
     */
837
    public function executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp) : ResultStatement
838
    {
839
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
840
841
        if ($resultCache === null) {
842 8566
            throw NoResultDriverConfigured::new();
843
        }
844 8566
845
        $connectionParams = $this->getParams();
846
        unset($connectionParams['platform']);
847
848
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
849
850
        // fetch the row pointers entry
851
        $data = $resultCache->fetch($cacheKey);
852
853
        if ($data !== false) {
854
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
855
            if (isset($data[$realKey])) {
856 8836
                $stmt = new ArrayStatement($data[$realKey]);
857
            } elseif (array_key_exists($realKey, $data)) {
858
                $stmt = new ArrayStatement([]);
859 8836
            }
860 8759
        }
861 8759
862
        if (! isset($stmt)) {
863
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
864 8284
        }
865
866 8284
        $stmt->setFetchMode($this->defaultFetchMode);
867
868
        return $stmt;
869
    }
870
871
    /**
872
     * Executes an, optionally parametrized, SQL query and returns the result,
873
     * applying a given projection/transformation function on each row of the result.
874
     *
875
     * @param string                                 $query    The SQL query to execute.
876
     * @param array<int, mixed>|array<string, mixed> $params   The parameters, if any.
877
     * @param Closure                                $function The transformation function that is applied on each row.
878
     *                                                          The function receives a single parameter, an array, that
879
     *                                                          represents a row of the result set.
880
     *
881
     * @return array<int, mixed> The projected result of the query.
882
     */
883
    public function project(string $query, array $params, Closure $function) : array
884 9262
    {
885
        $result = [];
886 9262
        $stmt   = $this->executeQuery($query, $params);
887 4248
888
        while ($row = $stmt->fetch()) {
889
            $result[] = $function($row);
890 9262
        }
891
892 9262
        $stmt->closeCursor();
893 9262
894 7674
        return $result;
895
    }
896
897
    /**
898 9262
     * {@inheritDoc}
899 6799
     */
900
    public function query(string $sql) : ResultStatement
901 6799
    {
902 6799
        $connection = $this->getWrappedConnection();
903 6729
904 6729
        $logger = $this->_config->getSQLLogger();
905
        $logger->startQuery($sql);
906 6799
907
        try {
908
            $statement = $connection->query($sql);
909 9254
        } catch (Throwable $ex) {
910
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
911 8823
        }
912 8823
913
        $statement->setFetchMode($this->defaultFetchMode);
914
915 7698
        $logger->stopQuery();
916
917 7698
        return $statement;
918 7660
    }
919
920
    /**
921 7698
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
922
     * and returns the number of affected rows.
923
     *
924
     * This method supports PDO binding types as well as DBAL mapping types.
925
     *
926
     * @param string                                           $query  The SQL query.
927
     * @param array<int, mixed>|array<string, mixed>           $params The query parameters.
928
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
929
     *
930
     * @throws DBALException
931
     */
932
    public function executeUpdate(string $query, array $params = [], array $types = []) : int
933
    {
934
        $connection = $this->getWrappedConnection();
935
936 8162
        $logger = $this->_config->getSQLLogger();
937
        $logger->startQuery($query, $params, $types);
938 8162
939
        try {
940 8162
            if ($params) {
941
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
942
943
                $stmt = $connection->prepare($query);
944 8162
945 8162
                if ($types) {
946
                    $this->_bindTypedValues($stmt, $params, $types);
947 8162
                    $stmt->execute();
948
                } else {
949
                    $stmt->execute($params);
950 8162
                }
951
                $result = $stmt->rowCount();
952 8162
            } else {
953
                $result = $connection->exec($query);
954 8154
            }
955 8154
        } catch (Throwable $ex) {
956
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
957
        }
958
959
        $logger->stopQuery();
960
961 8162
        return $result;
962 4250
    }
963
964
    /**
965 8162
     * {@inheritDoc}
966
     */
967 8162
    public function exec(string $statement) : int
968
    {
969
        $connection = $this->getWrappedConnection();
970
971
        $logger = $this->_config->getSQLLogger();
972
        $logger->startQuery($statement);
973
974
        try {
975
            $result = $connection->exec($statement);
976
        } catch (Throwable $ex) {
977
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
978
        }
979
980
        $logger->stopQuery();
981
982
        return $result;
983
    }
984
985
    /**
986
     * Returns the current transaction nesting level.
987
     *
988
     * @return int The nesting level. A value of 0 means there's no active transaction.
989
     */
990
    public function getTransactionNestingLevel() : int
991
    {
992
        return $this->transactionNestingLevel;
993
    }
994
995
    /**
996
     * Returns the ID of the last inserted row, or the last value from a sequence object,
997
     * depending on the underlying driver.
998
     *
999
     * Note: This method may not return a meaningful or consistent result across different drivers,
1000
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
1001
     * columns or sequences.
1002
     *
1003 8866
     * @param string|null $name Name of the sequence object from which the ID should be returned.
1004
     *
1005 8866
     * @return string A string representation of the last inserted ID.
1006
     */
1007 8866
    public function lastInsertId(?string $name = null) : string
1008
    {
1009 8866
        return $this->getWrappedConnection()->lastInsertId($name);
1010 8866
    }
1011 7459
1012
    /**
1013
     * Executes a function in a transaction.
1014
     *
1015 8866
     * The function gets passed this Connection instance as an (optional) parameter.
1016 8834
     *
1017 8834
     * If an exception occurs during execution of the function or transaction commit,
1018
     * the transaction is rolled back and the exception re-thrown.
1019
     *
1020 7461
     * @param Closure $func The function to execute transactionally.
1021
     *
1022 7461
     * @return mixed The value returned by $func
1023 7459
     *
1024
     * @throws Throwable
1025
     */
1026 7461
    public function transactional(Closure $func)
1027
    {
1028
        $this->beginTransaction();
1029
        try {
1030
            $res = $func($this);
1031
            $this->commit();
1032
1033
            return $res;
1034
        } catch (Throwable $e) {
1035
            $this->rollBack();
1036
            throw $e;
1037
        }
1038
    }
1039
1040
    /**
1041
     * Sets if nested transactions should use savepoints.
1042
     *
1043 9146
     * @throws ConnectionException
1044
     */
1045 9146
    public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void
1046
    {
1047 9146
        if ($this->transactionNestingLevel > 0) {
1048 9146
            throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new();
1049 7808
        }
1050
1051
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1052
            throw SavepointsNotSupported::new();
1053 9146
        }
1054 8451
1055
        $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
1056 8451
    }
1057
1058 8451
    /**
1059 7475
     * Gets if nested transactions should use savepoints.
1060 7475
     */
1061
    public function getNestTransactionsWithSavepoints() : bool
1062 8430
    {
1063
        return $this->nestTransactionsWithSavepoints;
1064 8447
    }
1065
1066 9142
    /**
1067
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1068 9060
     * "savepointFormat" parameter is not set
1069 9060
     *
1070
     * @return mixed A string with the savepoint name or false.
1071
     */
1072 8628
    protected function _getNestedTransactionSavePointName()
1073 7790
    {
1074
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1075
    }
1076 8628
1077
    /**
1078
     * {@inheritDoc}
1079
     */
1080
    public function beginTransaction() : void
1081
    {
1082
        $connection = $this->getWrappedConnection();
1083
1084
        ++$this->transactionNestingLevel;
1085
1086
        $logger = $this->_config->getSQLLogger();
1087
1088 9021
        if ($this->transactionNestingLevel === 1) {
1089
            $logger->startQuery('"START TRANSACTION"');
1090 9021
1091
            try {
1092 9015
                $connection->beginTransaction();
1093 9015
            } finally {
1094 5985
                $logger->stopQuery();
1095
            }
1096
        } elseif ($this->nestTransactionsWithSavepoints) {
1097
            $logger->startQuery('"SAVEPOINT"');
1098 9015
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1099 8969
            $logger->stopQuery();
1100 8969
        }
1101
    }
1102
1103 5881
    /**
1104 5875
     * {@inheritDoc}
1105
     *
1106
     * @throws ConnectionException If the commit failed due to no active transaction or
1107 5881
     *                                            because the transaction was marked for rollback only.
1108
     */
1109
    public function commit() : void
1110
    {
1111
        if ($this->transactionNestingLevel === 0) {
1112
            throw NoActiveTransaction::new();
1113
        }
1114
        if ($this->isRollbackOnly) {
1115 8562
            throw CommitFailedRollbackOnly::new();
1116
        }
1117 8562
1118
        $result = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1119
1120
        $connection = $this->getWrappedConnection();
1121
1122
        $logger = $this->_config->getSQLLogger();
1123
1124
        if ($this->transactionNestingLevel === 1) {
1125
            $logger->startQuery('"COMMIT"');
1126
1127
            try {
1128
                $connection->commit();
1129
            } finally {
1130
                $logger->stopQuery();
1131
            }
1132
        } elseif ($this->nestTransactionsWithSavepoints) {
1133
            $logger->startQuery('"RELEASE SAVEPOINT"');
1134
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1135
            $logger->stopQuery();
1136
        }
1137
1138
        --$this->transactionNestingLevel;
1139
1140
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1141
            return;
1142
        }
1143
1144
        $this->beginTransaction();
1145
    }
1146
1147
    /**
1148
     * Commits all current nesting transactions.
1149
     *
1150 809
     * @throws ConnectionException
1151
     * @throws DriverException
1152 809
     */
1153
    private function commitAll() : void
1154
    {
1155
        while ($this->transactionNestingLevel !== 0) {
1156
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1157
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1158
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1159
                $this->commit();
1160
1161
                return;
1162
            }
1163
1164
            $this->commit();
1165
        }
1166
    }
1167
1168
    /**
1169
     * {@inheritDoc}
1170 7112
     *
1171
     * @throws ConnectionException If the rollback operation failed.
1172 7112
     */
1173
    public function rollBack() : void
1174 7112
    {
1175 7058
        if ($this->transactionNestingLevel === 0) {
1176
            throw NoActiveTransaction::new();
1177 7058
        }
1178 7108
1179 7106
        $connection = $this->getWrappedConnection();
1180 7106
1181 7081
        $logger = $this->_config->getSQLLogger();
1182 7081
1183 7081
        if ($this->transactionNestingLevel === 1) {
1184
            $logger->startQuery('"ROLLBACK"');
1185
            $this->transactionNestingLevel = 0;
1186
1187
            try {
1188
                $connection->rollBack();
1189
            } finally {
1190
                $this->isRollbackOnly = false;
1191
                $logger->stopQuery();
1192
1193
                if ($this->autoCommit === false) {
1194
                    $this->beginTransaction();
1195
                }
1196 7208
            }
1197
        } elseif ($this->nestTransactionsWithSavepoints) {
1198 7208
            $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1199 6972
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1200
            --$this->transactionNestingLevel;
1201
            $logger->stopQuery();
1202 7206
        } else {
1203 236
            $this->isRollbackOnly = true;
1204
            --$this->transactionNestingLevel;
1205
        }
1206 6970
    }
1207 6970
1208
    /**
1209
     * Creates a new savepoint.
1210
     *
1211
     * @param string $savepoint The name of the savepoint to create.
1212
     *
1213
     * @throws ConnectionException
1214 6970
     */
1215
    public function createSavepoint(string $savepoint) : void
1216 6970
    {
1217
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1218
            throw SavepointsNotSupported::new();
1219
        }
1220
1221
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1222
    }
1223
1224
    /**
1225 6970
     * Releases the given savepoint.
1226
     *
1227 6970
     * @param string $savepoint The name of the savepoint to release.
1228
     *
1229
     * @throws ConnectionException
1230
     */
1231
    public function releaseSavepoint(string $savepoint) : void
1232
    {
1233 8678
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1234
            throw SavepointsNotSupported::new();
1235 8678
        }
1236
1237 8678
        if (! $this->platform->supportsReleaseSavepoints()) {
1238
            return;
1239 8678
        }
1240
1241 8678
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1242 8678
    }
1243 7311
1244
    /**
1245
     * Rolls back to the given savepoint.
1246 8678
     *
1247
     * @param string $savepoint The name of the savepoint to rollback to.
1248 8678
     *
1249 8678
     * @throws ConnectionException
1250
     */
1251 8540
    public function rollbackSavepoint(string $savepoint) : void
1252 6970
    {
1253 6970
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1254
            throw SavepointsNotSupported::new();
1255 6970
        }
1256 6970
1257 6970
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1258
    }
1259
1260
    /**
1261 8678
     * Gets the wrapped driver connection.
1262
     */
1263
    public function getWrappedConnection() : DriverConnection
1264
    {
1265
        $this->connect();
1266
1267
        return $this->_conn;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_conn could return the type null which is incompatible with the type-hinted return Doctrine\DBAL\Driver\Connection. Consider adding an additional type-check to rule them out.
Loading history...
1268
    }
1269
1270 9060
    /**
1271
     * Gets the SchemaManager that can be used to inspect or change the
1272 9060
     * database schema through the connection.
1273 9034
     */
1274
    public function getSchemaManager() : AbstractSchemaManager
1275 8633
    {
1276 7283
        if ($this->_schemaManager === null) {
1277
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1278
        }
1279 8629
1280
        return $this->_schemaManager;
1281 8629
    }
1282
1283 8629
    /**
1284
     * Marks the current transaction so that the only possible
1285 8629
     * outcome for the transaction to be rolled back.
1286 8629
     *
1287 7215
     * @throws ConnectionException If no transaction is active.
1288
     */
1289
    public function setRollbackOnly() : void
1290 8629
    {
1291
        if ($this->transactionNestingLevel === 0) {
1292 8629
            throw NoActiveTransaction::new();
1293 8629
        }
1294
        $this->isRollbackOnly = true;
1295 8536
    }
1296 6970
1297 6970
    /**
1298
     * Checks whether the current transaction is marked for rollback only.
1299 6970
     *
1300 6970
     * @throws ConnectionException If no transaction is active.
1301 6970
     */
1302
    public function isRollbackOnly() : bool
1303
    {
1304
        if ($this->transactionNestingLevel === 0) {
1305 8629
            throw NoActiveTransaction::new();
1306
        }
1307 8629
1308 8602
        return $this->isRollbackOnly;
1309
    }
1310
1311 8611
    /**
1312
     * Converts a given value to its database representation according to the conversion
1313 8611
     * rules of a specific DBAL mapping type.
1314
     *
1315
     * @param mixed  $value The value to convert.
1316
     * @param string $type  The name of the DBAL mapping type.
1317
     *
1318
     * @return mixed The converted value.
1319 8534
     */
1320
    public function convertToDatabaseValue($value, string $type)
1321 8534
    {
1322 8534
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1323
    }
1324
1325 8534
    /**
1326
     * Converts a given value to its PHP representation according to the conversion
1327 8534
     * rules of a specific DBAL mapping type.
1328
     *
1329
     * @param mixed  $value The value to convert.
1330 8534
     * @param string $type  The name of the DBAL mapping type.
1331
     *
1332 8534
     * @return mixed The converted type.
1333
     */
1334
    public function convertToPHPValue($value, string $type)
1335
    {
1336
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1337
    }
1338
1339 9033
    /**
1340
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1341 9033
     * or DBAL mapping type, to a given statement.
1342 9009
     *
1343
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1344
     *           raw PDOStatement instances.
1345 8581
     *
1346
     * @param DriverStatement                                  $stmt   The statement to bind the values to.
1347 8581
     * @param array<int, mixed>|array<string, mixed>           $params The map/list of named/positional parameters.
1348
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1349 8581
     */
1350 8579
    private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
1351 7299
    {
1352
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1353 8579
        if (is_int(key($params))) {
1354 8579
            // Positional parameters
1355 8579
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1356 8579
            $bindIndex  = 1;
1357 7299
            foreach ($params as $value) {
1358
                $typeIndex = $bindIndex + $typeOffset;
1359
                if (isset($types[$typeIndex])) {
1360 8579
                    $type                  = $types[$typeIndex];
1361 8579
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1362
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1363 7258
                } else {
1364 6970
                    $stmt->bindValue($bindIndex, $value);
1365 6970
                }
1366
                ++$bindIndex;
1367 6970
            }
1368 6970
        } else {
1369 6970
            // Named parameters
1370 6970
            foreach ($params as $name => $value) {
1371
                if (isset($types[$name])) {
1372
                    $type                  = $types[$name];
1373 7256
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1374 7256
                    $stmt->bindValue($name, $value, $bindingType);
1375
                } else {
1376 8581
                    $stmt->bindValue($name, $value);
1377
                }
1378
            }
1379
        }
1380
    }
1381
1382
    /**
1383
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1384
     *
1385
     * @param mixed           $value The value to bind.
1386
     * @param int|string|null $type  The type to bind (PDO or DBAL).
1387 7205
     *
1388
     * @return array<int, mixed> [0] => the (escaped) value, [1] => the binding type.
1389 7205
     */
1390 235
    private function getBindingInfo($value, $type) : array
1391
    {
1392
        if (is_string($type)) {
1393 6970
            $type = Type::getType($type);
1394 6970
        }
1395
        if ($type instanceof Type) {
1396
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1397
            $bindingType = $type->getBindingType();
1398
        } else {
1399
            $bindingType = $type;
1400
        }
1401
1402
        return [$value, $bindingType];
1403
    }
1404
1405 6970
    /**
1406
     * Resolves the parameters to a format which can be displayed.
1407 6970
     *
1408
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1409
     *           copy/paste the code as this method may change, or be removed without prior notice.
1410
     *
1411 6970
     * @param array<int, mixed>|array<string, mixed>           $params
1412 504
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1413
     *
1414
     * @return array<int, mixed>|array<string, mixed>
1415 6466
     */
1416 6466
    public function resolveParams(array $params, array $types) : array
1417
    {
1418
        $resolvedParams = [];
1419
1420
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1421
        if (is_int(key($params))) {
1422
            // Positional parameters
1423
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1424
            $bindIndex  = 1;
1425
            foreach ($params as $value) {
1426
                $typeIndex = $bindIndex + $typeOffset;
1427 6970
                if (isset($types[$typeIndex])) {
1428
                    $type                       = $types[$typeIndex];
1429 6970
                    [$value]                    = $this->getBindingInfo($value, $type);
1430
                    $resolvedParams[$bindIndex] = $value;
1431
                } else {
1432
                    $resolvedParams[$bindIndex] = $value;
1433 6970
                }
1434 6970
                ++$bindIndex;
1435
            }
1436
        } else {
1437
            // Named parameters
1438
            foreach ($params as $name => $value) {
1439
                if (isset($types[$name])) {
1440
                    $type                  = $types[$name];
1441 9500
                    [$value]               = $this->getBindingInfo($value, $type);
1442
                    $resolvedParams[$name] = $value;
1443 9500
                } else {
1444
                    $resolvedParams[$name] = $value;
1445 9494
                }
1446
            }
1447
        }
1448
1449
        return $resolvedParams;
1450
    }
1451
1452
    /**
1453
     * Creates a new instance of a SQL query builder.
1454 8324
     */
1455
    public function createQueryBuilder() : QueryBuilder
1456 8324
    {
1457 8013
        return new Query\QueryBuilder($this);
1458
    }
1459
1460 8324
    /**
1461
     * Ping the server
1462
     *
1463
     * When the server is not available the method throws a DBALException.
1464
     * It is responsibility of the developer to handle this case
1465
     * and abort the request or close the connection so that it's reestablished
1466
     * upon the next statement execution.
1467
     *
1468
     * @throws DBALException
1469
     *
1470
     * @example
1471 7283
     *
1472
     *   try {
1473 7283
     *      $conn->ping();
1474 2
     *   } catch (DBALException $e) {
1475
     *      $conn->close();
1476 7281
     *   }
1477 7281
     *
1478
     * It is undefined if the underlying driver attempts to reconnect
1479
     * or disconnect when the connection is not available anymore
1480
     * as long it successfully returns when a reconnect succeeded
1481
     * and throws an exception if the connection was dropped.
1482
     */
1483
    public function ping() : void
1484
    {
1485
        $connection = $this->getWrappedConnection();
1486 7260
1487
        if (! $connection instanceof PingableConnection) {
1488 7260
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1489 2
1490
            return;
1491
        }
1492 7258
1493
        try {
1494
            $connection->ping();
1495
        } catch (DriverException $e) {
1496
            throw DBALException::driverException($this->_driver, $e);
1497
        }
1498
    }
1499
}
1500