Passed
Pull Request — master (#197)
by Wilmer
16:15
created

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