Passed
Pull Request — master (#240)
by Wilmer
11:51
created

Connection::getQueryBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Connection;
6
7
use PDO;
8
use PDOException;
9
use Psr\Log\LogLevel;
10
use Psr\Log\LoggerInterface;
11
use Throwable;
12
use Yiisoft\Cache\Dependency\Dependency;
13
use Yiisoft\Db\AwareTrait\LoggerAwareTrait;
14
use Yiisoft\Db\AwareTrait\ProfilerAwareTrait;
15
use Yiisoft\Db\Cache\QueryCache;
16
use Yiisoft\Db\Command\Command;
17
use Yiisoft\Db\Exception\Exception;
18
use Yiisoft\Db\Exception\InvalidCallException;
19
use Yiisoft\Db\Exception\InvalidConfigException;
20
use Yiisoft\Db\Exception\NotSupportedException;
21
use Yiisoft\Db\Factory\DatabaseFactory;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Factory\DatabaseFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use Yiisoft\Db\Query\QueryBuilder;
23
use Yiisoft\Db\Schema\Schema;
24
use Yiisoft\Db\Schema\TableSchema;
25
use Yiisoft\Db\Transaction\Transaction;
26
use Yiisoft\Profiler\ProfilerInterface;
27
28
use function array_keys;
29
use function str_replace;
30
use function strncmp;
31
32
/**
33
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
34
 *
35
 * Connection works together with {@see Command}, {@see DataReader} and {@see Transaction} to provide data access to
36
 * various DBMS in a common set of APIs. They are a thin wrapper of the
37
 * [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
38
 *
39
 * Connection supports database replication and read-write splitting. In particular, a Connection component can be
40
 * configured with multiple {@see setMasters()} and {@see setSlaves()}. It will do load balancing and failover by
41
 * choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations
42
 * to the masters.
43
 *
44
 * To establish a DB connection, set {@see dsn}, {@see setUsername()} and {@see setPassword}, and then call
45
 * {@see open()} to connect to the database server. The current state of the connection can be checked using
46
 * {@see $isActive}.
47
 *
48
 * The following example shows how to create a Connection instance and establish the DB connection:
49
 *
50
 * ```php
51
 * $connection = new \Yiisoft\Db\Mysql\Connection($dsn, $queryCache);
52
 * $connection->open();
53
 * ```
54
 *
55
 * After the DB connection is established, one can execute SQL statements like the following:
56
 *
57
 * ```php
58
 * $command = $connection->createCommand('SELECT * FROM post');
59
 * $posts = $command->queryAll();
60
 * $command = $connection->createCommand('UPDATE post SET status=1');
61
 * $command->execute();
62
 * ```
63
 *
64
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
65
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
66
 * following is an example:
67
 *
68
 * ```php
69
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
70
 * $command->bindValue(':id', $_GET['id']);
71
 * $post = $command->query();
72
 * ```
73
 *
74
 * For more information about how to perform various DB queries, please refer to {@see Command}.
75
 *
76
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
77
 *
78
 * ```php
79
 * $transaction = $connection->beginTransaction();
80
 * try {
81
 *     $connection->createCommand($sql1)->execute();
82
 *     $connection->createCommand($sql2)->execute();
83
 *     // ... executing other SQL statements ...
84
 *     $transaction->commit();
85
 * } catch (Exceptions $e) {
86
 *     $transaction->rollBack();
87
 * }
88
 * ```
89
 *
90
 * You also can use shortcut for the above like the following:
91
 *
92
 * ```php
93
 * $connection->transaction(function () {
94
 *     $order = new Order($customer);
95
 *     $order->save();
96
 *     $order->addItems($items);
97
 * });
98
 * ```
99
 *
100
 * If needed you can pass transaction isolation level as a second parameter:
101
 *
102
 * ```php
103
 * $connection->transaction(function (Connection $db) {
104
 *     //return $db->...
105
 * }, Transaction::READ_UNCOMMITTED);
106
 * ```
107
 *
108
 * Connection is often used as an application component and configured in the container-di configuration like the
109
 * following:
110
 *
111
 * ```php
112
 * Connection::class => static function (ContainerInterface $container) {
113
 *     $connection = new Connection(
114
 *         $container->get(CacheInterface::class),
115
 *         $container->get(LoggerInterface::class),
116
 *         $container->get(Profiler::class),
117
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
118
 *     );
119
 *
120
 *     $connection->setUsername(root);
121
 *     $connection->setPassword('');
122
 *
123
 *     return $connection;
124
 * },
125
 * ```
126
 *
127
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Connection\Dsn}:
128
 *
129
 * ```php
130
 * Connection::class => static function (ContainerInterface $container) {
131
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
132
 *
133
 *     $connection = new Connection(
134
 *         $container->get(CacheInterface::class),
135
 *         $container->get(LoggerInterface::class),
136
 *         $container->get(Profiler::class),
137
 *         $dsn->getDsn()
138
 *     );
139
 *
140
 *     $connection->setUsername(root);
141
 *     $connection->setPassword('');
142
 *
143
 *     return $connection;
144
 * },
145
 * ```
146
 *
147
 * @property string $driverName Name of the DB driver.
148
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
149
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
150
 * object. This property is read-only.
151
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
152
 * available. This property is read-only.
153
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
154
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
155
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
156
 * @property Schema $schema The schema information for the database opened by this connection. This property is
157
 * read-only.
158
 * @property string $serverVersion Server version as a string. This property is read-only.
159
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
160
 * available and `$fallbackToMaster` is false. This property is read-only.
161
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
162
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
163
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
164
 * property is read-only.
165
 */
166
abstract class Connection implements ConnectionInterface
167
{
168
    use LoggerAwareTrait;
169
    use ProfilerAwareTrait;
170
171
    private string $dsn;
172
    private ?string $username = null;
173
    private ?string $password = null;
174
    private array $attributes = [];
175
    private ?string $charset = null;
176
    private ?bool $emulatePrepare = null;
177
    private string $tablePrefix = '';
178
    private bool $enableSavepoint = true;
179
    private int $serverRetryInterval = 600;
180
    private bool $enableSlaves = true;
181
    private array $slaves = [];
182
    private array $masters = [];
183
    private bool $shuffleMasters = true;
184
    private array $quotedTableNames = [];
185
    private array $quotedColumnNames = [];
186
    private ?Connection $master = null;
187
    private ?Connection $slave = null;
188
    private ?PDO $pdo = null;
189
    private QueryCache $queryCache;
190
    private ?Transaction $transaction = null;
191
192
    public function __construct(string $dsn, QueryCache $queryCache)
193
    {
194
        $this->dsn = $dsn;
195
        $this->queryCache = $queryCache;
196 3016
    }
197
198 3016
    /**
199 3016
     * Creates a command for execution.
200 3016
     *
201
     * @param string|null $sql the SQL statement to be executed
202
     * @param array $params the parameters to be bound to the SQL statement
203
     *
204
     * @throws Exception|InvalidConfigException
205
     *
206
     * @return Command the DB command
207
     */
208
    abstract public function createCommand(?string $sql = null, array $params = []): Command;
209
210
    /**
211
     * Returns the schema information for the database opened by this connection.
212
     *
213
     * @return Schema the schema information for the database opened by this connection.
214
     */
215
    abstract public function getSchema(): Schema;
216
217
    /**
218
     * Creates the PDO instance.
219
     *
220
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
221
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
222
     *
223
     * @return PDO the pdo instance
224
     */
225
    abstract protected function createPdoInstance(): PDO;
226
227
    /**
228
     * Initializes the DB connection.
229
     *
230
     * This method is invoked right after the DB connection is established.
231
     *
232
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
233
     *
234
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
235
     *
236
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
237
     */
238
    abstract protected function initConnection(): void;
239
240
    /**
241
     * Reset the connection after cloning.
242
     */
243
    public function __clone()
244
    {
245
        $this->master = null;
246
        $this->slave = null;
247 10
        $this->transaction = null;
248
249 10
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
250 10
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
251 10
            $this->pdo = null;
252 10
        }
253
    }
254 10
255
    /**
256 10
     * Close the connection before serializing.
257
     *
258 10
     * @return array
259
     */
260
    public function __sleep(): array
261
    {
262
        $fields = (array) $this;
263
264
        unset(
265 6
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
266
            $fields["\000" . __CLASS__ . "\000" . 'master'],
267 6
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
268
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
269
            $fields["\000" . __CLASS__ . "\000" . 'schema']
270 6
        );
271 6
272 6
        return array_keys($fields);
273 6
    }
274 6
275
    /**
276
     * Starts a transaction.
277 6
     *
278
     * @param string|null $isolationLevel The isolation level to use for this transaction.
279
     *
280
     * {@see Transaction::begin()} for details.
281
     *
282
     * @throws Exception|InvalidConfigException|NotSupportedException|Throwable
283
     *
284
     * @return Transaction the transaction initiated
285
     */
286
    public function beginTransaction(string $isolationLevel = null): Transaction
287
    {
288
        $this->open();
289
290
        if (($transaction = $this->getTransaction()) === null) {
291 40
            $transaction = $this->transaction = new Transaction($this);
292
            if ($this->logger !== null) {
293 40
                $transaction->setLogger($this->logger);
294
            }
295 40
        }
296 40
297
        $transaction->begin($isolationLevel);
298
299 40
        return $transaction;
300
    }
301 40
302
    /**
303
     * Uses query cache for the queries performed with the callable.
304
     *
305
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
306
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
307
     *
308
     * For example,
309
     *
310
     * ```php
311
     * // The customer will be fetched from cache if available.
312
     * // If not, the query will be made against DB and cached for use next time.
313
     * $customer = $db->cache(function (Connection $db) {
314
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
315
     * });
316
     * ```
317
     *
318
     * Note that query cache is only meaningful for queries that return results. For queries performed with
319
     * {@see Command::execute()}, query cache will not be used.
320
     *
321
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
322
     * The signature of the callable is `function (Connection $db)`.
323
     * @param int|null $duration the number of seconds that query results can remain valid in the cache. If this is not
324
     * set, the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will
325
     * never expire.
326
     * @param Dependency|null $dependency the cache dependency associated with the cached query
327
     * results.
328
     *
329
     * @throws Throwable if there is any exception during query
330
     *
331
     * @return mixed the return result of the callable
332
     *
333
     * {@see setEnableQueryCache()}
334
     * {@see queryCache}
335
     * {@see noCache()}
336
     */
337
    public function cache(callable $callable, int $duration = null, Dependency $dependency = null)
338
    {
339 10
        $this->queryCache->setInfo(
340
            [$duration ?? $this->queryCache->getDuration(), $dependency]
341 10
        );
342 10
        $result = $callable($this);
343
        $this->queryCache->removeLastInfo();
344
        return $result;
345 10
    }
346
347 10
    public function getAttributes(): array
348
    {
349 10
        return $this->attributes;
350
    }
351
352 1853
    public function getCharset(): ?string
353
    {
354 1853
        return $this->charset;
355
    }
356
357 754
    public function getDsn(): string
358
    {
359 754
        return $this->dsn;
360
    }
361
362 1878
    public function getEmulatePrepare(): ?bool
363
    {
364 1878
        return $this->emulatePrepare;
365
    }
366
367 1484
    public function isSavepointEnabled(): bool
368
    {
369 1484
        return $this->enableSavepoint;
370
    }
371
372 1717
    public function areSlavesEnabled(): bool
373
    {
374 1717
        return $this->enableSlaves;
375
    }
376
377 1853
    /**
378
     * Returns a value indicating whether the DB connection is established.
379 1853
     *
380
     * @return bool whether the DB connection is established
381
     */
382 10
    public function isActive(): bool
383
    {
384 10
        return $this->pdo !== null;
385
    }
386
387 1
    /**
388
     * Returns the ID of the last inserted row or sequence value.
389 1
     *
390
     * @param string $sequenceName name of the sequence object (required by some DBMS)
391
     *
392
     * @throws Exception
393
     * @throws InvalidCallException
394
     *
395
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
396
     *
397 193
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
398
     */
399 193
    public function getLastInsertID(string $sequenceName = ''): string
400
    {
401
        return $this->getSchema()->getLastInsertID($sequenceName);
402
    }
403
404
    /**
405
     * Returns the currently active master connection.
406
     *
407
     * If this method is called for the first time, it will try to open a master connection.
408
     *
409
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
410
     */
411
    public function getMaster(): ?self
412
    {
413
        if ($this->master === null) {
414 10
            $this->master = $this->shuffleMasters
415
                ? $this->openFromPool($this->masters)
416 10
                : $this->openFromPoolSequentially($this->masters);
417
        }
418
419
        return $this->master;
420
    }
421
422
    /**
423
     * Returns the PDO instance for the currently active master connection.
424
     *
425
     * This method will open the master DB connection and then return {@see pdo}.
426 13
     *
427
     * @throws Exception
428 13
     *
429 13
     * @return PDO the PDO instance for the currently active master connection.
430 7
     */
431 8
    public function getMasterPdo(): PDO
432
    {
433
        $this->open();
434 13
        return $this->pdo;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->pdo could return the type null which is incompatible with the type-hinted return PDO. Consider adding an additional type-check to rule them out.
Loading history...
435
    }
436
437
    public function getPassword(): ?string
438
    {
439
        return $this->password;
440
    }
441
442
    /**
443
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
444
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
445
     * it will be null.
446 1817
     *
447
     * @return PDO|null
448 1817
     *
449
     * {@see pdoClass}
450 1817
     */
451
    public function getPDO(): ?PDO
452
    {
453 1853
        return $this->pdo;
454
    }
455 1853
456
    /**
457
     * Returns the query builder for the current DB connection.
458
     *
459
     * @return QueryBuilder the query builder for the current DB connection.
460
     */
461
    public function getQueryBuilder(): QueryBuilder
462
    {
463
        return $this->getSchema()->getQueryBuilder();
464
    }
465
466
    /**
467 1853
     * Returns a server version as a string comparable by {@see \version_compare()}.
468
     *
469 1853
     * @throws Exception
470
     *
471
     * @return string server version as a string.
472
     */
473
    public function getServerVersion(): string
474
    {
475
        return $this->getSchema()->getServerVersion();
476
    }
477 955
478
    /**
479 955
     * Returns the currently active slave connection.
480
     *
481
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
482
     * is true.
483
     *
484
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
485
     * available.
486
     *
487
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
488
     * `$fallbackToMaster` is false.
489 314
     */
490
    public function getSlave(bool $fallbackToMaster = true): ?self
491 314
    {
492
        if (!$this->enableSlaves) {
493
            return $fallbackToMaster ? $this : null;
494
        }
495
496
        if ($this->slave === null) {
497
            $this->slave = $this->openFromPool($this->slaves);
498
        }
499
500
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
501
    }
502
503
    /**
504
     * Returns the PDO instance for the currently active slave connection.
505
     *
506 1799
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
507
     * returned by this method.
508 1799
     *
509 6
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
510
     *
511
     * @throws Exception
512 1798
     *
513 1798
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
514
     * is available and `$fallbackToMaster` is false.
515
     */
516 1798
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
517
    {
518
        $db = $this->getSlave(false);
519
520
        if ($db === null) {
521
            return $fallbackToMaster ? $this->getMasterPdo() : null;
522
        }
523
524
        return $db->getPdo();
525
    }
526
527
    public function getTablePrefix(): string
528
    {
529
        return $this->tablePrefix;
530
    }
531
532 1797
    /**
533
     * Obtains the schema information for the named table.
534 1797
     *
535
     * @param string $name table name.
536 1797
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
537 1792
     *
538
     * @return TableSchema
539
     */
540 6
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
541
    {
542
        return $this->getSchema()->getTableSchema($name, $refresh);
543 130
    }
544
545 130
    /**
546
     * Returns the currently active transaction.
547
     *
548
     * @return Transaction|null the currently active transaction. Null if no active transaction.
549
     */
550
    public function getTransaction(): ?Transaction
551
    {
552
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
553
    }
554
555
    public function getUsername(): ?string
556 196
    {
557
        return $this->username;
558 196
    }
559
560
    /**
561
     * Disables query cache temporarily.
562
     *
563
     * Queries performed within the callable will not use query cache at all. For example,
564
     *
565
     * ```php
566 1732
     * $db->cache(function (Connection $db) {
567
     *
568 1732
     *     // ... queries that use query cache ...
569
     *
570
     *     return $db->noCache(function (Connection $db) {
571 1977
     *         // this query will not use query cache
572
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
573 1977
     *     });
574
     * });
575
     * ```
576
     *
577
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
578
     * of the callable is `function (Connection $db)`.
579
     *
580
     * @throws Throwable if there is any exception during query
581
     *
582
     * @return mixed the return result of the callable
583
     *
584
     * {@see enableQueryCache}
585
     * {@see queryCache}
586
     * {@see cache()}
587
     */
588
    public function noCache(callable $callable)
589
    {
590
        $queryCache = $this->queryCache;
591
        $queryCache->setInfo(false);
592
        $result = $callable($this);
593
        $queryCache->removeLastInfo();
594
        return $result;
595
    }
596
597
    /**
598
     * Establishes a DB connection.
599
     *
600
     * It does nothing if a DB connection has already been established.
601
     *
602
     * @throws Exception|InvalidConfigException if connection fails
603
     */
604 10
    public function open(): void
605
    {
606 10
        if (!empty($this->pdo)) {
607
            return;
608 10
        }
609
610 10
        if (!empty($this->masters)) {
611
            $db = $this->getMaster();
612 10
613
            if ($db !== null) {
614 10
                $this->pdo = $db->getPDO();
615
616
                return;
617
            }
618
619
            throw new InvalidConfigException('None of the master DB servers is available.');
620
        }
621
622
        if (empty($this->dsn)) {
623
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
624 1853
        }
625
626 1853
        $token = 'Opening DB connection: ' . $this->dsn;
627 1685
628
        try {
629
            if ($this->logger !== null) {
630 1853
                $this->logger->log(LogLevel::INFO, $token);
631 11
            }
632
633 11
            if ($this->profiler !== null) {
634 8
                $this->profiler->begin($token, [__METHOD__]);
635
            }
636 8
637
            $this->pdo = $this->createPdoInstance();
638
639 10
            $this->initConnection();
640
641
            if ($this->profiler !== null) {
642 1853
                $this->profiler->end($token, [__METHOD__]);
643
            }
644
        } catch (PDOException $e) {
645
            if ($this->profiler !== null) {
646 1853
                $this->profiler->end($token, [__METHOD__]);
647
            }
648
649 1853
            if ($this->logger !== null) {
650 1853
                $this->logger->log(LogLevel::ERROR, $token);
651
            }
652
653 1853
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
654 1853
        }
655
    }
656
657 1853
    /**
658
     * Closes the currently active DB connection.
659 1853
     *
660
     * It does nothing if the connection is already closed.
661 1853
     */
662 1853
    public function close(): void
663
    {
664 15
        if ($this->master) {
665 15
            if ($this->pdo === $this->master->getPDO()) {
666 15
                $this->pdo = null;
667
            }
668
669 15
            $this->master->close();
670 15
671
            $this->master = null;
672
        }
673 15
674
        if ($this->pdo !== null) {
675 1853
            if ($this->logger !== null) {
676
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
677
            }
678
679
            $this->pdo = null;
680
            $this->transaction = null;
681
        }
682 2922
683
        if ($this->slave) {
684 2922
            $this->slave->close();
685 7
            $this->slave = null;
686 7
        }
687
    }
688
689 7
    /**
690
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
691 7
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
692
     * {@see logger->log()}.
693
     *
694 2922
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
695 1853
     * @param int $level Transaction level just after {@see beginTransaction()} call.
696 1843
     */
697
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
698
    {
699 1853
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
700 1853
            /**
701 1853
             * {@see https://github.com/yiisoft/yii2/pull/13347}
702
             */
703
            try {
704 2922
                $transaction->rollBack();
705 5
            } catch (Exception $e) {
706 5
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
0 ignored issues
show
Bug introduced by
The method log() 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

706
                $this->logger->/** @scrutinizer ignore-call */ 
707
                               log(LogLevel::ERROR, $e, [__METHOD__]);

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...
707
                /** hide this exception to be able to continue throwing original exception outside */
708 2922
            }
709
        }
710
    }
