Passed
Pull Request — master (#197)
by Wilmer
13:46
created

Connection::setEnableQueryCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\LoggerInterface;
10
use Psr\Log\LogLevel;
11
use Throwable;
12
use Yiisoft\Cache\Dependency\Dependency;
13
use Yiisoft\Db\Cache\ConnectionCache;
14
use Yiisoft\Db\Command\Command;
15
use Yiisoft\Db\Exception\Exception;
16
use Yiisoft\Db\Exception\InvalidCallException;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Exception\NotSupportedException;
19
use Yiisoft\Db\Factory\DatabaseFactory;
20
use Yiisoft\Db\Query\QueryBuilder;
21
use Yiisoft\Db\Schema\Schema;
22
use Yiisoft\Db\Schema\TableSchema;
23
use Yiisoft\Db\Transaction\Transaction;
24
use Yiisoft\Profiler\Profiler;
25
26
use function array_keys;
27
use function str_replace;
28
use function strncmp;
29
30
/**
31
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
32
 *
33
 * Connection works together with {@see Command}, {@see DataReader} and {@see Transaction} to provide data access to
34
 * various DBMS in a common set of APIs. They are a thin wrapper of the
35
 * [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
36
 *
37
 * Connection supports database replication and read-write splitting. In particular, a Connection component can be
38
 * configured with multiple {@see setMasters()} and {@see setSlaves()}. It will do load balancing and failover by
39
 * choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations
40
 * to the masters.
41
 *
42
 * To establish a DB connection, set {@see dsn}, {@see setUsername()} and {@see setPassword}, and then call
43
 * {@see open()} to connect to the database server. The current state of the connection can be checked using
44
 * {@see $isActive}.
45
 *
46
 * The following example shows how to create a Connection instance and establish the DB connection:
47
 *
48
 * ```php
49
 * $connection = new \Yiisoft\Db\Mysql\Connection(
50
 *     $cache,
51
 *     $logger,
52
 *     $profiler,
53
 *     $dsn
54
 * );
55
 * $connection->open();
56
 * ```
57
 *
58
 * After the DB connection is established, one can execute SQL statements like the following:
59
 *
60
 * ```php
61
 * $command = $connection->createCommand('SELECT * FROM post');
62
 * $posts = $command->queryAll();
63
 * $command = $connection->createCommand('UPDATE post SET status=1');
64
 * $command->execute();
65
 * ```
66
 *
67
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
68
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
69
 * following is an example:
70
 *
71
 * ```php
72
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
73
 * $command->bindValue(':id', $_GET['id']);
74
 * $post = $command->query();
75
 * ```
76
 *
77
 * For more information about how to perform various DB queries, please refer to {@see Command}.
78
 *
79
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
80
 *
81
 * ```php
82
 * $transaction = $connection->beginTransaction();
83
 * try {
84
 *     $connection->createCommand($sql1)->execute();
85
 *     $connection->createCommand($sql2)->execute();
86
 *     // ... executing other SQL statements ...
87
 *     $transaction->commit();
88
 * } catch (Exceptions $e) {
89
 *     $transaction->rollBack();
90
 * }
91
 * ```
92
 *
93
 * You also can use shortcut for the above like the following:
94
 *
95
 * ```php
96
 * $connection->transaction(function () {
97
 *     $order = new Order($customer);
98
 *     $order->save();
99
 *     $order->addItems($items);
100
 * });
101
 * ```
102
 *
103
 * If needed you can pass transaction isolation level as a second parameter:
104
 *
105
 * ```php
106
 * $connection->transaction(function (Connection $db) {
107
 *     //return $db->...
108
 * }, Transaction::READ_UNCOMMITTED);
109
 * ```
110
 *
111
 * Connection is often used as an application component and configured in the container-di configuration like the
112
 * following:
113
 *
114
 * ```php
115
 * Connection::class => static function (ContainerInterface $container) {
116
 *     $connection = new Connection(
117
 *         $container->get(CacheInterface::class),
118
 *         $container->get(LoggerInterface::class),
119
 *         $container->get(Profiler::class),
120
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
121
 *     );
122
 *
123
 *     $connection->setUsername(root);
124
 *     $connection->setPassword('');
125
 *
126
 *     return $connection;
127
 * },
128
 * ```
129
 *
130
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Connection\Dsn}:
131
 *
132
 * ```php
133
 * Connection::class => static function (ContainerInterface $container) {
134
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
135
 *
136
 *     $connection = new Connection(
137
 *         $container->get(CacheInterface::class),
138
 *         $container->get(LoggerInterface::class),
139
 *         $container->get(Profiler::class),
140
 *         $dsn->getDsn()
141
 *     );
142
 *
143
 *     $connection->setUsername(root);
144
 *     $connection->setPassword('');
145
 *
146
 *     return $connection;
147
 * },
148
 * ```
149
 *
150
 * @property string $driverName Name of the DB driver.
151
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
152
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
153
 * object. This property is read-only.
154
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
155
 * available. This property is read-only.
156
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
157
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
158
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
159
 * @property Schema $schema The schema information for the database opened by this connection. This property is
160
 * read-only.
161
 * @property string $serverVersion Server version as a string. This property is read-only.
162
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
163
 * available and `$fallbackToMaster` is false. This property is read-only.
164
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
165
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
166
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
167
 * property is read-only.
168
 */
169
abstract class Connection implements ConnectionInterface
170
{
171
    private string $dsn;
172
    private ?string $username = null;
173
    private ?string $password = null;
174
    private array $attributes = [];
175
    private ?PDO $pdo = null;
176
    private ?string $charset = null;
177
    private ?bool $emulatePrepare = null;
178
    private string $tablePrefix = '';
179
    private bool $enableSavepoint = true;
180
    private int $serverRetryInterval = 600;
181
    private bool $enableSlaves = true;
182
    private array $slaves = [];
183
    private array $masters = [];
184
    private bool $shuffleMasters = true;
185
    private bool $enableLogging = true;
186
    private array $quotedTableNames = [];
187
    private array $quotedColumnNames = [];
188
    private ?Connection $master = null;
189
    private ?Connection $slave = null;
190
    private LoggerInterface $logger;
191
    private ?Transaction $transaction = null;
192
    private ?Schema $schema = null;
193
    private Profiler $profiler;
194
    private bool $enableProfiling = true;
195
    private ConnectionCache $connectionCache;
196
197
    public function __construct(
198
        ConnectionCache $connectionCache,
199
        LoggerInterface $logger,
200
        Profiler $profiler,
201
        string $dsn
202
    ) {
203
        $this->connectionCache = $connectionCache;
204 2436
        $this->logger = $logger;
205
        $this->profiler = $profiler;
206 2436
        $this->dsn = $dsn;
207 2436
    }
208 2436
209 2436
    /**
210 2436
     * Creates a command for execution.
211
     *
212
     * @param string|null $sql the SQL statement to be executed
213
     * @param array $params the parameters to be bound to the SQL statement
214
     *
215
     * @throws Exception|InvalidConfigException
216
     *
217
     * @return Command the DB command
218
     */
219
    abstract public function createCommand(?string $sql = null, array $params = []): Command;
220
221
    /**
222
     * Returns the schema information for the database opened by this connection.
223
     *
224
     * @return Schema the schema information for the database opened by this connection.
225
     */
226
    abstract public function getSchema(): Schema;
227
228
    /**
229
     * Creates the PDO instance.
230
     *
231
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
232
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
233
     *
234
     * @return PDO the pdo instance
235
     */
236
    abstract protected function createPdoInstance(): PDO;
237
238
    /**
239
     * Initializes the DB connection.
240
     *
241
     * This method is invoked right after the DB connection is established.
242
     *
243
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
244
     *
245
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
246
     *
247
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
248
     */
249
    abstract protected function initConnection(): void;
250
251
    /**
252
     * Reset the connection after cloning.
253
     */
254
    public function __clone()
255
    {
256
        $this->master = null;
257 9
        $this->slave = null;
258
        $this->schema = null;
259 9
        $this->transaction = null;
260 9
261 9
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
262 9
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
263
            $this->pdo = null;
264 9
        }
265
    }
266 9
267
    /**
268 9
     * Close the connection before serializing.
269
     *
270
     * @return array
271
     */
272
    public function __sleep(): array
273
    {
274
        $fields = (array) $this;
275 5
276
        unset(
277 5
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
278
            $fields["\000" . __CLASS__ . "\000" . 'master'],
279
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
280 5
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
281 5
            $fields["\000" . __CLASS__ . "\000" . 'schema']
282 5
        );
283 5
284 5
        return array_keys($fields);
285
    }
286
287 5
    /**
288
     * Starts a transaction.
289
     *
290
     * @param string|null $isolationLevel The isolation level to use for this transaction.
291
     *
292
     * {@see Transaction::begin()} for details.
293
     *
294
     * @throws Exception|InvalidConfigException|NotSupportedException
295
     *
296
     * @return Transaction the transaction initiated
297
     */
298
    public function beginTransaction($isolationLevel = null): Transaction
299
    {
300
        $this->open();
301 32
302
        if (($transaction = $this->getTransaction()) === null) {
303 32
            $transaction = $this->transaction = new Transaction($this, $this->logger);
304
        }
305 32
306 32
        $transaction->begin($isolationLevel);
307
308
        return $transaction;
309 32
    }
310
311 32
    /**
312
     * Uses query cache for the queries performed with the callable.
313
     *
314
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
315
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
316
     *
317
     * For example,
318
     *
319
     * ```php
320
     * // The customer will be fetched from cache if available.
321
     * // If not, the query will be made against DB and cached for use next time.
322
     * $customer = $db->cache(function (Connection $db) {
323
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
324
     * });
325
     * ```
326
     *
327
     * Note that query cache is only meaningful for queries that return results. For queries performed with
328
     * {@see Command::execute()}, query cache will not be used.
329
     *
330
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
331
     * The signature of the callable is `function (Connection $db)`.
332
     * @param int|null $duration the number of seconds that query results can remain valid in the cache. If this is not
333
     * set, the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will
334
     * never expire.
335
     * @param Dependency|null $dependency the cache dependency associated with the cached query
336
     * results.
337
     *
338
     * @throws Throwable if there is any exception during query
339
     *
340
     * @return mixed the return result of the callable
341
     *
342
     * {@see setEnableQueryCache()}
343
     * {@see queryCache}
344
     * {@see noCache()}
345
     */
346
    public function cache(callable $callable, int $duration = null, Dependency $dependency = null)
347
    {
348
        $this->connectionCache->setQueryCacheInfo(
349 8
            [$duration ?? $this->connectionCache->getQueryCacheDuration(), $dependency]
350
        );
351 8
352
        try {
353
            $result = $callable($this);
354 8
355
            $this->connectionCache->queryCacheInfoArrayPop();
356 8
357
            return $result;
358 8
        } catch (Throwable $e) {
359
            $this->connectionCache->queryCacheInfoArrayPop();
360
361
            throw $e;
362
        }
363
    }
364
365
    public function getAttributes(): array
366 1457
    {
367
        return $this->attributes;
368 1457
    }
369
370
    public function getCharset(): ?string
371 731
    {
372
        return $this->charset;
373 731
    }
374
375
    public function getConnectionCache(): ConnectionCache
376 1477
    {
377
        return $this->connectionCache;
378 1477
    }
379
380
    public function getDsn(): string
381 1089
    {
382
        return $this->dsn;
383 1089
    }
384
385
    public function getEmulatePrepare(): ?bool
386 1374
    {
387
        return $this->emulatePrepare;
388 1374
    }
389
390
    public function isLoggingEnabled(): bool
391 1374
    {
392
        return $this->enableLogging;
393 1374
    }
394
395
    public function isProfilingEnabled(): bool
396
    {
397
        return $this->enableProfiling;
398
    }
399
400
    public function isSavepointEnabled(): bool
401 8
    {
402
        return $this->enableSavepoint;
403 8
    }
404
405
    public function areSlavesEnabled(): bool
406 1286
    {
407
        return $this->enableSlaves;
408 1286
    }
409
410
    /**
411 1
     * Returns a value indicating whether the DB connection is established.
412
     *
413 1
     * @return bool whether the DB connection is established
414
     */
415
    public function isActive(): bool
416
    {
417
        return $this->pdo !== null;
418
    }
419
420
    /**
421 158
     * Returns the ID of the last inserted row or sequence value.
422
     *
423 158
     * @param string $sequenceName name of the sequence object (required by some DBMS)
424
     *
425
     * @throws Exception
426
     * @throws InvalidCallException
427
     *
428
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
429
     *
430
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
431
     */
432
    public function getLastInsertID($sequenceName = ''): string
433
    {
434
        return $this->getSchema()->getLastInsertID($sequenceName);
435
    }
436
437
    public function getLogger(): LoggerInterface
438 8
    {
439
        return $this->logger;
440 8
    }
441
442
    /**
443 1417
     * Returns the currently active master connection.
444
     *
445 1417
     * If this method is called for the first time, it will try to open a master connection.
446
     *
447
     * @throws InvalidConfigException
448
     *
449
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
450
     */
451
    public function getMaster(): ?Connection
452
    {
453
        if ($this->master === null) {
454
            $this->master = $this->shuffleMasters
455
                ? $this->openFromPool($this->masters)
456
                : $this->openFromPoolSequentially($this->masters);
457 11
        }
458
459 11
        return $this->master;
460 11
    }
461 6
462 9
    /**
463
     * Returns the PDO instance for the currently active master connection.
464
     *
465 11
     * This method will open the master DB connection and then return {@see pdo}.
466
     *
467
     * @throws Exception
468
     *
469
     * @return PDO the PDO instance for the currently active master connection.
470
     */
471
    public function getMasterPdo(): PDO
472
    {
473
        $this->open();
474
475
        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...
476
    }
477 1429
478
    public function getPassword(): ?string
479 1429
    {
480
        return $this->password;
481 1429
    }
482
483
    /**
484 1457
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
485
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
486 1457
     * it will be null.
487
     *
488
     * @return PDO|null
489
     *
490
     * {@see pdoClass}
491
     */
492
    public function getPDO(): ?PDO
493
    {
494
        return $this->pdo;
495
    }
496
497
    /**
498 1457
     * Returns the query builder for the current DB connection.
499
     *
500 1457
     * @return QueryBuilder the query builder for the current DB connection.
501
     */
502
    public function getQueryBuilder(): QueryBuilder
503 1417
    {
504
        return $this->getSchema()->getQueryBuilder();
505 1417
    }
506
507
    public function getProfiler(): Profiler
508
    {
509
        return $this->profiler;
510
    }
511
512
    /**
513 759
     * Returns a server version as a string comparable by {@see \version_compare()}.
514
     *
515 759
     * @return string server version as a string.
516
     */
517
    public function getServerVersion(): string
518 8
    {
519
        return $this->getSchema()->getServerVersion();
520 8
    }
521
522
    /**
523
     * Returns the currently active slave connection.
524
     *
525
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
526
     * is true.
527
     *
528
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
529
     * available.
530
     *
531
     * @throws InvalidConfigException
532
     *
533
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
534 1346
     * `$fallbackToMaster` is false.
535
     */
536 1346
    public function getSlave(bool $fallbackToMaster = true): ?Connection
537
    {
538 1346
        if (!$this->enableSlaves) {
539 1346
            return $fallbackToMaster ? $this : null;
540
        }
541 1346
542 8
        if ($this->slave === null) {
543 8
            $this->slave = $this->openFromPool($this->slaves);
544
        }
545
546 8
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
547 8
    }
548
549
    /**
550
     * Returns the PDO instance for the currently active slave connection.
551 1346
     *
552 8
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
553 8
     * returned by this method.
554
     *
555
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
556
     *
557
     * @throws Exception|InvalidConfigException
558 1346
     *
559
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
560
     * is available and `$fallbackToMaster` is false.
561 2010
     */
562
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
563 2010
    {
564
        $db = $this->getSlave(false);
565
566 1238
        if ($db === null) {
567
            return $fallbackToMaster ? $this->getMasterPdo() : null;
568 1238
        }
569
570
        return $db->getPdo();
571 1286
    }
572
573 1286
    public function getTablePrefix(): string
574
    {
575
        return $this->tablePrefix;
576
    }
577
578
    /**
579
     * Obtains the schema information for the named table.
580
     *
581 308
     * @param string $name table name.
582
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
583 308
     *
584
     * @return TableSchema
585
     */
586
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
587
    {
588
        return $this->getSchema()->getTableSchema($name, $refresh);
589
    }
590
591
    /**
592
     * Returns the currently active transaction.
593
     *
594
     * @return Transaction|null the currently active transaction. Null if no active transaction.
595
     */
596
    public function getTransaction(): ?Transaction
597
    {
598
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
599
    }
600 1415
601
    public function getUsername(): ?string
602 1415
    {
603 2
        return $this->username;
604
    }
605
606 1415
    /**
607 1415
     * Disables query cache temporarily.
608
     *
609
     * Queries performed within the callable will not use query cache at all. For example,
610 1415
     *
611
     * ```php
612
     * $db->cache(function (Connection $db) {
613
     *
614
     *     // ... queries that use query cache ...
615
     *
616
     *     return $db->noCache(function (Connection $db) {
617
     *         // this query will not use query cache
618
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
619
     *     });
620
     * });
621
     * ```
622
     *
623
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
624
     * of the callable is `function (Connection $db)`.
625
     *
626 1413
     * @throws Throwable if there is any exception during query
627
     *
628 1413
     * @return mixed the return result of the callable
629
     *
630 1413
     * {@see enableQueryCache}
631 1409
     * {@see queryCache}
632
     * {@see cache()}
633
     */
634 5
    public function noCache(callable $callable)
635
    {
636
        $this->connectionCache->setQueryCacheInfo(false);
637 107
638
        try {
639 107
            $result = $callable($this);
640
641
            $this->connectionCache->queryCacheInfoArrayPop();
642
643
            return $result;
644
        } catch (Throwable $e) {
645
            $this->connectionCache->queryCacheInfoArrayPop();
646
647
            throw $e;
648
        }
649
    }
650 164
651
    /**
652 164
     * Establishes a DB connection.
653
     *
654
     * It does nothing if a DB connection has already been established.
655
     *
656
     * @throws Exception|InvalidConfigException if connection fails
657
     */
658
    public function open(): void
659
    {
660 1386
        if (!empty($this->pdo)) {
661
            return;
662 1386
        }
663
664
        if (!empty($this->masters)) {
665 1473
            $db = $this->getMaster();
666
667 1473
            if ($db !== null) {
668
                $this->pdo = $db->getPDO();
669
670
                return;
671
            }
672
673
            throw new InvalidConfigException('None of the master DB servers is available.');
674
        }
675
676
        if (empty($this->dsn)) {
677
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
678
        }
679
680
        $token = 'Opening DB connection: ' . $this->dsn;
681
682
        try {
683
            if ($this->enableLogging) {
684
                $this->logger->log(LogLevel::INFO, $token);
685
            }
686
687
            if ($this->isProfilingEnabled()) {
688
                $this->profiler->begin($token, [__METHOD__]);
689
            }
690
691
            $this->pdo = $this->createPdoInstance();
692
693
            $this->initConnection();
694
695
            if ($this->isProfilingEnabled()) {
696
                $this->profiler->end($token, [__METHOD__]);
697
            }
698 8
        } catch (PDOException $e) {
699
            if ($this->isProfilingEnabled()) {
700 8
                $this->profiler->end($token, [__METHOD__]);
701
            }
702
703 8
            if ($this->enableLogging) {
704 8
                $this->logger->log(LogLevel::ERROR, $token);
705
            }
706 8
707
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
708
        }
709
    }
710
711
    /**
712
     * Closes the currently active DB connection.
713
     *
714
     * It does nothing if the connection is already closed.
715
     */
716
    public function close(): void
717
    {
718
        if ($this->master) {
719
            if ($this->pdo === $this->master->getPDO()) {
720
                $this->pdo = null;
721 1457
            }
722
723 1457
            $this->master->close();
724 1339
725
            $this->master = null;
726
        }
727 1457
728 9
        if ($this->pdo !== null) {
729
            if ($this->enableLogging) {
730 9
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
731 9
            }
732
733 9
            $this->pdo = null;
734
            $this->schema = null;
735
            $this->transaction = null;
736 8
        }
737
738
        if ($this->slave) {
739 1457
            $this->slave->close();
740
            $this->slave = null;
741
        }
742
    }
743 1457
744
    /**
745
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
746 1457
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
747 1457
     * {@see logger->log()}.
748
     *
749
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
750 1457
     * @param int $level Transaction level just after {@see beginTransaction()} call.
751 1457
     *
752
     * @return void
753
     */
754 1457
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
755
    {
756 1457
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
757
            /**
758 1457
             * {@see https://github.com/yiisoft/yii2/pull/13347}
759 1457
             */
760
            try {
761 12
                $transaction->rollBack();
762 12
            } catch (Exception $e) {
763 12
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
764
                /** hide this exception to be able to continue throwing original exception outside */
765
            }
766 12
        }
767 12
    }
