Failed Conditions
Pull Request — 3.0.x (#3980)
by Guilherme
06:55
created

Connection::releaseSavepoint()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0416
1
<?php
2
3
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 count;
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 2778
    public function __construct(
183
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188 2778
        $this->_driver = $driver;
189 2778
        $this->params  = $params;
190
191 2778
        if (isset($params['platform'])) {
192 276
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
193 23
                throw DBALException::invalidPlatformType($params['platform']);
194
            }
195
196 253
            $this->platform = $params['platform'];
197
        }
198
199
        // Create default config and event manager if none given
200 2778
        if ($config === null) {
201 621
            $config = new Configuration();
202
        }
203
204 2778
        if ($eventManager === null) {
205 598
            $eventManager = new EventManager();
206
        }
207
208 2778
        $this->_config       = $config;
209 2778
        $this->_eventManager = $eventManager;
210
211 2778
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
212
213 2778
        $this->autoCommit = $config->getAutoCommit();
214 2778
    }
215
216
    /**
217
     * Gets the parameters used during instantiation.
218
     *
219
     * @return mixed[]
220
     */
221 3306
    public function getParams()
222
    {
223 3306
        return $this->params;
224
    }
225
226
    /**
227
     * Gets the name of the database this Connection is connected to.
228
     *
229
     * @return string
230
     */
231 1977
    public function getDatabase()
232
    {
233 1977
        return $this->_driver->getDatabase($this);
234
    }
235
236
    /**
237
     * Gets the hostname of the currently connected database.
238
     *
239
     * @deprecated
240
     *
241
     * @return string|null
242
     */
243 23
    public function getHost()
244
    {
245 23
        return $this->params['host'] ?? null;
246
    }
247
248
    /**
249
     * Gets the port of the currently connected database.
250
     *
251
     * @deprecated
252
     *
253
     * @return mixed
254
     */
255 23
    public function getPort()
256
    {
257 23
        return $this->params['port'] ?? null;
258
    }
259
260
    /**
261
     * Gets the username used by this connection.
262
     *
263
     * @deprecated
264
     *
265
     * @return string|null
266
     */
267 25
    public function getUsername()
268
    {
269 25
        return $this->params['user'] ?? null;
270
    }
271
272
    /**
273
     * Gets the password used by this connection.
274
     *
275
     * @deprecated
276
     *
277
     * @return string|null
278
     */
279 23
    public function getPassword()
280
    {
281 23
        return $this->params['password'] ?? null;
282
    }
283
284
    /**
285
     * Gets the DBAL driver instance.
286
     *
287
     * @return Driver
288
     */
289 1334
    public function getDriver()
290
    {
291 1334
        return $this->_driver;
292
    }
293
294
    /**
295
     * Gets the Configuration used by the Connection.
296
     *
297
     * @return Configuration
298
     */
299 7788
    public function getConfiguration()
300
    {
301 7788
        return $this->_config;
302
    }
303
304
    /**
305
     * Gets the EventManager used by the Connection.
306
     *
307
     * @return EventManager
308
     */
309 307
    public function getEventManager()
310
    {
311 307
        return $this->_eventManager;
312
    }
313
314
    /**
315
     * Gets the DatabasePlatform for the connection.
316
     *
317
     * @return AbstractPlatform
318
     *
319
     * @throws DBALException
320
     */
321 5826
    public function getDatabasePlatform()
322
    {
323 5826
        if ($this->platform === null) {
324 691
            $this->detectDatabasePlatform();
325
        }
326
327 5803
        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 8007
    public function connect()
347
    {
348 8007
        if ($this->isConnected) {
349 7659
            return false;
350
        }
351
352 1208
        $driverOptions = $this->params['driverOptions'] ?? [];
353 1208
        $user          = $this->params['user'] ?? null;
354 1208
        $password      = $this->params['password'] ?? null;
355
356 1208
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
357 1130
        $this->isConnected = true;
358
359 1130
        $this->transactionNestingLevel = 0;
360
361 1130
        if ($this->autoCommit === false) {
362 69
            $this->beginTransaction();
363
        }
364
365 1130
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
366 73
            $eventArgs = new Event\ConnectionEventArgs($this);
367 73
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
368
        }
369
370 1130
        return true;
371
    }
372
373
    /**
374
     * Detects and sets the database platform.
375
     *
376
     * Evaluates custom platform class and version in order to set the correct platform.
377
     *
378
     * @throws DBALException If an invalid platform was specified for this connection.
379
     */
380 691
    private function detectDatabasePlatform() : void
381
    {
382 691
        $version = $this->getDatabasePlatformVersion();
383
384 619
        if ($version !== null) {
385 424
            assert($this->_driver instanceof VersionAwarePlatformDriver);
386
387 424
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
388
        } else {
389 195
            $this->platform = $this->_driver->getDatabasePlatform();
390
        }
391
392 619
        $this->platform->setEventManager($this->_eventManager);
393 619
    }
394
395
    /**
396
     * Returns the version of the related platform if applicable.
397
     *
398
     * Returns null if either the driver is not capable to create version
399
     * specific platform instances, no explicit server version was specified
400
     * or the underlying driver connection cannot determine the platform
401
     * version without having to query it (performance reasons).
402
     *
403
     * @return string|null
404
     *
405
     * @throws Exception
406
     */
407 691
    private function getDatabasePlatformVersion()