711
712
    /**
713
     * Opens the connection to a server in the pool.
714
     *
715
     * This method implements the load balancing among the given list of the servers.
716
     *
717
     * Connections will be tried in random order.
718 10
     *
719
     * @param array $pool the list of connection configurations in the server pool
720 10
     *
721
     * @return Connection|null the opened DB connection, or `null` if no server is available
722
     */
723
    protected function openFromPool(array $pool): ?self
724
    {
725 10
        shuffle($pool);
726
        return $this->openFromPoolSequentially($pool);
727
    }
728
729
    /**
730
     * Opens the connection to a server in the pool.
731 10
     *
732
     * This method implements the load balancing among the given list of the servers.
733
     *
734
     * Connections will be tried in sequential order.
735
     *
736
     * @param array $pool
737
     *
738
     * @return Connection|null the opened DB connection, or `null` if no server is available
739
     */
740
    protected function openFromPoolSequentially(array $pool): ?self
741
    {
742
        if (!$pool) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pool of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
743
            return null;
744 1803
        }
745
746 1803
        foreach ($pool as $poolConnetion) {
747
            $key = [__METHOD__, $poolConnetion->getDsn()];
748 1803
749
            if (
750
                $this->getSchema()->getSchemaCache()->isEnabled() &&
751
                $this->getSchema()->getSchemaCache()->getOrSet($key, null, $this->serverRetryInterval)
752
            ) {
753
                /** should not try this dead server now */
754
                continue;
755
            }
756
757
            try {
758
                $poolConnetion->open();
759
760
                return $poolConnetion;
761
            } catch (Exception $e) {
762 1808
                if ($this->logger !== null) {
763
                    $this->logger->log(
764 1808
                        LogLevel::WARNING,
765 1791
                        "Connection ({$poolConnetion->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
766
                    );
767
                }
768 18
769
                if ($this->getSchema()->getSchemaCache()->isEnabled()) {
770 18
                    /** mark this server as dead and only retry it after the specified interval */
771
                    $this->getSchema()->getSchemaCache()->set($key, 1, $this->serverRetryInterval);
772 18
                }
773
774
                return null;
775 18
            }
776 18
        }
