Passed
Push — master ( 14175d...40c9a5 )
by Alexander
09:38
created

Connection::openFromPoolSequentially()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 39
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8.0747

Importance

Changes 0
Metric Value
cc 8
eloc 19
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 39
ccs 17
cts 19
cp 0.8947
crap 8.0747
rs 8.4444
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 2988
    public function __construct(
200
        LoggerInterface $logger,
201
        Profiler $profiler,
202
        QueryCache $queryCache,
203
        SchemaCache $schemaCache,
204
        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 2988
    }
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
     */
258 10
    public function __clone()
259
    {
260 10
        $this->master = null;
261 10
        $this->slave = null;
262 10
        $this->schema = null;
263 10
        $this->transaction = null;
264
265 10
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
266
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
267 10
            $this->pdo = null;
268
        }
269 10
    }
270
271
    /**
272
     * Close the connection before serializing.
273
     *
274
     * @return array
275
     */
276 6
    public function __sleep(): array
277
    {
278 6
        $fields = (array) $this;
279
280
        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 6
            $fields["\000" . __CLASS__ . "\000" . 'schema']
286
        );
287
288 6
        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
     */
302 40
    public function beginTransaction($isolationLevel = null): Transaction
303
    {
304 40
        $this->open();
305
306 40
        if (($transaction = $this->getTransaction()) === null) {
307 40
            $transaction = $this->transaction = new Transaction($this, $this->logger);
308
        }
309
310 40
        $transaction->begin($isolationLevel);
311
312 40
        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
     */
350 10
    public function cache(callable $callable, int $duration = null, Dependency $dependency = null)
351
    {
352 10
        $this->queryCache->setInfo(
353 10
            [$duration ?? $this->queryCache->getDuration(), $dependency]
354
        );
355
356 10
        $result = $callable($this);
357
358 10
        $this->queryCache->removeLastInfo();
359
360 10
        return $result;
361
    }
362
363 1831
    public function getAttributes(): array
364
    {
365 1831
        return $this->attributes;
366
    }
367
368 733
    public function getCharset(): ?string
369
    {
370 733
        return $this->charset;
371
    }
372
373 1856
    public function getDsn(): string
374
    {
375 1856
        return $this->dsn;
376
    }
377
378 1463
    public function getEmulatePrepare(): ?bool
379
    {
380 1463
        return $this->emulatePrepare;
381
    }
382
383 1752
    public function getQueryCache(): QueryCache
384
    {
385 1752
        return $this->queryCache;
386
    }
387
388 2490
    public function getSchemaCache(): SchemaCache
389
    {
390 2490
        return $this->schemaCache;
391
    }
392
393 1698
    public function isLoggingEnabled(): bool
394
    {
395 1698
        return $this->enableLogging;
396
    }
397
398 1831
    public function isProfilingEnabled(): bool
399
    {
400 1831
        return $this->enableProfiling;
401
    }
402
403 10
    public function isSavepointEnabled(): bool
404
    {
405 10
        return $this->enableSavepoint;
406
    }
407
408 1
    public function areSlavesEnabled(): bool
409
    {
410 1
        return $this->enableSlaves;
411
    }
412
413
    /**
414
     * Returns a value indicating whether the DB connection is established.
415
     *
416
     * @return bool whether the DB connection is established
417
     */
418 193
    public function isActive(): bool
419
    {
420 193
        return $this->pdo !== null;
421
    }
422
423
    /**
424
     * Returns the ID of the last inserted row or sequence value.
425
     *
426
     * @param string $sequenceName name of the sequence object (required by some DBMS)
427
     *
428
     * @throws Exception
429
     * @throws InvalidCallException
430
     *
431
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
432
     *
433
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
434
     */
435 10
    public function getLastInsertID($sequenceName = ''): string
436
    {
437 10
        return $this->getSchema()->getLastInsertID($sequenceName);
438
    }
439
440 1752
    public function getLogger(): LoggerInterface
441
    {
442 1752
        return $this->logger;
443
    }
444
445
    /**
446
     * Returns the currently active master connection.
447
     *
448
     * If this method is called for the first time, it will try to open a master connection.
449
     *
450
     * @throws InvalidConfigException
451
     *
452
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
453
     */
454 13
    public function getMaster(): ?self
455
    {
456 13
        if ($this->master === null) {
457 13
            $this->master = $this->shuffleMasters
458 7
                ? $this->openFromPool($this->masters)
459 11
                : $this->openFromPoolSequentially($this->masters);
460
        }
461
462 13
        return $this->master;
463
    }
464
465
    /**
466
     * Returns the PDO instance for the currently active master connection.
467
     *
468
     * This method will open the master DB connection and then return {@see pdo}.
469
     *
470
     * @throws Exception
471
     *
472
     * @return PDO the PDO instance for the currently active master connection.
473
     */
474 1797
    public function getMasterPdo(): PDO
475
    {
476 1797
        $this->open();
477
478 1797
        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...
479
    }
480
481 1831
    public function getPassword(): ?string
482
    {
483 1831
        return $this->password;
484
    }
485
486
    /**
487
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
488
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
489
     * it will be null.
490
     *
491
     * @return PDO|null
492
     *
493
     * {@see pdoClass}
494
     */
495 1831
    public function getPDO(): ?PDO
496
    {
497 1831
        return $this->pdo;
498
    }
499
500
    /**
501
     * Returns the query builder for the current DB connection.
502
     *
503
     * @return QueryBuilder the query builder for the current DB connection.
504
     */
505 941
    public function getQueryBuilder(): QueryBuilder
506
    {
507 941
        return $this->getSchema()->getQueryBuilder();
508
    }
509
510 1752
    public function getProfiler(): Profiler
511
    {
512 1752
        return $this->profiler;
513
    }
514
515
    /**
516
     * Returns a server version as a string comparable by {@see \version_compare()}.
517
     *
518
     * @return string server version as a string.
519
     */
520 311
    public function getServerVersion(): string
521
    {
522 311
        return $this->getSchema()->getServerVersion();
523
    }
524
525
    /**
526
     * Returns the currently active slave connection.
527
     *
528
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
529
     * is true.
530
     *
531
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
532
     * available.
533
     *
534
     * @throws InvalidConfigException
535
     *
536
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
537
     * `$fallbackToMaster` is false.
538
     */
539 1780
    public function getSlave(bool $fallbackToMaster = true): ?self
540
    {
541 1780
        if (!$this->enableSlaves) {
542 6
            return $fallbackToMaster ? $this : null;
543
        }
544
545 1779
        if ($this->slave === null) {
546 1779
            $this->slave = $this->openFromPool($this->slaves);
547
        }
548
549 1779
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
550
    }
551
552
    /**
553
     * Returns the PDO instance for the currently active slave connection.
554
     *
555
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
556
     * returned by this method.
557
     *
558
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
559
     *
560
     * @throws Exception|InvalidConfigException
561
     *
562
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
563
     * is available and `$fallbackToMaster` is false.
564
     */
565 1778
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
566
    {
567 1778
        $db = $this->getSlave(false);
568
569 1778
        if ($db === null) {
570 1773
            return $fallbackToMaster ? $this->getMasterPdo() : null;
571
        }
572
573 6
        return $db->getPdo();
574
    }
575
576 130
    public function getTablePrefix(): string
577
    {
578 130
        return $this->tablePrefix;
579
    }
580
581
    /**
582
     * Obtains the schema information for the named table.
583
     *
584
     * @param string $name table name.
585
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
586
     *
587
     * @return TableSchema
588
     */
589 193
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
590
    {
591 193
        return $this->getSchema()->getTableSchema($name, $refresh);
592
    }
593
594
    /**
595
     * Returns the currently active transaction.
596
     *
597
     * @return Transaction|null the currently active transaction. Null if no active transaction.
598
     */
599 1713
    public function getTransaction(): ?Transaction
600
    {
601 1713
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
602
    }
603
604 1955
    public function getUsername(): ?string
605
    {
606 1955
        return $this->username;
607
    }
608
609
    /**
610
     * Disables query cache temporarily.
611
     *
612
     * Queries performed within the callable will not use query cache at all. For example,
613
     *
614
     * ```php
615
     * $db->cache(function (Connection $db) {
616
     *
617
     *     // ... queries that use query cache ...
618
     *
619
     *     return $db->noCache(function (Connection $db) {
620
     *         // this query will not use query cache
621
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
622
     *     });
623
     * });
624
     * ```
625
     *
626
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
627
     * of the callable is `function (Connection $db)`.
628
     *
629
     * @throws Throwable if there is any exception during query
630
     *
631
     * @return mixed the return result of the callable
632
     *
633
     * {@see enableQueryCache}
634
     * {@see queryCache}
635
     * {@see cache()}
636
     */
637 10
    public function noCache(callable $callable)
638
    {
639 10
        $this->queryCache->setInfo(false);
640
641 10
        $result = $callable($this);
642
643 10
        $this->queryCache->removeLastInfo();
644
645 10
        return $result;
646
    }
647
648
    /**
649
     * Establishes a DB connection.
650
     *
651
     * It does nothing if a DB connection has already been established.
652
     *
653
     * @throws Exception|InvalidConfigException if connection fails
654
     */
655 1831
    public function open(): void
656
    {
657 1831
        if (!empty($this->pdo)) {
658 1663
            return;
659
        }
660
661 1831
        if (!empty($this->masters)) {
662 11
            $db = $this->getMaster();
663
664 11
            if ($db !== null) {
665 11
                $this->pdo = $db->getPDO();
666
667 11
                return;
668
            }
669
670 10
            throw new InvalidConfigException('None of the master DB servers is available.');
671
        }
672
673 1831
        if (empty($this->dsn)) {
674
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
675
        }
676
677 1831
        $token = 'Opening DB connection: ' . $this->dsn;
678
679
        try {
680 1831
            if ($this->enableLogging) {
681 1831
                $this->logger->log(LogLevel::INFO, $token);
682
            }
683
684 1831
            if ($this->isProfilingEnabled()) {
685 1831
                $this->profiler->begin($token, [__METHOD__]);
686
            }
687
688 1831
            $this->pdo = $this->createPdoInstance();
689
690 1831
            $this->initConnection();
691
692 1831
            if ($this->isProfilingEnabled()) {
693 1831
                $this->profiler->end($token, [__METHOD__]);
694
            }
695 15
        } catch (PDOException $e) {
696 15
            if ($this->isProfilingEnabled()) {
697 15
                $this->profiler->end($token, [__METHOD__]);
698
            }
699
700 15
            if ($this->enableLogging) {
701 15
                $this->logger->log(LogLevel::ERROR, $token);
702
            }
703
704 15
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
705
        }
706 1831
    }
707
708
    /**
709
     * Closes the currently active DB connection.
710
     *
711
     * It does nothing if the connection is already closed.
712
     */
713 2894
    public function close(): void
714
    {
715 2894
        if ($this->master) {
716 10
            if ($this->pdo === $this->master->getPDO()) {
717 10
                $this->pdo = null;
718
            }
719
720 10
            $this->master->close();
721
722 10
            $this->master = null;
723
        }
724
725 2894
        if ($this->pdo !== null) {
726 1831
            if ($this->enableLogging) {
727 1821
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
728
            }
729
730 1831
            $this->pdo = null;
731 1831
            $this->schema = null;
732 1831
            $this->transaction = null;
733
        }
734
735 2894
        if ($this->slave) {
736 5
            $this->slave->close();
737 5
            $this->slave = null;
738
        }
739 2894
    }
740
741
    /**
742
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
743
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
744
     * {@see logger->log()}.
745
     *
746
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
747
     * @param int $level Transaction level just after {@see beginTransaction()} call.
748
     */
749 10
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
750
    {
751 10
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
752
            /**
753
             * {@see https://github.com/yiisoft/yii2/pull/13347}
754
             */
755
            try {
756 10
                $transaction->rollBack();
757
            } catch (Exception $e) {
758
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
759
                /** hide this exception to be able to continue throwing original exception outside */
760
            }
761
        }
762 10
    }
