Failed Conditions
Push — master ( 94cec7...7f79d0 )
by Marco
25s queued 13s
created

Connection   F

Complexity

Total Complexity 179

Size/Duplication

Total Lines 1636
Duplicated Lines 0 %

Test Coverage

Coverage 90.23%

Importance

Changes 0
Metric Value
wmc 179
eloc 441
dl 0
loc 1636
ccs 434
cts 481
cp 0.9023
rs 2
c 0
b 0
f 0

68 Methods

Rating   Name   Duplication   Size   Complexity  
A close() 0 5 1
A getDriver() 0 3 1
A isTransactionActive() 0 3 1
A getEventManager() 0 3 1
A getDatabase() 0 3 1
A getServerVersion() 0 11 3
A getHost() 0 3 1
A __construct() 0 39 6
A isConnected() 0 3 1
A getConfiguration() 0 3 1
A getDatabasePlatform() 0 7 2
A getUsername() 0 3 1
A fetchColumn() 0 3 1
B getDatabasePlatformVersion() 0 49 7
A getPort() 0 3 1
A isAutoCommit() 0 3 1
A getPassword() 0 3 1
A fetchArray() 0 3 1
A setAutoCommit() 0 17 4
A fetchAssoc() 0 3 1
A getExpressionBuilder() 0 3 1
A setFetchMode() 0 3 1
A detectDatabasePlatform() 0 13 2
A getParams() 0 3 1
A connect() 0 23 4
A setTransactionIsolation() 0 5 1
A getTransactionIsolation() 0 7 2
B commit() 0 40 11
B _bindTypedValues() 0 27 7
A setNestTransactionsWithSavepoints() 0 11 3
A _getNestedTransactionSavePointName() 0 3 1
B executeUpdate() 0 33 6
A rollbackSavepoint() 0 7 2
B beginTransaction() 0 27 7
A releaseSavepoint() 0 11 3
A getNestTransactionsWithSavepoints() 0 3 1
A addIdentifierCondition() 0 17 3
B resolveParams() 0 34 7
A insert() 0 21 4
A update() 0 20 3
B rollBack() 0 36 9
A getBindingInfo() 0 13 3
A getSchemaManager() 0 7 2
A errorInfo() 0 5 1
A transactional() 0 13 3
B executeCacheQuery() 0 28 7
A setRollbackOnly() 0 6 2
A fetchAll() 0 3 1
A quoteIdentifier() 0 3 1
A lastInsertId() 0 5 1
A errorCode() 0 5 1
A createSavepoint() 0 7 2
A commitAll() 0 12 4
A isRollbackOnly() 0 7 2
A convertToPHPValue() 0 3 1
A exec() 0 20 4
A ping() 0 14 3
A getWrappedConnection() 0 5 1
A createQueryBuilder() 0 3 1
A query() 0 24 4
A convertToDatabaseValue() 0 3 1
B executeQuery() 0 38 7
A delete() 0 14 3
A project() 0 12 2
A prepare() 0 11 2
A quote() 0 7 1
A extractTypeValues() 0 9 2
A getTransactionNestingLevel() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.

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
    public function __construct(
183 3727
        array $params,
184
        Driver $driver,
185
        ?Configuration $config = null,
186
        ?EventManager $eventManager = null
187
    ) {
188
        $this->_driver = $driver;
189 3727
        $this->params  = $params;
190 3727
191
        if (isset($params['pdo'])) {
192 3727
            $this->_conn       = $params['pdo'];
193 324
            $this->isConnected = true;
194 324
            unset($this->params['pdo']);
195 324
        }
196
197
        if (isset($params['platform'])) {
198 3727
            if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
199 756
                throw DBALException::invalidPlatformType($params['platform']);
200 27
            }
201
202
            $this->platform = $params['platform'];
203 729
            unset($this->params['platform']);
204 729
        }
205
206
        // Create default config and event manager if none given
207
        if (! $config) {
208 3727
            $config = new Configuration();
209 837
        }
210
211
        if (! $eventManager) {
212 3727
            $eventManager = new EventManager();
213 837
        }
214
215
        $this->_config       = $config;
216 3727
        $this->_eventManager = $eventManager;
217 3727
218
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
219 3727
220
        $this->autoCommit = $config->getAutoCommit();
221 3727
    }
222 3727
223
    /**
224
     * Gets the parameters used during instantiation.
225
     *
226
     * @return mixed[]
227
     */
228
    public function getParams()
