Failed Conditions
Push — master ( 30b923...92920e )
by Marco
19s queued 13s
created

Connection::executeCacheQuery()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 29
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.288

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 29
ccs 12
cts 15
cp 0.8
rs 9.2222
c 0
b 0
f 0
cc 6
nc 9
nop 4
crap 6.288
1
<?php
2
3
namespace Doctrine\DBAL;
4
5
use Closure;
6
use Doctrine\Common\EventManager;
7
use Doctrine\DBAL\Cache\ArrayStatement;
8
use Doctrine\DBAL\Cache\CacheException;
9
use Doctrine\DBAL\Cache\QueryCacheProfile;
10
use Doctrine\DBAL\Cache\ResultCacheStatement;
11
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12
use Doctrine\DBAL\Driver\PingableConnection;
13
use Doctrine\DBAL\Driver\ResultStatement;
14
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
15
use Doctrine\DBAL\Driver\Statement as DriverStatement;
16
use Doctrine\DBAL\Exception\InvalidArgumentException;
17
use Doctrine\DBAL\Platforms\AbstractPlatform;
18
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
19
use Doctrine\DBAL\Query\QueryBuilder;
20
use Doctrine\DBAL\Schema\AbstractSchemaManager;
21
use Doctrine\DBAL\Types\Type;
22
use Exception;
23
use Throwable;
24
use function array_key_exists;
25
use function assert;
26
use function func_get_args;
27
use function implode;
28
use function is_int;
29
use function is_string;
30
use function key;
31
32
/**
33
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
34
 * events, transaction isolation levels, configuration, emulated transaction nesting,
35
 * lazy connecting and more.
36
 */
37
class Connection implements DriverConnection
38
{
39
    /**
40
     * Constant for transaction isolation level READ UNCOMMITTED.
41
     *
42
     * @deprecated Use TransactionIsolationLevel::READ_UNCOMMITTED.
43
     */
44
    public const TRANSACTION_READ_UNCOMMITTED = TransactionIsolationLevel::READ_UNCOMMITTED;
45
46
    /**
47
     * Constant for transaction isolation level READ COMMITTED.
48
     *
49
     * @deprecated Use TransactionIsolationLevel::READ_COMMITTED.
50
     */
51
    public const TRANSACTION_READ_COMMITTED = TransactionIsolationLevel::READ_COMMITTED;
52
53
    /**
54
     * Constant for transaction isolation level REPEATABLE READ.
55
     *
56
     * @deprecated Use TransactionIsolationLevel::REPEATABLE_READ.
57
     */
58
    public const TRANSACTION_REPEATABLE_READ = TransactionIsolationLevel::REPEATABLE_READ;
59
60
    /**
61
     * Constant for transaction isolation level SERIALIZABLE.
62
     *
63
     * @deprecated Use TransactionIsolationLevel::SERIALIZABLE.
64
     */
65
    public const TRANSACTION_SERIALIZABLE = TransactionIsolationLevel::SERIALIZABLE;
66
67
    /**
68
     * Represents an array of ints to be expanded by Doctrine SQL parsing.
69
     */
70
    public const PARAM_INT_ARRAY = ParameterType::INTEGER + self::ARRAY_PARAM_OFFSET;
71
72
    /**
73
     * Represents an array of strings to be expanded by Doctrine SQL parsing.
74
     */
75
    public const PARAM_STR_ARRAY = ParameterType::STRING + self::ARRAY_PARAM_OFFSET;
76
77
    /**
78
     * Offset by which PARAM_* constants are detected as arrays of the param type.
79
     */
80
    public const ARRAY_PARAM_OFFSET = 100;
81
82
    /**
83
     * The wrapped driver connection.
84
     *
85
     * @var \Doctrine\DBAL\Driver\Connection|null
86
     */
87
    protected $_conn;
88
89
    /** @var Configuration */
90
    protected $_config;
91
92
    /** @var EventManager */
93
    protected $_eventManager;
94
95
    /** @var ExpressionBuilder */
96
    protected $_expr;
97
98
    /**
99
     * Whether or not a connection has been established.
100
     *
101
     * @var bool
102
     */
103
    private $isConnected = false;
104
105
    /**
106
     * The current auto-commit mode of this connection.
107
     *
108
     * @var bool
109
     */
110
    private $autoCommit = true;
111
112
    /**
113
     * The transaction nesting level.
114
     *
115
     * @var int
116
     */
117
    private $transactionNestingLevel = 0;
118
119
    /**
120
     * The currently active transaction isolation level.
121
     *
122
     * @var int
123
     */
124
    private $transactionIsolationLevel;
125
126
    /**
127
     * If nested transactions should use savepoints.
128
     *
129
     * @var bool
130
     */
131
    private $nestTransactionsWithSavepoints = false;
132
133
    /**
134
     * The parameters used during creation of the Connection instance.
135
     *
136
     * @var mixed[]
137
     */
138
    private $params = [];
139
140
    /**
141
     * The DatabasePlatform object that provides information about the
142
     * database platform used by the connection.
143
     *
144
     * @var AbstractPlatform
145
     */
146
    private $platform;
147
148
    /**
149
     * The schema manager.
150
     *
151
     * @var AbstractSchemaManager|null
152
     */
153
    protected $_schemaManager;
154
155
    /**
156
     * The used DBAL driver.
157
     *
158
     * @var Driver
159
     */
160
    protected $_driver;
161
162
    /**
163
     * Flag that indicates whether the current transaction is marked for rollback only.
164
     *
165
     * @var bool
166
     */
167
    private $isRollbackOnly = false;
168
169
    /** @var int */
170
    protected $defaultFetchMode = FetchMode::ASSOCIATIVE;
171
172
    /**
173
     * Initializes a new instance of the Connection class.
174
     *
175
     * @param mixed[]            $params       The connection parameters.
176
     * @param Driver             $driver       The driver to use.
177
     * @param Configuration|null $config       The configuration, optional.
178
     * @param EventManager|null  $eventManager The event manager, optional.
179
     *
180
     * @throws DBALException
181
     */
182 3673
    public function __construct(
183
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188 3673
        $this->_driver = $driver;
189 3673
        $this->params  = $params;
190
191 3673
        if (isset($params['pdo'])) {
192 324
            $this->_conn       = $params['pdo'];
193 324
            $this->isConnected = true;
194 324
            unset($this->params['pdo']);
195
        }
196
197 3673
        if (isset($params['platform'])) {
198 756
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199 27
                throw DBALException::invalidPlatformType($params['platform']);
200
            }
201
202 729
            $this->platform = $params['platform'];
203 729
            unset($this->params['platform']);
204
        }
205
206
        // Create default config and event manager if none given
207 3673
        if (! $config) {
208 810
            $config = new Configuration();
209
        }
210
211 3673
        if (! $eventManager) {
212 810
            $eventManager = new EventManager();
213
        }
214
215 3673
        $this->_config       = $config;
216 3673
        $this->_eventManager = $eventManager;
217
218 3673
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
219
220 3673
        $this->autoCommit = $config->getAutoCommit();
221 3673
    }
