Passed
Pull Request — master (#175)
by Wilmer
13:09 queued 14s
created

Connection   F

Complexity

Total Complexity 127

Size/Duplication

Total Lines 1254
Duplicated Lines 0 %

Test Coverage

Coverage 86.89%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 251
dl 0
loc 1254
ccs 265
cts 305
cp 0.8689
rs 2
c 1
b 0
f 0
wmc 127

71 Methods

Rating   Name   Duplication   Size   Complexity  
A getAttributes() 0 3 1
A cache() 0 14 2
A __clone() 0 10 2
A beginTransaction() 0 11 2
A getCharset() 0 3 1
A __sleep() 0 13 1
A __construct() 0 6 1
A setMasters() 0 3 1
A quoteTableName() 0 7 2
A setDriverName() 0 3 1
A setEmulatePrepare() 0 3 1
A setSlaves() 0 3 1
A noCache() 0 13 2
A isQueryCacheEnabled() 0 3 1
A setShuffleMasters() 0 3 1
A getEmulatePrepare() 0 3 1
A setAttributes() 0 3 1
A isSavepointEnabled() 0 3 1
A getMasterPdo() 0 5 1
A transaction() 0 19 4
B openFromPoolSequentially() 0 35 8
A getQueryCacheDuration() 0 3 1
B getQueryCacheInfo() 0 25 8
A setSchemaCacheExclude() 0 3 1
A areSlavesEnabled() 0 3 1
A getLastInsertID() 0 3 1
A getUsername() 0 3 1
A quoteValue() 0 3 1
A getServerVersion() 0 3 1
A getMaster() 0 9 3
A getSlave() 0 11 6
A getSlavePdo() 0 9 3
A getTransaction() 0 3 3
A setEnableSlaves() 0 3 1
A isSchemaCacheEnabled() 0 3 1
A setUsername() 0 3 1
A getSchemaCacheDuration() 0 3 1
A getDsn() 0 3 1
A setQueryBuilder() 0 6 2
A openFromPool() 0 5 1
A isLoggingEnabled() 0 3 1
A quoteSql() 0 12 2
A getTablePrefix() 0 3 1
A setPassword() 0 3 1
A getPDO() 0 3 1
A setEnableQueryCache() 0 3 1
A setServerRetryInterval() 0 3 1
A setQueryCache() 0 3 1
A setSchemaCache() 0 3 1
A setQueryCacheDuration() 0 3 1
A quoteColumnName() 0 7 2
B open() 0 50 11
A getQueryBuilder() 0 3 1
A getProfiler() 0 3 1
A rollbackTransactionOnLevel() 0 10 4
A isProfilingEnabled() 0 3 1
A getTableSchema() 0 3 1
A isActive() 0 3 1
A useMaster() 0 18 3
A getSchemaCache() 0 3 1
A getPassword() 0 3 1
A setEnableSchemaCache() 0 3 1
A getSchemaCacheExclude() 0 3 1
A setEnableSavepoint() 0 3 1
A setTablePrefix() 0 3 1
A setSchemaCacheDuration() 0 3 1
A getLogger() 0 3 1
A close() 0 25 6
A setEnableProfiling() 0 3 1
A setCharset() 0 3 1
A setEnableLogging() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

753
                $this->logger->/** @scrutinizer ignore-call */ 
754
                               log(LogLevel::INFO, $token);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
754
            }
755 1224
756 9
            if ($this->enableProfiling) {
757
                $this->profiler->begin($token, [__METHOD__]);
0 ignored issues
show
Bug introduced by
The method begin() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

757
                $this->profiler->/** @scrutinizer ignore-call */ 
758
                                 begin($token, [__METHOD__]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
758 9
            }
759 9
760
            $this->pdo = $this->createPdoInstance();
761 9
762
            $this->initConnection();
763
764 8
            if ($this->enableProfiling) {
765
                $this->profiler->end($token, [__METHOD__]);
766
            }
767 1224
        } catch (PDOException $e) {
768
            if ($this->enableProfiling) {
769
                $this->profiler->end($token, [__METHOD__]);
770
            }
771 1224
772
            if ($this->enableLogging) {
773
                $this->logger->log(LogLevel::ERROR, $token);
774 1224
            }
775 1224
776
            throw new Exception($e->getMessage(), $e->errorInfo, (string) $e->getCode(), $e);
777
        }
778 1224
    }
779 1224
780
    /**
781
     * Closes the currently active DB connection.
782 1224
     *
783
     * It does nothing if the connection is already closed.
784 1224
     */
