Completed
Push — 2.10.x ( 6c789b...72d908 )
by Grégoire
22s queued 15s
created

Connection::convertToDatabaseValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 2
crap 2
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 8402
    public function __construct(
183
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188 8402
        $this->_driver = $driver;
189 8402
        $this->params  = $params;
190
191 8402
        if (isset($params['pdo'])) {
192 7591
            $this->_conn       = $params['pdo'];
193 7591
            $this->isConnected = true;
194 7591
            unset($this->params['pdo']);
195
        }
196
197 8402
        if (isset($params['platform'])) {
198 7755
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199 7349
                throw DBALException::invalidPlatformType($params['platform']);
200
            }
201
202 7754
            $this->platform = $params['platform'];
203
        }
204
205
        // Create default config and event manager if none given
206 8402
        if (! $config) {
207 8118
            $config = new Configuration();
208
        }
209
210 8402
        if (! $eventManager) {
211 7887
            $eventManager = new EventManager();
212
        }
213
214 8402
        $this->_config       = $config;
215 8402
        $this->_eventManager = $eventManager;
216
217 8402
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
218
219 8402
        $this->autoCommit = $config->getAutoCommit();
220 8402
    }
221
222
    /**
223
     * Gets the parameters used during instantiation.
224
     *
225
     * @return mixed[]
226
     */
227 7701
    public function getParams()
228
    {
229 7701
        return $this->params;
230
    }
231
232
    /**
233
     * Gets the name of the database this Connection is connected to.
234
     *
235
     * @return string
236
     */
237 7196
    public function getDatabase()
