Passed
Push — master ( 9f7d35...3f1c7e )
by Wilmer
08:50 queued 06:32
created

Connection::openFromPoolSequentially()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8.0109

Importance

Changes 0
Metric Value
cc 8
eloc 18
nc 8
nop 1
dl 0
loc 35
ccs 17
cts 18
cp 0.9444
crap 8.0109
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Connection;
6
7
use PDO;
8
use PDOException;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\LogLevel;
11
use Throwable;
12
use Yiisoft\Cache\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\Connection\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 = null;
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 1624
    public function __construct(CacheInterface $cache, LoggerInterface $logger, Profiler $profiler, string $dsn)
206
    {
207 1624
        $this->schemaCache = $cache;
208 1624
        $this->logger = $logger;
209 1624
        $this->profiler = $profiler;
210 1624
        $this->dsn = $dsn;
211 1624
    }
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 743
    public function getAttributes(): array
371
    {
372 743
        return $this->attributes;
373
    }
374
375 366
    public function getCharset(): ?string
376
    {
377 366
        return $this->charset;
378
    }
379
380
    /**
381
     * Returns the name of the DB driver. Based on the the current {@see dsn}, in case it was not set explicitly by an
382
     * end user.
383
     *
384
     * @throws Exception
385
     * @throws InvalidConfigException
386
     *
387
     * @return string|null name of the DB driver
388
     */
389 222
    public function getDriverName(): ?string
390
    {
391 222
        if ($this->driverName === null) {
392 222
            if (($pos = strpos($this->dsn, ':')) !== false) {
393 222
                $this->driverName = strtolower(substr($this->dsn, 0, $pos));
394
            } else {
395
                $this->driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
396
            }
397
        }
398
399 222
        return $this->driverName;
400
    }
401
402 763
    public function getDsn(): ?string
403
    {
404 763
        return $this->dsn;
405
    }
406
407 547
    public function getEmulatePrepare(): ?bool
408
    {
409 547
        return $this->emulatePrepare;
410
    }
411
412 660
    public function isLoggingEnabled(): bool
413
    {
414 660
        return $this->enableLogging;
415
    }
416
417 660
    public function isProfilingEnabled(): bool
418
    {
419 660
        return $this->enableProfiling;
420
    }
421
422
    public function isQueryCacheEnabled(): bool
423
    {
424
        return $this->enableQueryCache;
425
    }
426
427 8
    public function isSavepointEnabled(): bool
428
    {
429 8
        return $this->enableSavepoint;
430
    }
431
432 589
    public function isSchemaCacheEnabled(): bool
433
    {
434 589
        return $this->enableSchemaCache;
435
    }
436
437 1
    public function areSlavesEnabled(): bool
438
    {
439 1
        return $this->enableSlaves;
440
    }
441
442
    /**
443
     * Returns a value indicating whether the DB connection is established.
444
     *
445
     * @return bool whether the DB connection is established
446
     */
447 49
    public function isActive(): bool
448
    {
449 49
        return $this->pdo !== null;
450
    }
451
452
    /**
453
     * Returns the ID of the last inserted row or sequence value.
454
     *
455
     * @param string $sequenceName name of the sequence object (required by some DBMS)
456
     *
457
     * @throws Exception
458
     * @throws InvalidCallException
459
     *
460
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
461
     *
462
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
463
     */
464 8
    public function getLastInsertID($sequenceName = ''): string
465
    {
466 8
        return $this->getSchema()->getLastInsertID($sequenceName);
467
    }
468
469 703
    public function getLogger(): LoggerInterface
470
    {
471 703
        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...
472
    }
473
474
    /**
475
     * Returns the currently active master connection.
476
     *
477
     * If this method is called for the first time, it will try to open a master connection.
478
     *
479
     * @throws InvalidConfigException
480
     *
481
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
482
     */
483 11
    public function getMaster(): ?Connection
