Completed
Push — master ( 6d673d...7f4ef4 )
by Sergei
40:47 queued 40:43
created

Connection::releaseSavepoint()   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 3060
    public function __construct(
164
        array $params,
165
        Driver $driver,
166
        ?Configuration $config = null,
167
        ?EventManager $eventManager = null
168
    ) {
169 3060
        $this->_driver = $driver;
170 3060
        $this->params  = $params;
171
172 3060
        if (isset($params['platform'])) {
173 324
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
174 27
                throw InvalidPlatformType::new($params['platform']);
175
            }
176
177 297
            $this->platform = $params['platform'];
178
        }
179
180
        // Create default config and event manager if none given
181 3060
        if (! $config) {
182 675
            $config = new Configuration();
183
        }
184
185 3060
        if (! $eventManager) {
186 648
            $eventManager = new EventManager();
187
        }
188
189 3060
        $this->_config       = $config;
190 3060
        $this->_eventManager = $eventManager;
191
192 3060
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
193
194 3060
        $this->autoCommit = $config->getAutoCommit();
195 3060
    }
196
197
    /**
198
     * Gets the parameters used during instantiation.
199
     *
200
     * @return array<string, mixed>
201
     */
202 2062
    public function getParams() : array
203
    {
204 2062
        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 2260
    public function getDatabase() : ?string
217
    {
218 2260
        $platform = $this->getDatabasePlatform();
219 2260
        $query    = $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
220 2260
        $database = $this->query($query)->fetchColumn();
221
222 2260
        assert(is_string($database) || $database === null);
223
224 2260
        return $database;
225
    }
226
227
    /**
228
     * Gets the DBAL driver instance.
229
     */
230 1575
    public function getDriver() : Driver
231
    {
232 1575
        return $this->_driver;
233
    }
234
235
    /**
236
     * Gets the Configuration used by the Connection.
237
     */
238 10389
    public function getConfiguration() : Configuration
239
    {
240 10389
        return $this->_config;
241
    }
242
243
    /**
244
     * Gets the EventManager used by the Connection.
245
     */
246 350
    public function getEventManager() : EventManager
247
    {
248 350
        return $this->_eventManager;
249
    }
250
251
    /**
252
     * Gets the DatabasePlatform for the connection.
253
     *
254
     * @throws DBALException
255
     */
256 8668
    public function getDatabasePlatform() : AbstractPlatform
257
    {
258 8668
        if ($this->platform === null) {
259 815
            $this->detectDatabasePlatform();
260
        }
261
262 8641
        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 10629
    public function connect() : void
279
    {
280 10629
        if ($this->isConnected) {
281 10115
            return;
282
        }
283
284 1355
        $driverOptions = $this->params['driverOptions'] ?? [];
285 1355
        $user          = $this->params['user'] ?? '';
286 1355
        $password      = $this->params['password'] ?? '';
287
288 1355
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
289 1265
        $this->isConnected = true;
290
291 1265
        $this->transactionNestingLevel = 0;
292
293 1265
        if ($this->autoCommit === false) {
294 81
            $this->beginTransaction();
295
        }
296
297 1265
        if (! $this->_eventManager->hasListeners(Events::postConnect)) {
298 1191
            return;
299
        }
300
301 74
        $eventArgs = new Event\ConnectionEventArgs($this);
302 74
        $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
303 74
    }
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 815
    private function detectDatabasePlatform() : void
313
    {
314 815
        $version = $this->getDatabasePlatformVersion();
315
316 731
        if ($version !== null) {
317 503
            assert($this->_driver instanceof VersionAwarePlatformDriver);
318
319 503
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
320
        } else {
321 228
            $this->platform = $this->_driver->getDatabasePlatform();
322
        }
323
324 731
        $this->platform->setEventManager($this->_eventManager);
325 731
    }
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 815
    private function getDatabasePlatformVersion() : ?string
338
    {
339
        // Driver does not support version specific platforms.
340 815
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
341 228
            return null;
342
        }
343
344
        // Explicit platform version requested (supersedes auto-detection).
345 587
        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 587
        if ($this->_conn === null) {
351
            try {
352 464
                $this->connect();
353 106
            } catch (Throwable $originalException) {
354 106
                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 106
                $databaseName           = $this->params['dbname'];
361 106
                $this->params['dbname'] = null;
362
363
                try {
364 106
                    $this->connect();
365 84
                } 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 84
                    $this->params['dbname'] = $databaseName;
370
371 84
                    throw $originalException;
372
                }
373
374
                // Reset connection parameters.
375 22
                $this->params['dbname'] = $databaseName;
376 22
                $serverVersion          = $this->getServerVersion();
377
378
                // Close "temporary" connection to allow connecting to the real database again.
379 22
                $this->close();
380
381 22
                return $serverVersion;
382
            }
383
        }
384
385 503
        return $this->getServerVersion();
386
    }