222
223
    /**
224
     * Gets the parameters used during instantiation.
225
     *
226
     * @return mixed[]
227
     */
228 3427
    public function getParams()
229
    {
230 3427
        return $this->params;
231
    }
232
233
    /**
234
     * Gets the name of the database this Connection is connected to.
235
     *
236
     * @return string
237
     */
238 1804
    public function getDatabase()
239
    {
240 1804
        return $this->_driver->getDatabase($this);
241
    }
242
243
    /**
244
     * Gets the hostname of the currently connected database.
245
     *
246
     * @return string|null
247
     */
248 27
    public function getHost()
249
    {
250 27
        return $this->params['host'] ?? null;
251
    }
252
253
    /**
254
     * Gets the port of the currently connected database.
255
     *
256
     * @return mixed
257
     */
258 27
    public function getPort()
259
    {
260 27
        return $this->params['port'] ?? null;
261
    }
262
263
    /**
264
     * Gets the username used by this connection.
265
     *
266
     * @return string|null
267
     */
268 82
    public function getUsername()
269
    {
270 82
        return $this->params['user'] ?? null;
271
    }
272
273
    /**
274
     * Gets the password used by this connection.
275
     *
276
     * @return string|null
277
     */
278 27
    public function getPassword()
279
    {
280 27
        return $this->params['password'] ?? null;
281
    }
282
283
    /**
284
     * Gets the DBAL driver instance.
285
     *
286
     * @return Driver
287
     */
288 1695
    public function getDriver()
289
    {
290 1695
        return $this->_driver;
291
    }
292
293
    /**
294
     * Gets the Configuration used by the Connection.
295
     *
296
     * @return Configuration
297
     */
298 8156
    public function getConfiguration()
299
    {
300 8156
        return $this->_config;
301
    }
302
303
    /**
304
     * Gets the EventManager used by the Connection.
305
     *
306
     * @return EventManager
307
     */
308 386
    public function getEventManager()
309
    {
310 386
        return $this->_eventManager;
311
    }
312
313
    /**
314
     * Gets the DatabasePlatform for the connection.
315
     *
316
     * @return AbstractPlatform
317
     *
318
     * @throws DBALException
319
     */
320 7011
    public function getDatabasePlatform()
321
    {
322 7011
        if ($this->platform === null) {
323 990
            $this->detectDatabasePlatform();
324
        }
325
326 6984
        return $this->platform;
327
    }
328
329
    /**
330
     * Gets the ExpressionBuilder for the connection.
331
     *
332
     * @return ExpressionBuilder
333
     */
334
    public function getExpressionBuilder()
335
    {
336
        return $this->_expr;
337
    }
338
339
    /**
340
     * Establishes the connection with the database.
341
     *
342
     * @return bool TRUE if the connection was successfully established, FALSE if
343
     *              the connection is already open.
344
     */
345 8314
    public function connect()
346
    {
347 8314
        if ($this->isConnected) {
348 7982
            return false;
349
        }
350
351 1253
        $driverOptions = $this->params['driverOptions'] ?? [];
352 1253
        $user          = $this->params['user'] ?? null;
353 1253
        $password      = $this->params['password'] ?? null;
354
355 1253
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
356 1163
        $this->isConnected = true;
357
358 1163
        if ($this->autoCommit === false) {
359 81
            $this->beginTransaction();
360
        }
361
362 1163
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
363 75
            $eventArgs = new Event\ConnectionEventArgs($this);
364 75
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
365
        }
366
367 1163
        return true;
368
    }
369
370
    /**
371
     * Detects and sets the database platform.
372
     *
373
     * Evaluates custom platform class and version in order to set the correct platform.
374
     *
375
     * @throws DBALException If an invalid platform was specified for this connection.
376
     */
377 990
    private function detectDatabasePlatform()
378
    {
379 990
        $version = $this->getDatabasePlatformVersion();
380
381 907
        if ($version !== null) {
382 650
            assert($this->_driver instanceof VersionAwarePlatformDriver);
383
384 650
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
385
        } else {
386 257
            $this->platform = $this->_driver->getDatabasePlatform();
387
        }
388
389 907
        $this->platform->setEventManager($this->_eventManager);
390 907
    }
391
392
    /**
393
     * Returns the version of the related platform if applicable.
394
     *
395
     * Returns null if either the driver is not capable to create version
396
     * specific platform instances, no explicit server version was specified
397
     * or the underlying driver connection cannot determine the platform
398
     * version without having to query it (performance reasons).
399
     *
400
     * @return string|null
401
     *
402
     * @throws Exception
403
     */
404 990
    private function getDatabasePlatformVersion()
405
    {
406
        // Driver does not support version specific platforms.
407 990
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
408 257
            return null;
409
        }
410
411
        // Explicit platform version requested (supersedes auto-detection).
412 733
        if (isset($this->params['serverVersion'])) {
413
            return $this->params['serverVersion'];
414
        }
415
416
        // If not connected, we need to connect now to determine the platform version.
