Passed
Push — 2.9 ( d389f3...7345cd )
by Sergei
31:44 queued 28:51
created

Connection::executeCacheQuery()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.392

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 28
ccs 12
cts 15
cp 0.8
rs 8.8333
c 0
b 0
f 0
cc 7
nc 9
nop 4
crap 7.392
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 4259
    public function __construct(
184
        array $params,
185
        Driver $driver,
186
        ?Configuration $config = null,
187
        ?EventManager $eventManager = null
188
    ) {
189 4259
        $this->_driver = $driver;
190 4259
        $this->params  = $params;
191
192 4259
        if (isset($params['pdo'])) {
193 360
            $this->_conn       = $params['pdo'];
194 360
            $this->isConnected = true;
195 360
            unset($this->params['pdo']);
196
        }
197
198 4259
        if (isset($params['platform'])) {
199 840
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
200 30
                throw DBALException::invalidPlatformType($params['platform']);
201
            }
202
203 810
            $this->platform = $params['platform'];
204 810
            unset($this->params['platform']);
205
        }
206
207
        // Create default config and event manager if none given
208 4259
        if (! $config) {
209 930
            $config = new Configuration();
210
        }
211
212 4259
        if (! $eventManager) {
213 930
            $eventManager = new EventManager();
214
        }
215
216 4259
        $this->_config       = $config;
217 4259
        $this->_eventManager = $eventManager;
218
219 4259
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
220
221 4259
        $this->autoCommit = $config->getAutoCommit();
222 4259
    }
223
224
    /**
225
     * Gets the parameters used during instantiation.
226
     *
227
     * @return mixed[]
228
     */
229 3880
    public function getParams()
230
    {
231 3880
        return $this->params;
232
    }
233
234
    /**
235
     * Gets the name of the database this Connection is connected to.
236
     *
237
     * @return string
238
     */
239 1985
    public function getDatabase()
240
    {
241 1985
        return $this->_driver->getDatabase($this);
242
    }
243
244
    /**
245
     * Gets the hostname of the currently connected database.
246
     *
247
     * @return string|null
248
     */
249 30
    public function getHost()
250
    {
251 30
        return $this->params['host'] ?? null;
252
    }
253
254
    /**
255
     * Gets the port of the currently connected database.
256
     *
257
     * @return mixed
258
     */
259 30
    public function getPort()
260
    {
261 30
        return $this->params['port'] ?? null;
262
    }
263
264
    /**
265
     * Gets the username used by this connection.
266
     *
267
     * @return string|null
268
     */
269 83
    public function getUsername()
270
    {
271 83
        return $this->params['user'] ?? null;
272
    }
273
274
    /**
275
     * Gets the password used by this connection.
276
     *
277
     * @return string|null
278
     */
279 30
    public function getPassword()
280
    {
281 30
        return $this->params['password'] ?? null;
282
    }
283
284
    /**
285
     * Gets the DBAL driver instance.
286
     *
287
     * @return Driver
288
     */
289 1948
    public function getDriver()
290
    {
291 1948
        return $this->_driver;
292
    }
293
294
    /**
295
     * Gets the Configuration used by the Connection.
296
     *
297
     * @return Configuration
298
     */
299 9275
    public function getConfiguration()
300
    {
301 9275
        return $this->_config;
302
    }
303
304
    /**
305
     * Gets the EventManager used by the Connection.
306
     *
307
     * @return EventManager
308
     */
309 398
    public function getEventManager()
310
    {
311 398
        return $this->_eventManager;
312
    }
313
314
    /**
315
     * Gets the DatabasePlatform for the connection.
316
     *
317
     * @return AbstractPlatform
318
     *
319
     * @throws DBALException
320
     */
321 7831
    public function getDatabasePlatform()
