Completed
Pull Request — master (#3790)
by
unknown
35:39
created

Connection::commitAll()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 3
nop 0
crap 4
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 2904
    public function __construct(
164
        array $params,
165
        Driver $driver,
166
        ?Configuration $config = null,
167
        ?EventManager $eventManager = null
168
    ) {
169 2904
        $this->_driver = $driver;
170 2904
        $this->params  = $params;
171
172 2904
        if (isset($params['platform'])) {
173 312
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
174 26
                throw InvalidPlatformType::new($params['platform']);
175
            }
176
177 286
            $this->platform = $params['platform'];
178
        }
179
180
        // Create default config and event manager if none given
181 2904
        if (! $config) {
182 650
            $config = new Configuration();
183
        }
184
185 2904
        if (! $eventManager) {
186 624
            $eventManager = new EventManager();
187
        }
188
189 2904
        $this->_config       = $config;
190 2904
        $this->_eventManager = $eventManager;
191
192 2904
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
193
194 2904
        $this->autoCommit = $config->getAutoCommit();
195 2904
    }
196
197
    /**
198
     * Gets the parameters used during instantiation.
199
     *
200
     * @return array<string, mixed>
201
     */
202 1924
    public function getParams() : array
203
    {
204 1924
        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 2099
    public function getDatabase() : ?string
217
    {
218 2099
        $platform = $this->getDatabasePlatform();
219 2099
        $query    = $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
220 2099
        $database = $this->query($query)->fetchColumn();
221
222 2099
        assert(is_string($database) || $database === null);
223
224 2099
        return $database;
225
    }
226
227
    /**
228
     * Gets the DBAL driver instance.
229
     */
230 1479
    public function getDriver() : Driver
231
    {
232 1479
        return $this->_driver;
233
    }
234
235
    /**
236
     * Gets the Configuration used by the Connection.
237
     */
238 9872
    public function getConfiguration() : Configuration
239
    {
240 9872
        return $this->_config;
241
    }
242
243
    /**
244
     * Gets the EventManager used by the Connection.
245
     */
246 361
    public function getEventManager() : EventManager
247
    {
248 361
        return $this->_eventManager;
249
    }
250
251
    /**
252
     * Gets the DatabasePlatform for the connection.
253
     *
254
     * @throws DBALException
255
     */
256 8192
    public function getDatabasePlatform() : AbstractPlatform
257
    {
258 8192
        if ($this->platform === null) {
259 765
            $this->detectDatabasePlatform();
260
        }
261
262 8166
        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 10090
    public function connect() : void
279
    {
280 10090
        if ($this->isConnected) {
281 9584
            return;
282
        }
283
284 1302
        $driverOptions = $this->params['driverOptions'] ?? [];
285 1302
        $user          = $this->params['user'] ?? '';
286 1302
        $password      = $this->params['password'] ?? '';
287
288 1302
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
289 1220
        $this->isConnected = true;
290
291 1220
        $this->transactionNestingLevel = 0;
292
293 1220
        if ($this->autoCommit === false) {
294 78
            $this->beginTransaction();
295
        }
296
297 1220
        if (! $this->_eventManager->hasListeners(Events::postConnect)) {
298 1098
            return;
299
        }
300
301 122
        $eventArgs = new Event\ConnectionEventArgs($this);
302 122
        $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
303 122
    }
304
305
    /**
306
     * Detects and sets the database platform.
307
     *
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 765
    private function detectDatabasePlatform() : void
313
    {
314 765
        $version = $this->getDatabasePlatformVersion();
315
316 695
        if ($version !== null) {
317 398
            assert($this->_driver instanceof VersionAwarePlatformDriver);
318
319 398
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
320
        } else {
321 297
            $this->platform = $this->_driver->getDatabasePlatform();
322
        }
323
324 695
        $this->platform->setEventManager($this->_eventManager);
325 695
    }
326
327
    /**
328
     * Returns the version of the related platform if applicable.
329
     *
330
     * 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
     * version without having to query it (performance reasons).
334
     *
335
     * @throws Exception
336
     */
337 765
    private function getDatabasePlatformVersion() : ?string
338
    {
339
        // Driver does not support version specific platforms.
340 765
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
341 297
            return null;
342
        }
343
344
        // Explicit platform version requested (supersedes auto-detection).
345 468
        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 468
        if ($this->_conn === null) {
351
            try {
352 372
                $this->connect();
353 87
            } catch (Throwable $originalException) {
354 87
                if (empty($this->params['dbname'])) {
355
                    throw $originalException;
356
                }
357
358
                // The database to connect to might not yet exist.
359
                // Retry detection without database name connection parameter.
360 87
                $databaseName           = $this->params['dbname'];
361 87
                $this->params['dbname'] = null;
362
363
                try {
364 87
                    $this->connect();
365 70
                } catch (Throwable $fallbackException) {
366
                    // Either the platform does not support database-less connections
367
                    // or something else went wrong.
368
                    // Reset connection parameters and rethrow the original exception.
369 70
                    $this->params['dbname'] = $databaseName;
370
371 70
                    throw $originalException;
372
                }
373
374
                // Reset connection parameters.
375 17
                $this->params['dbname'] = $databaseName;
376 17
                $serverVersion          = $this->getServerVersion();
377
378
                // Close "temporary" connection to allow connecting to the real database again.
379 17
                $this->close();
380
381 17
                return $serverVersion;
382
            }
383
        }
384
385 398
        return $this->getServerVersion();
386
    }
387
388
    /**
389
     * Returns the database server version if the underlying driver supports it.
390
     */
391 398
    private function getServerVersion() : ?string
392
    {
393 398
        $connection = $this->getWrappedConnection();
394
395
        // Automatic platform version detection.
396 398
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
397 398
            return $connection->getServerVersion();
398
        }
399
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 52
    public function isAutoCommit() : bool
412
    {
413 52
        return $this->autoCommit;
414
    }
415
416
    /**
417
     * 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
     * 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
     * @see isAutoCommit
427
     *
428
     * @throws ConnectionException
429
     * @throws DriverException
430
     */
431 130
    public function setAutoCommit(bool $autoCommit) : void
432
    {
433
        // Mode not changed, no-op.
434 130
        if ($autoCommit === $this->autoCommit) {
435
            return;
436
        }
437
438 130
        $this->autoCommit = $autoCommit;
439
440
        // Commit all currently active transactions if any when switching auto-commit mode.
441 130
        if (! $this->isConnected || $this->transactionNestingLevel === 0) {
442 104
            return;
443
        }
444
445 26
        $this->commitAll();
446 26
    }
447
448
    /**
449
     * Sets the fetch mode.
450
     */
451 26
    public function setFetchMode(int $fetchMode) : void
452
    {
453 26
        $this->defaultFetchMode = $fetchMode;
454 26
    }
455
456
    /**
457
     * 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
     * @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 2316
    public function fetchAssoc(string $query, array $params = [], array $types = [])
469
    {
470 2316
        return $this->executeQuery($query, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
471
    }
472
473
    /**
474
     * Prepares and executes an SQL query and returns the first row of the result
475
     * 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 97
    public function fetchArray(string $query, array $params = [], array $types = [])
486
    {
487 97
        return $this->executeQuery($query, $params, $types)->fetch(FetchMode::NUMERIC);
488
    }
489
490
    /**
491
     * 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 1528
    public function fetchColumn(string $query, array $params = [], int $column = 0, array $types = [])
504
    {
505 1528
        return $this->executeQuery($query, $params, $types)->fetchColumn($column);
506
    }
507
508
    /**
509
     * Whether an actual connection to the database is established.
510
     */
511 224
    public function isConnected() : bool
512
    {
513 224
        return $this->isConnected;
514
    }
515
516
    /**
517
     * Checks whether a transaction is currently active.
518
     *
519
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
520
     */
521 9846
    public function isTransactionActive() : bool
522
    {
523 9846
        return $this->transactionNestingLevel > 0;
524
    }
525
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
     * @throws DBALException
535
     */
536 348
    private function addIdentifierCondition(
537
        array $identifier,
538
        array &$columns,
539
        array &$values,
540
        array &$conditions
541
    ) : void {
542 348
        $platform = $this->getDatabasePlatform();
543
544 348
        foreach ($identifier as $columnName => $value) {
545 348
            if ($value === null) {
546 104
                $conditions[] = $platform->getIsNullExpression($columnName);
547 104
                continue;
548
            }
549
550 296
            $columns[]    = $columnName;
551 296
            $values[]     = $value;
552 296
            $conditions[] = $columnName . ' = ?';
553
        }
554 348
    }
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
     *
567
     * @throws DBALException
568
     * @throws InvalidArgumentException
569
     */
570 151
    public function delete(string $table, array $identifier, array $types = []) : int
571
    {
572 151
        if (empty($identifier)) {
573 26
            throw EmptyCriteriaNotAllowed::new();
574
        }
575
576 125
        $columns = $values = $conditions = [];
577
578 125
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
579
580 125
        return $this->executeUpdate(
581 125
            'DELETE FROM ' . $table . ' WHERE ' . implode(' AND ', $conditions),
582
            $values,
583 125
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
584
        );
585
    }
586
587
    /**
588
     * Closes the connection.
589
     */
590 637
    public function close() : void
591
    {
592 637
        $this->_conn = null;
593
594 637
        $this->isConnected = false;
595 637
    }
596
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
        $this->transactionIsolationLevel = $level;
605
606
        $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
620
        return $this->transactionIsolationLevel;
621
    }