417 733
        if ($this->_conn === null) {
418
            try {
419 687
                $this->connect();
420 106
            } catch (Throwable $originalException) {
421 106
                if (empty($this->params['dbname'])) {
422
                    throw $originalException;
423
                }
424
425
                // The database to connect to might not yet exist.
426
                // Retry detection without database name connection parameter.
427 106
                $databaseName           = $this->params['dbname'];
428 106
                $this->params['dbname'] = null;
429
430
                try {
431 106
                    $this->connect();
432 83
                } catch (Throwable $fallbackException) {
433
                    // Either the platform does not support database-less connections
434
                    // or something else went wrong.
435
                    // Reset connection parameters and rethrow the original exception.
436 83
                    $this->params['dbname'] = $databaseName;
437
438 83
                    throw $originalException;
439
                }
440
441
                // Reset connection parameters.
442 23
                $this->params['dbname'] = $databaseName;
443 23
                $serverVersion          = $this->getServerVersion();
444
445
                // Close "temporary" connection to allow connecting to the real database again.
446 23
                $this->close();
447
448 23
                return $serverVersion;
449
            }
450
        }
451
452 650
        return $this->getServerVersion();
453
    }
454
455
    /**
456
     * Returns the database server version if the underlying driver supports it.
457
     *
458
     * @return string|null
459
     */
460 650
    private function getServerVersion()
461
    {
462 650
        $connection = $this->getWrappedConnection();
463
464
        // Automatic platform version detection.
465 650
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
466 650
            return $connection->getServerVersion();
467
        }
468
469
        // Unable to detect platform version.
470
        return null;
471
    }
472
473
    /**
474
     * Returns the current auto-commit mode for this connection.
475
     *
476
     * @see    setAutoCommit
477
     *
478
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
479
     */
480 54
    public function isAutoCommit()
481
    {
482 54
        return $this->autoCommit === true;
483
    }
484
485
    /**
486
     * Sets auto-commit mode for this connection.
487
     *
488
     * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
489
     * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
490
     * the method commit or the method rollback. By default, new connections are in auto-commit mode.
491
     *
492
     * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
493
     * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
494
     *
495
     * @see   isAutoCommit
496
     *
497
     * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
498
     */
499 135
    public function setAutoCommit($autoCommit)
500
    {
501 135
        $autoCommit = (bool) $autoCommit;
502
503
        // Mode not changed, no-op.
504 135
        if ($autoCommit === $this->autoCommit) {
505 27
            return;
506
        }
507
508 135
        $this->autoCommit = $autoCommit;
509
510
        // Commit all currently active transactions if any when switching auto-commit mode.
511 135
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
512 108
            return;
513
        }
514
515 27
        $this->commitAll();
516 27
    }
517
518
    /**
519
     * Sets the fetch mode.
520
     *
521
     * @param int $fetchMode
522
     *
523
     * @return void
524
     */
525 27
    public function setFetchMode($fetchMode)
526
    {
527 27
        $this->defaultFetchMode = $fetchMode;
528 27
    }
529
530
    /**
531
     * Prepares and executes an SQL query and returns the first row of the result
532
     * as an associative array.
533
     *
534
     * @param string         $statement The SQL query.
535
     * @param mixed[]        $params    The query parameters.
536
     * @param int[]|string[] $types     The query parameter types.
537
     *
538
     * @return mixed[]|false False is returned if no rows are found.
539
     *
540
     * @throws DBALException
541
     */
542 1777
    public function fetchAssoc($statement, array $params = [], array $types = [])
543
    {
544 1777
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
545
    }
546
547
    /**
548
     * Prepares and executes an SQL query and returns the first row of the result
549
     * as a numerically indexed array.
550
     *
551
     * @param string         $statement The SQL query to be executed.
552
     * @param mixed[]        $params    The prepared statement params.
553
     * @param int[]|string[] $types     The query parameter types.
554
     *
555
     * @return mixed[]|false False is returned if no rows are found.
556
     */
557 100
    public function fetchArray($statement, array $params = [], array $types = [])
558
    {
559 100
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
560
    }
561
562
    /**
563
     * Prepares and executes an SQL query and returns the value of a single column
564
     * of the first row of the result.
565
     *
566
     * @param string         $statement The SQL query to be executed.
567
     * @param mixed[]        $params    The prepared statement params.
568
     * @param int            $column    The 0-indexed column number to retrieve.
569
     * @param int[]|string[] $types     The query parameter types.
570
     *
571
     * @return mixed|false False is returned if no rows are found.
572
     *
573
     * @throws DBALException
574
     */
575 1029
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
576
    {
577 1029
        return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
578
    }
579
580
    /**
581
     * Whether an actual connection to the database is established.
582
     *
583
     * @return bool
584
     */
585 105
    public function isConnected()
586
    {
587 105
        return $this->isConnected;
588
    }
589
590
    /**
591
     * Checks whether a transaction is currently active.
592
     *
593
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
594
     */
595 8129
    public function isTransactionActive()
596
    {
597 8129
        return $this->transactionNestingLevel > 0;
598
    }
599
600
    /**
601
     * Adds identifier condition to the query components
602
     *
603
     * @param mixed[]  $identifier Map of key columns to their values
604
     * @param string[] $columns    Column names
605
     * @param mixed[]  $values     Column values
606
     * @param string[] $conditions Key conditions
607
     *
608
     * @throws DBALException
609
     */
610 421
    private function addIdentifierCondition(
611
        array $identifier,
612
        array &$columns,
613
        array &$values,
614
        array &$conditions
615
    ) : void {
616 421
        $platform = $this->getDatabasePlatform();
617
618 421
        foreach ($identifier as $columnName => $value) {
619 421
            if ($value === null) {
620 108
                $conditions[] = $platform->getIsNullExpression($columnName);
621 108
                continue;
622
            }
623
624 367
            $columns[]    = $columnName;
625 367
            $values[]     = $value;
626 367
            $conditions[] = $columnName . ' = ?';
627
        }
628 421
    }
629
630
    /**
631
     * Executes an SQL DELETE statement on a table.
632
     *
633
     * Table expression and columns are not escaped and are not safe for user-input.
634
     *
635
     * @param string         $tableExpression The expression of the table on which to delete.
636
     * @param mixed[]        $identifier      The deletion criteria. An associative array containing column-value pairs.
637
     * @param int[]|string[] $types           The types of identifiers.
638
     *
639
     * @return int The number of affected rows.
640
     *
641
     * @throws DBALException
642
     * @throws InvalidArgumentException
643
     */