484
    {
485 11
        if ($this->master === null) {
486 11
            $this->master = $this->shuffleMasters
487 6
                ? $this->openFromPool($this->masters)
488 9
                : $this->openFromPoolSequentially($this->masters);
489
        }
490
491 11
        return $this->master;
492
    }
493
494
    /**
495
     * Returns the PDO instance for the currently active master connection.
496
     *
497
     * This method will open the master DB connection and then return {@see pdo}.
498
     *
499
     * @throws Exception
500
     *
501
     * @return PDO the PDO instance for the currently active master connection.
502
     */
503 715
    public function getMasterPdo(): PDO
504
    {
505 715
        $this->open();
506
507 715
        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...
508
    }
509
510 743
    public function getPassword(): ?string
511
    {
512 743
        return $this->password;
513
    }
514
515
    /**
516
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
517
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
518
     * it will be null.
519
     *
520
     * @return PDO|null
521
     *
522
     * {@see pdoClass}
523
     */
524 743
    public function getPDO(): ?PDO
525
    {
526 743
        return $this->pdo;
527
    }
528
529 703
    public function getProfiler(): profiler
530
    {
531 703
        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...
532
    }
533
534
    /**
535
     * Returns the query builder for the current DB connection.
536
     *
537
     * @return QueryBuilder the query builder for the current DB connection.
538
     */
539 225
    public function getQueryBuilder(): QueryBuilder
540
    {
541 225
        return $this->getSchema()->getQueryBuilder();
542
    }
543
544 8
    public function getQueryCacheDuration(): ?int
545
    {
546 8
        return $this->queryCacheDuration;
547
    }
548
549
    /**
550
     * Returns the current query cache information.
551
     *
552
     * This method is used internally by {@see Command}.
553
     *
554
     * @param int|null $duration the preferred caching duration. If null, it will be ignored.
555
     * @param Dependency|null $dependency the preferred caching dependency. If null, it will be
556
     * ignored.
557
     *
558
     * @return array|null the current query cache information, or null if query cache is not enabled.
559
     */
560 632
    public function getQueryCacheInfo(?int $duration, ?Dependency $dependency): ?array
561
    {
562 632
        $result = null;
563
564 632
        if ($this->enableQueryCache) {
565 632
            $info = end($this->queryCacheInfo);
566
567 632
            if (is_array($info)) {
568 8
                if ($duration === null) {
569 8
                    $duration = $info[0];
570
                }
571
572 8
                if ($dependency === null) {
573 8
                    $dependency = $info[1];
574
                }
575
            }
576
577 632
            if ($duration === 0 || $duration > 0) {
578 8
                if ($this->schemaCache instanceof CacheInterface) {
579 8
                    $result = [$this->schemaCache, $duration, $dependency];
580
                }
581
            }
582
        }
583
584 632
        return $result;
585
    }
586
587 1296
    public function getSchemaCache(): CacheInterface
588
    {
589 1296
        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...
590
    }
591
592 541
    public function getSchemaCacheDuration(): int
593
    {
594 541
        return $this->schemaCacheDuration;
595
    }
596
597 589
    public function getSchemaCacheExclude(): array
598
    {
599 589
        return $this->schemaCacheExclude;
600
    }
601
602
    /**
603
     * Returns a server version as a string comparable by {@see \version_compare()}.
604
     *
605
     * @return string server version as a string.
606
     */
607 124
    public function getServerVersion(): string
608
    {
609 124
        return $this->getSchema()->getServerVersion();
610
    }
611
612
    /**
613
     * Returns the currently active slave connection.
614
     *
615
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
616
     * is true.
617
     *
618
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
619
     * available.
620
     *
621
     * @throws InvalidConfigException
622
     *
623
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
624
     * `$fallbackToMaster` is false.
625
     */
626 701
    public function getSlave(bool $fallbackToMaster = true): ?Connection