408
    {
409
        // Driver does not support version specific platforms.
410 691
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
411 195
            return null;
412
        }
413
414
        // Explicit platform version requested (supersedes auto-detection).
415 496
        if (isset($this->params['serverVersion'])) {
416
            return $this->params['serverVersion'];
417
        }
418
419
        // If not connected, we need to connect now to determine the platform version.
420 496
        if ($this->_conn === null) {
421
            try {
422 369
                $this->connect();
423 91
            } catch (Throwable $originalException) {
424 91
                if (! isset($this->params['dbname'])) {
425
                    throw $originalException;
426
                }
427
428
                // The database to connect to might not yet exist.
429
                // Retry detection without database name connection parameter.
430 91
                $databaseName           = $this->params['dbname'];
431 91
                $this->params['dbname'] = null;
432
433
                try {
434 91
                    $this->connect();
435 72
                } catch (Throwable $fallbackException) {
436
                    // Either the platform does not support database-less connections
437
                    // or something else went wrong.
438
                    // Reset connection parameters and rethrow the original exception.
439 72
                    $this->params['dbname'] = $databaseName;
440
441 72
                    throw $originalException;
442
                }
443
444
                // Reset connection parameters.
445 19
                $this->params['dbname'] = $databaseName;
446 19
                $serverVersion          = $this->getServerVersion();
447
448
                // Close "temporary" connection to allow connecting to the real database again.
449 19
                $this->close();
450
451 19
                return $serverVersion;
452
            }
453
        }
454
455 424
        return $this->getServerVersion();
456
    }
457
458
    /**
459
     * Returns the database server version if the underlying driver supports it.
460
     *
461
     * @return string|null
462
     */
463 424
    private function getServerVersion()
464
    {
465 424
        $connection = $this->getWrappedConnection();
466
467
        // Automatic platform version detection.
468 424
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
469 424
            return $connection->getServerVersion();
470
        }
471
472
        // Unable to detect platform version.
473
        return null;
474
    }
475
476
    /**
477
     * Returns the current auto-commit mode for this connection.
478
     *
479
     * @see    setAutoCommit
480
     *
481
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
482
     */
483 46
    public function isAutoCommit()
484
    {
485 46
        return $this->autoCommit === true;
486
    }
487
488
    /**
489
     * Sets auto-commit mode for this connection.
490
     *
491
     * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
492
     * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
493
     * the method commit or the method rollback. By default, new connections are in auto-commit mode.
494
     *
495
     * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
496
     * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
497
     *
498
     * @see   isAutoCommit
499
     *
500
     * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
501
     *
502
     * @return void
503
     */
504 115
    public function setAutoCommit($autoCommit)
505
    {
506 115
        $autoCommit = (bool) $autoCommit;
507
508
        // Mode not changed, no-op.
509 115
        if ($autoCommit === $this->autoCommit) {
510 23
            return;
511
        }
512
513 115
        $this->autoCommit = $autoCommit;
514
515
        // Commit all currently active transactions if any when switching auto-commit mode.
516 115
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
517 92
            return;
518
        }
519
520 23
        $this->commitAll();
521 23
    }
522
523
    /**
524
     * Sets the fetch mode.
525
     *
526
     * @param int $fetchMode
527
     *
528
     * @return void
529
     */
530 23
    public function setFetchMode($fetchMode)
531
    {
532 23
        $this->defaultFetchMode = $fetchMode;
533 23
    }
534
535
    /**
536
     * Prepares and executes an SQL query and returns the first row of the result
537
     * as an associative array.
538
     *
539
     * @param string         $statement The SQL query.
540
     * @param mixed[]        $params    The query parameters.
541
     * @param int[]|string[] $types     The query parameter types.
542
     *
543
     * @return mixed[]|false False is returned if no rows are found.
544
     *
545
     * @throws DBALException
546
     */
547 2219
    public function fetchAssoc($statement, array $params = [], array $types = [])
548
    {
549 2219
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
550
    }
551
552
    /**
553
     * Prepares and executes an SQL query and returns the first row of the result
554
     * as a numerically indexed array.
555
     *
556
     * @param string         $statement The SQL query to be executed.
557
     * @param mixed[]        $params    The prepared statement params.
558
     * @param int[]|string[] $types     The query parameter types.
559
     *
560
     * @return mixed[]|false False is returned if no rows are found.
561
     */
562 86
    public function fetchArray($statement, array $params = [], array $types = [])
563
    {
564 86
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
565
    }
566
567
    /**
568
     * Prepares and executes an SQL query and returns the value of a single column
569
     * of the first row of the result.
570
     *
571
     * @param string         $statement The SQL query to be executed.
572
     * @param mixed[]        $params    The prepared statement params.
573
     * @param int[]|string[] $types     The query parameter types.
574
     *
575
     * @return mixed|false False is returned if no rows are found.
576
     *
577
     * @throws DBALException
578
     */
579 1319
    public function fetchColumn($statement, array $params = [], array $types = [])
580
    {
581 1319
        return $this->executeQuery($statement, $params, $types)->fetchColumn();
582
    }
583
584
    /**
585
     * Whether an actual connection to the database is established.
586
     *
587
     * @return bool
588
     */
589 67
    public function isConnected()
590
    {
591 67
        return $this->isConnected;
592
    }
593
594
    /**
595
     * Checks whether a transaction is currently active.
596
     *
597
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
598
     */
599 7788
    public function isTransactionActive()