644 185
    public function delete($tableExpression, array $identifier, array $types = [])
645
    {
646 185
        if (empty($identifier)) {
647 27
            throw InvalidArgumentException::fromEmptyCriteria();
648
        }
649
650 158
        $columns = $values = $conditions = [];
651
652 158
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
653
654 158
        return $this->executeUpdate(
655 158
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
656 158
            $values,
657 158
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
658
        );
659
    }
660
661
    /**
662
     * Closes the connection.
663
     *
664
     * @return void
665
     */
666 642
    public function close()
667
    {
668 642
        $this->_conn = null;
669
670 642
        $this->isConnected = false;
671 642
    }
672
673
    /**
674
     * Sets the transaction isolation level.
675
     *
676
     * @param int $level The level to set.
677
     *
678
     * @return int
679
     */
680
    public function setTransactionIsolation($level)
681
    {
682
        $this->transactionIsolationLevel = $level;
683
684
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
685
    }
686
687
    /**
688
     * Gets the currently active transaction isolation level.
689
     *
690
     * @return int The current transaction isolation level.
691
     */
692
    public function getTransactionIsolation()
693
    {
694
        if ($this->transactionIsolationLevel === null) {
695
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
696
        }
697
698
        return $this->transactionIsolationLevel;
699
    }
700
701
    /**
702
     * Executes an SQL UPDATE statement on a table.
703
     *
704
     * Table expression and columns are not escaped and are not safe for user-input.
705
     *
706
     * @param string         $tableExpression The expression of the table to update quoted or unquoted.
707
     * @param mixed[]        $data            An associative array containing column-value pairs.
708
     * @param mixed[]        $identifier      The update criteria. An associative array containing column-value pairs.
709
     * @param int[]|string[] $types           Types of the merged $data and $identifier arrays in that order.
710
     *
711
     * @return int The number of affected rows.
712
     *
713
     * @throws DBALException
714
     */
715 263
    public function update($tableExpression, array $data, array $identifier, array $types = [])
716
    {
717 263
        $columns = $values = $conditions = $set = [];
718
719 263
        foreach ($data as $columnName => $value) {
720 263
            $columns[] = $columnName;
721 263
            $values[]  = $value;
722 263
            $set[]     = $columnName . ' = ?';
723
        }
724
725 263
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
726
727 263
        if (is_string(key($types))) {
728 135
            $types = $this->extractTypeValues($columns, $types);
729
        }
730
731 263
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
732 263
                . ' WHERE ' . implode(' AND ', $conditions);
733
734 263
        return $this->executeUpdate($sql, $values, $types);
735
    }
736
737
    /**
738
     * Inserts a table row with specified data.
739
     *
740
     * Table expression and columns are not escaped and are not safe for user-input.
741
     *
742
     * @param string         $tableExpression The expression of the table to insert data into, quoted or unquoted.
743
     * @param mixed[]        $data            An associative array containing column-value pairs.
744
     * @param int[]|string[] $types           Types of the inserted data.
745
     *
746
     * @return int The number of affected rows.
747
     *
748
     * @throws DBALException
749
     */
750 2419
    public function insert($tableExpression, array $data, array $types = [])
751
    {
752 2419
        if (empty($data)) {
753 27
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
754
        }
755
756 2392
        $columns = [];
757 2392
        $values  = [];
758 2392
        $set     = [];
759
760 2392
        foreach ($data as $columnName => $value) {
761 2392
            $columns[] = $columnName;
762 2392
            $values[]  = $value;
763 2392
            $set[]     = '?';
764
        }
765
766 2392
        return $this->executeUpdate(
767 2392
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
768 2392
            ' VALUES (' . implode(', ', $set) . ')',
769 2392
            $values,
770 2392
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
771
        );
772
    }
773
774
    /**
775
     * Extract ordered type list from an ordered column list and type map.
776
     *
777
     * @param int[]|string[] $columnList
778
     * @param int[]|string[] $types
779
     *
780
     * @return int[]|string[]
781
     */
782 243
    private function extractTypeValues(array $columnList, array $types)
783
    {
784 243
        $typeValues = [];
785
786 243
        foreach ($columnList as $columnIndex => $columnName) {
787 243
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
788
        }
789
790 243
        return $typeValues;
791
    }
792
793
    /**
794
     * Quotes a string so it can be safely used as a table or column name, even if
795
     * it is a reserved name.
796
     *
797
     * Delimiting style depends on the underlying database platform that is being used.
798
     *
799
     * NOTE: Just because you CAN use quoted identifiers does not mean
800
     * you SHOULD use them. In general, they end up causing way more
801
     * problems than they solve.
802
     *
803
     * @param string $str The name to be quoted.
804
     *
805
     * @return string The quoted name.
806
     */
807 27
    public function quoteIdentifier($str)
808
    {
809 27
        return $this->getDatabasePlatform()->quoteIdentifier($str);
810
    }
811
812
    /**
813
     * {@inheritDoc}
814
     */
815 256
    public function quote($input, $type = null)
816
    {
817 256
        $connection = $this->getWrappedConnection();
818
819 256
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
820
821 256
        return $connection->quote($value, $bindingType);
822
    }
823
824
    /**
825
     * Prepares and executes an SQL query and returns the result as an associative array.
826
     *
827
     * @param string         $sql    The SQL query.
828
     * @param mixed[]        $params The query parameters.
829
     * @param int[]|string[] $types  The query parameter types.
830
     *
831
     * @return mixed[]
832
     */
833 2850
    public function fetchAll($sql, array $params = [], $types = [])
834
    {
835 2850
        return $this->executeQuery($sql, $params, $types)->fetchAll();
836
    }
837
838
    /**
839
     * Prepares an SQL statement.
840
     *
841
     * @param string $statement The SQL statement to prepare.
842
     *
843
     * @return DriverStatement The prepared statement.
844
     *
845
     * @throws DBALException
846
     */
847 1162
    public function prepare($statement)
848
    {
849
        try {
850 1162
            $stmt = new Statement($statement, $this);
851 27
        } catch (Throwable $ex) {
852 27
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
853
        }
854
855 1135
        $stmt->setFetchMode($this->defaultFetchMode);
856
857 1135
        return $stmt;
858
    }
