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

Connection::addIdentifierCondition()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 17
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 4
crap 3
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 Jim Cottrell
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 Johannes M. Schmitt
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 Kim Hemsø Rasmussen
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