Passed
Push — master ( c5030b...c13ec3 )
by Wilmer
09:57 queued 27s
created

Connection::open()   B

Complexity

Conditions 11
Paths 96

Size

Total Lines 50
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 11.0069

Importance

Changes 0
Metric Value
cc 11
eloc 26
c 0
b 0
f 0
nc 96
nop 0
dl 0
loc 50
ccs 25
cts 26
cp 0.9615
crap 11.0069
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        $cache = $this->schemaCache->getCache();
800
801 18
        foreach ($pool as $config) {
802
            /* @var $db Connection */
803 18
            $db = DatabaseFactory::createClass($config);
804
805 18
            $key = $this->schemaCache->normalize([__METHOD__, $db->getDsn()]);
806
807 18
            if ($this->schemaCache->isEnabled() && $cache->get($key)) {
808
                /** should not try this dead server now */
809
                continue;
810
            }
811
812
            try {
813 18
                $db->open();
814
815 18
                return $db;
816 10
            } catch (Exception $e) {
817 10
                if ($this->enableLogging) {
818 10
                    $this->logger->log(
819 10
                        LogLevel::WARNING,
820 10
                        "Connection ({$db->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
821
                    );
822
                }
823
824 10
                if ($this->schemaCache->isEnabled()) {
825
                    /** mark this server as dead and only retry it after the specified interval */
826 5
                    $cache->set($key, 1, $this->serverRetryInterval);
827
                }
828
829 10
                return null;
830
            }
831
        }
832
833
        return null;
834
    }
835
836
    /**
837
     * Quotes a column name for use in a query.
838
     *
839
     * If the column name contains prefix, the prefix will also be properly quoted.
840
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
841
     * method will do nothing.
842
     *
843
     * @param string $name column name
844
     *
845
     * @return string the properly quoted column name
846
     */
847 1587
    public function quoteColumnName(string $name): string
848
    {
849 1587
        return $this->quotedColumnNames[$name]
850 1587
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
851
    }
852
853
    /**
854
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
855
     *
856
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
857
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
858
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
859
     *
860
     * @param string $sql the SQL to be quoted
861
     *
862
     * @return string the quoted SQL
863
     */
864 1823
    public function quoteSql(string $sql): string
865
    {
866 1823
        return preg_replace_callback(
867 1823
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
868 1823
            function ($matches) {
869 687
                if (isset($matches[3])) {
870 567
                    return $this->quoteColumnName($matches[3]);
871
                }
872
873 491
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
874 1823
            },
875
            $sql
876
        );
877
    }
878
879
    /**
880
     * Quotes a table name for use in a query.
881
     *
882
     * If the table name contains schema prefix, the prefix will also be properly quoted.
883
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
884
     * will do nothing.
885
     *
886
     * @param string $name table name
887
     *
888
     * @return string the properly quoted table name
889
     */
890 1370
    public function quoteTableName(string $name): string
891
    {
892 1370
        return $this->quotedTableNames[$name]
893 1370
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
894
    }
895
896
    /**
897
     * Quotes a string value for use in a query.
898
     *
899
     * Note that if the parameter is not a string, it will be returned without change.
900
     *
901
     * @param int|string $value string to be quoted
902
     *
903
     * @return int|string the properly quoted string
904
     *
905
     * {@see http://php.net/manual/en/pdo.quote.php}
906
     */
907 1354
    public function quoteValue($value)
908
    {
909 1354
        return $this->getSchema()->quoteValue($value);
910
    }
911
912
    /**
913
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
914
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
915
     * attributes.
916
     *
917
     * @param array $value
918
     */
919
    public function setAttributes(array $value): void
920
    {
921
        $this->attributes = $value;
922
    }
923
924
    /**
925
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
926
     * null, meaning using default charset as configured by the database.
927
     *
928
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
929
     * `;charset=UTF-8` to the DSN string.
930
     *
931
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
932
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
933
     *
934
     * @param string|null $value
935
     */
936 1
    public function setCharset(?string $value): void
937
    {
938 1
        $this->charset = $value;
939 1
    }
940
941
    /**
942
     * Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want
943
     * to disable this option in a production environment to gain performance if you do not need the information being
944
     * logged.
945
     *
946
     * @param bool $value
947
     */
948 10
    public function setEnableProfiling(bool $value): void
949
    {
950 10
        $this->enableProfiling = $value;
951 10
    }
952
953
    /**
954
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
955
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
956
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
957
     * ATTR_EMULATE_PREPARES value will not be changed.
958
     *
959
     * @param bool $value
960
     */
961 5
    public function setEmulatePrepare(bool $value): void
962
    {
963 5
        $this->emulatePrepare = $value;
964 5
    }
965
966
    /**
967
     * Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a
968
     * production environment to gain performance if you do not need the information being logged.
969
     *
970
     * @param bool $value
971
     */