622
623
    /**
624
     * Executes an SQL UPDATE statement on a table.
625
     *
626
     * Table expression and columns are not escaped and are not safe for user-input.
627
     *
628
     * @param string                                           $table      The SQL expression of the table to update quoted or unquoted.
629
     * @param array<string, mixed>                             $data       An associative array containing column-value pairs.
630
     * @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
     * @return int The number of affected rows.
634
     *
635
     * @throws DBALException
636
     */
637 223
    public function update(string $table, array $data, array $identifier, array $types = []) : int
638
    {
639 223
        $columns = $values = $conditions = $set = [];
640
641 223
        foreach ($data as $columnName => $value) {
642 223
            $columns[] = $columnName;
643 223
            $values[]  = $value;
644 223
            $set[]     = $columnName . ' = ?';
645
        }
646
647 223
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
648
649 223
        if (is_string(key($types))) {
650 130
            $types = $this->extractTypeValues($columns, $types);
651
        }
652
653 223
        $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set)
654 223
                . ' WHERE ' . implode(' AND ', $conditions);
655
656 223
        return $this->executeUpdate($sql, $values, $types);
657
    }
658
659
    /**
660
     * Inserts a table row with specified data.
661
     *
662
     * Table expression and columns are not escaped and are not safe for user-input.
663
     *
664
     * @param string                                           $table The SQL expression of the table to insert data into, quoted or unquoted.
665
     * @param array<string, mixed>                             $data  An associative array containing column-value pairs.
666
     * @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 2419
    public function insert(string $table, array $data, array $types = []) : int
673
    {
674 2419
        if (empty($data)) {
675 26
            return $this->executeUpdate('INSERT INTO ' . $table . ' () VALUES ()');
676
        }
677
678 2393
        $columns = [];
679 2393
        $values  = [];
680 2393
        $set     = [];
681
682 2393
        foreach ($data as $columnName => $value) {
683 2393
            $columns[] = $columnName;
684 2393
            $values[]  = $value;
685 2393
            $set[]     = '?';
686
        }
687
688 2393
        return $this->executeUpdate(
689 2393
            'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' .
690 2393
            ' VALUES (' . implode(', ', $set) . ')',
691
            $values,
692 2393
            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 234
    private function extractTypeValues(array $columnList, array $types)
705
    {
706 234
        $typeValues = [];
707
708 234
        foreach ($columnList as $columnName) {
709 234
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
710
        }
711
712 234
        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
     *
725
     * @param string $identifier The identifier to be quoted.
726
     *
727
     * @return string The quoted identifier.
728
     */