777
778
        return null;
779
    }
780
781
    /**
782
     * Quotes a column name for use in a query.
783 18
     *
784
     * If the column name contains prefix, the prefix will also be properly quoted.
785 15
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
786 10
     * method will do nothing.
787 10
     *
788 10
     * @param string $name column name
789 10
     *
790 10
     * @return string the properly quoted column name
791
     */
792
    public function quoteColumnName(string $name): string
793
    {
794 10
        return $this->quotedColumnNames[$name]
795
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
796 5
    }
797
798
    /**
799 10
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
800
     *
801
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
802
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
803
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
804
     *
805
     * @param string $sql the SQL to be quoted
806
     *
807
     * @return string the quoted SQL
808
     */
809
    public function quoteSql(string $sql): string
810
    {
811
        return preg_replace_callback(
812
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
813
            function ($matches) {
814
                if (isset($matches[3])) {
815
                    return $this->quoteColumnName($matches[3]);
816
                }
817 1594
818
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
819 1594
            },
820 1594
            $sql
821
        );
822
    }
823
824
    /**
825
     * Quotes a table name for use in a query.
826
     *
827
     * If the table name contains schema prefix, the prefix will also be properly quoted.
828
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
829
     * will do nothing.
830
     *
831
     * @param string $name table name
832
     *
833
     * @return string the properly quoted table name
834 1842
     */