972 10
    public function setEnableLogging(bool $value): void
973
    {
974 10
        $this->enableLogging = $value;
975 10
    }
976
977
    /**
978
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
979
     * support savepoint, setting this property to be true will have no effect.
980
     *
981
     * @param bool $value
982
     */
983 5
    public function setEnableSavepoint(bool $value): void
984
    {
985 5
        $this->enableSavepoint = $value;
986 5
    }
987
988
    /**
989
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
990
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
991
     *
992
     * @param bool $value
993
     */
994
    public function setEnableSlaves(bool $value): void
995
    {
996
        $this->enableSlaves = $value;
997
    }
998
999
    /**
1000
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
1001
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
1002
     *
1003
     * @param string $key index master connection.
1004
     * @param array $config The configuration that should be merged with every master configuration
1005
     */
1006 14
    public function setMasters(string $key, array $config = []): void
1007
    {
1008 14
        $this->masters[$key] = $config;
1009 14
    }
1010
1011
    /**
1012
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
1013
     *
1014
     * @param string|null $value
1015
     */
1016 2603
    public function setPassword(?string $value): void
1017
    {
1018 2603
        $this->password = $value;
1019 2603
    }
1020
1021
    /**
1022
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
1023
     *
1024
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
1025
     */
1026
    public function setQueryBuilder(iterable $config): void
1027
    {
1028
        $builder = $this->getQueryBuilder();
1029
1030
        foreach ($config as $key => $value) {
1031
            $builder->{$key} = $value;
1032
        }
1033
    }
1034
1035
    /**
1036
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
1037
     *
1038
     * @param int $value
1039
     */
1040
    public function setServerRetryInterval(int $value): void
1041
    {
1042
        $this->serverRetryInterval = $value;
1043
    }
1044
1045
    /**
1046
     * Whether to shuffle {@see setMasters()} before getting one.
1047
     *
1048
     * @param bool $value
1049
     */
1050 12
    public function setShuffleMasters(bool $value): void
1051
    {
1052 12
        $this->shuffleMasters = $value;
1053 12
    }
1054
1055
    /**
1056
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
1057
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
1058
     *
1059
     * @param string $key index slave connection.
1060
     * @param array $config The configuration that should be merged with every slave configuration
1061
     */
1062 9
    public function setSlaves(string $key, array $config = []): void
1063
    {
1064 9
        $this->slaves[$key] = $config;
1065 9
    }
1066
1067
    /**
1068
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1069
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1070
     *
1071
     * @param string $value
1072
     */
1073 24
    public function setTablePrefix(string $value): void
1074
    {
1075 24
        $this->tablePrefix = $value;
1076 24
    }
1077
1078
    /**
1079
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1080
     *
1081
     * @param string|null $value
1082
     */
1083 2603
    public function setUsername(?string $value): void
1084
    {
1085 2603
        $this->username = $value;
1086 2603
    }
1087
1088
    /**
1089
     * Executes callback provided in a transaction.
1090
     *
1091
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1092
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1093
     * for details.
1094
     *
1095
     * @throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1096
     *
1097
     * @return mixed result of callback function
1098
     */
1099 25
    public function transaction(callable $callback, $isolationLevel = null)
1100
    {
1101 25
        $transaction = $this->beginTransaction($isolationLevel);
1102
1103 25
        $level = $transaction->getLevel();
1104
1105
        try {
1106 25
            $result = $callback($this);
1107
1108 15
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1109 15
                $transaction->commit();
1110
            }
1111 10
        } catch (Throwable $e) {
1112 10
            $this->rollbackTransactionOnLevel($transaction, $level);
1113
1114 10
            throw $e;
1115
        }
1116
1117 15
        return $result;
1118
    }
1119
1120
    /**
1121
     * Executes the provided callback by using the master connection.
1122
     *
1123
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1124
     * even if they are read queries. For example,
1125
     *
1126
     * ```php
1127
     * $result = $db->useMaster(function ($db) {
1128
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1129
     * });
1130
     * ```
1131
     *
1132
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1133
     * `function (Connection $db)`. Its return value will be returned by this method.
1134
     *
1135
     * @throws Throwable if there is any exception thrown from the callback
1136
     *
1137
     * @return mixed the return value of the callback
1138
     */
1139 7
    public function useMaster(callable $callback)
1140
    {
1141 7
        if ($this->enableSlaves) {
1142 7
            $this->enableSlaves = false;
1143
1144
            try {
1145 7
                $result = $callback($this);
1146 1
            } catch (Throwable $e) {
1147 1
                $this->enableSlaves = true;
1148
1149 1
                throw $e;
1150
            }
1151 6
            $this->enableSlaves = true;
1152
        } else {
1153
            $result = $callback($this);
1154
        }
1155
1156 6
        return $result;
1157
    }
1158
}
1159