729 26
    public function quoteIdentifier(string $identifier) : string
730
    {
731 26
        return $this->getDatabasePlatform()->quoteIdentifier($identifier);
732
    }
733
734
    /**
735
     * {@inheritDoc}
736
     */
737 208
    public function quote(string $input) : string
738
    {
739 208
        return $this->getWrappedConnection()->quote($input);
740
    }
741
742
    /**
743
     * 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 2802
    public function fetchAll(string $query, array $params = [], array $types = []) : array
752
    {
753 2802
        return $this->executeQuery($query, $params, $types)->fetchAll();
754
    }
755
756
    /**
757
     * Prepares an SQL statement.
758
     *
759
     * @param string $sql The SQL statement to prepare.
760
     *
761
     * @throws DBALException
762
     */
763 2275
    public function prepare(string $sql) : DriverStatement
764
    {
765
        try {
766 2275
            $stmt = new Statement($sql, $this);
767 26
        } catch (Throwable $ex) {
768 26
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
769
        }
770
771 2249
        $stmt->setFetchMode($this->defaultFetchMode);
772
773 2249
        return $stmt;
774
    }
775
776
    /**
777
     * Executes an, optionally parametrized, SQL query.
778
     *
779
     * 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 6003
    public function executeQuery(string $query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) : ResultStatement
792
    {
793 6003
        if ($qcp !== null) {
794 286
            return $this->executeCacheQuery($query, $params, $types, $qcp);
795
        }
796
797 6003
        $connection = $this->getWrappedConnection();
798
799 6003
        $logger = $this->_config->getSQLLogger();
800 6003
        $logger->startQuery($query, $params, $types);
801
802
        try {
803 6003
            if ($params) {
804 1023
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
805
806 1023
                $stmt = $connection->prepare($query);
807 1023
                if ($types) {
808 414
                    $this->_bindTypedValues($stmt, $params, $types);
809 414
                    $stmt->execute();
810
                } else {
811 1023
                    $stmt->execute($params);
812
                }
813
            } else {
814 5927
                $stmt = $connection->query($query);
815
            }
816 171
        } catch (Throwable $ex) {
817 171
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
818
        }
819
820 5832
        $stmt->setFetchMode($this->defaultFetchMode);
821
822 5832
        $logger->stopQuery();
823
824 5832
        return $stmt;
825
    }
826
827
    /**
828
     * Executes a caching query.
829
     *
830
     * @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 390
    public function executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp) : ResultStatement
838
    {
839 390
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
840
841 390
        if ($resultCache === null) {
842
            throw NoResultDriverConfigured::new();
843
        }
844
845 390
        $connectionParams = $this->getParams();
846 390
        unset($connectionParams['platform']);
847
848 390
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
849
850
        // fetch the row pointers entry
851 390
        $data = $resultCache->fetch($cacheKey);
852
853 390
        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 286
            if (isset($data[$realKey])) {
856 286
                $stmt = new ArrayStatement($data[$realKey]);
857
            } elseif (array_key_exists($realKey, $data)) {
858
                $stmt = new ArrayStatement([]);
859
            }
860
        }
861
862 390
        if (! isset($stmt)) {
863 312
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
864
        }
865
866 390
        $stmt->setFetchMode($this->defaultFetchMode);
867
868 390
        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
    {
885
        $result = [];
886
        $stmt   = $this->executeQuery($query, $params);
887
888
        while ($row = $stmt->fetch()) {
889
            $result[] = $function($row);
890
        }
891
892
        $stmt->closeCursor();
893
894
        return $result;
895
    }
896
897
    /**
898
     * {@inheritDoc}
899
     */