768
769
    /**
770 12
     * Opens the connection to a server in the pool.
771
     *
772 1457
     * This method implements the load balancing among the given list of the servers.
773
     *
774
     * Connections will be tried in random order.
775
     *
776
     * @param array $pool the list of connection configurations in the server pool
777
     *
778
     * @return Connection|null the opened DB connection, or `null` if no server is available
779 2342
     */
780
    protected function openFromPool(array $pool): ?Connection
781 2342
    {
782 8
        shuffle($pool);
783 8
784
        return $this->openFromPoolSequentially($pool);
785
    }
786 8
787
    /**
788 8
     * Opens the connection to a server in the pool.
789
     *
790
     * This method implements the load balancing among the given list of the servers.
791 2342
     *
792 1457
     * Connections will be tried in sequential order.
793 1449
     *
794
     * @param array $pool
795
     *
796 1457
     * @return Connection|null the opened DB connection, or `null` if no server is available
797 1457
     */
798 1457
    protected function openFromPoolSequentially(array $pool): ?Connection
799
    {
800
        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...
801 2342
            return null;
802 4
        }
803 4
804
        foreach ($pool as $config) {
805 2342
            /* @var $db Connection */
806
            $db = DatabaseFactory::createClass($config);
807
808
            $key = $this->connectionCache->normalize([__METHOD__, $db->getDsn()]);
809
810
            if ($this->connectionCache->isSchemaCacheEnabled() && $this->connectionCache->getSchemaCache()->get($key)) {
811
                /** should not try this dead server now */
812
                continue;
813
            }
814
815
            try {
816
                $db->open();
817 4
818
                return $db;
819 4
            } catch (Exception $e) {
820
                if ($this->enableLogging) {
821
                    $this->logger->log(
822
                        LogLevel::WARNING,
823
                        "Connection ({$db->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
824 4
                    );
825
                }
826
827
                if ($this->connectionCache->isSchemaCacheEnabled()) {
828
                    /** mark this server as dead and only retry it after the specified interval */
829
                    $this->connectionCache->getSchemaCache()->set($key, 1, $this->serverRetryInterval);
830 4
                }
831
832
                return null;
833
            }
834
        }