859
860
    /**
861
     * Executes an, optionally parametrized, SQL query.
862
     *
863
     * If the query is parametrized, a prepared statement is used.
864
     * If an SQLLogger is configured, the execution is logged.
865
     *
866
     * @param string                 $query  The SQL query to execute.
867
     * @param mixed[]                $params The parameters to bind to the query, if any.
868
     * @param int[]|string[]         $types  The types the previous parameters are in.
869
     * @param QueryCacheProfile|null $qcp    The query cache profile, optional.
870
     *
871
     * @return ResultStatement The executed statement.
872
     *
873
     * @throws DBALException
874
     */
875 5651
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
876
    {
877 5651
        if ($qcp !== null) {
878 297
            return $this->executeCacheQuery($query, $params, $types, $qcp);
879
        }
880
881 5651
        $connection = $this->getWrappedConnection();
882
883 5651
        $logger = $this->_config->getSQLLogger();
884 5651
        if ($logger) {
885 5474
            $logger->startQuery($query, $params, $types);
886
        }
887
888
        try {
889 5651
            if ($params) {
890 1021
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
891
892 1021
                $stmt = $connection->prepare($query);
893 1021
                if ($types) {
894 431
                    $this->_bindTypedValues($stmt, $params, $types);
895 431
                    $stmt->execute();
896
                } else {
897 1021
                    $stmt->execute($params);
898
                }
899
            } else {
900 5575
                $stmt = $connection->query($query);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\DBAL\Driver\Connection::query() has too many arguments starting with $query. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

900
                /** @scrutinizer ignore-call */ 
901
                $stmt = $connection->query($query);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
901
            }
902 175
        } catch (Throwable $ex) {
903 175
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
904
        }
905
906 5476
        $stmt->setFetchMode($this->defaultFetchMode);
907
908 5476
        if ($logger) {
909 5326
            $logger->stopQuery();
910
        }
911
912 5476
        return $stmt;
913
    }
914
915
    /**
916
     * Executes a caching query.
917
     *
918
     * @param string            $query  The SQL query to execute.
919
     * @param mixed[]           $params The parameters to bind to the query, if any.
920
     * @param int[]|string[]    $types  The types the previous parameters are in.
921
     * @param QueryCacheProfile $qcp    The query cache profile.
922
     *
923
     * @return ResultStatement
924
     *
925
     * @throws CacheException
926
     */
927 351
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
928
    {
929 351
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
930
931 351
        if ($resultCache === null) {
932
            throw CacheException::noResultDriverConfigured();
933
        }
934
935 351
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $this->getParams());
936
937
        // fetch the row pointers entry
938 351
        $data = $resultCache->fetch($cacheKey);
939
940 351
        if ($data !== false) {
941
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
942 243
            if (isset($data[$realKey])) {
943 243
                $stmt = new ArrayStatement($data[$realKey]);
944
            } elseif (array_key_exists($realKey, $data)) {
945
                $stmt = new ArrayStatement([]);
946
            }
947
        }
948
949 351
        if (! isset($stmt)) {
950 297
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
951
        }
952
953 351
        $stmt->setFetchMode($this->defaultFetchMode);
954
955 351
        return $stmt;
956
    }
957
958
    /**
959
     * Executes an, optionally parametrized, SQL query and returns the result,
960
     * applying a given projection/transformation function on each row of the result.
961
     *
962
     * @param string  $query    The SQL query to execute.
963
     * @param mixed[] $params   The parameters, if any.
964
     * @param Closure $function The transformation function that is applied on each row.
965
     *                           The function receives a single parameter, an array, that
966
     *                           represents a row of the result set.
967
     *
968
     * @return mixed[] The projected result of the query.
969
     */
970
    public function project($query, array $params, Closure $function)
971
    {
972
        $result = [];
973
        $stmt   = $this->executeQuery($query, $params);
974
975
        while ($row = $stmt->fetch()) {
976
            $result[] = $function($row);
977
        }
978
979
        $stmt->closeCursor();
980
981
        return $result;
982
    }
983
984
    /**
985
     * Executes an SQL statement, returning a result set as a Statement object.
986
     *
987
     * @return \Doctrine\DBAL\Driver\Statement
988
     *
989
     * @throws DBALException
990
     */
991 541
    public function query()
992
    {
993 541
        $connection = $this->getWrappedConnection();
994
995 541
        $args = func_get_args();
996
997 541
        $logger = $this->_config->getSQLLogger();
998 541
        if ($logger) {
999 514
            $logger->startQuery($args[0]);
1000
        }
1001
1002
        try {
1003 541
            $statement = $connection->query(...$args);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\DBAL\Driver\Connection::query() has too many arguments starting with $args. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1003
            /** @scrutinizer ignore-call */ 
1004
            $statement = $connection->query(...$args);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
1004 27
        } catch (Throwable $ex) {
1005 27
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1006
        }
1007
1008 514
        $statement->setFetchMode($this->defaultFetchMode);
1009
1010 514
        if ($logger) {
1011 514
            $logger->stopQuery();
1012
        }
1013
1014 514
        return $statement;
1015
    }
1016
1017
    /**
1018
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
1019
     * and returns the number of affected rows.
1020
     *
1021
     * This method supports PDO binding types as well as DBAL mapping types.
1022
     *
1023
     * @param string         $query  The SQL query.
1024
     * @param mixed[]        $params The query parameters.
1025
     * @param int[]|string[] $types  The parameter types.
1026
     *
1027
     * @return int The number of affected rows.
1028
     *
1029
     * @throws DBALException
1030
     */
1031 5226
    public function executeUpdate($query, array $params = [], array $types = [])
1032
    {
1033 5226
        $connection = $this->getWrappedConnection();
1034
1035 5226
        $logger = $this->_config->getSQLLogger();
1036 5226
        if ($logger) {
1037 5091
            $logger->startQuery($query, $params, $types);
1038
        }
1039
1040
        try {
1041 5226
            if ($params) {
1042 2587
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1043
1044 2587
                $stmt = $connection->prepare($query);
1045
1046 2579
                if ($types) {
1047 403
                    $this->_bindTypedValues($stmt, $params, $types);
1048 403
                    $stmt->execute();
1049
                } else {
1050 2176
                    $stmt->execute($params);
1051
                }
1052 2539
                $result = $stmt->rowCount();
1053
            } else {
1054 5178
                $result = $connection->exec($query);
1055
            }
1056 3055
        } catch (Throwable $ex) {
1057 3055
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
1058
        }
1059
1060 4763
        if ($logger) {
1061 4653
            $logger->stopQuery();
1062
        }
1063
1064 4763
        return $result;
1065
    }