900 2583
    public function query(string $sql) : ResultStatement
901
    {
902 2583
        $connection = $this->getWrappedConnection();
903
904 2583
        $logger = $this->_config->getSQLLogger();
905 2583
        $logger->startQuery($sql);
906
907
        try {
908 2583
            $statement = $connection->query($sql);
909 26
        } catch (Throwable $ex) {
910 26
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
911
        }
912
913 2557
        $statement->setFetchMode($this->defaultFetchMode);
914
915 2557
        $logger->stopQuery();
916
917 2557
        return $statement;
918
    }
919
920
    /**
921
     * 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 4855
    public function executeUpdate(string $query, array $params = [], array $types = []) : int
933
    {
934 4855
        $connection = $this->getWrappedConnection();
935
936 4855
        $logger = $this->_config->getSQLLogger();
937 4855
        $logger->startQuery($query, $params, $types);
938
939
        try {
940 4855
            if ($params) {
941 2500
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
942
943 2500
                $stmt = $connection->prepare($query);
944
945 2492
                if ($types) {
946 351
                    $this->_bindTypedValues($stmt, $params, $types);
947 351
                    $stmt->execute();
948
                } else {
949 2141
                    $stmt->execute($params);
950
                }
951 2454
                $result = $stmt->rowCount();
952
            } else {
953 4809
                $result = $connection->exec($query);
954
            }
955 2592
        } catch (Throwable $ex) {
956 2592
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
957
        }
958
959 4510
        $logger->stopQuery();
960
961 4510
        return $result;
962
    }
963
964
    /**
965
     * {@inheritDoc}
966
     */