600
    {
601 7788
        return $this->transactionNestingLevel > 0;
602
    }
603
604
    /**
605
     * Adds identifier condition to the query components
606
     *
607
     * @param mixed[]  $identifier Map of key columns to their values
608
     * @param string[] $columns    Column names
609
     * @param mixed[]  $values     Column values
610
     * @param string[] $conditions Key conditions
611
     *
612
     * @throws DBALException
613
     */
614 316
    private function addIdentifierCondition(
615
        array $identifier,
616
        array &$columns,
617
        array &$values,
618
        array &$conditions
619
    ) : void {
620 316
        $platform = $this->getDatabasePlatform();
621
622 316
        foreach ($identifier as $columnName => $value) {
623 316
            if ($value === null) {
624 92
                $conditions[] = $platform->getIsNullExpression($columnName);
625 92
                continue;
626
            }
627
628 270
            $columns[]    = $columnName;
629 270
            $values[]     = $value;
630 270
            $conditions[] = $columnName . ' = ?';
631
        }
632 316
    }
633
634
    /**
635
     * Executes an SQL DELETE statement on a table.
636
     *
637
     * Table expression and columns are not escaped and are not safe for user-input.
638
     *
639
     * @param string         $tableExpression The expression of the table on which to delete.
640
     * @param mixed[]        $identifier      The deletion criteria. An associative array containing column-value pairs.
641
     * @param int[]|string[] $types           The types of identifiers.
642
     *
643
     * @return int The number of affected rows.
644
     *
645
     * @throws DBALException
646
     * @throws InvalidArgumentException
647
     */
648 136
    public function delete($tableExpression, array $identifier, array $types = [])
649
    {
650 136
        if (count($identifier) === 0) {
651 23
            throw InvalidArgumentException::fromEmptyCriteria();
652
        }
653
654 113
        $columns = $values = $conditions = [];
655
656 113
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
657
658 113
        return $this->executeUpdate(
659 113
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
660
            $values,
661 113
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
662
        );
663
    }
664
665
    /**
666
     * Closes the connection.
667
     *
668
     * @return void
669
     */
670 627
    public function close()
671
    {
672 627
        $this->_conn = null;
673
674 627
        $this->isConnected = false;
675 627
    }
676
677
    /**
678
     * Sets the transaction isolation level.
679
     *
680
     * @param int $level The level to set.
681
     *
682
     * @return int
683
     */
684
    public function setTransactionIsolation($level)
685
    {
686
        $this->transactionIsolationLevel = $level;
687
688
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
689
    }
690
691
    /**
692
     * Gets the currently active transaction isolation level.
693
     *
694
     * @return int The current transaction isolation level.
695
     */
696
    public function getTransactionIsolation()
697
    {
698
        if ($this->transactionIsolationLevel === null) {
699
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
700
        }
701
702
        return $this->transactionIsolationLevel;
703
    }
704
705
    /**
706
     * Executes an SQL UPDATE statement on a table.
707
     *
708
     * Table expression and columns are not escaped and are not safe for user-input.
709
     *
710
     * @param string         $tableExpression The expression of the table to update quoted or unquoted.
711
     * @param mixed[]        $data            An associative array containing column-value pairs.
712
     * @param mixed[]        $identifier      The update criteria. An associative array containing column-value pairs.
713
     * @param int[]|string[] $types           Types of the merged $data and $identifier arrays in that order.
714
     *
715
     * @return int The number of affected rows.
716
     *
717
     * @throws DBALException
718
     */
719 203
    public function update($tableExpression, array $data, array $identifier, array $types = [])
720
    {
721 203
        $columns = $values = $conditions = $set = [];
722
723 203
        foreach ($data as $columnName => $value) {
724 203
            $columns[] = $columnName;
725 203
            $values[]  = $value;
726 203
            $set[]     = $columnName . ' = ?';
727
        }
728
729 203
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
730
731 203
        if (is_string(key($types))) {
732 115
            $types = $this->extractTypeValues($columns, $types);
733
        }
734
735 203
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
736 203
                . ' WHERE ' . implode(' AND ', $conditions);
737
738 203
        return $this->executeUpdate($sql, $values, $types);
739
    }
740
741
    /**
742
     * Inserts a table row with specified data.
743
     *
744
     * Table expression and columns are not escaped and are not safe for user-input.
745
     *
746
     * @param string         $tableExpression The expression of the table to insert data into, quoted or unquoted.
747
     * @param mixed[]        $data            An associative array containing column-value pairs.
748
     * @param int[]|string[] $types           Types of the inserted data.
749
     *
750
     * @return int The number of affected rows.
751
     *
752
     * @throws DBALException
753
     */
754 2045
    public function insert($tableExpression, array $data, array $types = [])
755
    {
756 2045
        if (count($data) === 0) {
757 23
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
758
        }
759
760 2022
        $columns = [];
761 2022
        $values  = [];
762 2022
        $set     = [];
763
764 2022
        foreach ($data as $columnName => $value) {
765 2022
            $columns[] = $columnName;
766 2022
            $values[]  = $value;
767 2022
            $set[]     = '?';
768
        }
769
770 2022
        return $this->executeUpdate(
771 2022
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
772 2022
            ' VALUES (' . implode(', ', $set) . ')',
773
            $values,
774 2022
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
775
        );
776
    }