835
836
        return null;
837
    }
838
839
    /**
840
     * Quotes a column name for use in a query.
841
     *
842
     * If the column name contains prefix, the prefix will also be properly quoted.
843 1419
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
844
     * method will do nothing.
845 1419
     *
846
     * @param string $name column name
847 1419
     *
848
     * @return string the properly quoted column name
849
     */
850
    public function quoteColumnName(string $name): string
851
    {
852
        return $this->quotedColumnNames[$name]
853
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
854
    }
855
856
    /**
857
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
858
     *
859
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
860
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
861 1423
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
862
     *
863 1423
     * @param string $sql the SQL to be quoted
864 1409
     *
865
     * @return string the quoted SQL
866
     */
867 15
    public function quoteSql(string $sql): string
868
    {
869 15
        return preg_replace_callback(
870
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
871 15
            function ($matches) {
872
                if (isset($matches[3])) {
873 15
                    return $this->quoteColumnName($matches[3]);
874
                }
875
876
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
877
            },
878
            $sql
879 15
        );
880
    }
881 15
882 8
    /**
883 8
     * Quotes a table name for use in a query.
884 8
     *
885 8
     * If the table name contains schema prefix, the prefix will also be properly quoted.
886 8
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
887
     * will do nothing.
888
     *
889
     * @param string $name table name
890 8
     *
891
     * @return string the properly quoted table name
892 4
     */
