Completed
Push — master ( e0a92b...6ff21f )
by Sergei
28s queued 15s
created

Connection::fetchAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 3
crap 1
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 2261
    public function getDatabase() : ?string
217
    {
218 2261
        $platform = $this->getDatabasePlatform();
219 2261
        $query    = $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
220 2261
        $database = $this->query($query)->fetchColumn();
221
222 2261
        assert(is_string($database) || $database === null);
223
224 2261
        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 10390
    public function getConfiguration() : Configuration
239
    {
240 10390
        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 8669
    public function getDatabasePlatform() : AbstractPlatform
257
    {
258 8669
        if ($this->platform === null) {
259 815
            $this->detectDatabasePlatform();
260
        }
261
262 8642
        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 10630
    public function connect() : void
279
    {
280 10630
        if ($this->isConnected) {
281 10116
            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 2508
    public function fetchAssoc(string $query, array $params = [], array $types = [])
469
    {
470 2508
        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 10363
    public function isTransactionActive() : bool
522
    {
523 10363
        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, 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 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, 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 2994
    public function fetchAll(string $query, array $params = [], array $types = []) : array
752
    {
753 2994
        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 6318
    public function executeQuery(string $query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) : ResultStatement
792
    {
793 6318
        if ($qcp !== null) {
794 297
            return $this->executeCacheQuery($query, $params, $types, $qcp);
795
        }
796
797 6318
        $connection = $this->getWrappedConnection();
798
799 6318
        $logger = $this->_config->getSQLLogger();
800 6318
        $logger->startQuery($query, $params, $types);
801
802
        try {
803 6318
            if ($params) {
804 985
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
805
806 985
                $stmt = $connection->prepare($query);
807 985
                if ($types) {
808 432
                    $this->_bindTypedValues($stmt, $params, $types);
809 432
                    $stmt->execute();
810
                } else {
811 985
                    $stmt->execute($params);
812
                }
813
            } else {
814 6250
                $stmt = $connection->query($query);
815
            }
816 170
        } catch (Throwable $ex) {
817 170
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
818
        }
819
820 6148
        $stmt->setFetchMode($this->defaultFetchMode);
821
822 6148
        $logger->stopQuery();
823
824 6148
        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 405
    public function executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp) : ResultStatement
838
    {
839 405
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
840
841 405
        if ($resultCache === null) {
842
            throw NoResultDriverConfigured::new();
843
        }
844
845 405
        $connectionParams = $this->getParams();
846 405
        unset($connectionParams['platform']);
847
848 405
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
849
850
        // fetch the row pointers entry
851 405
        $data = $resultCache->fetch($cacheKey);
852
853 405
        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 297
            if (isset($data[$realKey])) {
856 297
                $stmt = new ArrayStatement($data[$realKey]);
857
            } elseif (array_key_exists($realKey, $data)) {
858
                $stmt = new ArrayStatement([]);
859
            }
860
        }
861
862 405
        if (! isset($stmt)) {
863 324
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
864
        }
865
866 405
        $stmt->setFetchMode($this->defaultFetchMode);
867
868 405
        return $stmt;
869
    }
870
871
    /**
872
     * {@inheritDoc}
873
     */
874
    public function query(string $sql) : ResultStatement
875
    {
876
        $connection = $this->getWrappedConnection();
877
878
        $logger = $this->_config->getSQLLogger();
879
        $logger->startQuery($sql);
880
881
        try {
882
            $statement = $connection->query($sql);
883
        } catch (Throwable $ex) {
884
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
885
        }
886
887
        $statement->setFetchMode($this->defaultFetchMode);
888
889
        $logger->stopQuery();
890
891
        return $statement;
892
    }
893
894
    /**
895
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
896
     * and returns the number of affected rows.
897
     *
898
     * This method supports PDO binding types as well as DBAL mapping types.
899
     *
900 2754
     * @param string                                           $query  The SQL query.
901
     * @param array<int, mixed>|array<string, mixed>           $params The query parameters.
902 2754
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
903
     *
904 2754
     * @throws DBALException
905 2754
     */
906
    public function executeUpdate(string $query, array $params = [], array $types = []) : int
907
    {
908 2754
        $connection = $this->getWrappedConnection();
909 27
910 27
        $logger = $this->_config->getSQLLogger();
911
        $logger->startQuery($query, $params, $types);
912
913 2727
        try {
914
            if ($params) {
915 2727
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
916
917 2727
                $stmt = $connection->prepare($query);
918
919
                if ($types) {
920
                    $this->_bindTypedValues($stmt, $params, $types);
921
                    $stmt->execute();
922
                } else {
923
                    $stmt->execute($params);
924
                }
925
                $result = $stmt->rowCount();
926
            } else {
927
                $result = $connection->exec($query);
928
            }
929
        } catch (Throwable $ex) {
930
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
931
        }
932 5175
933
        $logger->stopQuery();
934 5175
935
        return $result;
936 5175
    }
937 5175
938
    /**
939
     * {@inheritDoc}
940 5175
     */
941 2669
    public function exec(string $statement) : int
942
    {
943 2669
        $connection = $this->getWrappedConnection();
944
945 2659
        $logger = $this->_config->getSQLLogger();
946 374
        $logger->startQuery($statement);
947 374
948
        try {
949 2285
            $result = $connection->exec($statement);
950
        } catch (Throwable $ex) {
951 2619
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
952
        }
953 5125
954
        $logger->stopQuery();
955 2696
956 2696
        return $result;
957
    }
958
959 4790
    /**
960
     * Returns the current transaction nesting level.
961 4790
     *
962
     * @return int The nesting level. A value of 0 means there's no active transaction.
963
     */
964
    public function getTransactionNestingLevel() : int
965
    {
966
        return $this->transactionNestingLevel;
967 2634
    }
968
969 2634
    /**
970
     * Returns the ID of the last inserted row, or the last value from a sequence object,
971 2628
     * depending on the underlying driver.
972 2628
     *
973
     * Note: This method may not return a meaningful or consistent result across different drivers,
974
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
975 2628
     * columns or sequences.
976 1993
     *
977 1993
     * @param string|null $name Name of the sequence object from which the ID should be returned.
978
     *
979
     * @return string A string representation of the last inserted ID.
980 709
     */
981
    public function lastInsertId(?string $name = null) : string
982 709
    {
983
        return $this->getWrappedConnection()->lastInsertId($name);
984
    }
985
986
    /**
987
     * Executes a function in a transaction.
988
     *
989
     * The function gets passed this Connection instance as an (optional) parameter.
990 342
     *
991
     * If an exception occurs during execution of the function or transaction commit,
992 342
     * the transaction is rolled back and the exception re-thrown.
993
     *
994
     * @param Closure $func The function to execute transactionally.
995
     *
996
     * @return mixed The value returned by $func
997
     *
998
     * @throws Throwable
999
     */
1000
    public function transactional(Closure $func)
1001
    {
1002
        $this->beginTransaction();
1003
        try {
1004
            $res = $func($this);
1005
            $this->commit();
1006
1007 100
            return $res;
1008
        } catch (Throwable $e) {
1009 100
            $this->rollBack();
1010
            throw $e;
1011
        }
1012
    }
1013
1014
    /**
1015
     * Sets if nested transactions should use savepoints.
1016
     *
1017
     * @throws ConnectionException
1018
     */
1019
    public function setNestTransactionsWithSavepoints(bool $nestTransactionsWithSavepoints) : void
1020
    {
1021
        if ($this->transactionNestingLevel > 0) {
1022
            throw MayNotAlterNestedTransactionWithSavepointsInTransaction::new();
1023
        }
1024
1025
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1026 108
            throw SavepointsNotSupported::new();
1027
        }
1028 108
1029
        $this->nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
1030 108
    }
1031 54
1032
    /**
1033 54
     * Gets if nested transactions should use savepoints.
1034 54
     */
1035 54
    public function getNestTransactionsWithSavepoints() : bool
1036 54
    {
1037
        return $this->nestTransactionsWithSavepoints;
1038
    }
1039
1040
    /**
1041
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1042
     * "savepointFormat" parameter is not set
1043
     *
1044
     * @return mixed A string with the savepoint name or false.
1045 54
     */
1046
    protected function _getNestedTransactionSavePointName()
1047 54
    {
1048 54
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1049
    }
1050
1051 27
    /**
1052
     * {@inheritDoc}
1053
     */
1054
    public function beginTransaction() : void
1055 27
    {
1056 27
        $connection = $this->getWrappedConnection();
1057
1058
        ++$this->transactionNestingLevel;
1059
1060
        $logger = $this->_config->getSQLLogger();
1061 27
1062
        if ($this->transactionNestingLevel === 1) {
1063 27
            $logger->startQuery('"START TRANSACTION"');
1064
1065
            try {
1066
                $connection->beginTransaction();
1067
            } finally {
1068
                $logger->stopQuery();
1069
            }
1070
        } elseif ($this->nestTransactionsWithSavepoints) {
1071
            $logger->startQuery('"SAVEPOINT"');
1072 27
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1073
            $logger->stopQuery();
1074 27
        }
1075
    }
1076
1077
    /**
1078
     * {@inheritDoc}
1079
     *
1080 555
     * @throws ConnectionException If the commit failed due to no active transaction or
1081
     *                                            because the transaction was marked for rollback only.
1082 555
     */
1083
    public function commit() : void
1084 555
    {
1085
        if ($this->transactionNestingLevel === 0) {
1086 555
            throw NoActiveTransaction::new();
1087
        }
1088 555
        if ($this->isRollbackOnly) {
1089 555
            throw CommitFailedRollbackOnly::new();
1090
        }
1091
1092 555
        $result = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1093 555
1094 555
        $connection = $this->getWrappedConnection();
1095
1096 108
        $logger = $this->_config->getSQLLogger();
1097 27
1098 27
        if ($this->transactionNestingLevel === 1) {
1099 27
            $logger->startQuery('"COMMIT"');
1100
1101 555
            try {
1102
                $connection->commit();
1103
            } finally {
1104
                $logger->stopQuery();
1105
            }
1106
        } elseif ($this->nestTransactionsWithSavepoints) {
1107
            $logger->startQuery('"RELEASE SAVEPOINT"');
1108
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1109 314
            $logger->stopQuery();
1110
        }
1111 314
1112 27
        --$this->transactionNestingLevel;
1113
1114 287
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1115 54
            return;
1116
        }
1117
1118 233
        $this->beginTransaction();
1119
    }
1120 233
1121
    /**
1122 233
     * Commits all current nesting transactions.
1123
     *
1124 233
     * @throws ConnectionException
1125 233
     * @throws DriverException
1126
     */
1127
    private function commitAll() : void
1128 233
    {
1129 233
        while ($this->transactionNestingLevel !== 0) {
1130 233
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1131
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1132 54
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1133 27
                $this->commit();
1134 27
1135 27
                return;
1136
            }
1137
1138 233
            $this->commit();
1139
        }
1140 233
    }
1141 206
1142
    /**
1143
     * {@inheritDoc}
1144 54
     *
1145 54
     * @throws ConnectionException If the rollback operation failed.
1146
     */
1147
    public function rollBack() : void
1148
    {
1149
        if ($this->transactionNestingLevel === 0) {
1150
            throw NoActiveTransaction::new();
1151
        }
1152
1153 27
        $connection = $this->getWrappedConnection();
1154
1155 27
        $logger = $this->_config->getSQLLogger();
1156 27
1157
        if ($this->transactionNestingLevel === 1) {
1158
            $logger->startQuery('"ROLLBACK"');
1159 27
            $this->transactionNestingLevel = 0;
1160
1161 27
            try {
1162
                $connection->rollBack();
1163
            } finally {
1164 27
                $this->isRollbackOnly = false;
1165
                $logger->stopQuery();
1166 27
1167
                if ($this->autoCommit === false) {
1168
                    $this->beginTransaction();
1169
                }
1170
            }
1171
        } elseif ($this->nestTransactionsWithSavepoints) {
1172
            $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1173 375
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1174
            --$this->transactionNestingLevel;
1175 375
            $logger->stopQuery();
1176 27
        } else {
1177
            $this->isRollbackOnly = true;
1178
            --$this->transactionNestingLevel;
1179 348
        }
1180
    }
1181 348
1182
    /**
1183 348
     * Creates a new savepoint.
1184 321
     *
1185 321
     * @param string $savepoint The name of the savepoint to create.
1186
     *
1187
     * @throws ConnectionException
1188 321
     */
1189 321
    public function createSavepoint(string $savepoint) : void
1190 321
    {
1191 321
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1192
            throw SavepointsNotSupported::new();
1193 321
        }
1194 321
1195
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1196
    }
1197 55
1198 27
    /**
1199 27
     * Releases the given savepoint.
1200 27
     *
1201 27
     * @param string $savepoint The name of the savepoint to release.
1202
     *
1203 28
     * @throws ConnectionException
1204 28
     */
1205
    public function releaseSavepoint(string $savepoint) : void
1206 348
    {
1207
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1208
            throw SavepointsNotSupported::new();
1209
        }
1210
1211
        if (! $this->platform->supportsReleaseSavepoints()) {
1212
            return;
1213
        }
1214
1215 27
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1216
    }
1217 27
1218
    /**
1219
     * Rolls back to the given savepoint.
1220
     *
1221 27
     * @param string $savepoint The name of the savepoint to rollback to.
1222 27
     *
1223
     * @throws ConnectionException
1224
     */
1225
    public function rollbackSavepoint(string $savepoint) : void
1226
    {
1227
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1228
            throw SavepointsNotSupported::new();
1229
        }
1230
1231 27
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1232
    }
1233 27
1234
    /**
1235
     * Gets the wrapped driver connection.
1236
     */
1237 27
    public function getWrappedConnection() : DriverConnection
1238 4
    {
1239
        $this->connect();
1240
1241 23
        assert($this->_conn !== null);
1242 23
1243
        return $this->_conn;
1244
    }
1245
1246
    /**
1247
     * Gets the SchemaManager that can be used to inspect or change the
1248
     * database schema through the connection.
1249
     */
1250
    public function getSchemaManager() : AbstractSchemaManager
1251 27
    {
1252
        if ($this->_schemaManager === null) {
1253 27
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1254
        }
1255
1256
        return $this->_schemaManager;
1257 27
    }
1258 27
1259
    /**
1260
     * Marks the current transaction so that the only possible
1261
     * outcome for the transaction to be rolled back.
1262
     *
1263 10502
     * @throws ConnectionException If no transaction is active.
1264
     */
1265 10502
    public function setRollbackOnly() : void
1266
    {
1267 10496
        if ($this->transactionNestingLevel === 0) {
1268
            throw NoActiveTransaction::new();
1269
        }
1270
        $this->isRollbackOnly = true;
1271
    }
1272
1273
    /**
1274 5286
     * Checks whether the current transaction is marked for rollback only.
1275
     *
1276 5286
     * @throws ConnectionException If no transaction is active.
1277 349
     */
1278
    public function isRollbackOnly() : bool
1279
    {
1280 5286
        if ($this->transactionNestingLevel === 0) {
1281
            throw NoActiveTransaction::new();
1282
        }
1283
1284
        return $this->isRollbackOnly;
1285
    }
1286
1287
    /**
1288
     * Converts a given value to its database representation according to the conversion
1289 54
     * rules of a specific DBAL mapping type.
1290
     *
1291 54
     * @param mixed  $value The value to convert.
1292 27
     * @param string $type  The name of the DBAL mapping type.
1293
     *
1294 27
     * @return mixed The converted value.
1295 27
     */
1296
    public function convertToDatabaseValue($value, string $type)
1297
    {
1298
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1299
    }
1300
1301
    /**
1302 81
     * Converts a given value to its PHP representation according to the conversion
1303
     * rules of a specific DBAL mapping type.
1304 81
     *
1305 27
     * @param mixed  $value The value to convert.
1306
     * @param string $type  The name of the DBAL mapping type.
1307
     *
1308 54
     * @return mixed The converted type.
1309
     */
1310
    public function convertToPHPValue($value, string $type)
1311
    {
1312
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1313
    }
1314
1315
    /**
1316
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1317
     * or DBAL mapping type, to a given statement.
1318
     *
1319
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1320
     *           raw PDOStatement instances.
1321
     *
1322
     * @param DriverStatement                                  $stmt   The statement to bind the values to.
1323
     * @param array<int, mixed>|array<string, mixed>           $params The map/list of named/positional parameters.
1324
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1325
     */
1326
    private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
1327
    {
1328
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1329
        if (is_int(key($params))) {
1330
            // Positional parameters
1331
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1332
            $bindIndex  = 1;
1333
            foreach ($params as $value) {
1334
                $typeIndex = $bindIndex + $typeOffset;
1335
                if (isset($types[$typeIndex])) {
1336
                    $type                  = $types[$typeIndex];
1337
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1338
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1339
                } else {
1340
                    $stmt->bindValue($bindIndex, $value);
1341
                }
1342
                ++$bindIndex;
1343
            }
1344
        } else {
1345
            // Named parameters
1346
            foreach ($params as $name => $value) {
1347
                if (isset($types[$name])) {
1348
                    $type                  = $types[$name];
1349
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1350 753
                    $stmt->bindValue($name, $value, $bindingType);
1351
                } else {
1352
                    $stmt->bindValue($name, $value);
1353 753
                }
1354
            }
1355 753
        }
1356 753
    }
1357 753
1358 753
    /**
1359 753
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1360 753
     *
1361 753
     * @param mixed           $value The value to bind.
1362 753
     * @param int|string|null $type  The type to bind (PDO or DBAL).
1363
     *
1364 25
     * @return array<int, mixed> [0] => the (escaped) value, [1] => the binding type.
1365
     */
1366 753
    private function getBindingInfo($value, $type) : array
1367
    {
1368
        if (is_string($type)) {
1369
            $type = Type::getType($type);
1370
        }
1371
        if ($type instanceof Type) {
1372
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1373
            $bindingType = $type->getBindingType();
1374
        } else {
1375
            $bindingType = $type;
1376
        }
1377
1378
        return [$value, $bindingType];
1379
    }
1380 753
1381
    /**
1382
     * Resolves the parameters to a format which can be displayed.
1383
     *
1384
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1385
     *           copy/paste the code as this method may change, or be removed without prior notice.
1386
     *
1387
     * @param array<int, mixed>|array<string, mixed>           $params
1388
     * @param array<int, int|string>|array<string, int|string> $types  The query parameter types.
1389
     *
1390 753
     * @return array<int, mixed>|array<string, mixed>
1391
     */
1392 753
    public function resolveParams(array $params, array $types) : array
1393 297
    {
1394
        $resolvedParams = [];
1395 753
1396 297
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1397 297
        if (is_int(key($params))) {
1398
            // Positional parameters
1399 591
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1400
            $bindIndex  = 1;
1401
            foreach ($params as $value) {
1402 753
                $typeIndex = $bindIndex + $typeOffset;
1403
                if (isset($types[$typeIndex])) {
1404
                    $type                       = $types[$typeIndex];
1405
                    [$value]                    = $this->getBindingInfo($value, $type);
1406
                    $resolvedParams[$bindIndex] = $value;
1407
                } else {
1408
                    $resolvedParams[$bindIndex] = $value;
1409
                }
1410
                ++$bindIndex;
1411
            }
1412
        } else {
1413
            // Named parameters
1414
            foreach ($params as $name => $value) {
1415
                if (isset($types[$name])) {
1416 2881
                    $type                  = $types[$name];
1417
                    [$value]               = $this->getBindingInfo($value, $type);
1418 2881
                    $resolvedParams[$name] = $value;
1419
                } else {
1420
                    $resolvedParams[$name] = $value;
1421 2881
                }
1422
            }
1423 259
        }
1424 259
1425 259
        return $resolvedParams;
1426 259
    }
1427 259
1428
    /**
1429
     * Creates a new instance of a SQL query builder.
1430
     */
1431
    public function createQueryBuilder() : QueryBuilder
1432 259
    {
1433
        return new Query\QueryBuilder($this);
1434 259
    }
1435
1436
    /**
1437
     * Ping the server
1438 2629
     *
1439
     * When the server is not available the method throws a DBALException.
1440
     * It is responsibility of the developer to handle this case
1441
     * and abort the request or close the connection so that it's reestablished
1442
     * upon the next statement execution.
1443
     *
1444
     * @throws DBALException
1445
     *
1446
     * @example
1447
     *
1448
     *   try {
1449 2881
     *      $conn->ping();
1450
     *   } catch (DBALException $e) {
1451
     *      $conn->close();
1452
     *   }
1453
     *
1454
     * It is undefined if the underlying driver attempts to reconnect
1455
     * or disconnect when the connection is not available anymore
1456
     * as long it successfully returns when a reconnect succeeded
1457
     * and throws an exception if the connection was dropped.
1458
     */
1459
    public function ping() : void
1460
    {
1461
        $connection = $this->getWrappedConnection();
1462
1463
        if (! $connection instanceof PingableConnection) {
1464
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1465
1466
            return;
1467
        }
1468
1469
        try {
1470
            $connection->ping();
1471
        } catch (DriverException $e) {
1472
            throw DBALException::driverException($this->_driver, $e);
1473
        }
1474
    }
1475
}
1476