777
778
    /**
779
     * Extract ordered type list from an ordered column list and type map.
780
     *
781
     * @param int[]|string[] $columnList
782
     * @param int[]|string[] $types
783
     *
784
     * @return int[]|string[]
785
     */
786 207
    private function extractTypeValues(array $columnList, array $types)
787
    {
788 207
        $typeValues = [];
789
790 207
        foreach ($columnList as $columnIndex => $columnName) {
791 207
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
792
        }
793
794 207
        return $typeValues;
795
    }
796
797
    /**
798
     * Quotes a string so it can be safely used as a table or column name, even if
799
     * it is a reserved name.
800
     *
801
     * Delimiting style depends on the underlying database platform that is being used.
802
     *
803
     * NOTE: Just because you CAN use quoted identifiers does not mean
804
     * you SHOULD use them. In general, they end up causing way more
805
     * problems than they solve.
806
     *
807
     * @param string $str The name to be quoted.
808
     *
809
     * @return string The quoted name.
810
     */
811 23
    public function quoteIdentifier($str)
812
    {
813 23
        return $this->getDatabasePlatform()->quoteIdentifier($str);
814
    }
815
816
    /**
817
     * {@inheritDoc}
818
     */
819 242
    public function quote($input, $type = ParameterType::STRING)
820
    {
821 242
        $connection = $this->getWrappedConnection();
822
823 242
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
824
825 242
        return $connection->quote($value, $bindingType);
826
    }
827
828
    /**
829
     * Prepares and executes an SQL query and returns the result as an associative array.
830
     *
831
     * @param string         $sql    The SQL query.
832
     * @param mixed[]        $params The query parameters.
833
     * @param int[]|string[] $types  The query parameter types.
834
     *
835
     * @return mixed[]
836
     */
837 2863
    public function fetchAll($sql, array $params = [], $types = [])
838
    {
839 2863
        return $this->executeQuery($sql, $params, $types)->fetchAll();
840
    }
841
842
    /**
843
     * Prepares an SQL statement.
844
     *
845
     * @param string $sql The SQL statement to prepare.
846
     *
847
     * @throws DBALException
848
     */
849 918
    public function prepare(string $sql) : DriverStatement
850
    {
851
        try {
852 918
            $stmt = new Statement($sql, $this);
853 23
        } catch (Throwable $ex) {
854 23
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
855
        }
856
857 895
        $stmt->setFetchMode($this->defaultFetchMode);
858
859 895
        return $stmt;
860
    }
861
862
    /**
863
     * Executes an, optionally parametrized, SQL query.
864
     *
865
     * If the query is parametrized, a prepared statement is used.
866
     * If an SQLLogger is configured, the execution is logged.
867
     *
868
     * @param string                 $query  The SQL query to execute.
869
     * @param mixed[]                $params The parameters to bind to the query, if any.
870
     * @param int[]|string[]         $types  The types the previous parameters are in.
871
     * @param QueryCacheProfile|null $qcp    The query cache profile, optional.
872
     *
873
     * @return ResultStatement The executed statement.
874
     *
875
     * @throws DBALException
876
     */
877 5630
    public function executeQuery(string $query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) : ResultStatement
878
    {
879 5630
        if ($qcp !== null) {
880 253
            return $this->executeCacheQuery($query, $params, $types, $qcp);
881
        }
882
883 5630
        $connection = $this->getWrappedConnection();
884
885 5630
        $logger = $this->_config->getSQLLogger();
886 5630
        if ($logger !== null) {
887 5496
            $logger->startQuery($query, $params, $types);
888
        }
889
890
        try {
891 5630
            if (count($params) > 0) {
892 933
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
893
894 933
                $stmt = $connection->prepare($query);
895 933
                if (count($types) > 0) {
896 910
                    $this->_bindTypedValues($stmt, $params, $types);
897 842
                    $stmt->execute();
898
                } else {
899 865
                    $stmt->execute($params);
900
                }
901
            } else {
902 5562
                $stmt = $connection->query($query);
903
            }
904 160
        } catch (Throwable $ex) {
905 160
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
906
        }
907
908 5470
        $stmt->setFetchMode($this->defaultFetchMode);
909
910 5470
        if ($logger !== null) {
911 5359
            $logger->stopQuery();
912
        }
913
914 5470
        return $stmt;
915
    }
916
917
    /**
918
     * Executes a caching query.
919
     *
920
     * @param string            $query  The SQL query to execute.
921
     * @param mixed[]           $params The parameters to bind to the query, if any.
922
     * @param int[]|string[]    $types  The types the previous parameters are in.
923
     * @param QueryCacheProfile $qcp    The query cache profile.
924
     *
925
     * @throws CacheException
926
     */
927 345
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp) : ResultStatement
928
    {
929 345
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
930
931 345
        if ($resultCache === null) {
932
            throw CacheException::noResultDriverConfigured();
933
        }
934
935 345
        $connectionParams = $this->getParams();
936 345
        unset($connectionParams['platform']);
937
938 345
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
939
940
        // fetch the row pointers entry
941 345
        $data = $resultCache->fetch($cacheKey);
942
943 345
        if ($data !== false) {
944
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
945 253
            if (isset($data[$realKey])) {
946 253
                $stmt = new ArrayStatement($data[$realKey]);
947
            } elseif (array_key_exists($realKey, $data)) {
948
                $stmt = new ArrayStatement([]);
949
            }
950
        }
951
952 345
        if (! isset($stmt)) {
953 276
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
954
        }
955
956 345
        $stmt->setFetchMode($this->defaultFetchMode);
957
958 345
        return $stmt;
959
    }