229 3454
    {
230
        return $this->params;
231 3454
    }
232
233
    /**
234
     * Gets the name of the database this Connection is connected to.
235
     *
236
     * @return string
237
     */
238
    public function getDatabase()
239 1804
    {
240
        return $this->_driver->getDatabase($this);
241 1804
    }
242
243
    /**
244
     * Gets the hostname of the currently connected database.
245
     *
246
     * @return string|null
247
     */
248
    public function getHost()
249 27
    {
250
        return $this->params['host'] ?? null;
251 27
    }
252
253
    /**
254
     * Gets the port of the currently connected database.
255
     *
256
     * @return mixed
257
     */
258
    public function getPort()
259 27
    {
260
        return $this->params['port'] ?? null;
261 27
    }
262
263
    /**
264
     * Gets the username used by this connection.
265
     *
266
     * @return string|null
267
     */
268
    public function getUsername()
269 82
    {
270
        return $this->params['user'] ?? null;
271 82
    }
272
273
    /**
274
     * Gets the password used by this connection.
275
     *
276
     * @return string|null
277
     */
278
    public function getPassword()
279 27
    {
280
        return $this->params['password'] ?? null;
281 27
    }
282
283
    /**
284
     * Gets the DBAL driver instance.
285
     *
286
     * @return Driver
287
     */
288
    public function getDriver()
289 1695
    {
290
        return $this->_driver;
291 1695
    }
292
293
    /**
294
     * Gets the Configuration used by the Connection.
295
     *
296
     * @return Configuration
297
     */
298
    public function getConfiguration()
299 8183
    {
300
        return $this->_config;
301 8183
    }
302
303
    /**
304
     * Gets the EventManager used by the Connection.
305
     *
306
     * @return EventManager
307
     */
308
    public function getEventManager()
309 386
    {
310
        return $this->_eventManager;
311 386
    }
312
313
    /**
314
     * Gets the DatabasePlatform for the connection.
315
     *
316
     * @return AbstractPlatform
317
     *
318
     * @throws DBALException
319
     */
320
    public function getDatabasePlatform()
321 6876
    {
322
        if ($this->platform === null) {
323 6876
            $this->detectDatabasePlatform();
324 1017
        }
325
326
        return $this->platform;
327 6849
    }
328
329
    /**
330
     * Gets the ExpressionBuilder for the connection.
331
     *
332
     * @return ExpressionBuilder
333
     */
334
    public function getExpressionBuilder()
335
    {
336
        return $this->_expr;
337
    }
338
339
    /**
340
     * Establishes the connection with the database.
341
     *
342
     * @return bool TRUE if the connection was successfully established, FALSE if
343
     *              the connection is already open.
344
     */
345
    public function connect()
346 8341
    {
347
        if ($this->isConnected) {
348 8341
            return false;
349 7826
        }
350
351
        $driverOptions = $this->params['driverOptions'] ?? [];
352 1280
        $user          = $this->params['user'] ?? null;
353 1280
        $password      = $this->params['password'] ?? null;
354 1280
355
        $this->_conn       = $this->_driver->connect($this->params, $user, $password, $driverOptions);
356 1280
        $this->isConnected = true;
357 1190
358
        if ($this->autoCommit === false) {
359 1190
            $this->beginTransaction();
360 81
        }
361
362
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
363 1190
            $eventArgs = new Event\ConnectionEventArgs($this);
364 75
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
365 75
        }
366
367
        return true;
368 1190
    }
369
370
    /**
371
     * Detects and sets the database platform.
372
     *
373
     * Evaluates custom platform class and version in order to set the correct platform.
374
     *
375
     * @throws DBALException If an invalid platform was specified for this connection.
376
     */
377
    private function detectDatabasePlatform()
378 1017
    {
379
        $version = $this->getDatabasePlatformVersion();
380 1017
381
        if ($version !== null) {
382 934
            assert($this->_driver instanceof VersionAwarePlatformDriver);
383 650
384
            $this->platform = $this->_driver->createDatabasePlatformForVersion($version);
385 650
        } else {
386
            $this->platform = $this->_driver->getDatabasePlatform();
387 284
        }
388
389
        $this->platform->setEventManager($this->_eventManager);
390 934
    }
391 934
392
    /**
393
     * Returns the version of the related platform if applicable.
394
     *
395
     * Returns null if either the driver is not capable to create version
396
     * specific platform instances, no explicit server version was specified
397
     * or the underlying driver connection cannot determine the platform
398
     * version without having to query it (performance reasons).
399
     *
400
     * @return string|null
401
     *
402
     * @throws Exception
403
     */