835
    public function quoteTableName(string $name): string
836 1842
    {
837 1842
        return $this->quotedTableNames[$name]
838 1842
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
839 689
    }
840 569
841
    /**
842
     * Quotes a string value for use in a query.
843 493
     *
844 1842
     * Note that if the parameter is not a string, it will be returned without change.
845
     *
846
     * @param int|string $value string to be quoted
847
     *
848
     * @throws Exception
849
     *
850
     * @return int|string the properly quoted string
851
     *
852
     * {@see http://php.net/manual/en/pdo.quote.php}
853
     */
854
    public function quoteValue($value)
855
    {
856
        return $this->getSchema()->quoteValue($value);
857
    }
858
859
    /**
860 1388
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
861
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
862 1388
     * attributes.
863 1388
     *
864
     * @param array $value
865
     */
866
    public function setAttributes(array $value): void
867
    {
868
        $this->attributes = $value;
869
    }
870
871
    /**
872
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
873
     * null, meaning using default charset as configured by the database.
874
     *
875
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
876
     * `;charset=UTF-8` to the DSN string.
877
     *
878
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
879 1370
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
880
     *
881 1370
     * @param string|null $value
882
     */
883
    public function setCharset(?string $value): void
884
    {
885
        $this->charset = $value;
886
    }
