Passed
Pull Request — 2.10.x (#3960)
by Grégoire
08:14
created

Connection::quoteIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
crap 1
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 8861
    public function __construct(
183
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188 8861
        $this->_driver = $driver;
189 8861
        $this->params  = $params;
190
191 8861
        if (isset($params['pdo'])) {
192 7969
            $this->_conn       = $params['pdo'];
193 7969
            $this->isConnected = true;
194 7969
            unset($this->params['pdo']);
195
        }
196
197 8861
        if (isset($params['platform'])) {
198 8140
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199 7717
                throw DBALException::invalidPlatformType($params['platform']);
200
            }
201
202 8139
            $this->platform = $params['platform'];
203
        }
204
205
        // Create default config and event manager if none given
206 8861
        if (! $config) {
207 8761
            $config = new Configuration();
208
        }
209
210 8861
        if (! $eventManager) {
211 8760
            $eventManager = new EventManager();
212
        }
213
214 8861
        $this->_config       = $config;
215 8861
        $this->_eventManager = $eventManager;
216
217 8861
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
218
219 8861
        $this->autoCommit = $config->getAutoCommit();
220 8861
    }
221
222
    /**
223
     * Gets the parameters used during instantiation.
224
     *
225
     * @return mixed[]
226
     */
227 8079
    public function getParams()
228
    {
229 8079
        return $this->params;
230
    }
231
232
    /**
233
     * Gets the name of the database this Connection is connected to.
234
     *
235
     * @return string
236
     */
237 7412
    public function getDatabase()