967 2455
    public function exec(string $statement) : int
968
    {
969 2455
        $connection = $this->getWrappedConnection();
970
971 2443
        $logger = $this->_config->getSQLLogger();
972 2443
        $logger->startQuery($statement);
973
974
        try {
975 2443
            $result = $connection->exec($statement);
976 1831
        } catch (Throwable $ex) {
977 1831
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
978
        }
979
980 685
        $logger->stopQuery();
981
982 685
        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 289
    public function getTransactionNestingLevel() : int
991
    {
992 289
        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
     * @param string|null $name Name of the sequence object from which the ID should be returned.
1004
     *
1005
     * @return string A string representation of the last inserted ID.
1006
     */
1007 97
    public function lastInsertId(?string $name = null) : string
1008
    {
1009 97
        return $this->getWrappedConnection()->lastInsertId($name);
1010
    }
1011
1012
    /**
1013
     * Executes a function in a transaction.
1014
     *
1015
     * The function gets passed this Connection instance as an (optional) parameter.
1016
     *
1017
     * 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
     * @param Closure $func The function to execute transactionally.
1021
     *
1022
     * @return mixed The value returned by $func
1023
     *
1024
     * @throws Throwable
1025
     */
1026 104
    public function transactional(Closure $func)
1027
    {
1028 104
        $this->beginTransaction();
1029
        try {
1030 104
            $res = $func($this);
1031 52
            $this->commit();
1032
1033 52
            return $res;
1034 52
        } catch (Throwable $e) {
1035 52
            $this->rollBack();
1036 52
            throw $e;
1037
        }
1038
    }
1039
1040
    /**
1041
     * Sets if nested transactions should use savepoints.
1042
     *
1043
     * @throws ConnectionException
1044
     */
1045 51
    public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void
1046
    {
1047 51
        if ($this->transactionNestingLevel > 0) {
1048 50
            throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new();
1049
        }
1050
1051 26
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1052 1
            throw SavepointsNotSupported::new();
1053
        }
1054
1055 25
        $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
1056 25
    }
1057
1058
    /**
1059
     * Gets if nested transactions should use savepoints.
1060
     */
1061 25
    public function getNestTransactionsWithSavepoints() : bool
1062
    {
1063 25
        return $this->nestTransactionsWithSavepoints;
1064
    }
1065
1066
    /**
1067
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1068
     * "savepointFormat" parameter is not set
1069
     *
1070
     * @return mixed A string with the savepoint name or false.
1071
     */
1072 25
    protected function _getNestedTransactionSavePointName()
1073
    {
1074 25
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1075
    }
1076
1077
    /**
1078
     * {@inheritDoc}
1079
     */
1080 526
    public function beginTransaction() : void
1081
    {
1082 526
        $connection = $this->getWrappedConnection();
1083
1084 526
        ++$this->transactionNestingLevel;
1085
1086 526
        $logger = $this->_config->getSQLLogger();
1087
1088 526
        if ($this->transactionNestingLevel === 1) {
1089 526
            $logger->startQuery('"START TRANSACTION"');
1090
1091
            try {
1092 526
                $connection->beginTransaction();
1093 526
            } finally {
1094 526
                $logger->stopQuery();
1095
            }
1096 103
        } elseif ($this->nestTransactionsWithSavepoints) {
1097 25
            $logger->startQuery('"SAVEPOINT"');
1098 25
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1099 25
            $logger->stopQuery();
1100
        }
1101 526
    }
1102
1103
    /**
1104
     * {@inheritDoc}
1105
     *
1106
     * @throws ConnectionException If the commit failed due to no active transaction or
1107
     *                                            because the transaction was marked for rollback only.
1108
     */
1109 297
    public function commit() : void
1110
    {
1111 297
        if ($this->transactionNestingLevel === 0) {
1112 26
            throw NoActiveTransaction::new();
1113
        }
1114 271
        if ($this->isRollbackOnly) {
1115 52
            throw CommitFailedRollbackOnly::new();
1116
        }
1117
1118 219
        $result = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1119
1120 219
        $connection = $this->getWrappedConnection();
1121
1122 219
        $logger = $this->_config->getSQLLogger();
1123
1124 219
        if ($this->transactionNestingLevel === 1) {
1125 219
            $logger->startQuery('"COMMIT"');
1126
1127
            try {
1128 219
                $connection->commit();
1129 219
            } finally {
1130 219
                $logger->stopQuery();
1131
            }
1132 51
        } elseif ($this->nestTransactionsWithSavepoints) {
1133 25
            $logger->startQuery('"RELEASE SAVEPOINT"');
1134 25
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1135 25
            $logger->stopQuery();
1136
        }
1137
1138 219
        --$this->transactionNestingLevel;
1139
1140 219
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1141 193
            return;
1142
        }
1143
1144 52
        $this->beginTransaction();
1145 52
    }