887
888
    /**
889
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
890
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
891
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
892
     * ATTR_EMULATE_PREPARES value will not be changed.
893
     *
894
     * @param bool $value
895
     */
896
    public function setEmulatePrepare(bool $value): void
897
    {
898
        $this->emulatePrepare = $value;
899
    }
900
901
    /**
902
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
903
     * support savepoint, setting this property to be true will have no effect.
904
     *
905
     * @param bool $value
906
     */
907
    public function setEnableSavepoint(bool $value): void
908 885
    {
909
        $this->enableSavepoint = $value;
910 885
    }
911 885
912
    /**
913
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
914
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
915
     *
916
     * @param bool $value
917
     */
918
    public function setEnableSlaves(bool $value): void
919
    {
920 10
        $this->enableSlaves = $value;
921
    }
922 10
923 10
    /**
924
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
925
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
926
     *
927
     * @param string $key index master connection.
928
     * @param ConnectionInterface $db The connection every master.
929
     */
930
    public function setMasters(string $key, ConnectionInterface $master): void
931
    {
932
        $this->masters[$key] = $master;
933 7
    }
934
935 7
    /**
936 7
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
937
     *
938
     * @param string|null $value
939
     */
940
    public function setPassword(?string $value): void
941
    {
942
        $this->password = $value;
943
    }