763
764
    /**
765
     * Opens the connection to a server in the pool.
766
     *
767
     * This method implements the load balancing among the given list of the servers.
768
     *
769
     * Connections will be tried in random order.
770
     *
771
     * @param array $pool the list of connection configurations in the server pool
772
     *
773
     * @return Connection|null the opened DB connection, or `null` if no server is available
774
     */
775 1784
    protected function openFromPool(array $pool): ?self
776
    {
777 1784
        shuffle($pool);
778
779 1784
        return $this->openFromPoolSequentially($pool);
780
    }
781
782
    /**
783
     * Opens the connection to a server in the pool.
784
     *
785
     * This method implements the load balancing among the given list of the servers.
786
     *
787
     * Connections will be tried in sequential order.
788
     *
789
     * @param array $pool
790
     *
791
     * @return Connection|null the opened DB connection, or `null` if no server is available
792
     */
793 1789
    protected function openFromPoolSequentially(array $pool): ?self
794
    {
795 1789
        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...
796 1772
            return null;
797
        }
798
799 18
        foreach ($pool as $config) {
800
            /* @var $db Connection */
801 18
            $db = DatabaseFactory::createClass($config);
802
803 18
            $key = $this->schemaCache->normalize([__METHOD__, $db->getDsn()]);
804
805 18
            if ($this->schemaCache->isEnabled() && $this->schemaCache->get($key)) {
806
                /** should not try this dead server now */
807
                continue;
808
            }
809
810
            try {
811 18
                $db->open();
812
813 18
                return $db;
814 10
            } catch (Exception $e) {
815 10
                if ($this->enableLogging) {
816 10
                    $this->logger->log(
817 10
                        LogLevel::WARNING,
818 10
                        "Connection ({$db->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
819
                    );
820
                }
821
822 10
                if ($this->schemaCache->isEnabled()) {
823
                    /** mark this server as dead and only retry it after the specified interval */
824 5
                    $this->schemaCache->set($key, 1, $this->serverRetryInterval);
825
                }
826
827 10
                return null;
828
            }
829
        }