893
    public function quoteTableName(string $name): string
894
    {
895 8
        return $this->quotedTableNames[$name]
896
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
897
    }
898
899
    /**
900
     * Quotes a string value for use in a query.
901
     *
902
     * Note that if the parameter is not a string, it will be returned without change.
903
     *
904
     * @param string|int $value string to be quoted
905
     *
906
     * @return string|int the properly quoted string
907
     *
908
     * {@see http://php.net/manual/en/pdo.quote.php}
909
     */
910
    public function quoteValue($value)
911
    {
912
        return $this->getSchema()->quoteValue($value);
913 1274
    }
914
915 1274
    /**
916 1274
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
917
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
918
     * attributes.
919
     *
920
     * @param array $value
921
     *
922
     * @return void
923
     */
924
    public function setAttributes(array $value): void
925
    {
926
        $this->attributes = $value;
927
    }
928
929
    /**
930 1471
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
931
     * null, meaning using default charset as configured by the database.
932 1471
     *
933 1471
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
934 1471
     * `;charset=UTF-8` to the DSN string.
935 512
     *
936 415
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
937
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
938
     *
939 376
     * @param string|null $value
940 1471
     *
941
     * @return void
942
     */
943
    public function setCharset(?string $value): void
944
    {
945
        $this->charset = $value;
946
    }