960
961
    /**
962
     * Executes an, optionally parametrized, SQL query and returns the result,
963
     * applying a given projection/transformation function on each row of the result.
964
     *
965
     * @param string  $query    The SQL query to execute.
966
     * @param mixed[] $params   The parameters, if any.
967
     * @param Closure $function The transformation function that is applied on each row.
968
     *                           The function receives a single parameter, an array, that
969
     *                           represents a row of the result set.
970
     *
971
     * @return mixed[] The projected result of the query.
972
     */
973
    public function project($query, array $params, Closure $function)
974
    {
975
        $result = [];
976
        $stmt   = $this->executeQuery($query, $params);
977
978
        while ($row = $stmt->fetch()) {
979
            $result[] = $function($row);
980
        }
981
982
        $stmt->closeCursor();
983
984
        return $result;
985
    }
986
987
    /**
988
     * {@inheritDoc}
989
     */
990 459
    public function query(string $sql) : ResultStatement
991
    {
992 459
        $connection = $this->getWrappedConnection();
993
994 459
        $logger = $this->_config->getSQLLogger();
995 459
        if ($logger !== null) {
996 436
            $logger->startQuery($sql);
997
        }
998
999
        try {
1000 459
            $statement = $connection->query($sql);
1001 23
        } catch (Throwable $ex) {
1002 23
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $sql);
1003
        }
1004
1005 436
        $statement->setFetchMode($this->defaultFetchMode);
1006
1007 436
        if ($logger !== null) {
1008 436
            $logger->stopQuery();
1009
        }
1010
1011 436
        return $statement;
1012
    }
1013
1014
    /**
1015
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
1016
     * and returns the number of affected rows.
1017
     *
1018
     * This method supports PDO binding types as well as DBAL mapping types.
1019
     *
1020
     * @param string         $query  The SQL query.
1021
     * @param mixed[]        $params The query parameters.
1022
     * @param int[]|string[] $types  The parameter types.
1023
     *
1024
     * @throws DBALException
1025
     */
1026 4438
    public function executeUpdate(string $query, array $params = [], array $types = []) : int
1027
    {
1028 4438
        $connection = $this->getWrappedConnection();
1029
1030 4438
        $logger = $this->_config->getSQLLogger();
1031 4438
        if ($logger !== null) {
1032 4401
            $logger->startQuery($query, $params, $types);
1033
        }
1034
1035
        try {
1036 4438
            if (count($params) > 0) {
1037 2117
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1038
1039 2117
                $stmt = $connection->prepare($query);
1040
1041 2109
                if (count($types) > 0) {
1042 2109
                    $this->_bindTypedValues($stmt, $params, $types);
1043 2109
                    $stmt->execute();
1044
                } else {
1045
                    $stmt->execute($params);
1046
                }
1047 2071
                $result = $stmt->rowCount();
1048
            } else {
1049 4392
                $result = $connection->exec($query);
1050
            }
1051 2727
        } catch (Throwable $ex) {
1052 2727
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
1053
        }
1054
1055 4040
        if ($logger !== null) {
1056 4024
            $logger->stopQuery();
1057
        }
1058
1059 4040
        return $result;
1060
    }
1061
1062
    /**
1063
     * {@inheritDoc}
1064
     */
1065 2266
    public function exec(string $statement) : int
1066
    {
1067 2266
        $connection = $this->getWrappedConnection();
1068
1069 2260
        $logger = $this->_config->getSQLLogger();
1070 2260
        if ($logger !== null) {
1071 2189
            $logger->startQuery($statement);
1072
        }
1073
1074
        try {
1075 2260
            $result = $connection->exec($statement);
1076 1781
        } catch (Throwable $ex) {
1077 1781
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1078
        }
1079
1080 549
        if ($logger !== null) {
1081 501
            $logger->stopQuery();
1082
        }
1083
1084 549
        return $result;
1085
    }
1086
1087
    /**
1088
     * Returns the current transaction nesting level.
1089
     *
1090
     * @return int The nesting level. A value of 0 means there's no active transaction.
1091
     */
1092 287
    public function getTransactionNestingLevel()
1093
    {
1094 287
        return $this->transactionNestingLevel;
1095
    }
1096
1097
    /**
1098
     * Fetches the SQLSTATE associated with the last database operation.
1099
     *
1100
     * @return string|null The last error code.
1101
     */
1102
    public function errorCode()
1103
    {
1104
        return $this->getWrappedConnection()->errorCode();
1105
    }
1106
1107
    /**
1108
     * {@inheritDoc}
1109
     */
1110
    public function errorInfo()
1111
    {
1112
        return $this->getWrappedConnection()->errorInfo();
1113
    }
1114
1115
    /**
1116
     * Returns the ID of the last inserted row, or the last value from a sequence object,
1117
     * depending on the underlying driver.
1118
     *
1119
     * Note: This method may not return a meaningful or consistent result across different drivers,
1120
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
1121
     * columns or sequences.
1122
     *
1123
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
1124
     *
1125
     * @return string A string representation of the last inserted ID.
1126
     */
1127 93
    public function lastInsertId($seqName = null)
1128
    {
1129 93
        return $this->getWrappedConnection()->lastInsertId($seqName);
1130
    }