944 10
945
    /**
946 10
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
947 10
     *
948
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
949
     */
950
    public function setQueryBuilder(iterable $config): void
951
    {
952
        $builder = $this->getQueryBuilder();
953
954
        foreach ($config as $key => $value) {
955 5
            $builder->{$key} = $value;
956
        }
957 5
    }
958 5
959
    /**
960
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
961
     *
962
     * @param int $value
963
     */
964
    public function setServerRetryInterval(int $value): void
965
    {
966
        $this->serverRetryInterval = $value;
967
    }
968
969
    /**
970
     * Whether to shuffle {@see setMasters()} before getting one.
971
     *
972
     * @param bool $value
973
     */
974
    public function setShuffleMasters(bool $value): void
975
    {
976
        $this->shuffleMasters = $value;
977
    }
978 14
979
    /**
980 14
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
981 14
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
982
     *
983
     * @param string $key index slave connection.
984
     * @param ConnectionInterface $slave The connection every slave.
985
     */
986
    public function setSlaves(string $key, ConnectionInterface $slave): void
987
    {
988 2631
        $this->slaves[$key] = $slave;
989
    }
990 2631
991 2631
    /**
992
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
993
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
994
     *
995
     * @param string $value
996
     */
997
    public function setTablePrefix(string $value): void