947
948
    /**
949
     * Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want
950
     * to disable this option in a production environment to gain performance if you do not need the information being
951
     * logged.
952
     *
953
     * @param bool $value
954
     *
955
     * @return void
956 1098
     *
957
     * {@see setEnableLogging()}
958 1098
     */
959 1098
    public function setEnableProfiling(bool $value): void
960
    {
961
        $this->enableProfiling = $value;
962
    }
963
964
    /**
965
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
966
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
967
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
968
     * ATTR_EMULATE_PREPARES value will not be changed.
969
     *
970
     * @param bool $value
971
     *
972
     * @return void
973 1021
     */
974
    public function setEmulatePrepare(bool $value): void
975 1021
    {
976
        $this->emulatePrepare = $value;
977
    }
978
979
    /**
980
     * Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a
981
     * production environment to gain performance if you do not need the information being logged.
982
     *
983
     * @param bool $value
984
     *
985
     * @return void
986
     *
987
     * {@see setEnableProfiling()}
988
     */
989
    public function setEnableLogging(bool $value): void
990
    {
991
        $this->enableLogging = $value;
992
    }
993
994
    /**
995
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
996
     * support savepoint, setting this property to be true will have no effect.
997
     *
998
     * @param bool $value
999
     *
1000
     * @return void
1001
     */