1131
1132
    /**
1133
     * Executes a function in a transaction.
1134
     *
1135
     * The function gets passed this Connection instance as an (optional) parameter.
1136
     *
1137
     * If an exception occurs during execution of the function or transaction commit,
1138
     * the transaction is rolled back and the exception re-thrown.
1139
     *
1140
     * @param Closure $func The function to execute transactionally.
1141
     *
1142
     * @return mixed The value returned by $func
1143
     *
1144
     * @throws Exception
1145
     * @throws Throwable
1146
     */
1147 92
    public function transactional(Closure $func)
1148
    {
1149 92
        $this->beginTransaction();
1150
        try {
1151 92
            $res = $func($this);
1152 46
            $this->commit();
1153
1154 46
            return $res;
1155 46
        } catch (Exception $e) {
1156 23
            $this->rollBack();
1157 23
            throw $e;
1158 23
        } catch (Throwable $e) {
1159 23
            $this->rollBack();
1160 23
            throw $e;
1161
        }
1162
    }
1163
1164
    /**
1165
     * Sets if nested transactions should use savepoints.
1166
     *
1167
     * @param bool $nestTransactionsWithSavepoints
1168
     *
1169
     * @return void
1170
     *
1171
     * @throws ConnectionException
1172
     */
1173 46
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
1174
    {
1175 46
        if ($this->transactionNestingLevel > 0) {
1176 46
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
1177
        }
1178
1179 23
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1180
            throw ConnectionException::savepointsNotSupported();
1181
        }
1182
1183 23
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1184 23
    }
1185
1186
    /**
1187
     * Gets if nested transactions should use savepoints.
1188
     *
1189
     * @return bool
1190
     */
1191 23
    public function getNestTransactionsWithSavepoints()
1192
    {
1193 23
        return $this->nestTransactionsWithSavepoints;
1194
    }
1195
1196
    /**
1197
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1198
     * "savepointFormat" parameter is not set
1199
     *
1200
     * @return mixed A string with the savepoint name or false.
1201
     */
1202 23
    protected function _getNestedTransactionSavePointName()
1203
    {
1204 23
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1205
    }
1206
1207
    /**
1208
     * {@inheritDoc}
1209
     */
1210 530
    public function beginTransaction()
1211
    {
1212 530
        $connection = $this->getWrappedConnection();
1213
1214 530
        ++$this->transactionNestingLevel;
1215
1216 530
        $logger = $this->_config->getSQLLogger();
1217
1218 530
        if ($this->transactionNestingLevel === 1) {
1219 530
            if ($logger !== null) {
1220 378
                $logger->startQuery('"START TRANSACTION"');
1221
            }
1222
1223 530
            $connection->beginTransaction();
1224
1225 530
            if ($logger !== null) {
1226 530
                $logger->stopQuery();
1227
            }
1228 92
        } elseif ($this->nestTransactionsWithSavepoints) {
1229 23
            if ($logger !== null) {
1230 23
                $logger->startQuery('"SAVEPOINT"');
1231
            }
1232 23
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1233 23
            if ($logger !== null) {
1234 23
                $logger->stopQuery();
1235
            }
1236
        }
1237
1238 530
        return true;
1239
    }
1240
1241
    /**
1242
     * {@inheritDoc}
1243
     *
1244
     * @throws ConnectionException If the commit failed due to no active transaction or
1245
     *                                            because the transaction was marked for rollback only.
1246
     */
1247 325
    public function commit()
1248
    {
1249 325
        if ($this->transactionNestingLevel === 0) {
1250 23
            throw ConnectionException::noActiveTransaction();
1251
        }
1252 302
        if ($this->isRollbackOnly) {
1253 46
            throw ConnectionException::commitFailedRollbackOnly();
1254
        }
1255
1256 256
        $result = true;
1257
1258 256
        $connection = $this->getWrappedConnection();
1259
1260 256
        $logger = $this->_config->getSQLLogger();
1261
1262 256
        if ($this->transactionNestingLevel === 1) {
1263 256
            if ($logger !== null) {
1264 150
                $logger->startQuery('"COMMIT"');
1265
            }
1266
1267 256
            $result = $connection->commit();
1268
1269 256
            if ($logger !== null) {
1270 256
                $logger->stopQuery();
1271
            }
1272 46
        } elseif ($this->nestTransactionsWithSavepoints) {
1273 23
            if ($logger !== null) {
1274 23
                $logger->startQuery('"RELEASE SAVEPOINT"');
1275
            }
1276 23
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1277 23
            if ($logger !== null) {
1278 23
                $logger->stopQuery();
1279
            }
1280
        }
1281
1282 256
        --$this->transactionNestingLevel;
1283
1284 256
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1285 233
            return $result;
1286
        }
1287
1288 46
        $this->beginTransaction();
1289
1290 46
        return $result;
1291
    }
1292
1293
    /**
1294
     * Commits all current nesting transactions.
1295
     */
1296 23
    private function commitAll() : void
1297
    {
1298 23
        while ($this->transactionNestingLevel !== 0) {
1299 23
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1300
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1301
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1302 23
                $this->commit();
1303
1304 23
                return;
1305
            }
1306
1307 23
            $this->commit();
1308
        }
1309 23
    }
1310
1311
    /**
1312
     * Cancels any database changes done during the current transaction.
1313
     *
1314
     * @return bool
1315
     *
1316
     * @throws ConnectionException If the rollback operation failed.
1317
     */