1066
1067
    /**
1068
     * Executes an SQL statement and return the number of affected rows.
1069
     *
1070
     * @param string $statement
1071
     *
1072
     * @return int The number of affected rows.
1073
     *
1074
     * @throws DBALException
1075
     */
1076 2647
    public function exec($statement)
1077
    {
1078 2647
        $connection = $this->getWrappedConnection();
1079
1080 2640
        $logger = $this->_config->getSQLLogger();
1081 2640
        if ($logger) {
1082 2558
            $logger->startQuery($statement);
1083
        }
1084
1085
        try {
1086 2640
            $result = $connection->exec($statement);
1087 2051
        } catch (Throwable $ex) {
1088 2051
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1089
        }
1090
1091 669
        if ($logger) {
1092 613
            $logger->stopQuery();
1093
        }
1094
1095 669
        return $result;
1096
    }
1097
1098
    /**
1099
     * Returns the current transaction nesting level.
1100
     *
1101
     * @return int The nesting level. A value of 0 means there's no active transaction.
1102
     */
1103 530
    public function getTransactionNestingLevel()
1104
    {
1105 530
        return $this->transactionNestingLevel;
1106
    }
1107
1108
    /**
1109
     * Fetches the SQLSTATE associated with the last database operation.
1110
     *
1111
     * @return string|null The last error code.
1112
     */
1113
    public function errorCode()
1114
    {
1115
        return $this->getWrappedConnection()->errorCode();
1116
    }
1117
1118
    /**
1119
     * {@inheritDoc}
1120
     */
1121
    public function errorInfo()
1122
    {
1123
        return $this->getWrappedConnection()->errorInfo();
1124
    }
1125
1126
    /**
1127
     * Returns the ID of the last inserted row, or the last value from a sequence object,
1128
     * depending on the underlying driver.
1129
     *
1130
     * Note: This method may not return a meaningful or consistent result across different drivers,
1131
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
1132
     * columns or sequences.
1133
     *
1134
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
1135
     *
1136
     * @return string A string representation of the last inserted ID.
1137
     */
1138 118
    public function lastInsertId($seqName = null)
1139
    {
1140 118
        return $this->getWrappedConnection()->lastInsertId($seqName);
1141
    }
1142
1143
    /**
1144
     * Executes a function in a transaction.
1145
     *
1146
     * The function gets passed this Connection instance as an (optional) parameter.
1147
     *
1148
     * If an exception occurs during execution of the function or transaction commit,
1149
     * the transaction is rolled back and the exception re-thrown.
1150
     *
1151
     * @param Closure $func The function to execute transactionally.
1152
     *
1153
     * @return mixed The value returned by $func
1154
     *
1155
     * @throws Exception
1156
     * @throws Throwable
1157
     */
1158 108
    public function transactional(Closure $func)
1159
    {
1160 108
        $this->beginTransaction();
1161
        try {
1162 108
            $res = $func($this);
1163 54
            $this->commit();
1164 54
            return $res;
1165 54
        } catch (Exception $e) {
1166 27
            $this->rollBack();
1167 27
            throw $e;
1168 27
        } catch (Throwable $e) {
1169 27
            $this->rollBack();
1170 27
            throw $e;
1171
        }
1172
    }
1173
1174
    /**
1175
     * Sets if nested transactions should use savepoints.
1176
     *
1177
     * @param bool $nestTransactionsWithSavepoints
1178
     *
1179
     * @return void
1180
     *
1181
     * @throws ConnectionException
1182
     */
1183 53
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
1184
    {
1185 53
        if ($this->transactionNestingLevel > 0) {
1186 52
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
1187
        }
1188
1189 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1190 1
            throw ConnectionException::savepointsNotSupported();
1191
        }
1192
1193 26
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1194 26
    }
1195
1196
    /**
1197
     * Gets if nested transactions should use savepoints.
1198
     *
1199
     * @return bool
1200
     */
1201 26
    public function getNestTransactionsWithSavepoints()
1202
    {
1203 26
        return $this->nestTransactionsWithSavepoints;
1204
    }
1205
1206
    /**
1207
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1208
     * "savepointFormat" parameter is not set
1209
     *
1210
     * @return mixed A string with the savepoint name or false.
1211
     */
1212 26
    protected function _getNestedTransactionSavePointName()
1213
    {
1214 26
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1215
    }
1216
1217
    /**
1218
     * {@inheritDoc}
1219
     */
1220 550
    public function beginTransaction()
1221
    {
1222 550
        $connection = $this->getWrappedConnection();
1223
1224 550
        ++$this->transactionNestingLevel;
1225
1226 550
        $logger = $this->_config->getSQLLogger();
1227
1228 550
        if ($this->transactionNestingLevel === 1) {
1229 550
            if ($logger) {
1230 401
                $logger->startQuery('"START TRANSACTION"');
1231
            }
1232
1233 550
            $connection->beginTransaction();
1234
1235 550
            if ($logger) {
1236 550
                $logger->stopQuery();
1237
            }
1238 80
        } elseif ($this->nestTransactionsWithSavepoints) {
1239 26
            if ($logger) {
1240 26
                $logger->startQuery('"SAVEPOINT"');
1241
            }
1242 26
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1243 26
            if ($logger) {
1244 26
                $logger->stopQuery();
1245
            }
1246
        }
1247
1248 550
        return true;
1249
    }
1250
1251
    /**
1252
     * {@inheritDoc}
1253
     *
1254
     * @throws ConnectionException If the commit failed due to no active transaction or
1255
     *                                            because the transaction was marked for rollback only.
1256
     */
1257 310
    public function commit()