830
831
        return null;
832
    }
833
834
    /**
835
     * Quotes a column name for use in a query.
836
     *
837
     * If the column name contains prefix, the prefix will also be properly quoted.
838
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
839
     * method will do nothing.
840
     *
841
     * @param string $name column name
842
     *
843
     * @return string the properly quoted column name
844
     */
845 1587
    public function quoteColumnName(string $name): string
846
    {
847 1587
        return $this->quotedColumnNames[$name]
848 1587
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
849
    }
850
851
    /**
852
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
853
     *
854
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
855
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
856
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
857
     *
858
     * @param string $sql the SQL to be quoted
859
     *
860
     * @return string the quoted SQL
861
     */
862 1823
    public function quoteSql(string $sql): string
863
    {
864 1823
        return preg_replace_callback(
865 1823
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
866 1823
            function ($matches) {
867 687
                if (isset($matches[3])) {
868 567
                    return $this->quoteColumnName($matches[3]);
869
                }
870
871 491
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
872 1823
            },
873
            $sql
874
        );
875
    }
876
877
    /**
878
     * Quotes a table name for use in a query.
879
     *
880
     * If the table name contains schema prefix, the prefix will also be properly quoted.
881
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
882
     * will do nothing.
883
     *
884
     * @param string $name table name
885
     *
886
     * @return string the properly quoted table name
887
     */