404
    private function getDatabasePlatformVersion()
405 1017
    {
406
        // Driver does not support version specific platforms.
407
        if (! $this->_driver instanceof VersionAwarePlatformDriver) {
408 1017
            return null;
409 257
        }
410
411
        // Explicit platform version requested (supersedes auto-detection).
412
        if (isset($this->params['serverVersion'])) {
413 760
            return $this->params['serverVersion'];
414
        }
415
416
        // If not connected, we need to connect now to determine the platform version.
417
        if ($this->_conn === null) {
418 760
            try {
419
                $this->connect();
420 714
            } catch (Throwable $originalException) {
421 106
                if (empty($this->params['dbname'])) {
422 106
                    throw $originalException;
423
                }
424
425
                // The database to connect to might not yet exist.
426
                // Retry detection without database name connection parameter.
427
                $databaseName           = $this->params['dbname'];
428 106
                $this->params['dbname'] = null;
429 106
430
                try {
431
                    $this->connect();
432 106
                } catch (Throwable $fallbackException) {
433 83
                    // Either the platform does not support database-less connections
434
                    // or something else went wrong.
435
                    // Reset connection parameters and rethrow the original exception.
436
                    $this->params['dbname'] = $databaseName;
437 83
438
                    throw $originalException;
439 83
                }
440
441
                // Reset connection parameters.
442
                $this->params['dbname'] = $databaseName;
443 23
                $serverVersion          = $this->getServerVersion();
444 23
445
                // Close "temporary" connection to allow connecting to the real database again.
446
                $this->close();
447 23
448
                return $serverVersion;
449 23
            }
450
        }
451
452
        return $this->getServerVersion();
453 677
    }
454
455
    /**
456
     * Returns the database server version if the underlying driver supports it.
457
     *
458
     * @return string|null
459
     */
460
    private function getServerVersion()
461 677
    {
462
        // Automatic platform version detection.
463
        if ($this->_conn instanceof ServerInfoAwareConnection &&
464 677
            ! $this->_conn->requiresQueryForServerVersion()
465 677
        ) {
466
            return $this->_conn->getServerVersion();
467 650
        }
468
469
        // Unable to detect platform version.
470
        return null;
471 27
    }
472
473
    /**
474
     * Returns the current auto-commit mode for this connection.
475
     *
476
     * @see    setAutoCommit
477
     *
478
     * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
479
     */
480
    public function isAutoCommit()
481 54
    {
482
        return $this->autoCommit === true;
483 54
    }
484
485
    /**
486
     * Sets auto-commit mode for this connection.
487
     *
488
     * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
489
     * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
490
     * the method commit or the method rollback. By default, new connections are in auto-commit mode.
491
     *
492
     * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
493
     * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
494
     *
495
     * @see   isAutoCommit
496
     *
497
     * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
498
     */
499
    public function setAutoCommit($autoCommit)
500 135
    {
501
        $autoCommit = (bool) $autoCommit;
502 135
503
        // Mode not changed, no-op.
504
        if ($autoCommit === $this->autoCommit) {
505 135
            return;
506 27
        }
507
508
        $this->autoCommit = $autoCommit;
509 135
510
        // Commit all currently active transactions if any when switching auto-commit mode.
511
        if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
512 135
            return;
513 108
        }
514
515
        $this->commitAll();
516 27
    }
517 27
518
    /**
519
     * Sets the fetch mode.
520
     *
521
     * @param int $fetchMode
522
     *
523
     * @return void
524
     */
525
    public function setFetchMode($fetchMode)
526 27
    {
527
        $this->defaultFetchMode = $fetchMode;
528 27
    }
529 27
530
    /**
531
     * Prepares and executes an SQL query and returns the first row of the result
532
     * as an associative array.
533
     *
534
     * @param string         $statement The SQL query.
535
     * @param mixed[]        $params    The query parameters.
536
     * @param int[]|string[] $types     The query parameter types.
537
     *
538
     * @return mixed[]|false False is returned if no rows are found.
539
     *
540
     * @throws DBALException
541
     */
542
    public function fetchAssoc($statement, array $params = [], array $types = [])
543 1777
    {
544
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
545 1777
    }