1146
1147
    /**
1148
     * Commits all current nesting transactions.
1149
     *
1150
     * @throws ConnectionException
1151
     * @throws DriverException
1152
     */
1153 26
    private function commitAll() : void
1154
    {
1155 26
        while ($this->transactionNestingLevel !== 0) {
1156 26
            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 26
                $this->commit();
1160
1161 26
                return;
1162
            }
1163
1164 26
            $this->commit();
1165
        }
1166 26
    }
1167
1168
    /**
1169
     * {@inheritDoc}
1170
     *
1171
     * @throws ConnectionException If the rollback operation failed.
1172
     */
1173 356
    public function rollBack() : void
1174
    {
1175 356
        if ($this->transactionNestingLevel === 0) {
1176 26
            throw NoActiveTransaction::new();
1177
        }
1178
1179 330
        $connection = $this->getWrappedConnection();
1180
1181 330
        $logger = $this->_config->getSQLLogger();
1182
1183 330
        if ($this->transactionNestingLevel === 1) {
1184 305
            $logger->startQuery('"ROLLBACK"');
1185 305
            $this->transactionNestingLevel = 0;
1186
1187
            try {
1188 305
                $connection->rollBack();
1189 305
            } finally {
1190 305
                $this->isRollbackOnly = false;
1191 305
                $logger->stopQuery();
1192
1193 305
                if ($this->autoCommit === false) {
1194 305
                    $this->beginTransaction();
1195
                }
1196
            }
1197 53
        } elseif ($this->nestTransactionsWithSavepoints) {
1198 25
            $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1199 25
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1200 25
            --$this->transactionNestingLevel;
1201 25
            $logger->stopQuery();
1202
        } else {
1203 28
            $this->isRollbackOnly = true;
1204 28
            --$this->transactionNestingLevel;
1205
        }
1206 330
    }