627
    {
628 701
        if (!$this->enableSlaves) {
629 2
            return $fallbackToMaster ? $this : null;
630
        }
631
632 701
        if ($this->slave === null) {
633 701
            $this->slave = $this->openFromPool($this->slaves);
634
        }
635
636 701
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
637
    }
638
639
    /**
640
     * Returns the PDO instance for the currently active slave connection.
641
     *
642
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
643
     * returned by this method.
644
     *
645
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
646
     *
647
     * @throws Exception
648
     * @throws InvalidConfigException
649
     *
650
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
651
     * is available and `$fallbackToMaster` is false.
652
     */
653 699
    public function getSlavePdo(bool $fallbackToMaster = true): PDO
654
    {
655 699
        $db = $this->getSlave(false);
656
657 699
        if ($db === null) {
658 695
            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...
659
        }
660
661 5
        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...
662
    }
663
664 92
    public function getTablePrefix(): string
665
    {
666 92
        return $this->tablePrefix;
667
    }
668
669
    /**
670
     * Obtains the schema information for the named table.
671
     *
672
     * @param string $name table name.
673
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
674
     *
675
     * @return TableSchema
676
     */
677 95
    public function getTableSchema($name, $refresh = false): ?TableSchema
678
    {
679 95
        return $this->getSchema()->getTableSchema($name, $refresh);
680
    }
681
682
    /**
683
     * Returns the currently active transaction.
684
     *
685
     * @return Transaction|null the currently active transaction. Null if no active transaction.
686
     */
687 672
    public function getTransaction(): ?Transaction
688
    {
689 672
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
690
    }
691
692 759
    public function getUsername(): ?string
693
    {
694 759
        return $this->username;
695
    }
696
697
    /**
698
     * Disables query cache temporarily.
699
     *
700
     * Queries performed within the callable will not use query cache at all. For example,
701
     *
702
     * ```php
703
     * $db->cache(function (Connection $db) {
704
     *
705
     *     // ... queries that use query cache ...
706
     *
707
     *     return $db->noCache(function (Connection $db) {
708
     *         // this query will not use query cache
709
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
710
     *     });
711
     * });
712
     * ```
713
     *
714
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
715
     * of the callable is `function (Connection $db)`.
716
     *
717
     * @throws Throwable if there is any exception during query
718
     *
719
     * @return mixed the return result of the callable
720
     *
721
     * {@see enableQueryCache}
722
     * {@see queryCache}
723
     * {@see cache()}
724
     */
725 8
    public function noCache(callable $callable)
726
    {
727 8
        $this->queryCacheInfo[] = false;
728
729
        try {
730 8
            $result = $callable($this);
731 8
            array_pop($this->queryCacheInfo);
732
733 8
            return $result;
734
        } catch (Throwable $e) {
735
            array_pop($this->queryCacheInfo);
736
737
            throw $e;
738
        }
739
    }
740
741
    /**
742
     * Establishes a DB connection.
743
     *
744
     * It does nothing if a DB connection has already been established.
745
     *
746
     * @throws Exception
747
     * @throws InvalidConfigException if connection fails
748
     */
749 743
    public function open()
750
    {
751 743
        if (!empty($this->pdo)) {
752 641
            return null;
753
        }
754
755 743
        if (!empty($this->masters)) {
756 9
            $db = $this->getMaster();
757
758 9
            if ($db !== null) {
759 9
                $this->pdo = $db->getPDO();
760
761 9
                return null;
762
            }
763
764 8
            throw new InvalidConfigException('None of the master DB servers is available.');
765
        }
766
767 743
        if (empty($this->dsn)) {
768
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
769
        }
770
771 743
        $token = 'Opening DB connection: ' . $this->dsn;
772
773
        try {
774 743
            if ($this->enableLogging) {
775 743
                $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

775
                $this->logger->/** @scrutinizer ignore-call */ 
776
                               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...
776
            }
777
778 743
            if ($this->enableProfiling) {
779 743
                $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

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

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