998
    {
999
        $this->tablePrefix = $value;
1000
    }
1001
1002
    /**
1003
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1004
     *
1005
     * @param string|null $value
1006
     */
1007
    public function setUsername(?string $value): void
1008
    {
1009
        $this->username = $value;
1010
    }
1011
1012
    /**
1013
     * Executes callback provided in a transaction.
1014
     *
1015
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1016
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1017
     * for details.
1018
     *
1019
     * @return mixed result of callback function
1020
     *@throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1021
     *
1022 12
     */
1023
    public function transaction(callable $callback, string $isolationLevel = null)
1024 12
    {
1025 12
        $transaction = $this->beginTransaction($isolationLevel);
1026
1027
        $level = $transaction->getLevel();
1028
1029
        try {
1030
            $result = $callback($this);
1031
1032
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1033
                $transaction->commit();
1034 9
            }
1035
        } catch (Throwable $e) {
1036 9
            $this->rollbackTransactionOnLevel($transaction, $level);
1037 9
1038
            throw $e;
1039
        }
1040
1041
        return $result;
1042
    }
1043
1044
    /**
1045 24
     * Executes the provided callback by using the master connection.
1046
     *
1047 24
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1048 24
     * even if they are read queries. For example,
1049
     *
1050
     * ```php
1051
     * $result = $db->useMaster(function ($db) {
1052
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1053
     * });
1054
     * ```
1055 2631
     *
1056
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1057 2631
     * `function (Connection $db)`. Its return value will be returned by this method.
1058 2631
     *
1059
     * @throws Throwable if there is any exception thrown from the callback
1060
     *
1061
     * @return mixed the return value of the callback
1062
     */
1063
    public function useMaster(callable $callback)
1064
    {
1065
        if ($this->enableSlaves) {
1066
            $this->enableSlaves = false;
1067
1068
            try {
1069
                $result = $callback($this);
1070
            } catch (Throwable $e) {
1071 25
                $this->enableSlaves = true;
1072
1073 25
                throw $e;
1074
            }
1075 25
            $this->enableSlaves = true;
1076
        } else {
1077
            $result = $callback($this);
1078 25
        }
1079
1080 15
        return $result;
1081 15
    }
1082
}
1083