888 1370
    public function quoteTableName(string $name): string
889
    {
890 1370
        return $this->quotedTableNames[$name]
891 1370
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
892
    }
893
894
    /**
895
     * Quotes a string value for use in a query.
896
     *
897
     * Note that if the parameter is not a string, it will be returned without change.
898
     *
899
     * @param int|string $value string to be quoted
900
     *
901
     * @return int|string the properly quoted string
902
     *
903
     * {@see http://php.net/manual/en/pdo.quote.php}
904
     */
905 1354
    public function quoteValue($value)
906
    {
907 1354
        return $this->getSchema()->quoteValue($value);
908
    }
909
910
    /**
911
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
912
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
913
     * attributes.
914
     *
915
     * @param array $value
916
     */
917
    public function setAttributes(array $value): void
918
    {
919
        $this->attributes = $value;
920
    }
921
922
    /**
923
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
924
     * null, meaning using default charset as configured by the database.
925
     *
926
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
927
     * `;charset=UTF-8` to the DSN string.
928
     *
929
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
930
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
931
     *
932
     * @param string|null $value
933
     */
934 1
    public function setCharset(?string $value): void
935
    {
936 1
        $this->charset = $value;
937 1
    }
938
939
    /**
940
     * Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want
941
     * to disable this option in a production environment to gain performance if you do not need the information being
942
     * logged.
943
     *
944
     * @param bool $value
945
     */
946 10
    public function setEnableProfiling(bool $value): void
947
    {
948 10
        $this->enableProfiling = $value;
949 10
    }
950
951
    /**
952
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
953
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
954
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
955
     * ATTR_EMULATE_PREPARES value will not be changed.
956
     *
957
     * @param bool $value
958
     */
959 5
    public function setEmulatePrepare(bool $value): void
960
    {
961 5
        $this->emulatePrepare = $value;
962 5
    }
963
964
    /**
965
     * Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a
966
     * production environment to gain performance if you do not need the information being logged.
967
     *
968
     * @param bool $value
969
     */
970 10
    public function setEnableLogging(bool $value): void
971
    {
972 10
        $this->enableLogging = $value;
973 10
    }
974
975
    /**
976
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
977
     * support savepoint, setting this property to be true will have no effect.
978
     *
979
     * @param bool $value
980
     */
981 5
    public function setEnableSavepoint(bool $value): void