1258
    {
1259 310
        if ($this->transactionNestingLevel === 0) {
1260 27
            throw ConnectionException::noActiveTransaction();
1261
        }
1262 283
        if ($this->isRollbackOnly) {
1263 54
            throw ConnectionException::commitFailedRollbackOnly();
1264
        }
1265
1266 229
        $connection = $this->getWrappedConnection();
1267
1268 229
        $logger = $this->_config->getSQLLogger();
1269
1270 229
        if ($this->transactionNestingLevel === 1) {
1271 229
            if ($logger) {
1272 161
                $logger->startQuery('"COMMIT"');
1273
            }
1274
1275 229
            $connection->commit();
1276
1277 229
            if ($logger) {
1278 229
                $logger->stopQuery();
1279
            }
1280 53
        } elseif ($this->nestTransactionsWithSavepoints) {
1281 26
            if ($logger) {
1282 26
                $logger->startQuery('"RELEASE SAVEPOINT"');
1283
            }
1284 26
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1285 26
            if ($logger) {
1286 26
                $logger->stopQuery();
1287
            }
1288
        }
1289
1290 229
        --$this->transactionNestingLevel;
1291
1292 229
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1293 202
            return true;
1294
        }
1295
1296 54
        $this->beginTransaction();
1297
1298 54
        return true;
1299
    }
1300
1301
    /**
1302
     * Commits all current nesting transactions.
1303
     */
1304 27
    private function commitAll()
1305
    {
1306 27
        while ($this->transactionNestingLevel !== 0) {
1307 27
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1308
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1309
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1310 27
                $this->commit();
1311
1312 27
                return;
1313
            }
1314
1315 27
            $this->commit();
1316
        }
1317 27
    }
1318
1319
    /**
1320
     * Cancels any database changes done during the current transaction.
1321
     *
1322
     * @throws ConnectionException If the rollback operation failed.
1323
     */
1324 346
    public function rollBack()
1325
    {
1326 346
        if ($this->transactionNestingLevel === 0) {
1327 27
            throw ConnectionException::noActiveTransaction();
1328
        }
1329
1330 319
        $connection = $this->getWrappedConnection();
1331
1332 319
        $logger = $this->_config->getSQLLogger();
1333
1334 319
        if ($this->transactionNestingLevel === 1) {
1335 293
            if ($logger) {
1336 266
                $logger->startQuery('"ROLLBACK"');
1337
            }
1338 293
            $this->transactionNestingLevel = 0;
1339 293
            $connection->rollBack();
1340 293
            $this->isRollbackOnly = false;
1341 293
            if ($logger) {
1342 266
                $logger->stopQuery();
1343
            }
1344
1345 293
            if ($this->autoCommit === false) {
1346 293
                $this->beginTransaction();
1347
            }
1348 53
        } elseif ($this->nestTransactionsWithSavepoints) {
1349 26
            if ($logger) {
1350 26
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1351
            }
1352 26
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1353 26
            --$this->transactionNestingLevel;
1354 26
            if ($logger) {
1355 26
                $logger->stopQuery();
1356
            }
1357
        } else {
1358 27
            $this->isRollbackOnly = true;
1359 27
            --$this->transactionNestingLevel;
1360
        }
1361 319
    }
1362
1363
    /**
1364
     * Creates a new savepoint.
1365
     *
1366
     * @param string $savepoint The name of the savepoint to create.
1367
     *
1368
     * @return void
1369
     *
1370
     * @throws ConnectionException
1371
     */
1372 27
    public function createSavepoint($savepoint)
1373
    {
1374 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1375 1
            throw ConnectionException::savepointsNotSupported();
1376
        }
1377
1378 26
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1379 26
    }
1380
1381
    /**
1382
     * Releases the given savepoint.
1383
     *
1384
     * @param string $savepoint The name of the savepoint to release.
1385
     *
1386
     * @return void
1387
     *
1388
     * @throws ConnectionException
1389
     */
1390 27
    public function releaseSavepoint($savepoint)
1391
    {
1392 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1393 1
            throw ConnectionException::savepointsNotSupported();
1394
        }
1395
1396 26
        if (! $this->platform->supportsReleaseSavepoints()) {
1397 4
            return;
1398
        }
1399
1400 22
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1401 22
    }
1402
1403
    /**
1404
     * Rolls back to the given savepoint.
1405
     *
1406
     * @param string $savepoint The name of the savepoint to rollback to.
1407
     *
1408
     * @return void
1409
     *
1410
     * @throws ConnectionException
1411
     */
1412 27
    public function rollbackSavepoint($savepoint)
1413
    {
1414 27
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1415 1
            throw ConnectionException::savepointsNotSupported();
1416
        }
1417
1418 26
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1419 26
    }
1420
1421
    /**
1422
     * Gets the wrapped driver connection.
1423
     *
1424
     * @return DriverConnection
1425
     */
1426 8392
    public function getWrappedConnection()
1427
    {
1428 8392
        $this->connect();
1429 8385
        assert($this->_conn instanceof DriverConnection);
1430
1431 8385
        return $this->_conn;
1432
    }
1433
1434
    /**
1435
     * Gets the SchemaManager that can be used to inspect or change the
1436
     * database schema through the connection.
1437
     *
1438
     * @return AbstractSchemaManager
1439
     */
1440 4789
    public function getSchemaManager()
1441
    {
1442 4789
        if ($this->_schemaManager === null) {
1443 314
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1444
        }
1445
1446 4789
        return $this->_schemaManager;
1447
    }
1448
1449
    /**
1450
     * Marks the current transaction so that the only possible
1451
     * outcome for the transaction to be rolled back.
1452
     *
1453
     * @return void
1454
     *
1455
     * @throws ConnectionException If no transaction is active.
1456
     */
1457 54
    public function setRollbackOnly()
1458
    {
1459 54
        if ($this->transactionNestingLevel === 0) {
1460 27
            throw ConnectionException::noActiveTransaction();
1461
        }
1462 27
        $this->isRollbackOnly = true;
1463 27
    }
1464
1465
    /**
1466
     * Checks whether the current transaction is marked for rollback only.
1467
     *
1468
     * @return bool
1469
     *
1470
     * @throws ConnectionException If no transaction is active.
1471
     */
1472 80
    public function isRollbackOnly()
1473
    {
1474 80
        if ($this->transactionNestingLevel === 0) {
1475 27
            throw ConnectionException::noActiveTransaction();
1476
        }
1477
1478 53
        return $this->isRollbackOnly;
1479
    }