387
388
    /**
389
     * Returns the database server version if the underlying driver supports it.
390
     */
391 503
    private function getServerVersion() : ?string
392
    {
393 503
        $connection = $this->getWrappedConnection();
394
395
        // Automatic platform version detection.
396 503
        if ($connection instanceof ServerInfoAwareConnection) {
397 503
            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 54
    public function isAutoCommit() : bool
412
    {
413 54
        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 135
    public function setAutoCommit(bool $autoCommit) : void
432
    {
433
        // Mode not changed, no-op.
434 135
        if ($autoCommit === $this->autoCommit) {
435
            return;
436
        }
437
438 135
        $this->autoCommit = $autoCommit;
439
440
        // Commit all currently active transactions if any when switching auto-commit mode.
441 135
        if (! $this->isConnected || $this->transactionNestingLevel === 0) {
442 108
            return;
443
        }
444
445 27
        $this->commitAll();
446 27
    }
447
448
    /**
449
     * Sets the fetch mode.
450
     */
451 27
    public function setFetchMode(int $fetchMode) : void
452
    {
453 27
        $this->defaultFetchMode = $fetchMode;
454 27
    }
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 2507
    public function fetchAssoc(string $query, array $params = [], array $types = [])
469
    {
470 2507
        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 98
    public function fetchArray(string $query, array $params = [], array $types = [])
486
    {
487 98
        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 1525
    public function fetchColumn(string $query, array $params = [], int $column = 0, array $types = [])
504
    {
505 1525
        return $this->executeQuery($query, $params, $types)->fetchColumn($column);
506
    }
507
508
    /**
509
     * Whether an actual connection to the database is established.
510
     */
511 239
    public function isConnected() : bool
512
    {
513 239
        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 10362
    public function isTransactionActive() : bool
522
    {
523 10362
        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 371
    private function addIdentifierCondition(
537
        array $identifier,
538
        array &$columns,
539
        array &$values,
540
        array &$conditions
541
    ) : void {
542 371
        $platform = $this->getDatabasePlatform();
543
544 371
        foreach ($identifier as $columnName => $value) {
545 371
            if ($value === null) {
546 108
                $conditions[] = $platform->getIsNullExpression($columnName);
547 108
                continue;
548
            }
549
550 317
            $columns[]    = $columnName;
551 317
            $values[]     = $value;
552 317
            $conditions[] = $columnName . ' = ?';
553
        }
554 371
    }
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|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 160
    public function delete(string $table, array $identifier, array $types = []) : int
571
    {
572 160
        if (empty($identifier)) {
573 27
            throw EmptyCriteriaNotAllowed::new();
574
        }
575
576 133
        $columns = $values = $conditions = [];
577
578 133
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
579
580 133
        return $this->executeUpdate(
581 133
            'DELETE FROM ' . $table . ' WHERE ' . implode(' AND ', $conditions),
582
            $values,
583 133
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
584
        );
585
    }
586
587
    /**
588
     * Closes the connection.
589
     */
590 660
    public function close() : void
591
    {
592 660
        $this->_conn = null;
593
594 660
        $this->isConnected = false;
595 660
    }
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 238
    public function update(string $table, array $data, array $identifier, array $types = []) : int
638
    {
639 238
        $columns = $values = $conditions = $set = [];
640
641 238
        foreach ($data as $columnName => $value) {
642 238
            $columns[] = $columnName;
643 238
            $values[]  = $value;
644 238
            $set[]     = $columnName . ' = ?';
645
        }
646
647 238
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
648
649 238
        if (is_string(key($types))) {
650 135
            $types = $this->extractTypeValues($columns, $types);
651
        }
652
653 238
        $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set)
654 238
                . ' WHERE ' . implode(' AND ', $conditions);
655
656 238
        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 2584
    public function insert(string $table, array $data, array $types = []) : int
673
    {
674 2584
        if (empty($data)) {
675 27
            return $this->executeUpdate('INSERT INTO ' . $table . ' () VALUES ()');
676
        }
677
678 2557
        $columns = [];
679 2557
        $values  = [];
680 2557
        $set     = [];
681
682 2557
        foreach ($data as $columnName => $value) {
683 2557
            $columns[] = $columnName;
684 2557
            $values[]  = $value;
685 2557
            $set[]     = '?';
686
        }
687
688 2557
        return $this->executeUpdate(
689 2557
            'INSERT INTO ' . $table . ' (' . implode(', ', $columns) . ')' .
690 2557
            ' VALUES (' . implode(', ', $set) . ')',
691
            $values,
692 2557
            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|string, int|string> $types      The query parameter types.
701
     *
702
     * @return array<int, int>|array<int, string>
703
     */
704 243
    private function extractTypeValues(array $columnList, array $types)
705
    {
706 243
        $typeValues = [];
707
708 243
        foreach ($columnList as $columnName) {
709 243
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
710
        }
711
712 243
        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 27
    public function quoteIdentifier(string $identifier) : string
730
    {
731 27
        return $this->getDatabasePlatform()->quoteIdentifier($identifier);
732
    }
733
734
    /**
735
     * {@inheritDoc}
736
     */
737 163
    public function quote(string $input) : string
738
    {
739 163
        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 2993
    public function fetchAll(string $query, array $params = [], array $types = []) : array
752
    {
753 2993
        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 2368
    public function prepare(string $sql) : DriverStatement
764
    {
765
        try {
766 2368
            $stmt = new Statement($sql, $this);
767 27
        } catch (Throwable $ex) {
768 27
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
769
        }
770
771 2341
        $stmt->setFetchMode($this->defaultFetchMode);
772
773 2341
        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 6317
    public function executeQuery(
792
        string $query,
793
        array $params = [],
794
        array $types = [],
795
        ?QueryCacheProfile $qcp = null
796
    ) : ResultStatement {
797 6317
        if ($qcp !== null) {
798 297
            return $this->executeCacheQuery($query, $params, $types, $qcp);
799
        }
800
801 6317
        $connection = $this->getWrappedConnection();
802
803 6317
        $logger = $this->_config->getSQLLogger();
804 6317
        $logger->startQuery($query, $params, $types);
805
806
        try {
807 6317
            if ($params) {
808 985
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
809
810 985
                $stmt = $connection->prepare($query);
811 985
                if ($types) {
812 432
                    $this->_bindTypedValues($stmt, $params, $types);
813 432
                    $stmt->execute();
814
                } else {
815 985
                    $stmt->execute($params);
816
                }
817
            } else {
818 6249
                $stmt = $connection->query($query);
819
            }
820 170
        } catch (Throwable $ex) {
821 170
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
822
        }
823
824 6147
        $stmt->setFetchMode($this->defaultFetchMode);
825
826 6147
        $logger->stopQuery();
827
828 6147
        return $stmt;
829
    }
830
831
    /**
832
     * Executes a caching query.
833
     *
834
     * @param string                                           $query  The SQL query to execute.
835
     * @param array<int, mixed>|array<string, mixed>           $params The parameters to bind to the query, if any.
836
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
837
     * @param QueryCacheProfile                                $qcp    The query cache profile.
838
     *
839
     * @throws CacheException
840
     */
841 405
    public function executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp) : ResultStatement
842
    {
843 405
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
844
845 405
        if ($resultCache === null) {
846
            throw NoResultDriverConfigured::new();
847
        }
848
849 405
        $connectionParams = $this->getParams();
850 405
        unset($connectionParams['platform']);
851
852 405
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
853
854
        // fetch the row pointers entry
855 405
        $data = $resultCache->fetch($cacheKey);
856
857 405
        if ($data !== false) {
858
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
859 297
            if (isset($data[$realKey])) {
860 297
                $stmt = new ArrayStatement($data[$realKey]);
861
            } elseif (array_key_exists($realKey, $data)) {
862
                $stmt = new ArrayStatement([]);
863
            }
864
        }
865
866 405
        if (! isset($stmt)) {
867 324
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
868
        }
869
870 405
        $stmt->setFetchMode($this->defaultFetchMode);
871
872 405
        return $stmt;
873
    }
874
875
    /**
876
     * {@inheritDoc}
877
     */
878 2753
    public function query(string $sql) : ResultStatement
879
    {
880 2753
        $connection = $this->getWrappedConnection();
881
882 2753
        $logger = $this->_config->getSQLLogger();
883 2753
        $logger->startQuery($sql);
884
885
        try {
886 2753
            $statement = $connection->query($sql);
887 27
        } catch (Throwable $ex) {
888 27
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
889
        }
890
891 2726
        $statement->setFetchMode($this->defaultFetchMode);
892
893 2726
        $logger->stopQuery();
894
895 2726
        return $statement;
896
    }
897
898
    /**
899
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
900
     * and returns the number of affected rows.
901
     *
902
     * This method supports PDO binding types as well as DBAL mapping types.
903
     *
904
     * @param string                                           $query  The SQL query.
905
     * @param array<int, mixed>|array<string, mixed>           $params The query parameters.
906
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
907
     *
908
     * @throws DBALException
909
     */
910 5174
    public function executeUpdate(string $query, array $params = [], array $types = []) : int
911
    {
912 5174
        $connection = $this->getWrappedConnection();
913
914 5174
        $logger = $this->_config->getSQLLogger();
915 5174
        $logger->startQuery($query, $params, $types);
916
917
        try {
918 5174
            if ($params) {
919 2669
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
920
921 2669
                $stmt = $connection->prepare($query);
922
923 2659
                if ($types) {
924 374
                    $this->_bindTypedValues($stmt, $params, $types);
925 374
                    $stmt->execute();
926
                } else {
927 2285
                    $stmt->execute($params);
928
                }
929 2619
                $result = $stmt->rowCount();
930
            } else {
931 5124
                $result = $connection->exec($query);
932
            }
933 2695
        } catch (Throwable $ex) {
934 2695
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
935
        }
936
937 4790
        $logger->stopQuery();
938
939 4790
        return $result;
940
    }
941
942
    /**
943
     * {@inheritDoc}
944
     */
945 2633
    public function exec(string $statement) : int
946
    {
947 2633
        $connection = $this->getWrappedConnection();
948
949 2627
        $logger = $this->_config->getSQLLogger();
950 2627
        $logger->startQuery($statement);
951
952
        try {
953 2627
            $result = $connection->exec($statement);
954 1992
        } catch (Throwable $ex) {
955 1992
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
956
        }
957
958 709
        $logger->stopQuery();
959
960 709
        return $result;
961
    }
962
963
    /**
964
     * Returns the current transaction nesting level.
965
     *
966
     * @return int The nesting level. A value of 0 means there's no active transaction.
967
     */
968 342
    public function getTransactionNestingLevel() : int
969
    {
970 342
        return $this->transactionNestingLevel;
971
    }
972
973
    /**
974
     * Returns the ID of the last inserted row, or the last value from a sequence object,
975
     * depending on the underlying driver.
976
     *
977
     * Note: This method may not return a meaningful or consistent result across different drivers,
978
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
979
     * columns or sequences.
980
     *
981
     * @param string|null $name Name of the sequence object from which the ID should be returned.
982
     *
983
     * @return string A string representation of the last inserted ID.
984
     */
985 100
    public function lastInsertId(?string $name = null) : string
986
    {
987 100
        return $this->getWrappedConnection()->lastInsertId($name);
988
    }
989
990
    /**
991
     * Executes a function in a transaction.
992
     *
993
     * The function gets passed this Connection instance as an (optional) parameter.
994
     *
995
     * If an exception occurs during execution of the function or transaction commit,
996
     * the transaction is rolled back and the exception re-thrown.
997
     *
998
     * @param Closure $func The function to execute transactionally.
999
     *
1000
     * @return mixed The value returned by $func
1001
     *
1002
     * @throws Throwable
1003
     */
1004 108
    public function transactional(Closure $func)
1005
    {
1006 108
        $this->beginTransaction();
1007
        try {
1008 108
            $res = $func($this);
1009 54
            $this->commit();
1010
1011 54
            return $res;
1012 54
        } catch (Throwable $e) {
1013 54
            $this->rollBack();
1014 54
            throw $e;
1015
        }
1016
    }
1017
1018
    /**
1019
     * Sets if nested transactions should use savepoints.
1020
     *
1021
     * @throws ConnectionException
1022
     */
1023 54
    public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void
1024
    {
1025 54
        if ($this->transactionNestingLevel > 0) {
1026 54
            throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new();
1027
        }
1028
1029 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1030
            throw SavepointsNotSupported::new();
1031
        }
1032
1033 27
        $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
1034 27
    }
1035
1036
    /**
1037
     * Gets if nested transactions should use savepoints.
1038
     */
1039 27
    public function getNestTransactionsWithSavepoints() : bool
1040
    {
1041 27
        return $this->nestTransactionsWithSavepoints;
1042
    }
1043
1044
    /**
1045
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1046
     * "savepointFormat" parameter is not set
1047
     *
1048
     * @return mixed A string with the savepoint name or false.
1049
     */
1050 27
    protected function _getNestedTransactionSavePointName()
1051
    {
1052 27
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1053
    }
1054
1055
    /**
1056
     * {@inheritDoc}
1057
     */
1058 555
    public function beginTransaction() : void
1059
    {
1060 555
        $connection = $this->getWrappedConnection();
1061
1062 555
        ++$this->transactionNestingLevel;
1063
1064 555
        $logger = $this->_config->getSQLLogger();
1065
1066 555
        if ($this->transactionNestingLevel === 1) {
1067 555
            $logger->startQuery('"START TRANSACTION"');
1068
1069
            try {
1070 555
                $connection->beginTransaction();
1071 555
            } finally {
1072 555
                $logger->stopQuery();
1073
            }
1074 108
        } elseif ($this->nestTransactionsWithSavepoints) {
1075 27
            $logger->startQuery('"SAVEPOINT"');
1076 27
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1077 27
            $logger->stopQuery();
1078
        }
1079 555
    }
1080
1081
    /**
1082
     * {@inheritDoc}
1083
     *
1084
     * @throws ConnectionException If the commit failed due to no active transaction or
1085
     *                                            because the transaction was marked for rollback only.
1086
     */
1087 314
    public function commit() : void
1088
    {
1089 314
        if ($this->transactionNestingLevel === 0) {
1090 27
            throw NoActiveTransaction::new();
1091
        }
1092 287
        if ($this->isRollbackOnly) {
1093 54
            throw CommitFailedRollbackOnly::new();
1094
        }
1095
1096 233
        $result = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1097
1098 233
        $connection = $this->getWrappedConnection();
1099
1100 233
        $logger = $this->_config->getSQLLogger();
1101
1102 233
        if ($this->transactionNestingLevel === 1) {
1103 233
            $logger->startQuery('"COMMIT"');
1104
1105
            try {
1106 233
                $connection->commit();
1107 233
            } finally {
1108 233
                $logger->stopQuery();
1109
            }
1110 54
        } elseif ($this->nestTransactionsWithSavepoints) {
1111 27
            $logger->startQuery('"RELEASE SAVEPOINT"');
1112 27
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1113 27
            $logger->stopQuery();
1114
        }
1115
1116 233
        --$this->transactionNestingLevel;
1117
1118 233
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1119 206
            return;
1120
        }
1121
1122 54
        $this->beginTransaction();
1123 54
    }
1124
1125
    /**
1126
     * Commits all current nesting transactions.
1127
     *
1128
     * @throws ConnectionException
1129
     * @throws DriverException
1130
     */
1131 27
    private function commitAll() : void
1132
    {
1133 27
        while ($this->transactionNestingLevel !== 0) {
1134 27
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1135
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1136
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1137 27
                $this->commit();
1138
1139 27
                return;
1140
            }
1141
1142 27
            $this->commit();
1143
        }
1144 27
    }
1145
1146
    /**
1147
     * {@inheritDoc}
1148
     *
1149
     * @throws ConnectionException If the rollback operation failed.
1150
     */
1151 375
    public function rollBack() : void
1152
    {
1153 375
        if ($this->transactionNestingLevel === 0) {
1154 27
            throw NoActiveTransaction::new();
1155
        }
1156
1157 348
        $connection = $this->getWrappedConnection();
1158
1159 348
        $logger = $this->_config->getSQLLogger();
1160
1161 348
        if ($this->transactionNestingLevel === 1) {
1162 321
            $logger->startQuery('"ROLLBACK"');
1163 321
            $this->transactionNestingLevel = 0;
1164
1165
            try {
1166 321
                $connection->rollBack();
1167 321
            } finally {
1168 321
                $this->isRollbackOnly = false;
1169 321
                $logger->stopQuery();
1170
1171 321
                if ($this->autoCommit === false) {
1172 321
                    $this->beginTransaction();
1173
                }
1174
            }
1175 55
        } elseif ($this->nestTransactionsWithSavepoints) {
1176 27
            $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1177 27
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1178 27
            --$this->transactionNestingLevel;
1179 27
            $logger->stopQuery();
1180
        } else {
1181 28
            $this->isRollbackOnly = true;
1182 28
            --$this->transactionNestingLevel;
1183
        }
1184 348
    }
1185
1186
    /**
1187
     * Creates a new savepoint.
1188
     *
1189
     * @param string $savepoint The name of the savepoint to create.
1190
     *
1191
     * @throws ConnectionException
1192
     */
1193 27
    public function createSavepoint(string $savepoint) : void
1194
    {
1195 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1196
            throw SavepointsNotSupported::new();
1197
        }
1198
1199 27
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1200 27
    }
1201
1202
    /**
1203
     * Releases the given savepoint.
1204
     *
1205
     * @param string $savepoint The name of the savepoint to release.
1206
     *
1207
     * @throws ConnectionException
1208
     */
1209 27
    public function releaseSavepoint(string $savepoint) : void
1210
    {
1211 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1212
            throw SavepointsNotSupported::new();
1213
        }
1214
1215 27
        if (! $this->platform->supportsReleaseSavepoints()) {
1216 4
            return;
1217
        }
1218
1219 23
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1220 23
    }
1221
1222
    /**
1223
     * Rolls back to the given savepoint.
1224
     *
1225
     * @param string $savepoint The name of the savepoint to rollback to.
1226
     *
1227
     * @throws ConnectionException
1228
     */
1229 27
    public function rollbackSavepoint(string $savepoint) : void
1230
    {
1231 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1232
            throw SavepointsNotSupported::new();
1233
        }
1234
1235 27
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1236 27
    }
1237
1238
    /**
1239
     * Gets the wrapped driver connection.
1240
     */
1241 10501
    public function getWrappedConnection() : DriverConnection
1242
    {
1243 10501
        $this->connect();
1244
1245 10495
        assert($this->_conn !== null);
1246
1247 10495
        return $this->_conn;
1248
    }
1249
1250
    /**
1251
     * Gets the SchemaManager that can be used to inspect or change the
1252
     * database schema through the connection.
1253
     */
1254 5285
    public function getSchemaManager() : AbstractSchemaManager
1255
    {
1256 5285
        if ($this->_schemaManager === null) {
1257 349
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1258
        }
1259
1260 5285
        return $this->_schemaManager;
1261
    }
1262
1263
    /**
1264
     * Marks the current transaction so that the only possible
1265
     * outcome for the transaction to be rolled back.
1266
     *
1267
     * @throws ConnectionException If no transaction is active.
1268
     */
1269 54
    public function setRollbackOnly() : void
1270
    {
1271 54
        if ($this->transactionNestingLevel === 0) {
1272 27
            throw NoActiveTransaction::new();
1273
        }
1274 27
        $this->isRollbackOnly = true;
1275 27
    }
1276
1277
    /**
1278
     * Checks whether the current transaction is marked for rollback only.
1279
     *
1280
     * @throws ConnectionException If no transaction is active.
1281
     */
1282 81
    public function isRollbackOnly() : bool
1283
    {
1284 81
        if ($this->transactionNestingLevel === 0) {
1285 27
            throw NoActiveTransaction::new();
1286
        }
1287
1288 54
        return $this->isRollbackOnly;
1289
    }
1290
1291
    /**
1292
     * Converts a given value to its database representation according to the conversion
1293
     * rules of a specific DBAL mapping type.
1294
     *
1295
     * @param mixed  $value The value to convert.
1296
     * @param string $type  The name of the DBAL mapping type.
1297
     *
1298
     * @return mixed The converted value.
1299
     */
1300
    public function convertToDatabaseValue($value, string $type)
1301
    {
1302
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1303
    }
1304
1305
    /**
1306
     * Converts a given value to its PHP representation according to the conversion
1307
     * rules of a specific DBAL mapping type.
1308
     *
1309
     * @param mixed  $value The value to convert.
1310
     * @param string $type  The name of the DBAL mapping type.
1311
     *
1312
     * @return mixed The converted type.
1313
     */
1314
    public function convertToPHPValue($value, string $type)
1315
    {
1316
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1317
    }
1318
1319
    /**
1320
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1321
     * or DBAL mapping type, to a given statement.
1322
     *
1323
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1324
     *           raw PDOStatement instances.
1325
     *
1326
     * @param DriverStatement                                  $stmt   The statement to bind the values to.
1327
     * @param array<int, mixed>|array<string, mixed>           $params The map/list of named/positional parameters.
1328
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1329
     */
1330 753
    private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
1331
    {
1332
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1333 753
        if (is_int(key($params))) {
1334
            // Positional parameters
1335 753
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1336 753
            $bindIndex  = 1;
1337 753
            foreach ($params as $value) {
1338 753
                $typeIndex = $bindIndex + $typeOffset;
1339 753
                if (isset($types[$typeIndex])) {
1340 753
                    $type                  = $types[$typeIndex];
1341 753
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1342 753
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1343
                } else {
1344 25
                    $stmt->bindValue($bindIndex, $value);
1345
                }
1346 753
                ++$bindIndex;
1347
            }
1348
        } else {
1349
            // Named parameters
1350
            foreach ($params as $name => $value) {
1351
                if (isset($types[$name])) {
1352
                    $type                  = $types[$name];
1353
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1354
                    $stmt->bindValue($name, $value, $bindingType);
1355
                } else {
1356
                    $stmt->bindValue($name, $value);
1357
                }
1358
            }
1359
        }
1360 753
    }
1361
1362
    /**
1363
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1364
     *
1365
     * @param mixed                $value The value to bind.
1366
     * @param int|string|Type|null $type  The type to bind (PDO or DBAL).
1367
     *
1368
     * @return array<int, mixed> [0] => the (escaped) value, [1] => the binding type.
1369
     */
1370 753
    private function getBindingInfo($value, $type) : array
1371
    {
1372 753
        if (is_string($type)) {
1373 297
            $type = Type::getType($type);
1374
        }
1375 753
        if ($type instanceof Type) {
1376 297
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1377 297
            $bindingType = $type->getBindingType();
1378
        } else {
1379 591
            $bindingType = $type;
1380
        }
1381
1382 753
        return [$value, $bindingType];
1383
    }
1384
1385
    /**
1386
     * Resolves the parameters to a format which can be displayed.
1387
     *
1388
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1389
     *           copy/paste the code as this method may change, or be removed without prior notice.
1390
     *
1391
     * @param array<int, mixed>|array<string, mixed>                     $params
1392
     * @param array<int, int|string|Type>|array<string, int|string|Type> $types  The query parameter types.
1393
     *
1394
     * @return array<int, mixed>|array<string, mixed>
1395
     */
1396 2880
    public function resolveParams(array $params, array $types) : array
1397
    {
1398 2880
        $resolvedParams = [];
1399
1400
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1401 2880
        if (is_int(key($params))) {
1402
            // Positional parameters
1403 259
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1404 259
            $bindIndex  = 1;
1405 259
            foreach ($params as $value) {
1406 259
                $typeIndex = $bindIndex + $typeOffset;
1407 259
                if (isset($types[$typeIndex])) {
1408
                    $type                       = $types[$typeIndex];
1409
                    [$value]                    = $this->getBindingInfo($value, $type);
1410
                    $resolvedParams[$bindIndex] = $value;
1411
                } else {
1412 259
                    $resolvedParams[$bindIndex] = $value;
1413
                }
1414 259
                ++$bindIndex;
1415
            }
1416
        } else {
1417
            // Named parameters
1418 2628
            foreach ($params as $name => $value) {
1419
                if (isset($types[$name])) {
1420
                    $type                  = $types[$name];
1421
                    [$value]               = $this->getBindingInfo($value, $type);
1422
                    $resolvedParams[$name] = $value;
1423
                } else {
1424
                    $resolvedParams[$name] = $value;
1425
                }
1426
            }
1427
        }
1428
1429 2880
        return $resolvedParams;
1430
    }
1431
1432
    /**
1433
     * Creates a new instance of a SQL query builder.
1434
     */
1435
    public function createQueryBuilder() : QueryBuilder
1436
    {
1437
        return new Query\QueryBuilder($this);
1438
    }
1439
1440
    /**
1441
     * Ping the server
1442
     *
1443
     * When the server is not available the method throws a DBALException.
1444
     * It is responsibility of the developer to handle this case
1445
     * and abort the request or close the connection so that it's reestablished
1446
     * upon the next statement execution.
1447
     *
1448
     * @throws DBALException
1449
     *
1450
     * @example
1451
     *
1452
     *   try {
1453
     *      $conn->ping();
1454
     *   } catch (DBALException $e) {
1455
     *      $conn->close();
1456
     *   }
1457
     *
1458
     * It is undefined if the underlying driver attempts to reconnect
1459
     * or disconnect when the connection is not available anymore
1460
     * as long it successfully returns when a reconnect succeeded
1461
     * and throws an exception if the connection was dropped.
1462
     */
1463 27
    public function ping() : void
1464
    {
1465 27
        $connection = $this->getWrappedConnection();
1466
1467 27
        if (! $connection instanceof PingableConnection) {
1468 18
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1469
1470 18
            return;
1471
        }
1472
1473
        try {
1474 9
            $connection->ping();
1475
        } catch (DriverException $e) {
1476
            throw DBALException::driverException($this->_driver, $e);
1477
        }
1478 9
    }
1479
}
1480