Completed
Pull Request — 2.10.x (#3994)
by Grégoire
11:52
created

Connection::getTransactionIsolation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

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

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

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

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

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

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

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

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

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

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