785
    public function close(): void
786 1224
    {
787 1224
        if ($this->master) {
788
            if ($this->pdo === $this->master->getPDO()) {
789 12
                $this->pdo = null;
790 12
            }
791 12
792
            $this->master->close();
793
794 12
            $this->master = null;
795 12
        }
796
797
        if ($this->pdo !== null) {
798 12
            if ($this->enableLogging) {
799
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
800 1224
            }
801
802
            $this->pdo = null;
803
            $this->schema = null;
804
            $this->transaction = null;
805
        }
806
807 2063
        if ($this->slave) {
808
            $this->slave->close();
809 2063
            $this->slave = null;
810 8
        }
811 8
    }
812
813
    /**
814 8
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
815
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
816 8
     * {@see logger->log()}.
817
     *
818
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
819 2063
     * @param int $level Transaction level just after {@see beginTransaction()} call.
820 1098
     *
821 1090
     * @return void
822
     */
823
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
824 1098
    {
825 1098
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
826 1098
            /**
827
             * {@see https://github.com/yiisoft/yii2/pull/13347}
828
             */
829 2063
            try {
830 4
                $transaction->rollBack();
831 4
            } catch (Exception $e) {
832
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
833 2063
                /* hide this exception to be able to continue throwing original exception outside */
834
            }
835
        }
836
    }
837
838
    /**
839
     * Opens the connection to a server in the pool.
840
     *
841
     * This method implements the load balancing among the given list of the servers.
842
     *
843
     * Connections will be tried in random order.
844
     *
845 4
     * @param array $pool the list of connection configurations in the server pool
846
     *
847 4
     * @throws InvalidConfigException
848
     *
849
     * @return Connection|null the opened DB connection, or `null` if no server is available
850
     */
851
    protected function openFromPool(array $pool): ?Connection
852 4
    {
853
        shuffle($pool);
854
855
        return $this->openFromPoolSequentially($pool);
856
    }
857
858 4
    /**
859
     * Opens the connection to a server in the pool.
860
     *
861
     * This method implements the load balancing among the given list of the servers.
862
     *
863
     * Connections will be tried in sequential order.
864
     *
865
     * @param array $pool
866
     *
867
     * @throws \Psr\SimpleCache\InvalidArgumentException
868
     *
869
     * @return Connection|null the opened DB connection, or `null` if no server is available
870
     */
871
    protected function openFromPoolSequentially(array $pool): ?Connection
872
    {
873 1182
        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...
874
            return null;
875 1182
        }