546
547
    /**
548
     * Prepares and executes an SQL query and returns the first row of the result
549
     * as a numerically indexed array.
550
     *
551
     * @param string         $statement The SQL query to be executed.
552
     * @param mixed[]        $params    The prepared statement params.
553
     * @param int[]|string[] $types     The query parameter types.
554
     *
555
     * @return mixed[]|false False is returned if no rows are found.
556
     */
557
    public function fetchArray($statement, array $params = [], array $types = [])
558 100
    {
559
        return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
560 100
    }
561
562
    /**
563
     * Prepares and executes an SQL query and returns the value of a single column
564
     * of the first row of the result.
565
     *
566
     * @param string         $statement The SQL query to be executed.
567
     * @param mixed[]        $params    The prepared statement params.
568
     * @param int            $column    The 0-indexed column number to retrieve.
569
     * @param int[]|string[] $types     The query parameter types.
570
     *
571
     * @return mixed|false False is returned if no rows are found.
572
     *
573
     * @throws DBALException
574
     */
575
    public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
576 1029
    {
577
        return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
578 1029
    }
579
580
    /**
581
     * Whether an actual connection to the database is established.
582
     *
583
     * @return bool
584
     */
585
    public function isConnected()
586 105
    {
587
        return $this->isConnected;
588 105
    }
589
590
    /**
591
     * Checks whether a transaction is currently active.
592
     *
593
     * @return bool TRUE if a transaction is currently active, FALSE otherwise.
594
     */
595
    public function isTransactionActive()
596 8156
    {
597
        return $this->transactionNestingLevel > 0;
598 8156
    }
599
600
    /**
601
     * Adds identifier condition to the query components
602
     *
603
     * @param mixed[]  $identifier Map of key columns to their values
604
     * @param string[] $columns    Column names
605
     * @param mixed[]  $values     Column values
606
     * @param string[] $conditions Key conditions
607
     *
608
     * @throws DBALException
609
     */
610
    private function addIdentifierCondition(
611 421
        array $identifier,
612
        array &$columns,
613 421
        array &$values,
614 421
        array &$conditions
615 421
    ) : void {
616
        $platform = $this->getDatabasePlatform();
617 421
618 421
        foreach ($identifier as $columnName => $value) {
619 108
            if ($value === null) {
620 108
                $conditions[] = $platform->getIsNullExpression($columnName);
621
                continue;
622
            }
623 367
624 367
            $columns[]    = $columnName;
625 367
            $values[]     = $value;
626
            $conditions[] = $columnName . ' = ?';
627
        }
628 421
    }
629
630
    /**
631
     * Executes an SQL DELETE statement on a table.
632
     *
633
     * Table expression and columns are not escaped and are not safe for user-input.
634
     *
635
     * @param string         $tableExpression The expression of the table on which to delete.
636
     * @param mixed[]        $identifier      The deletion criteria. An associative array containing column-value pairs.
637
     * @param int[]|string[] $types           The types of identifiers.
638
     *
639
     * @return int The number of affected rows.
640
     *
641
     * @throws DBALException
642
     * @throws InvalidArgumentException
643
     */
644
    public function delete($tableExpression, array $identifier, array $types = [])
645 185
    {
646
        if (empty($identifier)) {
647 185
            throw InvalidArgumentException::fromEmptyCriteria();
648 27
        }
649
650
        $columns = $values = $conditions = [];
651 158
652
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
653 158
654 158
        return $this->executeUpdate(
655 158
            'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
656 158
            $values,
657
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
658
        );
659
    }
660
661
    /**
662
     * Closes the connection.
663
     *
664
     * @return void
665 669
     */
666
    public function close()
667 669
    {
668
        $this->_conn = null;
669 669
670 669
        $this->isConnected = false;
671
    }
672
673
    /**
674
     * Sets the transaction isolation level.
675
     *
676
     * @param int $level The level to set.
677
     *
678
     * @return int
679
     */
680
    public function setTransactionIsolation($level)
681
    {
682
        $this->transactionIsolationLevel = $level;
683
684
        return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
685
    }
686
687
    /**
688
     * Gets the currently active transaction isolation level.
689
     *
690
     * @return int The current transaction isolation level.
691
     */
692
    public function getTransactionIsolation()
693
    {
694
        if ($this->transactionIsolationLevel === null) {
695
            $this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
696
        }
697
698
        return $this->transactionIsolationLevel;
699
    }
