Failed Conditions
Push — develop ( b4c2cf...86369f )
by Sergei
18s queued 13s
created

Connection::setNestTransactionsWithSavepoints()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

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