1318 318
    public function rollBack()
1319
    {
1320 318
        if ($this->transactionNestingLevel === 0) {
1321 23
            throw ConnectionException::noActiveTransaction();
1322
        }
1323
1324 295
        $connection = $this->getWrappedConnection();
1325
1326 295
        $logger = $this->_config->getSQLLogger();
1327
1328 295
        if ($this->transactionNestingLevel === 1) {
1329 272
            if ($logger !== null) {
1330 249
                $logger->startQuery('"ROLLBACK"');
1331
            }
1332 272
            $this->transactionNestingLevel = 0;
1333 272
            $connection->rollBack();
1334 272
            $this->isRollbackOnly = false;
1335 272
            if ($logger !== null) {
1336 249
                $logger->stopQuery();
1337
            }
1338
1339 272
            if ($this->autoCommit === false) {
1340 272
                $this->beginTransaction();
1341
            }
1342 48
        } elseif ($this->nestTransactionsWithSavepoints) {
1343 23
            if ($logger !== null) {
1344 23
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1345
            }
1346 23
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1347 23
            --$this->transactionNestingLevel;
1348 23
            if ($logger !== null) {
1349 23
                $logger->stopQuery();
1350
            }
1351
        } else {
1352 25
            $this->isRollbackOnly = true;
1353 25
            --$this->transactionNestingLevel;
1354
        }
1355
1356 295
        return true;
1357
    }
1358
1359
    /**
1360
     * Creates a new savepoint.
1361
     *
1362
     * @param string $savepoint The name of the savepoint to create.
1363
     *
1364
     * @return void
1365
     *
1366
     * @throws ConnectionException
1367
     */
1368 23
    public function createSavepoint($savepoint)
1369
    {
1370 23
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1371
            throw ConnectionException::savepointsNotSupported();
1372
        }
1373
1374 23
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1375 23
    }
1376
1377
    /**
1378
     * Releases the given savepoint.
1379
     *
1380
     * @param string $savepoint The name of the savepoint to release.
1381
     *
1382
     * @return void
1383
     *
1384
     * @throws ConnectionException
1385
     */
1386 23
    public function releaseSavepoint($savepoint)
1387
    {
1388 23
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1389
            throw ConnectionException::savepointsNotSupported();
1390
        }
1391
1392 23
        if (! $this->platform->supportsReleaseSavepoints()) {
1393 2
            return;
1394
        }
1395
1396 21
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1397 21
    }
1398
1399
    /**
1400
     * Rolls back to the given savepoint.
1401
     *
1402
     * @param string $savepoint The name of the savepoint to rollback to.
1403
     *
1404
     * @return void
1405
     *
1406
     * @throws ConnectionException
1407
     */
1408 23
    public function rollbackSavepoint($savepoint)
1409
    {
1410 23
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1411
            throw ConnectionException::savepointsNotSupported();
1412
        }
1413
1414 23
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1415 23
    }
1416
1417
    /**
1418
     * Gets the wrapped driver connection.
1419
     *
1420
     * @return DriverConnection
1421
     */
1422 7898
    public function getWrappedConnection()
1423
    {
1424 7898
        $this->connect();
1425
1426 7892
        return $this->_conn;
1427
    }
1428
1429
    /**
1430
     * Gets the SchemaManager that can be used to inspect or change the
1431
     * database schema through the connection.
1432
     *
1433
     * @return AbstractSchemaManager
1434
     */
1435 4615
    public function getSchemaManager()
1436
    {
1437 4615
        if ($this->_schemaManager === null) {
1438 308
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1439
        }
1440
1441 4615
        return $this->_schemaManager;
1442
    }
1443
1444
    /**
1445
     * Marks the current transaction so that the only possible
1446
     * outcome for the transaction to be rolled back.
1447
     *
1448
     * @return void
1449
     *
1450
     * @throws ConnectionException If no transaction is active.
1451
     */
1452 46
    public function setRollbackOnly()
1453
    {
1454 46
        if ($this->transactionNestingLevel === 0) {
1455 23
            throw ConnectionException::noActiveTransaction();
1456
        }
1457 23
        $this->isRollbackOnly = true;
1458 23
    }
1459
1460
    /**
1461
     * Checks whether the current transaction is marked for rollback only.
1462
     *
1463
     * @return bool
1464
     *
1465
     * @throws ConnectionException If no transaction is active.
1466
     */
1467 69
    public function isRollbackOnly()
1468
    {
1469 69
        if ($this->transactionNestingLevel === 0) {
1470 23
            throw ConnectionException::noActiveTransaction();
1471
        }
1472
1473 46
        return $this->isRollbackOnly;
1474
    }
1475
1476
    /**
1477
     * Converts a given value to its database representation according to the conversion
1478
     * rules of a specific DBAL mapping type.
1479
     *
1480
     * @param mixed  $value The value to convert.
1481
     * @param string $type  The name of the DBAL mapping type.
1482
     *
1483
     * @return mixed The converted value.
1484
     */
1485
    public function convertToDatabaseValue($value, $type)
1486
    {
1487
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1488
    }
1489
1490
    /**
1491
     * Converts a given value to its PHP representation according to the conversion
1492
     * rules of a specific DBAL mapping type.
1493
     *
1494
     * @param mixed  $value The value to convert.
1495
     * @param string $type  The name of the DBAL mapping type.
1496
     *
1497
     * @return mixed The converted type.
1498
     */