1002
    public function setEnableSavepoint(bool $value): void
1003
    {
1004
        $this->enableSavepoint = $value;
1005
    }
1006 1
1007
    /**
1008 1
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
1009 1
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
1010
     *
1011
     * @param bool $value
1012
     *
1013
     * @return void
1014
     */
1015
    public function setEnableSlaves(bool $value): void
1016
    {
1017
        $this->enableSlaves = $value;
1018
    }
1019
1020
    /**
1021
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
1022
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
1023
     *
1024
     * @param string $key index master connection.
1025
     * @param array $config The configuration that should be merged with every master configuration
1026
     *
1027
     * @return void
1028
     *
1029
     * For example,
1030
     *
1031 4
     * ```php
1032
     * $connection->setMasters(
1033 4
     *     '1',
1034 4
     *     [
1035
     *         '__construct()' => ['mysql:host=127.0.0.1;dbname=yiitest;port=3306'],
1036
     *         'setUsername()' => [$connection->getUsername()],
1037
     *         'setPassword()' => [$connection->getPassword()],
1038
     *     ]
1039
     * );
1040
     * ```
1041
     *
1042
     * {@see setShuffleMasters()}
1043
     */
1044
    public function setMasters(string $key, array $config = []): void
1045
    {
1046 8
        $this->masters[$key] = $config;
1047
    }