876
877 1182
        foreach ($pool as $config) {
878
            /* @var $db Connection */
879
            $db = DatabaseFactory::createClass($config);
880
881
            $key = [__METHOD__, $db->getDsn()];
882
883
            if ($this->schemaCache instanceof CacheInterface && $this->schemaCache->get($key)) {
0 ignored issues
show
Bug introduced by
$key of type array<integer,string> is incompatible with the type string expected by parameter $key of Psr\SimpleCache\CacheInterface::get(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

883
            if ($this->schemaCache instanceof CacheInterface && $this->schemaCache->get(/** @scrutinizer ignore-type */ $key)) {
Loading history...
884
                /* should not try this dead server now */
885
                continue;
886
            }
887
888
            try {
889
                $db->open();
890
891
                return $db;
892
            } catch (Exception $e) {
893 1186
                if ($this->enableLogging) {
894
                    $this->logger->log(
895 1186
                        LogLevel::WARNING,
896 1172
                        "Connection ({$db->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
897
                    );
898
                }
899 15
900
                if ($this->schemaCache instanceof CacheInterface) {
901 15
                    /* mark this server as dead and only retry it after the specified interval */
902
                    $this->schemaCache->set($key, 1, $this->serverRetryInterval);
903 15
                }
904
905 15
                return null;
906
            }
907
        }
908
    }
909
910
    /**
911 15
     * Quotes a column name for use in a query.
912
     *
913 15
     * If the column name contains prefix, the prefix will also be properly quoted.
914 8
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
915 8
     * method will do nothing.
916 8
     *
917 8
     * @param string $name column name
918 8
     *
919
     * @return string the properly quoted column name
920
     */
921
    public function quoteColumnName(string $name): string
922 8
    {
923
        if (isset($this->quotedColumnNames[$name])) {
924 4
            return $this->quotedColumnNames[$name];
925
        }
926
927 8
        return $this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
928
    }
929
930
    /**
931
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
932
     *
933
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
934
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
935
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
936
     *
937
     * @param string $sql the SQL to be quoted
938
     *
939
     * @return string the quoted SQL
940
     */
941
    public function quoteSql(string $sql): string
942
    {
943 1184
        return preg_replace_callback(
944
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
945 1184
            function ($matches) {
946 630
                if (isset($matches[3])) {
947
                    return $this->quoteColumnName($matches[3]);
948
                }
949 1184
950
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
951
            },
952
            $sql
953
        );
954
    }
955
956
    /**
957
     * Quotes a table name for use in a query.
958
     *
959
     * If the table name contains schema prefix, the prefix will also be properly quoted.
960
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
961
     * will do nothing.
962
     *
963 1238
     * @param string $name table name
964
     *
965 1238
     * @return string the properly quoted table name
966 1238
     */
967 1238
    public function quoteTableName(string $name): string
968 463
    {
969 380
        if (isset($this->quotedTableNames[$name])) {
970
            return $this->quotedTableNames[$name];
971
        }
972 331
973 1238
        return $this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
974
    }
975
976
    /**
977
     * Quotes a string value for use in a query.
978
     *
979
     * Note that if the parameter is not a string, it will be returned without change.
980
     *
981
     * @param string|int $value string to be quoted
982
     *
983
     * @return string|int the properly quoted string
984
     *
985
     * {@see http://php.net/manual/en/pdo.quote.php}
986
     */
987
    public function quoteValue($value)
988
    {
989 995
        return $this->getSchema()->quoteValue($value);
990
    }
991 995
992 644
    /**
993
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
994
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
995 995
     * attributes.
996
     *
997
     * @param array $value
998
     *
999
     * @return void
1000
     */
1001
    public function setAttributes(array $value): void
1002
    {
1003
        $this->attributes = $value;
1004
    }
1005
1006
    /**
1007
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
1008
     * null, meaning using default charset as configured by the database.
1009 824
     *
1010
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
1011 824
     * `;charset=UTF-8` to the DSN string.
1012
     *
1013
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
1014
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
1015
     *
1016
     * @param string $value
1017
     *
1018
     * @return void
1019
     */
1020
    public function setCharset(?string $value): void
1021
    {
1022
        $this->charset = $value;
1023
    }
1024
1025
    /**
1026
     * Changes the current driver name.
1027
     *
1028
     * @param string $driverName name of the DB driver
1029
     */
1030
    public function setDriverName(string $driverName): void
1031
    {
1032
        $this->driverName = strtolower($driverName);
1033
    }
1034
1035
    /**
1036
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
1037
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
1038
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
1039
     * ATTR_EMULATE_PREPARES value will not be changed.
1040
     *
1041
     * @param bool $value
1042 1
     *
1043
     * @return void
1044 1
     */
1045 1
    public function setEmulatePrepare(bool $value): void
1046
    {
1047
        $this->emulatePrepare = $value;
1048
    }
1049
1050
    /**
1051
     * Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a
1052
     * production environment to gain performance if you do not need the information being logged.
1053
     *
1054
     * @param bool $value
1055
     *
1056
     * @return void
1057
     *
1058
     * {@see setEnableProfiling()}
1059
     */
1060
    public function setEnableLogging(bool $value): void
1061
    {
1062
        $this->enableLogging = $value;
1063
    }
1064
1065
    /**
1066
     * Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want
1067 4
     * to disable this option in a production environment to gain performance if you do not need the information being
1068
     * logged.
1069 4
     *
1070 4
     * @param bool $value
1071
     *
1072
     * @return void
1073
     *
1074
     * {@see setEnableLogging()}
1075
     */
1076
    public function setEnableProfiling(bool $value): void
1077
    {
1078
        $this->enableProfiling = $value;
1079
    }
1080
1081
    /**
1082 8
     * Whether to enable query caching. Note that in order to enable query caching, a valid cache component as specified
1083
     * by {@see setQueryCache()} must be enabled and {@see enableQueryCache} must be set true. Also, only the results of
1084 8
     * the queries enclosed within {@see cache()} will be cached.
1085 8
     *
1086
     * @param bool $value
1087
     *
1088
     * @return void
1089
     *
1090
     * {@see setQueryCache()}
1091
     * {@see cache()}
1092
     * {@see noCache()}
1093
     */
1094
    public function setEnableQueryCache(bool $value): void
1095
    {
1096
        $this->enableQueryCache = $value;
1097
    }
1098 8
1099
    /**
1100 8
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
1101 8
     * support savepoint, setting this property to be true will have no effect.
1102
     *
1103
     * @param bool $value
1104
     *
1105
     * @return void
1106
     */
1107
    public function setEnableSavepoint(bool $value): void
1108
    {
1109
        $this->enableSavepoint = $value;
1110
    }
1111
1112
    /**
1113
     * Whether to enable schema caching. Note that in order to enable truly schema caching, a valid cache component as
1114
     * specified by {@see setSchemaCache()} must be enabled and {@see setEnableSchemaCache()} must be set true.
1115
     *
1116 8
     * @param bool $value
1117
     *
1118 8
     * @return void
1119 8
     *
1120
     * {@see setSchemaCacheDuration()}
1121
     * {@see setSchemaCacheExclude()}
1122
     * {@see setSchemaCache()}
1123
     */
1124
    public function setEnableSchemaCache(bool $value): void
1125
    {
1126
        $this->enableSchemaCache = $value;
1127
    }
1128
1129 4
    /**
1130
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
1131 4
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
1132 4
     *
1133
     * @param bool $value
1134
     *
1135
     * @return void
1136
     */
1137
    public function setEnableSlaves(bool $value): void
1138
    {
1139
        $this->enableSlaves = $value;
1140
    }
1141
1142
    /**
1143
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
1144
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
1145
     *
1146 32
     * @param string $key index master connection.
1147
     * @param array $config The configuration that should be merged with every master configuration
1148 32
     *
1149 32
     * @return void
1150
     *
1151
     * For example,
1152
     *
1153
     * ```php
1154
     * $connection->setMasters(
1155
     *     '1',
1156
     *     [
1157
     *         '__construct()' => ['mysql:host=127.0.0.1;dbname=yiitest;port=3306'],
1158
     *         'setUsername()' => [$connection->getUsername()],
1159
     *         'setPassword()' => [$connection->getPassword()],
1160
     *     ]
1161
     * );
1162
     * ```
1163
     *
1164
     * {@see setShuffleMasters()}
1165
     */
1166
    public function setMasters(string $key, array $config = []): void
1167
    {
1168
        $this->masters[$key] = $config;
1169
    }
1170
1171
    /**
1172
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
1173
     *
1174
     * @param string|null $value
1175
     *
1176
     * @return void
1177
     */
1178
    public function setPassword(?string $value): void
1179
    {
1180
        $this->password = $value;
1181
    }
1182
1183
    /**
1184
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
1185
     *
1186
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
1187
     *
1188 12
     * @return void
1189
     */
1190 12
    public function setQueryBuilder(iterable $config): void
1191 12
    {
1192
        $builder = $this->getQueryBuilder();
1193
1194
        foreach ($config as $key => $value) {
1195
            $builder->{$key} = $value;
1196
        }
1197
    }
1198
1199
    /**
1200 1825
     * The cache object or the ID of the cache application component that is used for query caching.
1201
     *
1202 1825
     * @param CacheInterface $value
1203 1825
     *
1204
     * @return void
1205
     *
1206
     * {@see setEnableQueryCache()}
1207
     */
1208
    public function setQueryCache(CacheInterface $value): void
1209
    {
1210
        $this->queryCache = $value;
1211
    }
1212
1213
    /**
1214
     * The default number of seconds that query results can remain valid in cache. Defaults to 3600, meaning 3600
1215
     * seconds, or one hour. Use 0 to indicate that the cached data will never expire. The value of this property will
1216
     * be used when {@see cache()} is called without a cache duration.
1217
     *
1218
     * @param int $value
1219
     *
1220
     * @return void
1221
     *
1222
     * {@see setEnableQueryCache()}
1223
     * {@see cache()}
1224
     */
1225
    public function setQueryCacheDuration(int $value): void
1226
    {
1227
        $this->queryCacheDuration = $value;
1228
    }
1229
1230 8
    /**
1231
     * The cache object or the ID of the cache application component that is used to cache the table metadata.
1232 8
     *
1233 8
     * @param $value
1234
     *
1235
     * @return void
1236
     *
1237
     * {@see setEnableSchemaCache()}
1238
     */
1239
    public function setSchemaCache(?CacheInterface $value): void
1240
    {
1241
        $this->schemaCache = $value;
1242
    }
1243
1244
    /**
1245
     * Number of seconds that table metadata can remain valid in cache. Use 0 to indicate that the cached data will
1246
     * never expire.
1247
     *
1248
     * @param int $value
1249
     *
1250
     * @return void
1251
     *
1252
     * {@see setEnableSchemaCache()}
1253
     */
1254
    public function setSchemaCacheDuration(int $value): void
1255
    {
1256
        $this->schemaCacheDuration = $value;
1257
    }
1258
1259
    /**
1260
     * List of tables whose metadata should NOT be cached. Defaults to empty array. The table names may contain schema
1261 36
     * prefix, if any. Do not quote the table names.
1262
     *
1263 36
     * @param array $value
1264 36
     *
1265
     * @return void
1266
     *
1267
     * {@see setEnableSchemaCache()}
1268
     */
1269
    public function setSchemaCacheExclude(array $value): void
1270
    {
1271
        $this->schemaCacheExclude = $value;
1272
    }
1273
1274
    /**
1275
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
1276
     *
1277
     * @param int $value
1278
     *
1279
     * @return void
1280
     */
1281
    public function setServerRetryInterval(int $value): void
1282
    {
1283
        $this->serverRetryInterval = $value;
1284
    }
1285
1286
    /**
1287
     * Whether to shuffle {@see setMasters()} before getting one.
1288
     *
1289
     * @param bool $value
1290
     *
1291
     * @return void
1292
     *
1293
     * {@see setMasters()}
1294
     */
1295
    public function setShuffleMasters(bool $value): void
1296
    {
1297
        $this->shuffleMasters = $value;
1298
    }
1299
1300
    /**
1301
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
1302
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
1303
     *
1304
     * @param string $key index slave connection.
1305
     * @param array $config The configuration that should be merged with every slave configuration
1306
     *
1307
     * @return void
1308
     *
1309
     * For example,
1310
     *
1311
     * ```php
1312
     * $connection->setSlaves(
1313
     *     '1',
1314
     *     [
1315
     *         '__construct()' => ['mysql:host=127.0.0.1;dbname=yiitest;port=3306'],
1316
     *         'setUsername()' => [$connection->getUsername()],
1317 10
     *         'setPassword()' => [$connection->getPassword()]
1318
     *     ]
1319 10
     * );
1320 10
     * ```
1321
     *
1322
     * {@see setEnableSlaves()}
1323
     */
1324
    public function setSlaves(string $key, array $config = []): void
1325
    {
1326
        $this->slaves[$key] = $config;
1327
    }
1328
1329
    /**
1330
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1331
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1332
     *
1333
     * @param string $value
1334
     *
1335
     * @return void
1336
     */
1337
    public function setTablePrefix(string $value): void
1338
    {
1339
        $this->tablePrefix = $value;
1340
    }
1341
1342
    /**
1343
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1344
     *
1345
     * @param string|null $value
1346 8
     *
1347
     * @return void
1348 8
     */
1349 8
    public function setUsername(?string $value): void
1350
    {
1351
        $this->username = $value;
1352
    }
1353
1354
    /**
1355
     * Executes callback provided in a transaction.
1356
     *
1357
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1358
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1359 24
     * for details.
1360
     *
1361 24
     * @throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1362 24
     *
1363
     * @return mixed result of callback function
1364
     */
1365
    public function transaction(callable $callback, $isolationLevel = null)
1366
    {
1367
        $transaction = $this->beginTransaction($isolationLevel);
1368
1369
        $level = $transaction->getLevel();
1370
1371 1825
        try {
1372
            $result = $callback($this);
1373 1825
1374 1825
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1375
                $transaction->commit();
1376
            }
1377
        } catch (Throwable $e) {
1378
            $this->rollbackTransactionOnLevel($transaction, $level);
1379
1380
            throw $e;
1381
        }
1382
1383
        return $result;
1384
    }
1385
1386
    /**
1387 20
     * Executes the provided callback by using the master connection.
1388
     *
1389 20
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1390
     * even if they are read queries. For example,
1391 20
     *
1392
     * ```php
1393
     * $result = $db->useMaster(function ($db) {
1394 20
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1395
     * });
1396 16
     * ```
1397 16
     *
1398
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1399 4
     * `function (Connection $db)`. Its return value will be returned by this method.
1400 4
     *
1401
     * @throws Throwable if there is any exception thrown from the callback
1402 4
     *
1403
     * @return mixed the return value of the callback
1404
     */
1405 16
    public function useMaster(callable $callback)
1406
    {
1407
        if ($this->enableSlaves) {
1408
            $this->enableSlaves = false;
1409
1410
            try {
1411
                $result = $callback($this);
1412
            } catch (Throwable $e) {
1413
                $this->enableSlaves = true;
1414
1415
                throw $e;
1416
            }
1417
            $this->enableSlaves = true;
1418
        } else {
1419
            $result = $callback($this);
1420
        }
1421
1422
        return $result;
1423
    }
1424
}
1425