1499
    public function convertToPHPValue($value, $type)
1500
    {
1501
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1502
    }
1503
1504
    /**
1505
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1506
     * or DBAL mapping type, to a given statement.
1507
     *
1508
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1509
     *           raw PDOStatement instances.
1510
     *
1511
     * @param DriverStatement $stmt   The statement to bind the values to.
1512
     * @param mixed[]         $params The map/list of named/positional parameters.
1513
     * @param int[]|string[]  $types  The parameter types (PDO binding types or DBAL mapping types).
1514
     */
1515 2855
    private function _bindTypedValues(DriverStatement $stmt, array $params, array $types) : void
1516
    {
1517
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1518 2855
        if (is_int(key($params))) {
1519
            // Positional parameters
1520 2855
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1521 2855
            $bindIndex  = 1;
1522 2855
            foreach ($params as $value) {
1523 2855
                $typeIndex = $bindIndex + $typeOffset;
1524 2855
                if (isset($types[$typeIndex])) {
1525 670
                    $type                  = $types[$typeIndex];
1526 670
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1527 670
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1528
                } else {
1529 2280
                    $stmt->bindValue($bindIndex, $value);
1530
                }
1531 2855
                ++$bindIndex;
1532
            }
1533
        } else {
1534
            // Named parameters
1535
            foreach ($params as $name => $value) {
1536
                if (isset($types[$name])) {
1537
                    $type                  = $types[$name];
1538
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1539
                    $stmt->bindValue($name, $value, $bindingType);
1540
                } else {
1541
                    $stmt->bindValue($name, $value);
1542
                }
1543
            }
1544
        }
1545 2787
    }
1546
1547
    /**
1548
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1549
     *
1550
     * @param mixed           $value The value to bind.
1551
     * @param int|string|null $type  The type to bind (PDO or DBAL).
1552
     *
1553
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1554
     */
1555 912
    private function getBindingInfo($value, $type)
1556
    {
1557 912
        if (is_string($type)) {
1558 276
            $type = Type::getType($type);
1559
        }
1560 912
        if ($type instanceof Type) {
1561 276
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1562 276
            $bindingType = $type->getBindingType();
1563
        } else {
1564 774
            $bindingType = $type;
1565
        }
1566
1567 912
        return [$value, $bindingType];
1568
    }
1569
1570
    /**
1571
     * Resolves the parameters to a format which can be displayed.
1572
     *
1573
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1574
     *           copy/paste the code as this method may change, or be removed without prior notice.
1575
     *
1576
     * @param mixed[]        $params
1577
     * @param int[]|string[] $types
1578
     *
1579
     * @return mixed[]
1580
     */
1581 2887
    public function resolveParams(array $params, array $types)
1582
    {
1583 2887
        $resolvedParams = [];
1584
1585
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1586 2887
        if (is_int(key($params))) {
1587
            // Positional parameters
1588 223
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1589 223
            $bindIndex  = 1;
1590 223
            foreach ($params as $value) {
1591 223
                $typeIndex = $bindIndex + $typeOffset;
1592 223
                if (isset($types[$typeIndex])) {
1593
                    $type                       = $types[$typeIndex];
1594
                    [$value]                    = $this->getBindingInfo($value, $type);
1595
                    $resolvedParams[$bindIndex] = $value;
1596
                } else {
1597 223
                    $resolvedParams[$bindIndex] = $value;
1598
                }
1599 223
                ++$bindIndex;
1600
            }
1601
        } else {
1602
            // Named parameters
1603 2670
            foreach ($params as $name => $value) {
1604
                if (isset($types[$name])) {
1605
                    $type                  = $types[$name];
1606
                    [$value]               = $this->getBindingInfo($value, $type);
1607
                    $resolvedParams[$name] = $value;
1608
                } else {
1609
                    $resolvedParams[$name] = $value;
1610
                }
1611
            }
1612
        }
1613
1614 2887
        return $resolvedParams;
1615
    }
1616
1617
    /**
1618
     * Creates a new instance of a SQL query builder.
1619
     *
1620
     * @return QueryBuilder
1621
     */
1622
    public function createQueryBuilder()
1623
    {
1624
        return new Query\QueryBuilder($this);
1625
    }
1626
1627
    /**
1628
     * Ping the server
1629
     *
1630
     * When the server is not available the method returns FALSE.
1631
     * It is responsibility of the developer to handle this case
1632
     * and abort the request or reconnect manually:
1633
     *
1634
     * @return bool
1635
     *
1636
     * @example
1637
     *
1638
     *   if ($conn->ping() === false) {
1639
     *      $conn->close();
1640
     *      $conn->connect();
1641
     *   }
1642
     *
1643
     * It is undefined if the underlying driver attempts to reconnect
1644
     * or disconnect when the connection is not available anymore
1645
     * as long it returns TRUE when a reconnect succeeded and
1646
     * FALSE when the connection was dropped.
1647
     */
1648 23
    public function ping()
1649
    {
1650 23
        $connection = $this->getWrappedConnection();
1651
1652 23
        if ($connection instanceof PingableConnection) {
1653 6
            return $connection->ping();
1654
        }
1655
1656
        try {
1657 17
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1658
1659 17
            return true;
1660
        } catch (DBALException $e) {
1661
            return false;
1662
        }
1663
    }
1664
}
1665