238
    {
239 7412
        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 8533
    public function getHost()
250
    {
251 8533
        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 410
    public function getUsername()
274
    {
275 410
        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 8580
    public function getDriver()
296
    {
297 8580
        return $this->_driver;
298
    }
299
300
    /**
301
     * Gets the Configuration used by the Connection.
302
     *
303
     * @return Configuration
304
     */
305 9044
    public function getConfiguration()
306
    {
307 9044
        return $this->_config;
308
    }
309
310
    /**
311
     * Gets the EventManager used by the Connection.
312
     *
313
     * @return EventManager
314
     */
315 6703
    public function getEventManager()
316
    {
317 6703
        return $this->_eventManager;
318
    }
319
320
    /**
321
     * Gets the DatabasePlatform for the connection.
322
     *
323
     * @return AbstractPlatform
324
     *
325
     * @throws DBALException
326
     */
327 8910
    public function getDatabasePlatform()
328
    {
329 8910
        if ($this->platform === null) {
330 8708
            $this->detectDatabasePlatform();
331
        }
332
333 8909
        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 9055
    public function connect()
353
    {
354 9055
        if ($this->isConnected) {
355 8561
            return false;
356
        }
357
358 8775
        $driverOptions = $this->params['driverOptions'] ?? [];
359 8775
        $user          = $this->params['user'] ?? null;
360 8775
        $password      = $this->params['password'] ?? null;
361
362 8775
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
363 8771
        $this->isConnected = true;
364
365 8771
        $this->transactionNestingLevel = 0;
366
367 8771
        if ($this->autoCommit === false) {
368 8247
            $this->beginTransaction();
369
        }
370
371 8771
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
372 8510
            $eventArgs = new Event\ConnectionEventArgs($this);
373 8510
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
374
        }
375
376 8771
        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 8708
    private function detectDatabasePlatform() : void
387
    {
388 8708
        $version = $this->getDatabasePlatformVersion();
389
390 8707
        if ($version !== null) {
391 7789
            assert($this->_driver instanceof VersionAwarePlatformDriver);
392
393 7789
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
394
        } else {
395 8706
            $this->platform = $this->_driver->getDatabasePlatform();
396
        }
397
398 8707
        $this->platform->setEventManager($this->_eventManager);
399 8707
    }
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 8708
    private function getDatabasePlatformVersion()
414
    {
415
        // Driver does not support version specific platforms.
416 8708
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
417 8706
            return null;
418
        }
419
420
        // Explicit platform version requested (supersedes auto-detection).
421 7790
        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 7790
        if ($this->_conn === null) {
427
            try {
428 7790
                $this->connect();
429 7693
            } catch (Throwable $originalException) {
430 7693
                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 7693
                $databaseName           = $this->params['dbname'];
437 7693
                $this->params['dbname'] = null;
438
439
                try {
440 7693
                    $this->connect();
441 7693
                } 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 7693
                    $this->params['dbname'] = $databaseName;
446
447 7693
                    throw $originalException;
448
                }
449
450
                // Reset connection parameters.
451 6125
                $this->params['dbname'] = $databaseName;
452 6125
                $serverVersion          = $this->getServerVersion();
453
454
                // Close "temporary" connection to allow connecting to the real database again.
455 6125
                $this->close();
456
457 6125
                return $serverVersion;
458
            }
459
        }
460
461 7789
        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 7789
    private function getServerVersion()
470
    {
471 7789
        $connection = $this->getWrappedConnection();
472
473
        // Automatic platform version detection.
474 7789
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
475 7789
            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 8294
    public function isAutoCommit()
490
    {
491 8294
        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 8273
    public function setAutoCommit($autoCommit)
511
    {
512 8273
        $autoCommit = (bool) $autoCommit;
513
514
        // Mode not changed, no-op.
515 8273
        if ($autoCommit === $this->autoCommit) {
516 8269
            return;
517
        }
518
519 8273
        $this->autoCommit = $autoCommit;
520
521
        // Commit all currently active transactions if any when switching auto-commit mode.
522 8273
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
523 8272
            return;
524
        }
525
526 8149
        $this->commitAll();
527 8149
    }
528
529
    /**
530
     * Sets the fetch mode.
531
     *
532
     * @param int $fetchMode
533
     *
534
     * @return void
535
     */
536 4137
    public function setFetchMode($fetchMode)
537
    {
538 4137
        $this->defaultFetchMode = $fetchMode;
539 4137
    }
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 8111
    public function fetchAssoc($statement, array $params = [], array $types = [])
554
    {
555 8111
        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 6238
    public function fetchArray($statement, array $params = [], array $types = [])
569
    {
570 6238
        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 8054
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
587
    {
588 8054
        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 8655
    public function isConnected()
597
    {
598 8655
        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 8944
    public function isTransactionActive()
607
    {
608 8944
        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 8115
    private function addIdentifierCondition(
622
        array $identifier,
623
        array &$columns,
624
        array &$values,
625
        array &$conditions
626
    ) : void {
627 8115
        $platform = $this->getDatabasePlatform();
628
629 8115
        foreach ($identifier as $columnName => $value) {
630 8115
            if ($value === null) {
631 8080
                $conditions[] = $platform->getIsNullExpression($columnName);
632 8080
                continue;
633
            }
634
635 8113
            $columns[]    = $columnName;
636 8113
            $values[]     = $value;
637 8113
            $conditions[] = $columnName . ' = ?';
638
        }
639 8115
    }
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 8059
    public function delete($tableExpression, array $identifier, array $types = [])
656
    {
657 8059
        if (empty($identifier)) {
658 7933
            throw InvalidArgumentException::fromEmptyCriteria();
659
        }
660
661 8058
        $columns = $values = $conditions = [];
662
663 8058
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
664
665 8058
        return $this->executeUpdate(
666 8058
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
667
            $values,
668 8058
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
669
        );
670
    }
671
672
    /**
673
     * Closes the connection.
674
     *
675
     * @return void
676
     */
677 7610
    public function close()
678
    {
679 7610
        $this->_conn = null;
680
681 7610
        $this->isConnected = false;
682 7610
    }
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 8109
    public function update($tableExpression, array $data, array $identifier, array $types = [])
727
    {
728 8109
        $columns = $values = $conditions = $set = [];
729
730 8109
        foreach ($data as $columnName => $value) {
731 8109
            $columns[] = $columnName;
732 8109
            $values[]  = $value;
733 8109
            $set[]     = $columnName . ' = ?';
734
        }
735
736 8109
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
737
738 8109
        if (is_string(key($types))) {
739 8105
            $types = $this->extractTypeValues($columns, $types);
740
        }
741
742 8109
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
743 8109
                . ' WHERE ' . implode(' AND ', $conditions);
744
745 8109
        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 8205
    public function insert($tableExpression, array $data, array $types = [])
762
    {
763 8205
        if (empty($data)) {
764 8125
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
765
        }
766
767 7964
        $columns = [];
768 7964
        $values  = [];
769 7964
        $set     = [];
770
771 7964
        foreach ($data as $columnName => $value) {
772 7964
            $columns[] = $columnName;
773 7964
            $values[]  = $value;
774 7964
            $set[]     = '?';
775
        }
776
777 7964
        return $this->executeUpdate(
778 7964
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
779 7964
            ' VALUES (' . implode(', ', $set) . ')',
780
            $values,
781 7964
            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 8109
    private function extractTypeValues(array $columnList, array $types)
794
    {
795 8109
        $typeValues = [];
796
797 8109
        foreach ($columnList as $columnIndex => $columnName) {
798 8109
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
799
        }
800
801 8109
        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 6461
    public function quoteIdentifier($str)
819
    {
820 6461
        return $this->getDatabasePlatform()->quoteIdentifier($str);
821
    }
822
823
    /**
824
     * {@inheritDoc}
825
     */
826 6712
    public function quote($input, $type = ParameterType::STRING)
827
    {
828 6712
        $connection = $this->getWrappedConnection();
829
830 6712
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
831
832 6712
        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 8085
    public function fetchAll($sql, array $params = [], $types = [])
845
    {
846 8085
        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 8724
    public function prepare($statement)
859
    {
860
        try {
861 8724
            $stmt = new Statement($statement, $this);
862 8341
        } catch (Throwable $ex) {
863 8341
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
864
        }
865
866 8723
        $stmt->setFetchMode($this->defaultFetchMode);
867
868 8723
        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 8957
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
887
    {
888 8957
        if ($qcp !== null) {
889 4055
            return $this->executeCacheQuery($query, $params, $types, $qcp);
890
        }
891
892 8957
        $connection = $this->getWrappedConnection();
893
894 8957
        $logger = $this->_config->getSQLLogger();
895 8957
        if ($logger) {
896 8952
            $logger->startQuery($query, $params, $types);
897
        }
898
899
        try {
900 8957
            if ($params) {
901 6454
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
902
903 6454
                $stmt = $connection->prepare($query);
904 6454
                if ($types) {
905 6453
                    $this->_bindTypedValues($stmt, $params, $types);
906 6449
                    $stmt->execute();
907
                } else {
908 6450
                    $stmt->execute($params);
909
                }
910
            } else {
911 8953
                $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 8396
        } catch (Throwable $ex) {
914 8396
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
915
        }
916
917 8949
        $stmt->setFetchMode($this->defaultFetchMode);
918
919 8949
        if ($logger) {
920 8945
            $logger->stopQuery();
921
        }
922
923 8949
        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 7779
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
939
    {
940 7779
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
941
942 7779
        if ($resultCache === null) {
943
            throw CacheException::noResultDriverConfigured();
944
        }
945
946 7779
        $connectionParams = $this->getParams();
947 7779
        unset($connectionParams['platform']);
948
949 7779
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
950
951
        // fetch the row pointers entry
952 7779
        $data = $resultCache->fetch($cacheKey);
953
954 7779
        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 7775
            if (isset($data[$realKey])) {
957 7775
                $stmt = new ArrayStatement($data[$realKey]);
958
            } elseif (array_key_exists($realKey, $data)) {
959
                $stmt = new ArrayStatement([]);
960
            }
961
        }
962
963 7779
        if (! isset($stmt)) {
964 4056
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
965
        }
966
967 7779
        $stmt->setFetchMode($this->defaultFetchMode);
968
969 7779
        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 8429
    public function query()
1006
    {
1007 8429
        $connection = $this->getWrappedConnection();
1008
1009 8429
        $args = func_get_args();
1010
1011 8429
        $logger = $this->_config->getSQLLogger();
1012 8429
        if ($logger) {
1013 7105
            $logger->startQuery($args[0]);
1014
        }
1015
1016
        try {
1017 8429
            $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 8413
        } catch (Throwable $ex) {
1019 8413
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1020
        }
1021
1022 7106
        $statement->setFetchMode($this->defaultFetchMode);
1023
1024 7106
        if ($logger) {
1025 7105
            $logger->stopQuery();
1026
        }
1027
1028 7106
        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 8886
    public function executeUpdate($query, array $params = [], array $types = [])
1046
    {
1047 8886
        $connection = $this->getWrappedConnection();
1048
1049 8886
        $logger = $this->_config->getSQLLogger();
1050 8886
        if ($logger) {
1051 8881
            $logger->startQuery($query, $params, $types);
1052
        }
1053
1054
        try {
1055 8886
            if ($params) {
1056 7995
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1057
1058 7995
                $stmt = $connection->prepare($query);
1059
1060 7995
                if ($types) {
1061 7995
                    $this->_bindTypedValues($stmt, $params, $types);
1062 7995
                    $stmt->execute();
1063
                } else {
1064
                    $stmt->execute($params);
1065
                }
1066 7993
                $result = $stmt->rowCount();
1067
            } else {
1068 8884
                $result = $connection->exec($query);
1069
            }
1070 8509
        } catch (Throwable $ex) {
1071 8509
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
1072
        }
1073
1074 8877
        if ($logger) {
1075 8872
            $logger->stopQuery();
1076
        }
1077
1078 8877
        return $result;
1079
    }
1080
1081
    /**
1082
     * Executes an SQL statement and return the number of affected rows.
1083
     *
1084
     * @param string $statement
1085
     *
1086
     * @return int The number of affected rows.
1087
     *
1088
     * @throws DBALException
1089
     */
1090 8517
    public function exec($statement)
1091
    {
1092 8517
        $connection = $this->getWrappedConnection();
1093
1094 8514
        $logger = $this->_config->getSQLLogger();
1095 8514
        if ($logger) {
1096 5633
            $logger->startQuery($statement);
1097
        }
1098
1099
        try {
1100 8514
            $result = $connection->exec($statement);
1101 8492
        } catch (Throwable $ex) {
1102 8492
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1103
        }
1104
1105 5581
        if ($logger) {
1106 5578
            $logger->stopQuery();
1107
        }
1108
1109 5581
        return $result;
1110
    }
1111
1112
    /**
1113
     * Returns the current transaction nesting level.
1114
     *
1115
     * @return int The nesting level. A value of 0 means there's no active transaction.
1116
     */
1117 8163
    public function getTransactionNestingLevel()
1118
    {
1119 8163
        return $this->transactionNestingLevel;
1120
    }
1121
1122
    /**
1123
     * Fetches the SQLSTATE associated with the last database operation.
1124
     *
1125
     * @return string|null The last error code.
1126
     */
1127
    public function errorCode()
1128
    {
1129
        return $this->getWrappedConnection()->errorCode();
1130
    }
1131
1132
    /**
1133
     * {@inheritDoc}
1134
     */
1135
    public function errorInfo()
1136
    {
1137
        return $this->getWrappedConnection()->errorInfo();
1138
    }
1139
1140
    /**
1141
     * Returns the ID of the last inserted row, or the last value from a sequence object,
1142
     * depending on the underlying driver.
1143
     *
1144
     * Note: This method may not return a meaningful or consistent result across different drivers,
1145
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
1146
     * columns or sequences.
1147
     *
1148
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
1149
     *
1150
     * @return string A string representation of the last inserted ID.
1151
     */
1152 810
    public function lastInsertId($seqName = null)
1153
    {
1154 810
        return $this->getWrappedConnection()->lastInsertId($seqName);
1155
    }
1156
1157
    /**
1158
     * Executes a function in a transaction.
1159
     *
1160
     * The function gets passed this Connection instance as an (optional) parameter.
1161
     *
1162
     * If an exception occurs during execution of the function or transaction commit,
1163
     * the transaction is rolled back and the exception re-thrown.
1164
     *
1165
     * @param Closure $func The function to execute transactionally.
1166
     *
1167
     * @return mixed The value returned by $func
1168
     *
1169
     * @throws Exception
1170
     * @throws Throwable
1171
     */
1172 6782
    public function transactional(Closure $func)
1173
    {
1174 6782
        $this->beginTransaction();
1175
        try {
1176 6782
            $res = $func($this);
1177 6732
            $this->commit();
1178
1179 6732
            return $res;
1180 6780
        } catch (Exception $e) {
1181 6779
            $this->rollBack();
1182 6779
            throw $e;
1183 6755
        } catch (Throwable $e) {
1184 6755
            $this->rollBack();
1185 6755
            throw $e;
1186
        }
1187
    }
1188
1189
    /**
1190
     * Sets if nested transactions should use savepoints.
1191
     *
1192
     * @param bool $nestTransactionsWithSavepoints
1193
     *
1194
     * @return void
1195
     *
1196
     * @throws ConnectionException
1197
     */
1198 6876
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
1199
    {
1200 6876
        if ($this->transactionNestingLevel > 0) {
1201 6876
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
1202
        }
1203
1204 6875
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1205
            throw ConnectionException::savepointsNotSupported();
1206
        }
1207
1208 6875
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1209 6875
    }
1210
1211
    /**
1212
     * Gets if nested transactions should use savepoints.
1213
     *
1214
     * @return bool
1215
     */
1216 6875
    public function getNestTransactionsWithSavepoints()
1217
    {
1218 6875
        return $this->nestTransactionsWithSavepoints;
1219
    }
1220
1221
    /**
1222
     * Returns the savepoint name to use for nested transactions are false if they are not supported
1223
     * "savepointFormat" parameter is not set
1224
     *
1225
     * @return mixed A string with the savepoint name or false.
1226
     */
1227 6875
    protected function _getNestedTransactionSavePointName()
1228
    {
1229 6875
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1230
    }
1231
1232
    /**
1233
     * {@inheritDoc}
1234
     */
1235 8267
    public function beginTransaction()
1236
    {
1237 8267
        $connection = $this->getWrappedConnection();
1238
1239 8267
        ++$this->transactionNestingLevel;
1240
1241 8267
        $logger = $this->_config->getSQLLogger();
1242
1243 8267
        if ($this->transactionNestingLevel === 1) {
1244 8267
            if ($logger) {
1245 6962
                $logger->startQuery('"START TRANSACTION"');
1246
            }
1247
1248 8267
            $connection->beginTransaction();
1249
1250 8267
            if ($logger) {
1251 8267
                $logger->stopQuery();
1252
            }
1253 8152
        } elseif ($this->nestTransactionsWithSavepoints) {
1254 6875
            if ($logger) {
1255 6875
                $logger->startQuery('"SAVEPOINT"');
1256
            }
1257 6875
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1258 6875
            if ($logger) {
1259 6875
                $logger->stopQuery();
1260
            }
1261
        }
1262
1263 8267
        return true;
1264
    }
1265
1266
    /**
1267
     * {@inheritDoc}
1268
     *
1269
     * @throws ConnectionException If the commit failed due to no active transaction or
1270
     *                                            because the transaction was marked for rollback only.
1271
     */
1272 8618
    public function commit()
1273
    {
1274 8618
        if ($this->transactionNestingLevel === 0) {
1275 8605
            throw ConnectionException::noActiveTransaction();
1276
        }
1277 8233
        if ($this->isRollbackOnly) {
1278 6948
            throw ConnectionException::commitFailedRollbackOnly();
1279
        }
1280
1281 8231
        $result = true;
1282
1283 8231
        $connection = $this->getWrappedConnection();
1284
1285 8231
        $logger = $this->_config->getSQLLogger();
1286
1287 8231
        if ($this->transactionNestingLevel === 1) {
1288 8231
            if ($logger) {
1289 6881
                $logger->startQuery('"COMMIT"');
1290
            }
1291
1292 8231
            $result = $connection->commit();
1293
1294 8231
            if ($logger) {
1295 8231
                $logger->stopQuery();
1296
            }
1297 8150
        } elseif ($this->nestTransactionsWithSavepoints) {
1298 6875
            if ($logger) {
1299 6875
                $logger->startQuery('"RELEASE SAVEPOINT"');
1300
            }
1301 6875
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1302 6875
            if ($logger) {
1303 6875
                $logger->stopQuery();
1304
            }
1305
        }
1306
1307 8231
        --$this->transactionNestingLevel;
1308
1309 8231
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1310 8206
            return $result;
1311
        }
1312
1313 8222
        $this->beginTransaction();
1314
1315 8222
        return $result;
1316
    }
1317
1318
    /**
1319
     * Commits all current nesting transactions.
1320
     */
1321 8149
    private function commitAll() : void
1322
    {
1323 8149
        while ($this->transactionNestingLevel !== 0) {
1324 8149
            if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
1325
                // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
1326
                // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
1327 8149
                $this->commit();
1328
1329 8149
                return;
1330
            }
1331
1332 8149
            $this->commit();
1333
        }
1334 8149
    }
1335
1336
    /**
1337
     * Cancels any database changes done during the current transaction.
1338
     *
1339
     * @return bool
1340
     *
1341
     * @throws ConnectionException If the rollback operation failed.
1342
     */
1343 8593
    public function rollBack()
1344
    {
1345 8593
        if ($this->transactionNestingLevel === 0) {
1346 8581
            throw ConnectionException::noActiveTransaction();
1347
        }
1348
1349 8184
        $connection = $this->getWrappedConnection();
1350
1351 8184
        $logger = $this->_config->getSQLLogger();
1352
1353 8184
        if ($this->transactionNestingLevel === 1) {
1354 8183
            if ($logger) {
1355 6956
                $logger->startQuery('"ROLLBACK"');
1356
            }
1357 8183
            $this->transactionNestingLevel = 0;
1358 8183
            $connection->rollBack();
1359 8183
            $this->isRollbackOnly = false;
1360 8183
            if ($logger) {
1361 6956
                $logger->stopQuery();
1362
            }
1363
1364 8183
            if ($this->autoCommit === false) {
1365 8183
                $this->beginTransaction();
1366
            }
1367 6924
        } elseif ($this->nestTransactionsWithSavepoints) {
1368 6875
            if ($logger) {
1369 6875
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1370
            }
1371 6875
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1372 6875
            --$this->transactionNestingLevel;
1373 6875
            if ($logger) {
1374 6875
                $logger->stopQuery();
1375
            }
1376
        } else {
1377 6923
            $this->isRollbackOnly = true;
1378 6923
            --$this->transactionNestingLevel;
1379
        }
1380
1381 8184
        return true;
1382
    }
1383
1384
    /**
1385
     * Creates a new savepoint.
1386
     *
1387
     * @param string $savepoint The name of the savepoint to create.
1388
     *
1389
     * @return void
1390
     *
1391
     * @throws ConnectionException
1392
     */
1393 6875
    public function createSavepoint($savepoint)
1394
    {
1395 6875
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1396
            throw ConnectionException::savepointsNotSupported();
1397
        }
1398
1399 6875
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1400 6875
    }
1401
1402
    /**
1403
     * Releases the given savepoint.
1404
     *
1405
     * @param string $savepoint The name of the savepoint to release.
1406
     *
1407
     * @return void
1408
     *
1409
     * @throws ConnectionException
1410
     */
1411 6875
    public function releaseSavepoint($savepoint)
1412
    {
1413 6875
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1414
            throw ConnectionException::savepointsNotSupported();
1415
        }
1416
1417 6875
        if (! $this->platform->supportsReleaseSavepoints()) {
1418 496
            return;
1419
        }
1420
1421 6379
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1422 6379
    }
1423
1424
    /**
1425
     * Rolls back to the given savepoint.
1426
     *
1427
     * @param string $savepoint The name of the savepoint to rollback to.
1428
     *
1429
     * @return void
1430
     *
1431
     * @throws ConnectionException
1432
     */
1433 6875
    public function rollbackSavepoint($savepoint)
1434
    {
1435 6875
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1436
            throw ConnectionException::savepointsNotSupported();
1437
        }
1438
1439 6875
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1440 6875
    }
1441
1442
    /**
1443
     * Gets the wrapped driver connection.
1444
     *
1445
     * @return DriverConnection
1446
     */
1447 9060
    public function getWrappedConnection()
1448
    {
1449 9060
        $this->connect();
1450
1451 9057
        return $this->_conn;
1452
    }
1453
1454
    /**
1455
     * Gets the SchemaManager that can be used to inspect or change the
1456
     * database schema through the connection.
1457
     *
1458
     * @return AbstractSchemaManager
1459
     */
1460 7777
    public function getSchemaManager()
1461
    {
1462 7777
        if ($this->_schemaManager === null) {
1463 7616
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1464
        }
1465
1466 7777
        return $this->_schemaManager;
1467
    }
1468
1469
    /**
1470
     * Marks the current transaction so that the only possible
1471
     * outcome for the transaction to be rolled back.
1472
     *
1473
     * @return void
1474
     *
1475
     * @throws ConnectionException If no transaction is active.
1476
     */
1477 6948
    public function setRollbackOnly()
1478
    {
1479 6948
        if ($this->transactionNestingLevel === 0) {
1480 1
            throw ConnectionException::noActiveTransaction();
1481
        }
1482 6947
        $this->isRollbackOnly = true;
1483 6947
    }
1484
1485
    /**
1486
     * Checks whether the current transaction is marked for rollback only.
1487
     *
1488
     * @return bool
1489
     *
1490
     * @throws ConnectionException If no transaction is active.
1491
     */
1492 6925
    public function isRollbackOnly()
1493
    {
1494 6925
        if ($this->transactionNestingLevel === 0) {
1495 1
            throw ConnectionException::noActiveTransaction();
1496
        }
1497
1498 6924
        return $this->isRollbackOnly;
1499
    }
1500
1501
    /**
1502
     * Converts a given value to its database representation according to the conversion
1503
     * rules of a specific DBAL mapping type.
1504
     *
1505
     * @param mixed  $value The value to convert.
1506
     * @param string $type  The name of the DBAL mapping type.
1507
     *
1508
     * @return mixed The converted value.
1509
     */
1510
    public function convertToDatabaseValue($value, $type)
1511
    {
1512
        return Type::getType($type)->convertToDatabaseValue($value, $this->getDatabasePlatform());
1513
    }
1514
1515
    /**
1516
     * Converts a given value to its PHP representation according to the conversion
1517
     * rules of a specific DBAL mapping type.
1518
     *
1519
     * @param mixed  $value The value to convert.
1520
     * @param string $type  The name of the DBAL mapping type.
1521
     *
1522
     * @return mixed The converted type.
1523
     */
1524
    public function convertToPHPValue($value, $type)
1525
    {
1526
        return Type::getType($type)->convertToPHPValue($value, $this->getDatabasePlatform());
1527
    }
1528
1529
    /**
1530
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1531
     * or DBAL mapping type, to a given statement.
1532
     *
1533
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1534
     *           raw PDOStatement instances.
1535
     *
1536
     * @param \Doctrine\DBAL\Driver\Statement $stmt   The statement to bind the values to.
1537
     * @param mixed[]                         $params The map/list of named/positional parameters.
1538
     * @param int[]|string[]                  $types  The parameter types (PDO binding types or DBAL mapping types).
1539
     *
1540
     * @return void
1541
     */
1542 8028
    private function _bindTypedValues($stmt, array $params, array $types)
1543
    {
1544
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1545 8028
        if (is_int(key($params))) {
1546
            // Positional parameters
1547 8028
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1548 8028
            $bindIndex  = 1;
1549 8028
            foreach ($params as $value) {
1550 8028
                $typeIndex = $bindIndex + $typeOffset;
1551 8028
                if (isset($types[$typeIndex])) {
1552 7142
                    $type                  = $types[$typeIndex];
1553 7142
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1554 7142
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1555
                } else {
1556 8003
                    $stmt->bindValue($bindIndex, $value);
1557
                }
1558 8028
                ++$bindIndex;
1559
            }
1560
        } else {
1561
            // Named parameters
1562
            foreach ($params as $name => $value) {
1563
                if (isset($types[$name])) {
1564
                    $type                  = $types[$name];
1565
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1566
                    $stmt->bindValue($name, $value, $bindingType);
1567
                } else {
1568
                    $stmt->bindValue($name, $value);
1569
                }
1570
            }
1571
        }
1572 8024
    }
1573
1574
    /**
1575
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1576
     *
1577
     * @param mixed           $value The value to bind.
1578
     * @param int|string|null $type  The type to bind (PDO or DBAL).
1579
     *
1580
     * @return mixed[] [0] => the (escaped) value, [1] => the binding type.
1581
     */
1582 7148
    private function getBindingInfo($value, $type)
1583
    {
1584 7148
        if (is_string($type)) {
1585 6718
            $type = Type::getType($type);
1586
        }
1587 7148
        if ($type instanceof Type) {
1588 6718
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1589 6718
            $bindingType = $type->getBindingType();
1590
        } else {
1591 7142
            $bindingType = $type;
1592
        }
1593
1594 7148
        return [$value, $bindingType];
1595
    }
1596
1597
    /**
1598
     * Resolves the parameters to a format which can be displayed.
1599
     *
1600
     * @internal This is a purely internal method. If you rely on this method, you are advised to
1601
     *           copy/paste the code as this method may change, or be removed without prior notice.
1602
     *
1603
     * @param mixed[]        $params
1604
     * @param int[]|string[] $types
1605
     *
1606
     * @return mixed[]
1607
     */
1608 8541
    public function resolveParams(array $params, array $types)
1609
    {
1610 8541
        $resolvedParams = [];
1611
1612
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1613 8541
        if (is_int(key($params))) {
1614
            // Positional parameters
1615 5881
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1616 5881
            $bindIndex  = 1;
1617 5881
            foreach ($params as $value) {
1618 5881
                $typeIndex = $bindIndex + $typeOffset;
1619 5881
                if (isset($types[$typeIndex])) {
1620
                    $type                       = $types[$typeIndex];
1621
                    [$value]                    = $this->getBindingInfo($value, $type);
1622
                    $resolvedParams[$bindIndex] = $value;
1623
                } else {
1624 5881
                    $resolvedParams[$bindIndex] = $value;
1625
                }
1626 5881
                ++$bindIndex;
1627
            }
1628
        } else {
1629
            // Named parameters
1630 8533
            foreach ($params as $name => $value) {
1631
                if (isset($types[$name])) {
1632
                    $type                  = $types[$name];
1633
                    [$value]               = $this->getBindingInfo($value, $type);
1634
                    $resolvedParams[$name] = $value;
1635
                } else {
1636
                    $resolvedParams[$name] = $value;
1637
                }
1638
            }
1639
        }
1640
1641 8541
        return $resolvedParams;
1642
    }
1643
1644
    /**
1645
     * Creates a new instance of a SQL query builder.
1646
     *
1647
     * @return QueryBuilder
1648
     */
1649
    public function createQueryBuilder()
1650
    {
1651
        return new Query\QueryBuilder($this);
1652
    }
1653
1654
    /**
1655
     * Ping the server
1656
     *
1657
     * When the server is not available the method returns FALSE.
1658
     * It is responsibility of the developer to handle this case
1659
     * and abort the request or reconnect manually:
1660
     *
1661
     * @return bool
1662
     *
1663
     * @example
1664
     *
1665
     *   if ($conn->ping() === false) {
1666
     *      $conn->close();
1667
     *      $conn->connect();
1668
     *   }
1669
     *
1670
     * It is undefined if the underlying driver attempts to reconnect
1671
     * or disconnect when the connection is not available anymore
1672
     * as long it returns TRUE when a reconnect succeeded and
1673
     * FALSE when the connection was dropped.
1674
     */
1675 6684
    public function ping()
1676
    {
1677 6684
        $connection = $this->getWrappedConnection();
1678
1679 6684
        if ($connection instanceof PingableConnection) {
1680 1663
            return $connection->ping();
1681
        }
1682
1683
        try {
1684 6666
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1685
1686 6666
            return true;
1687
        } catch (DBALException $e) {
1688
            return false;
1689
        }
1690
    }
1691
}
1692