1048 8
1049 8
    /**
1050
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
1051
     *
1052
     * @param string|null $value
1053
     *
1054
     * @return void
1055
     */
1056
    public function setPassword(?string $value): void
1057
    {
1058
        $this->password = $value;
1059
    }
1060
1061
    /**
1062 8
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
1063
     *
1064 8
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
1065 8
     *
1066
     * @return void
1067
     */
1068
    public function setQueryBuilder(iterable $config): void
1069
    {
1070
        $builder = $this->getQueryBuilder();
1071
1072
        foreach ($config as $key => $value) {
1073
            $builder->{$key} = $value;
1074
        }
1075
    }
1076
1077
    /**
1078
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
1079
     *
1080 8
     * @param int $value
1081
     *
1082 8
     * @return void
1083 8
     */
1084
    public function setServerRetryInterval(int $value): void
1085
    {
1086
        $this->serverRetryInterval = $value;
1087
    }
1088
1089
    /**
1090
     * Whether to shuffle {@see setMasters()} before getting one.
1091
     *
1092
     * @param bool $value
1093 4
     *
1094
     * @return void
1095 4
     *
1096 4
     * {@see setMasters()}
1097
     */
1098
    public function setShuffleMasters(bool $value): void
1099
    {
1100
        $this->shuffleMasters = $value;
1101
    }
