Passed
Pull Request — 2.10.x (#3979)
by Ben
08:48
created

Connection::setNestTransactionsWithSavepoints()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0416
1
<?php
2
3
namespace Doctrine\DBAL;
4
5
use Closure;
6
use Doctrine\Common\EventManager;
7
use Doctrine\DBAL\Cache\ArrayStatement;
8
use Doctrine\DBAL\Cache\CacheException;
9
use Doctrine\DBAL\Cache\QueryCacheProfile;
10
use Doctrine\DBAL\Cache\ResultCacheStatement;
11
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12
use Doctrine\DBAL\Driver\PingableConnection;
13
use Doctrine\DBAL\Driver\ResultStatement;
14
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
15
use Doctrine\DBAL\Driver\Statement as DriverStatement;
16
use Doctrine\DBAL\Exception\InvalidArgumentException;
17
use Doctrine\DBAL\Platforms\AbstractPlatform;
18
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
19
use Doctrine\DBAL\Query\QueryBuilder;
20
use Doctrine\DBAL\Schema\AbstractSchemaManager;
21
use Doctrine\DBAL\Types\Type;
22
use Exception;
23
use Throwable;
24
use function array_key_exists;
25
use function assert;
26
use function 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 9238
    public function __construct(
183
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188 9238
        $this->_driver = $driver;
189 9238
        $this->params  = $params;
190
191 9238
        if (isset($params['pdo'])) {
192 8314
            $this->_conn       = $params['pdo'];
193 8314
            $this->isConnected = true;
194 8314
            unset($this->params['pdo']);
195
        }
196
197 9238
        if (isset($params['platform'])) {
198 8492
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199 8052
                throw DBALException::invalidPlatformType($params['platform']);
200
            }
201
202 8491
            $this->platform = $params['platform'];
203
        }
204
205
        // Create default config and event manager if none given
206 9238
        if (! $config) {
207 9138
            $config = new Configuration();
208
        }
209
210 9238
        if (! $eventManager) {
211 9137
            $eventManager = new EventManager();
212
        }
213
214 9238
        $this->_config       = $config;
215 9238
        $this->_eventManager = $eventManager;
216
217 9238
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
218
219 9238
        $this->autoCommit = $config->getAutoCommit();
220 9238
    }
221
222
    /**
223
     * Gets the parameters used during instantiation.
224
     *
225
     * @return mixed[]
226
     */
227 8425
    public function getParams()
228
    {
229 8425
        return $this->params;
230
    }
231
232
    /**
233
     * Gets the name of the database this Connection is connected to.
234
     *
235
     * @return string
236
     */
237 7893
    public function getDatabase()
