Issues (420)

lib/Doctrine/DBAL/Connection.php (3 issues)

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

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

829
        return $this->_conn->/** @scrutinizer ignore-call */ quote($value, $bindingType);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
830
    }
831
832
    /**
833
     * Prepares and executes an SQL query and returns the result as an associative array.
834
     *
835
     * @param string         $sql    The SQL query.
836
     * @param mixed[]        $params The query parameters.
837
     * @param int[]|string[] $types  The query parameter types.
838
     *
839
     * @return mixed[]
840
     */
841 2766
    public function fetchAll($sql, array $params = [], $types = [])
842
    {
843 2766
        return $this->executeQuery($sql, $params, $types)->fetchAll();
844
    }
845
846
    /**
847
     * Prepares an SQL statement.
848
     *
849
     * @param string $statement The SQL statement to prepare.
850
     *
851
     * @return DriverStatement The prepared statement.
852
     *
853
     * @throws DBALException
854
     */
855 1162
    public function prepare($statement)
856
    {
857
        try {
858 1162
            $stmt = new Statement($statement, $this);
859 27
        } catch (Throwable $ex) {
860 27
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
861
        }
862
863 1135
        $stmt->setFetchMode($this->defaultFetchMode);
864
865 1135
        return $stmt;
866
    }
867
868
    /**
869
     * Executes an, optionally parametrized, SQL query.
870
     *
871
     * If the query is parametrized, a prepared statement is used.
872
     * If an SQLLogger is configured, the execution is logged.
873
     *
874
     * @param string                 $query  The SQL query to execute.
875
     * @param mixed[]                $params The parameters to bind to the query, if any.
876
     * @param int[]|string[]         $types  The types the previous parameters are in.
877
     * @param QueryCacheProfile|null $qcp    The query cache profile, optional.
878
     *
879
     * @return ResultStatement The executed statement.
880
     *
881
     * @throws DBALException
882
     */
883 5540
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
884
    {
885 5540
        if ($qcp !== null) {
886 270
            return $this->executeCacheQuery($query, $params, $types, $qcp);
887
        }
888
889 5540
        $this->connect();
890
891 5540
        $logger = $this->_config->getSQLLogger();
892 5540
        if ($logger) {
893 5363
            $logger->startQuery($query, $params, $types);
894
        }
895
896
        try {
897 5540
            if ($params) {
898 1021
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
899
900 1021
                $stmt = $this->_conn->prepare($query);
901 1021
                if ($types) {
902 431
                    $this->_bindTypedValues($stmt, $params, $types);
903 431
                    $stmt->execute();
904
                } else {
905 1021
                    $stmt->execute($params);
906
                }
907
            } else {
908 5464
                $stmt = $this->_conn->query($query);
0 ignored issues
show
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

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

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