322
    {
323 7831
        if ($this->platform === null) {
324 1222
            $this->detectDatabasePlatform();
325
        }
326
327 7801
        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 9451
    public function connect()
347
    {
348 9451
        if ($this->isConnected) {
349 8827
            return false;
350
        }
351
352 1511
        $driverOptions = $this->params['driverOptions'] ?? [];
353 1511
        $user          = $this->params['user'] ?? null;
354 1511
        $password      = $this->params['password'] ?? null;
355
356 1511
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
357 1386
        $this->isConnected = true;
358
359 1386
        $this->transactionNestingLevel = 0;
360
361 1386
        if ($this->autoCommit === false) {
362 90
            $this->beginTransaction();
363
        }
364
365 1386
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
366 30
            $eventArgs = new Event\ConnectionEventArgs($this);
367 30
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
368
        }
369
370 1386
        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 1222
    private function detectDatabasePlatform()
381
    {
382 1222
        $version = $this->getDatabasePlatformVersion();
383
384 1123
        if ($version !== null) {
385 821
            assert($this->_driver instanceof VersionAwarePlatformDriver);
386
387 821
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
388
        } else {
389 302
            $this->platform = $this->_driver->getDatabasePlatform();
390
        }
391
392 1123
        $this->platform->setEventManager($this->_eventManager);
393 1123
    }
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 1222
    private function getDatabasePlatformVersion()
408
    {
409
        // Driver does not support version specific platforms.
410 1222
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
411 272
            return null;
412
        }
413
414
        // Explicit platform version requested (supersedes auto-detection).
415 950
        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 950
        if ($this->_conn === null) {
421
            try {
422 894
                $this->connect();
423 127
            } catch (Throwable $originalException) {
424 127
                if (empty($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 127
                $databaseName           = $this->params['dbname'];
431 127
                $this->params['dbname'] = null;
432
433
                try {
434 127
                    $this->connect();
435 99
                } 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 99
                    $this->params['dbname'] = $databaseName;
440
441 99
                    throw $originalException;
442
                }
443
444
                // Reset connection parameters.
445 28
                $this->params['dbname'] = $databaseName;
446 28
                $serverVersion          = $this->getServerVersion();
447
448
                // Close "temporary" connection to allow connecting to the real database again.
449 28
                $this->close();
450
451 28
                return $serverVersion;
452
            }
453
        }
454
455 851
        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 851
    private function getServerVersion()
464
    {
465
        // Automatic platform version detection.
466 851
        if ($this->_conn instanceof ServerInfoAwareConnection &&
467 851
            ! $this->_conn->requiresQueryForServerVersion()
468
        ) {
469 821
            return $this->_conn->getServerVersion();
470
        }
471
472
        // Unable to detect platform version.
473 30
        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 60
    public function isAutoCommit()
484
    {
485 60
        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 150
    public function setAutoCommit($autoCommit)
503
    {
504 150
        $autoCommit = (bool) $autoCommit;
505
506
        // Mode not changed, no-op.
507 150
        if ($autoCommit === $this->autoCommit) {
508 30
            return;
509
        }
510
511 150
        $this->autoCommit = $autoCommit;
512
513
        // Commit all currently active transactions if any when switching auto-commit mode.
514 150
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
515 120
            return;
516
        }
517
518 30
        $this->commitAll();
519 30
    }
520
521
    /**
522
     * Sets the fetch mode.
523
     *
524
     * @param int $fetchMode
525
     *
526
     * @return void
527
     */
528 30
    public function setFetchMode($fetchMode)
529
    {
530 30
        $this->defaultFetchMode = $fetchMode;
531 30
    }
532
533
    /**
534
     * Prepares and executes an SQL query and returns the first row of the result
535
     * as an associative array.
536
     *
537
     * @param string         $statement The SQL query.
538
     * @param mixed[]        $params    The query parameters.
539
     * @param int[]|string[] $types     The query parameter types.
540
     *
541
     * @return mixed[]|false False is returned if no rows are found.
542
     *
543
     * @throws DBALException
544
     */
545 2058
    public function fetchAssoc($statement, array $params = [], array $types = [])
546
    {
547 2058
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
548
    }
549
550
    /**
551
     * Prepares and executes an SQL query and returns the first row of the result
552
     * as a numerically indexed array.
553
     *
554
     * @param string         $statement The SQL query to be executed.
555
     * @param mixed[]        $params    The prepared statement params.
556
     * @param int[]|string[] $types     The query parameter types.
557
     *
558
     * @return mixed[]|false False is returned if no rows are found.
559
     */
560 110
    public function fetchArray($statement, array $params = [], array $types = [])
561
    {
562 110
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
563
    }
564
565
    /**
566
     * Prepares and executes an SQL query and returns the value of a single column
567
     * of the first row of the result.
568
     *
569
     * @param string         $statement The SQL query to be executed.
570
     * @param mixed[]        $params    The prepared statement params.
571
     * @param int            $column    The 0-indexed column number to retrieve.
572
     * @param int[]|string[] $types     The query parameter types.
573
     *
574
     * @return mixed|false False is returned if no rows are found.
575
     *
576
     * @throws DBALException
577
     */
578 1160
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
579
    {
580 1160
        return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
581
    }
582
583
    /**
584
     * Whether an actual connection to the database is established.
585
     *
586
     * @return bool
587
     */
588 119
    public function isConnected()
589
    {
590 119
        return $this->isConnected;
591
    }
592
593
    /**
594
     * Checks whether a transaction is currently active.
595
     *
596
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
597
     */
598 9245
    public function isTransactionActive()
599
    {
600 9245
        return $this->transactionNestingLevel > 0;
601
    }
602
603
    /**
604
     * Gathers conditions for an update or delete call.
605
     *
606
     * @param mixed[] $identifiers Input array of columns to values
607
     *
608
     * @return string[][] a triplet with:
609
     *                    - the first key being the columns
610
     *                    - the second key being the values
611
     *                    - the third key being the conditions
612
     */
613 472
    private function gatherConditions(array $identifiers)
614
    {
615 472
        $columns    = [];
616 472
        $values     = [];
617 472
        $conditions = [];
618
619 472
        foreach ($identifiers as $columnName => $value) {
620 472
            if ($value === null) {
621 120
                $conditions[] = $this->getDatabasePlatform()->getIsNullExpression($columnName);
622 120
                continue;
623
            }
624
625 412
            $columns[]    = $columnName;
626 412
            $values[]     = $value;
627 412
            $conditions[] = $columnName . ' = ?';
628
        }
629
630 472
        return [$columns, $values, $conditions];
631
    }
632
633
    /**
634
     * Executes an SQL DELETE statement on a table.
635
     *
636
     * Table expression and columns are not escaped and are not safe for user-input.
637
     *
638
     * @param string         $tableExpression The expression of the table on which to delete.
639
     * @param mixed[]        $identifier      The deletion criteria. An associative array containing column-value pairs.
640
     * @param int[]|string[] $types           The types of identifiers.
641
     *
642
     * @return int The number of affected rows.
643
     *
644
     * @throws DBALException
645
     * @throws InvalidArgumentException
646
     */
647 206
    public function delete($tableExpression, array $identifier, array $types = [])
648
    {
649 206
        if (empty($identifier)) {
650 30
            throw InvalidArgumentException::fromEmptyCriteria();
651
        }
652
653 176
        [$columns, $values, $conditions] = $this->gatherConditions($identifier);
654
655 176
        return $this->executeUpdate(
656 176
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
657 176
            $values,
658 176
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
659
        );
660
    }
661
662
    /**
663
     * Closes the connection.
664
     *
665
     * @return void
666
     */
667 787
    public function close()
668
    {
669 787
        $this->_conn = null;
670
671 787
        $this->isConnected = false;
672 787
    }
673
674
    /**
675
     * Sets the transaction isolation level.
676
     *
677
     * @param int $level The level to set.
678
     *
679
     * @return int
680
     */
681
    public function setTransactionIsolation($level)
682
    {
683
        $this->transactionIsolationLevel = $level;
684
685
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
686
    }
687
688
    /**
689
     * Gets the currently active transaction isolation level.
690
     *
691
     * @return int The current transaction isolation level.
692
     */
693
    public function getTransactionIsolation()
694
    {
695
        if ($this->transactionIsolationLevel === null) {
696
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
697
        }
698
699
        return $this->transactionIsolationLevel;
700
    }
701
702
    /**
703
     * Executes an SQL UPDATE statement on a table.
704
     *
705
     * Table expression and columns are not escaped and are not safe for user-input.
706
     *
707
     * @param string         $tableExpression The expression of the table to update quoted or unquoted.
708
     * @param mixed[]        $data            An associative array containing column-value pairs.
709
     * @param mixed[]        $identifier      The update criteria. An associative array containing column-value pairs.
710
     * @param int[]|string[] $types           Types of the merged $data and $identifier arrays in that order.
711
     *
712
     * @return int The number of affected rows.
713
     *
714
     * @throws DBALException
715
     */
716 296
    public function update($tableExpression, array $data, array $identifier, array $types = [])
717
    {
718 296
        $setColumns = [];
719 296
        $setValues  = [];
720 296
        $set        = [];
721
722 296
        foreach ($data as $columnName => $value) {
723 296
            $setColumns[] = $columnName;
724 296
            $setValues[]  = $value;
725 296
            $set[]        = $columnName . ' = ?';
726
        }
727
728 296
        [$conditionColumns, $conditionValues, $conditions] = $this->gatherConditions($identifier);
729 296
        $columns                                           = array_merge($setColumns, $conditionColumns);
730 296
        $values                                            = array_merge($setValues, $conditionValues);
731
732 296
        if (is_string(key($types))) {
733 150
            $types = $this->extractTypeValues($columns, $types);
734
        }
735
736 296
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
737 296
                . ' WHERE ' . implode(' AND ', $conditions);
738
739 296
        return $this->executeUpdate($sql, $values, $types);
740
    }
741
742
    /**
743
     * Inserts a table row with specified data.
744
     *
745
     * Table expression and columns are not escaped and are not safe for user-input.
746
     *
747
     * @param string         $tableExpression The expression of the table to insert data into, quoted or unquoted.
748
     * @param mixed[]        $data            An associative array containing column-value pairs.
749
     * @param int[]|string[] $types           Types of the inserted data.
750
     *
751
     * @return int The number of affected rows.
752
     *
753
     * @throws DBALException
754
     */
755 2773
    public function insert($tableExpression, array $data, array $types = [])
756
    {
757 2773
        if (empty($data)) {
758 30
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
759
        }
760
761 2743
        $columns = [];
762 2743
        $values  = [];
763 2743
        $set     = [];
764
765 2743
        foreach ($data as $columnName => $value) {
766 2743
            $columns[] = $columnName;
767 2743
            $values[]  = $value;
768 2743
            $set[]     = '?';
769
        }
770
771 2743
        return $this->executeUpdate(
772 2743
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
773 2743
            ' VALUES (' . implode(', ', $set) . ')',
774 2743
            $values,
775 2743
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
776
        );
777
    }
778
779
    /**
780
     * Extract ordered type list from an ordered column list and type map.
781
     *
782
     * @param string[]       $columnList
783
     * @param int[]|string[] $types
784
     *
785
     * @return int[]|string[]
786
     */
787 270
    private function extractTypeValues(array $columnList, array $types)
788
    {
789 270
        $typeValues = [];
790
791 270
        foreach ($columnList as $columnIndex => $columnName) {
792 270
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
793
        }
794
795 270
        return $typeValues;
796
    }
797
798
    /**
799
     * Quotes a string so it can be safely used as a table or column name, even if
800
     * it is a reserved name.
801
     *
802
     * Delimiting style depends on the underlying database platform that is being used.
803
     *
804
     * NOTE: Just because you CAN use quoted identifiers does not mean
805
     * you SHOULD use them. In general, they end up causing way more
806
     * problems than they solve.
807
     *
808
     * @param string $str The name to be quoted.
809
     *
810
     * @return string The quoted name.
811
     */
812 30
    public function quoteIdentifier($str)
813
    {
814 30
        return $this->getDatabasePlatform()->quoteIdentifier($str);
815
    }
816
817
    /**
818
     * Quotes a given input parameter.
819
     *
820
     * @param mixed    $input The parameter to be quoted.
821
     * @param int|null $type  The type of the parameter.
822
     *
823
     * @return string The quoted parameter.
824
     */
825 274
    public function quote($input, $type = null)
826
    {
827 274
        $this->connect();
828
829 274
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
830
831 274
        return $this->_conn->quote($value, $bindingType);
0 ignored issues
show
Bug introduced by
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

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

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

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

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

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