1480
1481
    /**
1482
     * Converts a given value to its database representation according to the conversion
1483
     * rules of a specific DBAL mapping type.
1484
     *
1485
     * @param mixed  $value The value to convert.
1486
     * @param string $type  The name of the DBAL mapping type.
1487
     *
1488
     * @return mixed The converted value.
1489
     */
1490
    public function convertToDatabaseValue($value, $type)
1491
    {
1492
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1493
    }
1494
1495
    /**
1496
     * Converts a given value to its PHP representation according to the conversion
1497
     * rules of a specific DBAL mapping type.
1498
     *
1499
     * @param mixed  $value The value to convert.
1500
     * @param string $type  The name of the DBAL mapping type.
1501
     *
1502
     * @return mixed The converted type.
1503
     */
1504
    public function convertToPHPValue($value, $type)
1505
    {
1506
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1507
    }
1508
1509
    /**
1510
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1511
     * or DBAL mapping type, to a given statement.
1512
     *
1513
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1514
     *           raw PDOStatement instances.
1515
     *
1516
     * @param \Doctrine\DBAL\Driver\Statement $stmt   The statement to bind the values to.
1517
     * @param mixed[]                         $params The map/list of named/positional parameters.
1518
     * @param int[]|string[]                  $types  The parameter types (PDO binding types or DBAL mapping types).
1519
     *
1520
     * @return void
1521
     */
1522 781
    private function _bindTypedValues($stmt, array $params, array $types)
1523
    {
1524
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1525 781
        if (is_int(key($params))) {
1526
            // Positional parameters
1527 781
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1528 781
            $bindIndex  = 1;
1529 781
            foreach ($params as $value) {
1530 781
                $typeIndex = $bindIndex + $typeOffset;
1531 781
                if (isset($types[$typeIndex])) {
1532 781
                    $type                  = $types[$typeIndex];
1533 781
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1534 781
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1535
                } else {
1536 52
                    $stmt->bindValue($bindIndex, $value);
1537
                }
1538 781
                ++$bindIndex;
1539
            }
1540
        } else {
1541
            // Named parameters
1542
            foreach ($params as $name => $value) {
1543
                if (isset($types[$name])) {
1544
                    $type                  = $types[$name];
1545
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1546
                    $stmt->bindValue($name, $value, $bindingType);
1547
                } else {
1548
                    $stmt->bindValue($name, $value);
1549
                }
1550
            }
1551
        }
1552 781
    }
1553
1554
    /**
1555
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1556
     *
1557
     * @param mixed           $value The value to bind.
1558
     * @param int|string|null $type  The type to bind (PDO or DBAL).
1559
     *
1560
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1561
     */
1562 1029
    private function getBindingInfo($value, $type)
1563
    {
1564 1029
        if (is_string($type)) {
1565 324
            $type = Type::getType($type);
1566
        }
1567 1029
        if ($type instanceof Type) {
1568 324
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1569 324
            $bindingType = $type->getBindingType();
1570
        } else {
1571 867
            $bindingType = $type;
1572
        }
1573
1574 1029
        return [$value, $bindingType];
1575
    }
1576
1577
    /**
1578
     * Resolves the parameters to a format which can be displayed.
1579
     *
1580
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1581
     *           copy/paste the code as this method may change, or be removed without prior notice.
1582
     *
1583
     * @param mixed[]        $params
1584
     * @param int[]|string[] $types
1585
     *
1586
     * @return mixed[]
1587
     */
1588 3230
    public function resolveParams(array $params, array $types)
1589
    {
1590 3230
        $resolvedParams = [];
1591
1592
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1593 3230
        if (is_int(key($params))) {
1594
            // Positional parameters
1595 241
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1596 241
            $bindIndex  = 1;
1597 241
            foreach ($params as $value) {
1598 241
                $typeIndex = $bindIndex + $typeOffset;
1599 241
                if (isset($types[$typeIndex])) {
1600
                    $type                       = $types[$typeIndex];
1601
                    [$value]                    = $this->getBindingInfo($value, $type);
1602
                    $resolvedParams[$bindIndex] = $value;
1603
                } else {
1604 241
                    $resolvedParams[$bindIndex] = $value;
1605
                }
1606 241
                ++$bindIndex;
1607
            }
1608
        } else {
1609
            // Named parameters
1610 2995
            foreach ($params as $name => $value) {
1611
                if (isset($types[$name])) {
1612
                    $type                  = $types[$name];
1613
                    [$value]               = $this->getBindingInfo($value, $type);
1614
                    $resolvedParams[$name] = $value;
1615
                } else {
1616
                    $resolvedParams[$name] = $value;
1617
                }
1618
            }
1619
        }
1620
1621 3230
        return $resolvedParams;
1622
    }
1623
1624
    /**
1625
     * Creates a new instance of a SQL query builder.
1626
     *
1627
     * @return QueryBuilder
1628
     */
1629
    public function createQueryBuilder()
1630
    {
1631
        return new Query\QueryBuilder($this);
1632
    }
1633
1634
    /**
1635
     * Ping the server
1636
     *
1637
     * When the server is not available the method returns FALSE.
1638
     * It is responsibility of the developer to handle this case
1639
     * and abort the request or reconnect manually:
1640
     *
1641
     * @return bool
1642
     *
1643
     * @example
1644
     *
1645
     *   if ($conn->ping() === false) {
1646
     *      $conn->close();
1647
     *      $conn->connect();
1648
     *   }
1649
     *
1650
     * It is undefined if the underlying driver attempts to reconnect
1651
     * or disconnect when the connection is not available anymore
1652
     * as long it returns TRUE when a reconnect succeeded and
1653
     * FALSE when the connection was dropped.
1654
     */
1655 27
    public function ping()
1656
    {
1657 27
        $connection = $this->getWrappedConnection();
1658
1659 27
        if ($connection instanceof PingableConnection) {
1660 7
            return $connection->ping();
1661
        }
1662
1663
        try {
1664 20
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1665
1666 20
            return true;
1667
        } catch (DBALException $e) {
1668
            return false;
1669
        }
1670
    }
1671
}
1672