1207
1208
    /**
1209
     * Creates a new savepoint.
1210
     *
1211
     * @param string $savepoint The name of the savepoint to create.
1212
     *
1213
     * @throws ConnectionException
1214
     */
1215 26
    public function createSavepoint(string $savepoint) : void
1216
    {
1217 26
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1218 1
            throw SavepointsNotSupported::new();
1219
        }
1220
1221 25
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1222 25
    }
1223
1224
    /**
1225
     * Releases the given savepoint.
1226
     *
1227
     * @param string $savepoint The name of the savepoint to release.
1228
     *
1229
     * @throws ConnectionException
1230
     */
1231 26
    public function releaseSavepoint(string $savepoint) : void
1232
    {
1233 26
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1234 1
            throw SavepointsNotSupported::new();
1235
        }
1236
1237 25
        if (! $this->platform->supportsReleaseSavepoints()) {
1238 6
            return;
1239
        }
1240
1241 19
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1242 19
    }
1243
1244
    /**
1245
     * Rolls back to the given savepoint.
1246
     *
1247
     * @param string $savepoint The name of the savepoint to rollback to.
1248
     *
1249
     * @throws ConnectionException
1250
     */
1251 26
    public function rollbackSavepoint(string $savepoint) : void
1252
    {
1253 26
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1254 1
            throw SavepointsNotSupported::new();
1255
        }
1256
1257 25
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1258 25
    }
1259
1260
    /**
1261
     * Gets the wrapped driver connection.
1262
     */
1263 9974
    public function getWrappedConnection() : DriverConnection