1102
1103
    /**
1104
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
1105
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
1106
     *
1107
     * @param string $key index slave connection.
1108
     * @param array $config The configuration that should be merged with every slave configuration
1109
     *
1110 32
     * @return void
1111
     *
1112 32
     * For example,
1113 32
     *
1114
     * ```php
1115
     * $connection->setSlaves(
1116
     *     '1',
1117
     *     [
1118
     *         '__construct()' => ['mysql:host=127.0.0.1;dbname=yiitest;port=3306'],
1119
     *         'setUsername()' => [$connection->getUsername()],
1120
     *         'setPassword()' => [$connection->getPassword()]
1121
     *     ]
1122
     * );
1123
     * ```
1124
     *
1125
     * {@see setEnableSlaves()}
1126
     */
1127
    public function setSlaves(string $key, array $config = []): void
1128
    {
1129
        $this->slaves[$key] = $config;
1130
    }
1131
1132
    /**
1133
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1134
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1135
     *
1136
     * @param string $value
1137
     *
1138
     * @return void
1139
     */
1140
    public function setTablePrefix(string $value): void
1141
    {
1142
        $this->tablePrefix = $value;
1143
    }
1144
1145
    /**
1146
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1147
     *
1148
     * @param string|null $value
1149
     *
1150
     * @return void
1151
     */
1152 12
    public function setUsername(?string $value): void
1153
    {
1154 12
        $this->username = $value;
1155 12
    }
1156
1157
    /**
1158
     * Executes callback provided in a transaction.
1159
     *
1160
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1161
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1162
     * for details.
1163
     *
1164 2051
     * @throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1165
     *
1166 2051
     * @return mixed result of callback function
1167 2051
     */
1168
    public function transaction(callable $callback, $isolationLevel = null)
1169
    {
1170
        $transaction = $this->beginTransaction($isolationLevel);
1171
1172
        $level = $transaction->getLevel();
1173
1174
        try {
1175
            $result = $callback($this);
1176
1177
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1178
                $transaction->commit();
1179
            }
1180
        } catch (Throwable $e) {
1181
            $this->rollbackTransactionOnLevel($transaction, $level);
1182
1183
            throw $e;
1184
        }
1185
1186
        return $result;
1187
    }
1188
1189
    /**
1190
     * Executes the provided callback by using the master connection.
1191
     *
1192
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1193
     * even if they are read queries. For example,
1194 8
     *
1195
     * ```php
1196 8
     * $result = $db->useMaster(function ($db) {
1197 8
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1198
     * });
1199
     * ```
1200
     *
1201
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1202
     * `function (Connection $db)`. Its return value will be returned by this method.
1203
     *
1204
     * @throws Throwable if there is any exception thrown from the callback
1205
     *
1206
     * @return mixed the return value of the callback
1207
     */
1208
    public function useMaster(callable $callback)
1209
    {
1210
        if ($this->enableSlaves) {
1211
            $this->enableSlaves = false;
1212
1213
            try {
1214
                $result = $callback($this);
1215
            } catch (Throwable $e) {
1216
                $this->enableSlaves = true;
1217
1218
                throw $e;
1219
            }
1220
            $this->enableSlaves = true;
1221
        } else {
1222
            $result = $callback($this);
1223
        }
1224
1225 36
        return $result;
1226
    }
1227
}
1228