238
    {
239 7893
        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 8902
    public function getHost()
250
    {
251 8902
        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 427
    public function getUsername()
274
    {
275 427
        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 8948
    public function getDriver()
296
    {
297 8948
        return $this->_driver;
298
    }
299
300
    /**
301
     * Gets the Configuration used by the Connection.
302
     *
303
     * @return Configuration
304
     */
305 9422
    public function getConfiguration()
306
    {
307 9422
        return $this->_config;
308
    }
309
310
    /**
311
     * Gets the EventManager used by the Connection.
312
     *
313
     * @return EventManager
314
     */
315 6981
    public function getEventManager()
316
    {
317 6981
        return $this->_eventManager;
318
    }
319
320
    /**
321
     * Gets the DatabasePlatform for the connection.
322
     *
323
     * @return AbstractPlatform
324
     *
325
     * @throws DBALException
326
     */
327 9286
    public function getDatabasePlatform()
328
    {
329 9286
        if ($this->platform === null) {
330 9083
            $this->detectDatabasePlatform();
331
        }
332
333 9285
        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 9433
    public function connect()
353
    {
354 9433
        if ($this->isConnected) {
355 8919
            return false;
356
        }
357
358 9152
        $driverOptions = $this->params['driverOptions'] ?? [];
359 9152
        $user          = $this->params['user'] ?? null;
360 9152
        $password      = $this->params['password'] ?? null;
361
362 9152
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
363 9148
        $this->isConnected = true;
364
365 9148
        $this->transactionNestingLevel = 0;
366
367 9148
        if ($this->autoCommit === false) {
368 8604
            $this->beginTransaction();
369
        }
370
371 9148
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
372 8877
            $eventArgs = new Event\ConnectionEventArgs($this);
373 8877
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
374
        }
375
376 9148
        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 9083
    private function detectDatabasePlatform() : void
387
    {
388 9083
        $version = $this->getDatabasePlatformVersion();
389
390 9082
        if ($version !== null) {
391 8127
            assert($this->_driver instanceof VersionAwarePlatformDriver);
392
393 8127
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
394
        } else {
395 9081
            $this->platform = $this->_driver->getDatabasePlatform();
396
        }
397
398 9082
        $this->platform->setEventManager($this->_eventManager);
399 9082
    }
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 9083
    private function getDatabasePlatformVersion()
414
    {
415
        // Driver does not support version specific platforms.
416 9083
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
417 9081
            return null;
418
        }
419
420
        // Explicit platform version requested (supersedes auto-detection).
421 8128
        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 8128
        if ($this->_conn === null) {
427
            try {
428 8128
                $this->connect();
429 8027
            } catch (Throwable $originalException) {
430 8027
                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 8027
                $databaseName           = $this->params['dbname'];
437 8027
                $this->params['dbname'] = null;
438
439
                try {
440 8027
                    $this->connect();
441 8027
                } 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 8027
                    $this->params['dbname'] = $databaseName;
446
447 8027
                    throw $originalException;
448
                }
449
450
                // Reset connection parameters.
451 6663
                $this->params['dbname'] = $databaseName;
452 6663
                $serverVersion          = $this->getServerVersion();
453
454
                // Close "temporary" connection to allow connecting to the real database again.
455 6663
                $this->close();
456
457 6663
                return $serverVersion;
458
            }
459
        }
460
461 8127
        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 8127
    private function getServerVersion()
470
    {
471 8127
        $connection = $this->getWrappedConnection();
472
473
        // Automatic platform version detection.
474 8127
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
475 8127
            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 8653
    public function isAutoCommit()
490
    {
491 8653
        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 8631
    public function setAutoCommit($autoCommit)
511
    {
512 8631
        $autoCommit = (bool) $autoCommit;
513
514
        // Mode not changed, no-op.
515 8631
        if ($autoCommit === $this->autoCommit) {
516 8627
            return;
517
        }
518
519 8631
        $this->autoCommit = $autoCommit;
520
521
        // Commit all currently active transactions if any when switching auto-commit mode.
522 8631
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
523 8630
            return;
524
        }
525
526 8502
        $this->commitAll();
527 8502
    }
528
529
    /**
530
     * Sets the fetch mode.
531
     *
532
     * @param int $fetchMode
533
     *
534
     * @return void
535
     */
536 4309
    public function setFetchMode($fetchMode)
537
    {
538 4309
        $this->defaultFetchMode = $fetchMode;
539 4309
    }
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 8460
    public function fetchAssoc($statement, array $params = [], array $types = [])
554
    {
555 8460
        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 6510
    public function fetchArray($statement, array $params = [], array $types = [])
569
    {
570 6510
        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 8401
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
587
    {
588 8401
        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 9029
    public function isConnected()
597
    {
598 9029
        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 9318
    public function isTransactionActive()
607
    {
608 9318
        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 8466
    private function addIdentifierCondition(
622
        array $identifier,
623
        array &$columns,
624
        array &$values,
625
        array &$conditions
626
    ) : void {
627 8466
        $platform = $this->getDatabasePlatform();
628
629 8466
        foreach ($identifier as $columnName => $value) {
630 8466
            if ($value === null) {
631 8430
                $conditions[] = $platform->getIsNullExpression($columnName);
632 8430
                continue;
633
            }
634
635 8464
            $columns[]    = $columnName;
636 8464
            $values[]     = $value;
637 8464
            $conditions[] = $columnName . ' = ?';
638
        }
639 8466
    }
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 8408
    public function delete($tableExpression, array $identifier, array $types = [])
656
    {
657 8408
        if (empty($identifier)) {
658 8277
            throw InvalidArgumentException::fromEmptyCriteria();
659
        }
660
661 8407
        $columns = $values = $conditions = [];
662
663 8407
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
664
665 8407
        return $this->executeUpdate(
666 8407
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
667
            $values,
668 8407
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
669
        );
670
    }
671
672
    /**
673
     * Closes the connection.
674
     *
675
     * @return void
676
     */
677 7969
    public function close()
678
    {
679 7969
        $this->_conn = null;
680
681 7969
        $this->isConnected = false;
682 7969
    }
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 8460
    public function update($tableExpression, array $data, array $identifier, array $types = [])
727
    {
728 8460
        $columns = $values = $conditions = $set = [];
729
730 8460
        foreach ($data as $columnName => $value) {
731 8460
            $columns[] = $columnName;
732 8460
            $values[]  = $value;
733 8460
            $set[]     = $columnName . ' = ?';
734
        }
735
736 8460
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
737
738 8460
        if (is_string(key($types))) {
739 8456
            $types = $this->extractTypeValues($columns, $types);
740
        }
741
742 8460
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
743 8460
                . ' WHERE ' . implode(' AND ', $conditions);
744
745 8460
        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 8557
    public function insert($tableExpression, array $data, array $types = [])
762
    {
763 8557
        if (empty($data)) {
764 8477
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
765
        }
766
767 8306
        $columns = [];
768 8306
        $values  = [];
769 8306
        $set     = [];
770
771 8306
        foreach ($data as $columnName => $value) {
772 8306
            $columns[] = $columnName;
773 8306
            $values[]  = $value;
774 8306
            $set[]     = '?';
775
        }
776
777 8306
        return $this->executeUpdate(
778 8306
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
779 8306
            ' VALUES (' . implode(', ', $set) . ')',
780
            $values,
781 8306
            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 8460
    private function extractTypeValues(array $columnList, array $types)
794
    {
795 8460
        $typeValues = [];
796
797 8460
        foreach ($columnList as $columnIndex => $columnName) {
798 8460
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
799
        }
800
801 8460
        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 6739
    public function quoteIdentifier($str)
819
    {
820 6739
        return $this->getDatabasePlatform()->quoteIdentifier($str);
821
    }
822
823
    /**
824
     * {@inheritDoc}
825
     */
826 7002
    public function quote($input, $type = ParameterType::STRING)
827
    {
828 7002
        $connection = $this->getWrappedConnection();
829
830 7002
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
831
832 7002
        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 8432
    public function fetchAll($sql, array $params = [], $types = [])
845
    {
846 8432
        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 9099
    public function prepare($statement)
859
    {
860
        try {
861 9099
            $stmt = new Statement($statement, $this);
862 8702
        } catch (Throwable $ex) {
863 8702
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
864
        }
865
866 9098
        $stmt->setFetchMode($this->defaultFetchMode);
867
868 9098
        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 9335
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
887
    {
888 9335
        if ($qcp !== null) {
889 4229
            return $this->executeCacheQuery($query, $params, $types, $qcp);
890
        }
891
892 9335
        $connection = $this->getWrappedConnection();
893
894 9335
        $logger = $this->_config->getSQLLogger();
895 9335
        if ($logger) {
896 9330
            $logger->startQuery($query, $params, $types);
897
        }
898
899
        try {
900 9335
            if ($params) {
901 6730
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
902
903 6730
                $stmt = $connection->prepare($query);
904 6730
                if ($types) {
905 6729
                    $this->_bindTypedValues($stmt, $params, $types);
906 6725
                    $stmt->execute();
907
                } else {
908 6726
                    $stmt->execute($params);
909
                }
910
            } else {
911 9331
                $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 8759
        } catch (Throwable $ex) {
914 8759
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
915
        }
916
917 9327
        $stmt->setFetchMode($this->defaultFetchMode);
918
919 9327
        if ($logger) {
920 9323
            $logger->stopQuery();
921
        }
922
923 9327
        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 8116
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
939
    {
940 8116
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
941
942 8116
        if ($resultCache === null) {
943
            throw CacheException::noResultDriverConfigured();
944
        }
945
946 8116
        $connectionParams = $this->getParams();
947 8116
        unset($connectionParams['platform']);
948
949 8116
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
950
951
        // fetch the row pointers entry
952 8116
        $data = $resultCache->fetch($cacheKey);
953
954 8116
        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 8112
            if (isset($data[$realKey])) {
957 8112
                $stmt = new ArrayStatement($data[$realKey]);
958
            } elseif (array_key_exists($realKey, $data)) {
959
                $stmt = new ArrayStatement([]);
960
            }
961
        }
962
963 8116
        if (! isset($stmt)) {
964 4230
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
965
        }
966
967 8116
        $stmt->setFetchMode($this->defaultFetchMode);
968
969 8116
        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 8793
    public function query()
1006
    {
1007 8793
        $connection = $this->getWrappedConnection();
1008
1009 8793
        $args = func_get_args();
1010
1011 8793
        $logger = $this->_config->getSQLLogger();
1012 8793
        if ($logger) {
1013 7411
            $logger->startQuery($args[0]);
1014
        }
1015
1016
        try {
1017 8793
            $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 8777
        } catch (Throwable $ex) {
1019 8777
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1020
        }
1021
1022 7412
        $statement->setFetchMode($this->defaultFetchMode);
1023
1024 7412
        if ($logger) {
1025 7411
            $logger->stopQuery();
1026
        }
1027
1028 7412
        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 9263
    public function executeUpdate($query, array $params = [], array $types = [])
1046
    {
1047 9263
        $connection = $this->getWrappedConnection();
1048
1049 9263
        $logger = $this->_config->getSQLLogger();
1050 9263
        if ($logger) {
1051 9258
            $logger->startQuery($query, $params, $types);
1052
        }
1053
1054
        try {
1055 9263
            if ($params) {
1056 8338
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1057
1058 8338
                $stmt = $connection->prepare($query);
1059
1060 8338
                if ($types) {
1061 8338
                    $this->_bindTypedValues($stmt, $params, $types);
1062 8338
                    $stmt->execute();
1063
                } else {
1064
                    $stmt->execute($params);
1065
                }
1066
1067 8336
                $result = $stmt->rowCount();
1068
            } else {
1069 9261
                $result = $connection->exec($query);
1070
            }
1071 8872
        } catch (Throwable $ex) {
1072 8872
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
1073
        }
1074
1075 9253
        if ($logger) {
1076 9248
            $logger->stopQuery();
1077
        }
1078
1079 9253
        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 8883
    public function exec($statement)
1092
    {
1093 8883
        $connection = $this->getWrappedConnection();
1094
1095 8880
        $logger = $this->_config->getSQLLogger();
1096 8880
        if ($logger) {
1097 5878
            $logger->startQuery($statement);
1098
        }
1099
1100
        try {
1101 8880
            $result = $connection->exec($statement);
1102 8858
        } catch (Throwable $ex) {
1103 8858
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1104
        }
1105
1106 5826
        if ($logger) {
1107 5823
            $logger->stopQuery();
1108
        }
1109
1110 5826
        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 8516
    public function getTransactionNestingLevel()
1119
    {
1120 8516
        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 831
    public function lastInsertId($seqName = null)
1154
    {
1155 831
        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 7075
    public function transactional(Closure $func)
1174
    {
1175 7075
        $this->beginTransaction();
1176
        try {
1177 7075
            $res = $func($this);
1178 7023
            $this->commit();
1179
1180 7023
            return $res;
1181 7073
        } catch (Exception $e) {
1182 7072
            $this->rollBack();
1183
1184 7072
            throw $e;
1185 7047
        } catch (Throwable $e) {
1186 7047
            $this->rollBack();
1187
1188 7047
            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 7173
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
1202
    {
1203 7173
        if ($this->transactionNestingLevel > 0) {
1204 7173
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
1205
        }
1206
1207 7172
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1208
            throw ConnectionException::savepointsNotSupported();
1209
        }
1210
1211 7172
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1212 7172
    }
1213
1214
    /**
1215
     * Gets if nested transactions should use savepoints.
1216
     *
1217
     * @return bool
1218
     */
1219 7172
    public function getNestTransactionsWithSavepoints()
1220
    {
1221 7172
        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 7172
    protected function _getNestedTransactionSavePointName()
1231
    {
1232 7172
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1233
    }
1234
1235
    /**
1236
     * {@inheritDoc}
1237
     */
1238 8624
    public function beginTransaction()
1239
    {
1240 8624
        $connection = $this->getWrappedConnection();
1241
1242 8624
        ++$this->transactionNestingLevel;
1243
1244 8624
        $logger = $this->_config->getSQLLogger();
1245
1246 8624
        if ($this->transactionNestingLevel === 1) {
1247 8624
            if ($logger) {
1248 7262
                $logger->startQuery('"START TRANSACTION"');
1249
            }
1250
1251 8624
            $connection->beginTransaction();
1252
1253 8624
            if ($logger) {
1254 8624
                $logger->stopQuery();
1255
            }
1256 8505
        } elseif ($this->nestTransactionsWithSavepoints) {
1257 7172
            if ($logger) {
1258 7172
                $logger->startQuery('"SAVEPOINT"');
1259
            }
1260
1261 7172
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1262 7172
            if ($logger) {
1263 7172
                $logger->stopQuery();
1264
            }
1265
        }
1266
1267 8624
        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 8990
    public function commit()
1277
    {
1278 8990
        if ($this->transactionNestingLevel === 0) {
1279 8977
            throw ConnectionException::noActiveTransaction();
1280
        }
1281
1282 8589
        if ($this->isRollbackOnly) {
1283 7248
            throw ConnectionException::commitFailedRollbackOnly();
1284
        }
1285
1286 8587
        $result = true;
1287
1288 8587
        $connection = $this->getWrappedConnection();
1289
1290 8587
        $logger = $this->_config->getSQLLogger();
1291
1292 8587
        if ($this->transactionNestingLevel === 1) {
1293 8587
            if ($logger) {
1294 7178
                $logger->startQuery('"COMMIT"');
1295
            }
1296
1297 8587
            $result = $connection->commit();
1298
1299 8587
            if ($logger) {
1300 8587
                $logger->stopQuery();
1301
            }
1302 8503
        } elseif ($this->nestTransactionsWithSavepoints) {
1303 7172
            if ($logger) {
1304 7172
                $logger->startQuery('"RELEASE SAVEPOINT"');
1305
            }
1306
1307 7172
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1308 7172
            if ($logger) {
1309 7172
                $logger->stopQuery();
1310
            }
1311
        }
1312
1313 8587
        --$this->transactionNestingLevel;
1314
1315 8587
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1316 8561
            return $result;
1317
        }
1318
1319 8578
        $this->beginTransaction();
1320
1321 8578
        return $result;
1322
    }
1323
1324
    /**
1325
     * Commits all current nesting transactions.
1326
     */
1327 8502
    private function commitAll() : void
1328
    {
1329 8502
        while ($this->transactionNestingLevel !== 0) {
1330 8502
            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 8502
                $this->commit();
1334
1335 8502
                return;
1336
            }
1337
1338 8502
            $this->commit();
1339
        }
1340 8502
    }
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 8964
    public function rollBack()
1350
    {
1351 8964
        if ($this->transactionNestingLevel === 0) {
1352 8952
            throw ConnectionException::noActiveTransaction();
1353
        }
1354
1355 8538
        $connection = $this->getWrappedConnection();
1356
1357 8538
        $logger = $this->_config->getSQLLogger();
1358
1359 8538
        if ($this->transactionNestingLevel === 1) {
1360 8537
            if ($logger) {
1361 7256
                $logger->startQuery('"ROLLBACK"');
1362
            }
1363
1364 8537
            $this->transactionNestingLevel = 0;
1365 8537
            $connection->rollBack();
1366 8537
            $this->isRollbackOnly = false;
1367 8537
            if ($logger) {
1368 7256
                $logger->stopQuery();
1369
            }
1370
1371 8537
            if ($this->autoCommit === false) {
1372 8537
                $this->beginTransaction();
1373
            }
1374 7223
        } elseif ($this->nestTransactionsWithSavepoints) {
1375 7172
            if ($logger) {
1376 7172
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1377
            }
1378
1379 7172
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1380 7172
            --$this->transactionNestingLevel;
1381 7172
            if ($logger) {
1382 7172
                $logger->stopQuery();
1383
            }
1384
        } else {
1385 7222
            $this->isRollbackOnly = true;
1386 7222
            --$this->transactionNestingLevel;
1387
        }
1388
1389 8538
        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 7172
    public function createSavepoint($savepoint)
1402
    {
1403 7172
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1404
            throw ConnectionException::savepointsNotSupported();
1405
        }
1406
1407 7172
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1408 7172
    }
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 7172
    public function releaseSavepoint($savepoint)
1420
    {
1421 7172
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1422
            throw ConnectionException::savepointsNotSupported();
1423
        }
1424
1425 7172
        if (! $this->platform->supportsReleaseSavepoints()) {
1426 509
            return;
1427
        }
1428
1429 6663
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1430 6663
    }
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 7172
    public function rollbackSavepoint($savepoint)
1442
    {
1443 7172
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1444
            throw ConnectionException::savepointsNotSupported();
1445
        }
1446
1447 7172
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1448 7172
    }
1449
1450
    /**
1451
     * Gets the wrapped driver connection.
1452
     *
1453
     * @return DriverConnection
1454
     */
1455 9438
    public function getWrappedConnection()
1456
    {
1457 9438
        $this->connect();
1458
1459 9435
        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 8131
    public function getSchemaManager()
1469
    {
1470 8131
        if ($this->_schemaManager === null) {
1471 7969
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1472
        }
1473
1474 8131
        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 7248
    public function setRollbackOnly()
1486
    {
1487 7248
        if ($this->transactionNestingLevel === 0) {
1488 1
            throw ConnectionException::noActiveTransaction();
1489
        }
1490
1491 7247
        $this->isRollbackOnly = true;
1492 7247
    }
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 7224
    public function isRollbackOnly()
1502
    {
1503 7224
        if ($this->transactionNestingLevel === 0) {
1504 1
            throw ConnectionException::noActiveTransaction();
1505
        }
1506
1507 7223
        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 8371
    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 8371
        if (is_int(key($params))) {
1555
            // Positional parameters
1556 8371
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1557 8371
            $bindIndex  = 1;
1558 8371
            foreach ($params as $value) {
1559 8371
                $typeIndex = $bindIndex + $typeOffset;
1560 8371
                if (isset($types[$typeIndex])) {
1561 7449
                    $type                  = $types[$typeIndex];
1562 7449
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1563 7449
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1564
                } else {
1565 8346
                    $stmt->bindValue($bindIndex, $value);
1566
                }
1567
1568 8371
                ++$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 8367
    }
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 7455
    private function getBindingInfo($value, $type)
1593
    {
1594 7455
        if (is_string($type)) {
1595 7008
            $type = Type::getType($type);
1596
        }
1597
1598 7455
        if ($type instanceof Type) {
1599 7008
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1600 7008
            $bindingType = $type->getBindingType();
1601
        } else {
1602 7449
            $bindingType = $type;
1603
        }
1604
1605 7455
        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 8905
    public function resolveParams(array $params, array $types)
1620
    {
1621 8905
        $resolvedParams = [];
1622
1623
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1624 8905
        if (is_int(key($params))) {
1625
            // Positional parameters
1626 6060
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1627 6060
            $bindIndex  = 1;
1628 6060
            foreach ($params as $value) {
1629 6060
                $typeIndex = $bindIndex + $typeOffset;
1630 6060
                if (isset($types[$typeIndex])) {
1631
                    $type                       = $types[$typeIndex];
1632
                    [$value]                    = $this->getBindingInfo($value, $type);
1633
                    $resolvedParams[$bindIndex] = $value;
1634
                } else {
1635 6060
                    $resolvedParams[$bindIndex] = $value;
1636
                }
1637
1638 6060
                ++$bindIndex;
1639
            }
1640
        } else {
1641
            // Named parameters
1642 8897
            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 8905
        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 6973
    public function ping()
1688
    {
1689 6973
        $connection = $this->getWrappedConnection();
1690
1691 6973
        if ($connection instanceof PingableConnection) {
1692 2212
            return $connection->ping();
1693
        }
1694
1695
        try {
1696 6949
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1697
1698 6949
            return true;
1699
        } catch (DBALException $e) {
1700
            return false;
1701
        }
1702
    }
1703
}
1704