238
    {
239 7196
        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 8154
    public function getHost()
250
    {
251 8154
        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 637
    public function getUsername()
274
    {
275 637
        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 8202
    public function getDriver()
296
    {
297 8202
        return $this->_driver;
298
    }
299
300
    /**
301
     * Gets the Configuration used by the Connection.
302
     *
303
     * @return Configuration
304
     */
305 8495
    public function getConfiguration()
306
    {
307 8495
        return $this->_config;
308
    }
309
310
    /**
311
     * Gets the EventManager used by the Connection.
312
     *
313
     * @return EventManager
314
     */
315 6289
    public function getEventManager()
316
    {
317 6289
        return $this->_eventManager;
318
    }
319
320
    /**
321
     * Gets the DatabasePlatform for the connection.
322
     *
323
     * @return AbstractPlatform
324
     *
325
     * @throws DBALException
326
     */
327 8319
    public function getDatabasePlatform()
328
    {
329 8319
        if ($this->platform === null) {
330 8115
            $this->detectDatabasePlatform();
331
        }
332
333 8318
        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 8437
    public function connect()
353
    {
354 8437
        if ($this->isConnected) {
355 8173
            return false;
356
        }
357
358 8155
        $driverOptions = $this->params['driverOptions'] ?? [];
359 8155
        $user          = $this->params['user'] ?? null;
360 8155
        $password      = $this->params['password'] ?? null;
361
362 8155
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
363 8151
        $this->isConnected = true;
364
365 8151
        $this->transactionNestingLevel = 0;
366
367 8151
        if ($this->autoCommit === false) {
368 7857
            $this->beginTransaction();
369
        }
370
371 8151
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
372 8133
            $eventArgs = new Event\ConnectionEventArgs($this);
373 8133
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
374
        }
375
376 8151
        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 8115
    private function detectDatabasePlatform() : void
387
    {
388 8115
        $version = $this->getDatabasePlatformVersion();
389
390 8114
        if ($version !== null) {
391 7418
            assert($this->_driver instanceof VersionAwarePlatformDriver);
392
393 7418
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
394
        } else {
395 8113
            $this->platform = $this->_driver->getDatabasePlatform();
396
        }
397
398 8114
        $this->platform->setEventManager($this->_eventManager);
399 8114
    }
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 8115
    private function getDatabasePlatformVersion()
414
    {
415
        // Driver does not support version specific platforms.
416 8115
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
417 8113
            return null;
418
        }
419
420
        // Explicit platform version requested (supersedes auto-detection).
421 7419
        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 7419
        if ($this->_conn === null) {
427
            try {
428 7419
                $this->connect();
429 7326
            } catch (Throwable $originalException) {
430 7326
                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 7326
                $databaseName           = $this->params['dbname'];
437 7326
                $this->params['dbname'] = null;
438
439
                try {
440 7326
                    $this->connect();
441 7326
                } 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 7326
                    $this->params['dbname'] = $databaseName;
446
447 7326
                    throw $originalException;
448
                }
449
450
                // Reset connection parameters.
451 5845
                $this->params['dbname'] = $databaseName;
452 5845
                $serverVersion          = $this->getServerVersion();
453
454
                // Close "temporary" connection to allow connecting to the real database again.
455 5845
                $this->close();
456
457 5845
                return $serverVersion;
458
            }
459
        }
460
461 7418
        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 7418
    private function getServerVersion()
470
    {
471 7418
        $connection = $this->getWrappedConnection();
472
473
        // Automatic platform version detection.
474 7418
        if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
475 7418
            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 7902
    public function isAutoCommit()
490
    {
491 7902
        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 7882
    public function setAutoCommit($autoCommit)
511
    {
512 7882
        $autoCommit = (bool) $autoCommit;
513
514
        // Mode not changed, no-op.
515 7882
        if ($autoCommit === $this->autoCommit) {
516 7878
            return;
517
        }
518
519 7882
        $this->autoCommit = $autoCommit;
520
521
        // Commit all currently active transactions if any when switching auto-commit mode.
522 7882
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
523 7881
            return;
524
        }
525
526 7763
        $this->commitAll();
527 7763
    }
528
529
    /**
530
     * Sets the fetch mode.
531
     *
532
     * @param int $fetchMode
533
     *
534
     * @return void
535
     */
536 3895
    public function setFetchMode($fetchMode)
537
    {
538 3895
        $this->defaultFetchMode = $fetchMode;
539 3895
    }
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 7730
    public function fetchAssoc($statement, array $params = [], array $types = [])
554
    {
555 7730
        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 5935
    public function fetchArray($statement, array $params = [], array $types = [])
569
    {
570 5935
        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 7674
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
587
    {
588 7674
        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 8271
    public function isConnected()
597
    {
598 8271
        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 8563
    public function isTransactionActive()
607
    {
608 8563
        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 7731
    private function addIdentifierCondition(
622
        array $identifier,
623
        array &$columns,
624
        array &$values,
625
        array &$conditions
626
    ) : void {
627 7731
        $platform = $this->getDatabasePlatform();
628
629 7731
        foreach ($identifier as $columnName => $value) {
630 7731
            if ($value === null) {
631 7697
                $conditions[] = $platform->getIsNullExpression($columnName);
632 7697
                continue;
633
            }
634
635 7729
            $columns[]    = $columnName;
636 7729
            $values[]     = $value;
637 7729
            $conditions[] = $columnName . ' = ?';
638
        }
639 7731
    }
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 7677
    public function delete($tableExpression, array $identifier, array $types = [])
656
    {
657 7677
        if (empty($identifier)) {
658 7556
            throw InvalidArgumentException::fromEmptyCriteria();
659
        }
660
661 7676
        $columns = $values = $conditions = [];
662
663 7676
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
664
665 7676
        return $this->executeUpdate(
666 7676
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
667
            $values,
668 7676
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
669
        );
670
    }
671
672
    /**
673
     * Closes the connection.
674
     *
675
     * @return void
676
     */
677 7246
    public function close()
678
    {
679 7246
        $this->_conn = null;
680
681 7246
        $this->isConnected = false;
682 7246
    }
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 7725
    public function update($tableExpression, array $data, array $identifier, array $types = [])
727
    {
728 7725
        $columns = $values = $conditions = $set = [];
729
730 7725
        foreach ($data as $columnName => $value) {
731 7725
            $columns[] = $columnName;
732 7725
            $values[]  = $value;
733 7725
            $set[]     = $columnName . ' = ?';
734
        }
735
736 7725
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
737
738 7725
        if (is_string(key($types))) {
739 7721
            $types = $this->extractTypeValues($columns, $types);
740
        }
741
742 7725
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
743 7725
                . ' WHERE ' . implode(' AND ', $conditions);
744
745 7725
        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 7820
    public function insert($tableExpression, array $data, array $types = [])
762
    {
763 7820
        if (empty($data)) {
764 7740
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
765
        }
766
767 7589
        $columns = [];
768 7589
        $values  = [];
769 7589
        $set     = [];
770
771 7589
        foreach ($data as $columnName => $value) {
772 7589
            $columns[] = $columnName;
773 7589
            $values[]  = $value;
774 7589
            $set[]     = '?';
775
        }
776
777 7589
        return $this->executeUpdate(
778 7589
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
779 7589
            ' VALUES (' . implode(', ', $set) . ')',
780
            $values,
781 7589
            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 7725
    private function extractTypeValues(array $columnList, array $types)
794
    {
795 7725
        $typeValues = [];
796
797 7725
        foreach ($columnList as $columnIndex => $columnName) {
798 7725
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
799
        }
800
801 7725
        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 6148
    public function quoteIdentifier($str)
819
    {
820 6148
        return $this->getDatabasePlatform()->quoteIdentifier($str);
821
    }
822
823
    /**
824
     * {@inheritDoc}
825
     */
826 6425
    public function quote($input, $type = null)
827
    {
828 6425
        $connection = $this->getWrappedConnection();
829
830 6425
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
831
832 6425
        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 7706
    public function fetchAll($sql, array $params = [], $types = [])
845
    {
846 7706
        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 8017
    public function prepare($statement)
859
    {
860
        try {
861 8017
            $stmt = new Statement($statement, $this);
862 7970
        } catch (Throwable $ex) {
863 7970
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
864
        }
865
866 7510
        $stmt->setFetchMode($this->defaultFetchMode);
867
868 7510
        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 8248
    public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
887
    {
888 8248
        if ($qcp !== null) {
889 3815
            return $this->executeCacheQuery($query, $params, $types, $qcp);
890
        }
891
892 8248
        $connection = $this->getWrappedConnection();
893
894 8248
        $logger = $this->_config->getSQLLogger();
895 8248
        if ($logger) {
896 6794
            $logger->startQuery($query, $params, $types);
897
        }
898
899
        try {
900 8248
            if ($params) {
901 6143
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
902
903 6143
                $stmt = $connection->prepare($query);
904 6143
                if ($types) {
905 6142
                    $this->_bindTypedValues($stmt, $params, $types);
906 6138
                    $stmt->execute();
907
                } else {
908 6139
                    $stmt->execute($params);
909
                }
910
            } else {
911 8244
                $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 8023
        } catch (Throwable $ex) {
914 8023
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
915
        }
916
917 6820
        $stmt->setFetchMode($this->defaultFetchMode);
918
919 6820
        if ($logger) {
920 6787
            $logger->stopQuery();
921
        }
922
923 6820
        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 7409
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
939
    {
940 7409
        $resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
941
942 7409
        if ($resultCache === null) {
943
            throw CacheException::noResultDriverConfigured();
944
        }
945
946 7409
        $connectionParams = $this->getParams();
947 7409
        unset($connectionParams['platform']);
948
949 7409
        [$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $connectionParams);
950
951
        // fetch the row pointers entry
952 7409
        $data = $resultCache->fetch($cacheKey);
953
954 7409
        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 7405
            if (isset($data[$realKey])) {
957 7405
                $stmt = new ArrayStatement($data[$realKey]);
958
            } elseif (array_key_exists($realKey, $data)) {
959
                $stmt = new ArrayStatement([]);
960
            }
961
        }
962
963 7409
        if (! isset($stmt)) {
964 3816
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
965
        }
966
967 7409
        $stmt->setFetchMode($this->defaultFetchMode);
968
969 7409
        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 8055
    public function query()
1006
    {
1007 8055
        $connection = $this->getWrappedConnection();
1008
1009 8055
        $args = func_get_args();
1010
1011 8055
        $logger = $this->_config->getSQLLogger();
1012 8055
        if ($logger) {
1013 6764
            $logger->startQuery($args[0]);
1014
        }
1015
1016
        try {
1017 8055
            $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 8039
        } catch (Throwable $ex) {
1019 8039
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
1020
        }
1021
1022 6765
        $statement->setFetchMode($this->defaultFetchMode);
1023
1024 6765
        if ($logger) {
1025 6764
            $logger->stopQuery();
1026
        }
1027
1028 6765
        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 8177
    public function executeUpdate($query, array $params = [], array $types = [])
1046
    {
1047 8177
        $connection = $this->getWrappedConnection();
1048
1049 8177
        $logger = $this->_config->getSQLLogger();
1050 8177
        if ($logger) {
1051 6952
            $logger->startQuery($query, $params, $types);
1052
        }
1053
1054
        try {
1055 8177
            if ($params) {
1056 7619
                [$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
1057
1058 7619
                $stmt = $connection->prepare($query);
1059
1060 7619
                if ($types) {
1061 7619
                    $this->_bindTypedValues($stmt, $params, $types);
1062 7619
                    $stmt->execute();
1063
                } else {
1064
                    $stmt->execute($params);
1065
                }
1066 7617
                $result = $stmt->rowCount();
1067
            } else {
1068 8175
                $result = $connection->exec($query);
1069
            }
1070 8137
        } catch (Throwable $ex) {
1071 8137
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
1072
        }
1073
1074 7708
        if ($logger) {
1075 6943
            $logger->stopQuery();
1076
        }
1077
1078 7708
        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 8142
    public function exec($statement)
1091
    {
1092 8142
        $connection = $this->getWrappedConnection();
1093
1094 8139
        $logger = $this->_config->getSQLLogger();
1095 8139
        if ($logger) {
1096 5356
            $logger->startQuery($statement);
1097
        }
1098
1099
        try {
1100 8139
            $result = $connection->exec($statement);
1101 8117
        } catch (Throwable $ex) {
1102 8117
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
1103
        }
1104
1105 5304
        if ($logger) {
1106 5301
            $logger->stopQuery();
1107
        }
1108
1109 5304
        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 7777
    public function getTransactionNestingLevel()
1118
    {
1119 7777
        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 785
    public function lastInsertId($seqName = null)
1153
    {
1154 785
        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 6455
    public function transactional(Closure $func)
1173
    {
1174 6455
        $this->beginTransaction();
1175
        try {
1176 6455
            $res = $func($this);
1177 6407
            $this->commit();
1178
1179 6407
            return $res;
1180 6453
        } catch (Exception $e) {
1181 6452
            $this->rollBack();
1182 6452
            throw $e;
1183 6429
        } catch (Throwable $e) {
1184 6429
            $this->rollBack();
1185 6429
            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 6545
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
1199
    {
1200 6545
        if ($this->transactionNestingLevel > 0) {
1201 6314
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
1202
        }
1203
1204 6544
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1205 231
            throw ConnectionException::savepointsNotSupported();
1206
        }
1207
1208 6313
        $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
1209 6313
    }
1210
1211
    /**
1212
     * Gets if nested transactions should use savepoints.
1213
     *
1214
     * @return bool
1215
     */
1216 6313
    public function getNestTransactionsWithSavepoints()
1217
    {
1218 6313
        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 6313
    protected function _getNestedTransactionSavePointName()
1228
    {
1229 6313
        return 'DOCTRINE2_SAVEPOINT_' . $this->transactionNestingLevel;
1230
    }
1231
1232
    /**
1233
     * {@inheritDoc}
1234
     */
1235 7877
    public function beginTransaction()
1236
    {
1237 7877
        $connection = $this->getWrappedConnection();
1238
1239 7877
        ++$this->transactionNestingLevel;
1240
1241 7877
        $logger = $this->_config->getSQLLogger();
1242
1243 7877
        if ($this->transactionNestingLevel === 1) {
1244 7877
            if ($logger) {
1245 6628
                $logger->startQuery('"START TRANSACTION"');
1246
            }
1247
1248 7877
            $connection->beginTransaction();
1249
1250 7877
            if ($logger) {
1251 7877
                $logger->stopQuery();
1252
            }
1253 7766
        } elseif ($this->nestTransactionsWithSavepoints) {
1254 6313
            if ($logger) {
1255 6313
                $logger->startQuery('"SAVEPOINT"');
1256
            }
1257 6313
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1258 6313
            if ($logger) {
1259 6313
                $logger->stopQuery();
1260
            }
1261
        }
1262
1263 7877
        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 8236
    public function commit()
1273
    {
1274 8236
        if ($this->transactionNestingLevel === 0) {
1275 8223
            throw ConnectionException::noActiveTransaction();
1276
        }
1277 7844
        if ($this->isRollbackOnly) {
1278 6614
            throw ConnectionException::commitFailedRollbackOnly();
1279
        }
1280
1281 7842
        $result = true;
1282
1283 7842
        $connection = $this->getWrappedConnection();
1284
1285 7842
        $logger = $this->_config->getSQLLogger();
1286
1287 7842
        if ($this->transactionNestingLevel === 1) {
1288 7842
            if ($logger) {
1289 6547
                $logger->startQuery('"COMMIT"');
1290
            }
1291
1292 7842
            $result = $connection->commit();
1293
1294 7842
            if ($logger) {
1295 7842
                $logger->stopQuery();
1296
            }
1297 7764
        } elseif ($this->nestTransactionsWithSavepoints) {
1298 6313
            if ($logger) {
1299 6313
                $logger->startQuery('"RELEASE SAVEPOINT"');
1300
            }
1301 6313
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1302 6313
            if ($logger) {
1303 6313
                $logger->stopQuery();
1304
            }
1305
        }
1306
1307 7842
        --$this->transactionNestingLevel;
1308
1309 7842
        if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
1310 7818
            return $result;
1311
        }
1312
1313 7833
        $this->beginTransaction();
1314
1315 7833
        return $result;
1316
    }
1317
1318
    /**
1319
     * Commits all current nesting transactions.
1320
     */
1321 7763
    private function commitAll() : void
1322
    {
1323 7763
        while ($this->transactionNestingLevel !== 0) {
1324 7763
            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 7763
                $this->commit();
1328
1329 7763
                return;
1330
            }
1331
1332 7763
            $this->commit();
1333
        }
1334 7763
    }
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 8212
    public function rollBack()
1344
    {
1345 8212
        if ($this->transactionNestingLevel === 0) {
1346 8200
            throw ConnectionException::noActiveTransaction();
1347
        }
1348
1349 7797
        $connection = $this->getWrappedConnection();
1350
1351 7797
        $logger = $this->_config->getSQLLogger();
1352
1353 7797
        if ($this->transactionNestingLevel === 1) {
1354 7796
            if ($logger) {
1355 6622
                $logger->startQuery('"ROLLBACK"');
1356
            }
1357 7796
            $this->transactionNestingLevel = 0;
1358 7796
            $connection->rollBack();
1359 7796
            $this->isRollbackOnly = false;
1360 7796
            if ($logger) {
1361 6622
                $logger->stopQuery();
1362
            }
1363
1364 7796
            if ($this->autoCommit === false) {
1365 7796
                $this->beginTransaction();
1366
            }
1367 6591
        } elseif ($this->nestTransactionsWithSavepoints) {
1368 6313
            if ($logger) {
1369 6313
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
1370
            }
1371 6313
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
1372 6313
            --$this->transactionNestingLevel;
1373 6313
            if ($logger) {
1374 6313
                $logger->stopQuery();
1375
            }
1376
        } else {
1377 6590
            $this->isRollbackOnly = true;
1378 6590
            --$this->transactionNestingLevel;
1379
        }
1380
1381 7797
        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 6543
    public function createSavepoint($savepoint)
1394
    {
1395 6543
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1396 230
            throw ConnectionException::savepointsNotSupported();
1397
        }
1398
1399 6313
        $this->getWrappedConnection()->exec($this->platform->createSavePoint($savepoint));
1400 6313
    }
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 6313
    public function releaseSavepoint($savepoint)
1412
    {
1413 6313
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1414
            throw ConnectionException::savepointsNotSupported();
1415
        }
1416
1417 6313
        if (! $this->platform->supportsReleaseSavepoints()) {
1418 502
            return;
1419
        }
1420
1421 5811
        $this->getWrappedConnection()->exec($this->platform->releaseSavePoint($savepoint));
1422 5811
    }
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 6313
    public function rollbackSavepoint($savepoint)
1434
    {
1435 6313
        if (! $this->getDatabasePlatform()->supportsSavepoints()) {
1436
            throw ConnectionException::savepointsNotSupported();
1437
        }
1438
1439 6313
        $this->getWrappedConnection()->exec($this->platform->rollbackSavePoint($savepoint));
1440 6313
    }
1441
1442
    /**
1443
     * Gets the wrapped driver connection.
1444
     *
1445
     * @return DriverConnection
1446
     */
1447 8396
    public function getWrappedConnection()
1448
    {
1449 8396
        $this->connect();
1450
1451 8393
        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 7433
    public function getSchemaManager()
1461
    {
1462 7433
        if ($this->_schemaManager === null) {
1463 7272
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1464
        }
1465
1466 7433
        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 6614
    public function setRollbackOnly()
1478
    {
1479 6614
        if ($this->transactionNestingLevel === 0) {
1480 1
            throw ConnectionException::noActiveTransaction();
1481
        }
1482 6613
        $this->isRollbackOnly = true;
1483 6613
    }
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 6592
    public function isRollbackOnly()
1493
    {
1494 6592
        if ($this->transactionNestingLevel === 0) {
1495 1
            throw ConnectionException::noActiveTransaction();
1496
        }
1497
1498 6591
        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 7652
    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 7652
        if (is_int(key($params))) {
1546
            // Positional parameters
1547 7652
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1548 7652
            $bindIndex  = 1;
1549 7652
            foreach ($params as $value) {
1550 7652
                $typeIndex = $bindIndex + $typeOffset;
1551 7652
                if (isset($types[$typeIndex])) {
1552 6800
                    $type                  = $types[$typeIndex];
1553 6800
                    [$value, $bindingType] = $this->getBindingInfo($value, $type);
1554 6800
                    $stmt->bindValue($bindIndex, $value, $bindingType);
1555
                } else {
1556 7627
                    $stmt->bindValue($bindIndex, $value);
1557
                }
1558 7652
                ++$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 7648
    }
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 6827
    private function getBindingInfo($value, $type)
1583
    {
1584 6827
        if (is_string($type)) {
1585 6394
            $type = Type::getType($type);
1586
        }
1587 6827
        if ($type instanceof Type) {
1588 6394
            $value       = $type->convertToDatabaseValue($value, $this->getDatabasePlatform());
1589 6394
            $bindingType = $type->getBindingType();
1590
        } else {
1591 6821
            $bindingType = $type;
1592
        }
1593
1594 6827
        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 8168
    public function resolveParams(array $params, array $types)
1609
    {
1610 8168
        $resolvedParams = [];
1611
1612
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1613 8168
        if (is_int(key($params))) {
1614
            // Positional parameters
1615 5571
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1616 5571
            $bindIndex  = 1;
1617 5571
            foreach ($params as $value) {
1618 5571
                $typeIndex = $bindIndex + $typeOffset;
1619 5571
                if (isset($types[$typeIndex])) {
1620
                    $type                       = $types[$typeIndex];
1621
                    [$value]                    = $this->getBindingInfo($value, $type);
1622
                    $resolvedParams[$bindIndex] = $value;
1623
                } else {
1624 5571
                    $resolvedParams[$bindIndex] = $value;
1625
                }
1626 5571
                ++$bindIndex;
1627
            }
1628
        } else {
1629
            // Named parameters
1630 8160
            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 8168
        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 6361
    public function ping()
1676
    {
1677 6361
        $connection = $this->getWrappedConnection();
1678
1679 6361
        if ($connection instanceof PingableConnection) {
1680 1675
            return $connection->ping();
1681
        }
1682
1683
        try {
1684 6343
            $this->query($this->getDatabasePlatform()->getDummySelectSQL());
1685
1686 6343
            return true;
1687
        } catch (DBALException $e) {
1688
            return false;
1689
        }
1690
    }
1691
}
1692