700
701
    /**
702
     * Executes an SQL UPDATE statement on a table.
703
     *
704
     * Table expression and columns are not escaped and are not safe for user-input.
705
     *
706
     * @param string         $tableExpression The expression of the table to update quoted or unquoted.
707
     * @param mixed[]        $data            An associative array containing column-value pairs.
708
     * @param mixed[]        $identifier      The update criteria. An associative array containing column-value pairs.
709
     * @param int[]|string[] $types           Types of the merged $data and $identifier arrays in that order.
710
     *
711
     * @return int The number of affected rows.
712
     *
713
     * @throws DBALException
714 263
     */
715
    public function update($tableExpression, array $data, array $identifier, array $types = [])
716 263
    {
717 263
        $columns = $values = $conditions = $set = [];
718 263
719
        foreach ($data as $columnName => $value) {
720 263
            $columns[] = $columnName;
721 263
            $values[]  = $value;
722 263
            $set[]     = $columnName . ' = ?';
723 263
        }
724
725
        $this->addIdentifierCondition($identifier, $columns, $values, $conditions);
726 263
727 263
        if (is_string(key($types))) {
728 263
            $types = $this->extractTypeValues($columns, $types);
729
        }
730 263
731 135
        $sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
732
                . ' WHERE ' . implode(' AND ', $conditions);
733
734 263
        return $this->executeUpdate($sql, $values, $types);
735 263
    }
736
737 263
    /**
738
     * Inserts a table row with specified data.
739
     *
740
     * Table expression and columns are not escaped and are not safe for user-input.
741
     *
742
     * @param string         $tableExpression The expression of the table to insert data into, quoted or unquoted.
743
     * @param mixed[]        $data            An associative array containing column-value pairs.
744
     * @param int[]|string[] $types           Types of the inserted data.
745
     *
746
     * @return int The number of affected rows.
747
     *
748
     * @throws DBALException
749
     */
750
    public function insert($tableExpression, array $data, array $types = [])
751
    {
752
        if (empty($data)) {
753 2419
            return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
754
        }
755 2419
756 27
        $columns = [];
757
        $values  = [];
758
        $set     = [];
759 2392
760 2392
        foreach ($data as $columnName => $value) {
761 2392
            $columns[] = $columnName;
762
            $values[]  = $value;
763 2392
            $set[]     = '?';
764 2392
        }
765 2392
766 2392
        return $this->executeUpdate(
767
            'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
768
            ' VALUES (' . implode(', ', $set) . ')',
769 2392
            $values,
770 2392
            is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
771 2392
        );
772 2392
    }
773 2392
774
    /**
775
     * Extract ordered type list from an ordered column list and type map.
776
     *
777
     * @param int[]|string[] $columnList
778
     * @param int[]|string[] $types
779
     *
780
     * @return int[]|string[]
781
     */
782
    private function extractTypeValues(array $columnList, array $types)
783
    {
784
        $typeValues = [];
785 243
786
        foreach ($columnList as $columnIndex => $columnName) {
787 243
            $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
788
        }
789 243
790 243
        return $typeValues;
791
    }
792
793 243
    /**
794
     * Quotes a string so it can be safely used as a table or column name, even if
795
     * it is a reserved name.
796
     *
797
     * Delimiting style depends on the underlying database platform that is being used.
798
     *
799
     * NOTE: Just because you CAN use quoted identifiers does not mean
800
     * you SHOULD use them. In general, they end up causing way more
801
     * problems than they solve.
802
     *
803
     * @param string $str The name to be quoted.
804
     *
805
     * @return string The quoted name.
806
     */
807
    public function quoteIdentifier($str)
808
    {
809
        return $this->getDatabasePlatform()->quoteIdentifier($str);
810 27
    }
811
812 27
    /**
813
     * Quotes a given input parameter.
814
     *
815
     * @param mixed    $input The parameter to be quoted.
816
     * @param int|null $type  The type of the parameter.
817
     *
818
     * @return string The quoted parameter.
819
     */
820
    public function quote($input, $type = null)
821
    {
822
        $this->connect();
823 256
824
        [$value, $bindingType] = $this->getBindingInfo($input, $type);
825 256
826
        return $this->_conn->quote($value, $bindingType);
0 ignored issues
show
Bug introduced by
The method quote() does not exist on null. ( Ignorable by Annotation )

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

826
        return $this->_conn->/** @scrutinizer ignore-call */ quote($value, $bindingType);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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

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

905
                /** @scrutinizer ignore-call */ 
906
                $stmt = $this->_conn->query($query);

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

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

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

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

1007
            /** @scrutinizer ignore-call */ 
1008
            $statement = $this->_conn->query(...$args);

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

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

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