982
    {
983 5
        $this->enableSavepoint = $value;
984 5
    }
985
986
    /**
987
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
988
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
989
     *
990
     * @param bool $value
991
     */
992
    public function setEnableSlaves(bool $value): void
993
    {
994
        $this->enableSlaves = $value;
995
    }
996
997
    /**
998
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
999
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
1000
     *
1001
     * @param string $key index master connection.
1002
     * @param array $config The configuration that should be merged with every master configuration
1003
     */
1004 14
    public function setMasters(string $key, array $config = []): void
1005
    {
1006 14
        $this->masters[$key] = $config;
1007 14
    }
1008
1009
    /**
1010
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
1011
     *
1012
     * @param string|null $value
1013
     */
1014 2603
    public function setPassword(?string $value): void
1015
    {
1016 2603
        $this->password = $value;
1017 2603
    }
1018
1019
    /**
1020
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
1021
     *
1022
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
1023
     */
1024
    public function setQueryBuilder(iterable $config): void
1025
    {
1026
        $builder = $this->getQueryBuilder();
1027
1028
        foreach ($config as $key => $value) {
1029
            $builder->{$key} = $value;
1030
        }
1031
    }
1032
1033
    /**
1034
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
1035
     *
1036
     * @param int $value
1037
     */
1038
    public function setServerRetryInterval(int $value): void
1039
    {
1040
        $this->serverRetryInterval = $value;
1041
    }
1042
1043
    /**
1044
     * Whether to shuffle {@see setMasters()} before getting one.
1045
     *
1046
     * @param bool $value
1047
     */
1048 12
    public function setShuffleMasters(bool $value): void
1049
    {
1050 12
        $this->shuffleMasters = $value;
1051 12
    }
1052
1053
    /**
1054
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
1055
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
1056
     *
1057
     * @param string $key index slave connection.
1058
     * @param array $config The configuration that should be merged with every slave configuration
1059
     */
1060 9
    public function setSlaves(string $key, array $config = []): void
1061
    {
1062 9
        $this->slaves[$key] = $config;
1063 9
    }
1064
1065
    /**
1066
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1067
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1068
     *
1069
     * @param string $value
1070
     */
1071 24
    public function setTablePrefix(string $value): void
1072
    {
1073 24
        $this->tablePrefix = $value;
1074 24
    }
1075
1076
    /**
1077
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1078
     *
1079
     * @param string|null $value
1080
     */
1081 2603
    public function setUsername(?string $value): void
1082
    {
1083 2603
        $this->username = $value;
1084 2603
    }
1085
1086
    /**
1087
     * Executes callback provided in a transaction.
1088
     *
1089
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1090
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1091
     * for details.
1092
     *
1093
     * @throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1094
     *
1095
     * @return mixed result of callback function
1096
     */
1097 25
    public function transaction(callable $callback, $isolationLevel = null)
1098
    {
1099 25
        $transaction = $this->beginTransaction($isolationLevel);
1100
1101 25
        $level = $transaction->getLevel();
1102
1103
        try {
1104 25
            $result = $callback($this);
1105
1106 15
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1107 15
                $transaction->commit();
1108
            }
1109 10
        } catch (Throwable $e) {
1110 10
            $this->rollbackTransactionOnLevel($transaction, $level);
1111
1112 10
            throw $e;
1113
        }
1114
1115 15
        return $result;
1116
    }
1117
1118
    /**
1119
     * Executes the provided callback by using the master connection.
1120
     *
1121
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1122
     * even if they are read queries. For example,
1123
     *
1124
     * ```php
1125
     * $result = $db->useMaster(function ($db) {
1126
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1127
     * });
1128
     * ```
1129
     *
1130
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1131
     * `function (Connection $db)`. Its return value will be returned by this method.
1132
     *
1133
     * @throws Throwable if there is any exception thrown from the callback
1134
     *
1135
     * @return mixed the return value of the callback
1136
     */
1137 7
    public function useMaster(callable $callback)
1138
    {
1139 7
        if ($this->enableSlaves) {
1140 7
            $this->enableSlaves = false;
1141
1142
            try {
1143 7
                $result = $callback($this);
1144 1
            } catch (Throwable $e) {
1145 1
                $this->enableSlaves = true;
1146
1147 1
                throw $e;
1148
            }
1149 6
            $this->enableSlaves = true;
1150
        } else {
1151
            $result = $callback($this);
1152
        }
1153
1154 6
        return $result;
1155
    }
1156
}
1157