1264
    {
1265 9974
        $this->connect();
1266
1267 9962
        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
    /**
1271
     * Gets the SchemaManager that can be used to inspect or change the
1272
     * database schema through the connection.
1273
     */
1274 4934
    public function getSchemaManager() : AbstractSchemaManager
1275
    {
1276 4934
        if ($this->_schemaManager === null) {
1277 328
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1278
        }
1279
1280 4934
        return $this->_schemaManager;
1281
    }
1282
1283
    /**
1284
     * Marks the current transaction so that the only possible
1285
     * outcome for the transaction to be rolled back.
1286
     *
1287
     * @throws ConnectionException If no transaction is active.
1288
     */
1289 52
    public function setRollbackOnly() : void
1290
    {
1291 52
        if ($this->transactionNestingLevel === 0) {
1292 26
            throw NoActiveTransaction::new();
1293
        }
1294 26
        $this->isRollbackOnly = true;
1295 26
    }
1296
1297
    /**
1298
     * Checks whether the current transaction is marked for rollback only.
1299
     *
1300
     * @throws ConnectionException If no transaction is active.
1301
     */
1302 77
    public function isRollbackOnly() : bool
1303
    {
1304 77
        if ($this->transactionNestingLevel === 0) {
1305 26
            throw NoActiveTransaction::new();
1306
        }
1307
1308 51
        return $this->isRollbackOnly;
1309
    }
1310
1311
    /**
1312
     * Converts a given value to its database representation according to the conversion
1313
     * 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
     */
1320
    public function convertToDatabaseValue($value, string $type)
1321
    {
1322
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1323
    }
1324
1325
    /**
1326
     * Converts a given value to its PHP representation according to the conversion
1327
     * rules of a specific DBAL mapping type.
1328
     *
1329
     * @param mixed  $value The value to convert.
1330
     * @param string $type  The name of the DBAL mapping type.
1331
     *
1332
     * @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
    /**
1340
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1341
     * or DBAL mapping type, to a given statement.
1342
     *
1343
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1344
     *           raw PDOStatement instances.
1345
     *
1346
     * @param DriverStatement                                  $stmt   The statement to bind the values to.
1347
     * @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
     */
1350 715
    private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
1351
    {
1352
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1353 715
        if (is_int(key($params))) {
1354
            // Positional parameters
1355 715
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1356 715
            $bindIndex  = 1;
1357 715
            foreach ($params as $value) {
1358 715
                $typeIndex = $bindIndex + $typeOffset;
1359 715
                if (isset($types[$typeIndex])) {
1360 715
                    $type                  = $types[$typeIndex];
1361 715
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1362 715
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1363
                } else {
1364 22
                    $stmt->bindValue($bindIndex, $value);
1365
                }
1366 715
                ++$bindIndex;
1367
            }
1368
        } else {
1369
            // Named parameters
1370
            foreach ($params as $name => $value) {
1371
                if (isset($types[$name])) {
1372
                    $type                  = $types[$name];
1373
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1374
                    $stmt->bindValue($name, $value, $bindingType);
1375
                } else {
1376
                    $stmt->bindValue($name, $value);
1377
                }
1378
            }
1379
        }
1380 715
    }
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
     *
1388
     * @return array<int, mixed> [0] => the (escaped) value, [1] => the binding type.
1389
     */
1390 715
    private function getBindingInfo($value, $type) : array
1391
    {
1392 715
        if (is_string($type)) {
1393 286
            $type = Type::getType($type);
1394
        }
1395 715
        if ($type instanceof Type) {
1396 286
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1397 286
            $bindingType = $type->getBindingType();
1398
        } else {
1399 559
            $bindingType = $type;
1400
        }
1401
1402 715
        return [$value, $bindingType];
1403
    }
1404
1405
    /**
1406
     * Resolves the parameters to a format which can be displayed.
1407
     *
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
     * @param array<int, mixed>|array<string, mixed>           $params
1412
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1413
     *
1414
     * @return array<int, mixed>|array<string, mixed>
1415
     */
1416 2776
    public function resolveParams(array $params, array $types) : array
1417
    {
1418 2776
        $resolvedParams = [];
1419
1420
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1421 2776
        if (is_int(key($params))) {
1422
            // Positional parameters
1423 246
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1424 246
            $bindIndex  = 1;
1425 246
            foreach ($params as $value) {
1426 246
                $typeIndex = $bindIndex + $typeOffset;
1427 246
                if (isset($types[$typeIndex])) {
1428
                    $type                       = $types[$typeIndex];
1429
                    [$value]                    = $this->getBindingInfo($value, $type);
1430
                    $resolvedParams[$bindIndex] = $value;
1431
                } else {
1432 246
                    $resolvedParams[$bindIndex] = $value;
1433
                }
1434 246
                ++$bindIndex;
1435
            }
1436
        } else {
1437
            // Named parameters
1438 2544
            foreach ($params as $name => $value) {
1439
                if (isset($types[$name])) {
1440
                    $type                  = $types[$name];
1441
                    [$value]               = $this->getBindingInfo($value, $type);
1442
                    $resolvedParams[$name] = $value;
1443
                } else {
1444
                    $resolvedParams[$name] = $value;
1445
                }
1446
            }
1447
        }
1448
1449 2776
        return $resolvedParams;
1450
    }
1451
1452
    /**
1453
     * Creates a new instance of a SQL query builder.
1454
     */
1455
    public function createQueryBuilder() : QueryBuilder
1456
    {
1457
        return new Query\QueryBuilder($this);
1458
    }
1459
1460
    /**
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
     *
1472
     *   try {
1473
     *      $conn->ping();
1474
     *   } catch (DBALException $e) {
1475
     *      $conn->close();
1476
     *   }
1477
     *
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 26
    public function ping() : void
1484
    {
1485 26
        $connection = $this->getWrappedConnection();
1486
1487 26
        if (! $connection instanceof PingableConnection) {
1488 20
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1489
1490 20
            return;
1491
        }
1492
1493
        try {
1494 6
            $connection->ping();
1495
        } catch (DriverException $e) {
1496
            throw DBALException::driverException($this->_driver, $e);
1497
        }
1498 6
    }
1499
}
1500