Passed
Pull Request — master (#163)
by Wilmer
11:40
created

Connection::getEmulatePrepare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
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\InvalidCallException;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Exception\NotSupportedException;
19
use Yiisoft\Db\Factory\DatabaseFactory;
20
use Yiisoft\Db\Query\QueryBuilder;
21
use Yiisoft\Db\Schema\Schema;
22
use Yiisoft\Db\Schema\TableSchema;
23
use Yiisoft\Db\Transaction\Transaction;
24
use Yiisoft\Profiler\Profiler;
25
26
/**
27
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
28
 *
29
 * Connection works together with {@see Command}, {@see DataReader} and {@see Transaction} to provide data access to
30
 * various DBMS in a common set of APIs. They are a thin wrapper of the
31
 * [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
32
 *
33
 * Connection supports database replication and read-write splitting. In particular, a Connection component can be
34
 * configured with multiple {@see setMasters()} and {@see setSlaves()}. It will do load balancing and failover by
35
 * choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations
36
 * to the masters.
37
 *
38
 * To establish a DB connection, set {@see dsn}, {@see setUsername()} and {@see setPassword}, and then call
39
 * {@see open()} to connect to the database server. The current state of the connection can be checked using
40
 * {@see $isActive}.
41
 *
42
 * The following example shows how to create a Connection instance and establish the DB connection:
43
 *
44
 * ```php
45
 * $connection = new \Yiisoft\Db\Connection\Connection(
46
 *     $cache,
47
 *     $logger,
48
 *     $profiler,
49
 *     $dsn
50
 * );
51
 * $connection->open();
52
 * ```
53
 *
54
 * After the DB connection is established, one can execute SQL statements like the following:
55
 *
56
 * ```php
57
 * $command = $connection->createCommand('SELECT * FROM post');
58
 * $posts = $command->queryAll();
59
 * $command = $connection->createCommand('UPDATE post SET status=1');
60
 * $command->execute();
61
 * ```
62
 *
63
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
64
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
65
 * following is an example:
66
 *
67
 * ```php
68
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
69
 * $command->bindValue(':id', $_GET['id']);
70
 * $post = $command->query();
71
 * ```
72
 *
73
 * For more information about how to perform various DB queries, please refer to {@see Command}.
74
 *
75
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
76
 *
77
 * ```php
78
 * $transaction = $connection->beginTransaction();
79
 * try {
80
 *     $connection->createCommand($sql1)->execute();
81
 *     $connection->createCommand($sql2)->execute();
82
 *     // ... executing other SQL statements ...
83
 *     $transaction->commit();
84
 * } catch (Exceptions $e) {
85
 *     $transaction->rollBack();
86
 * }
87
 * ```
88
 *
89
 * You also can use shortcut for the above like the following:
90
 *
91
 * ```php
92
 * $connection->transaction(function () {
93
 *     $order = new Order($customer);
94
 *     $order->save();
95
 *     $order->addItems($items);
96
 * });
97
 * ```
98
 *
99
 * If needed you can pass transaction isolation level as a second parameter:
100
 *
101
 * ```php
102
 * $connection->transaction(function (Connection $db) {
103
 *     //return $db->...
104
 * }, Transaction::READ_UNCOMMITTED);
105
 * ```
106
 *
107
 * Connection is often used as an application component and configured in the container-di configuration like the
108
 * following:
109
 *
110
 * ```php
111
 * Connection::class => static function (ContainerInterface $container) {
112
 *     $connection = new Connection(
113
 *         $container->get(CacheInterface::class),
114
 *         $container->get(LoggerInterface::class),
115
 *         $container->get(Profiler::class),
116
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
117
 *     );
118
 *
119
 *     $connection->setUsername(root);
120
 *     $connection->setPassword('');
121
 *
122
 *     return $connection;
123
 * },
124
 * ```
125
 *
126
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Helper\Dsn}:
127
 *
128
 * ```php
129
 * Connection::class => static function (ContainerInterface $container) {
130
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
131
 *
132
 *     $connection = new Connection(
133
 *         $container->get(CacheInterface::class),
134
 *         $container->get(LoggerInterface::class),
135
 *         $container->get(Profiler::class),
136
 *         $dsn->getDsn()
137
 *     );
138
 *
139
 *     $connection->setUsername(root);
140
 *     $connection->setPassword('');
141
 *
142
 *     return $connection;
143
 * },
144
 * ```
145
 *
146
 * @property string $driverName Name of the DB driver.
147
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
148
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
149
 * object. This property is read-only.
150
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
151
 * available. This property is read-only.
152
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
153
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
154
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
155
 * @property Schema $schema The schema information for the database opened by this connection. This property is
156
 * read-only.
157
 * @property string $serverVersion Server version as a string. This property is read-only.
158
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
159
 * available and `$fallbackToMaster` is false. This property is read-only.
160
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
161
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
162
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
163
 * property is read-only.
164
 */
165
class Connection
166
{
167
    private ?string $driverName = null;
168
    private ?string $dsn = null;
169
    private ?string $username = null;
170
    private ?string $password = null;
171
    private array $attributes = [];
172
    private ?PDO $pdo = null;
173
    private bool $enableSchemaCache = true;
174
    private int $schemaCacheDuration = 3600;
175
    private array $schemaCacheExclude = [];
176
    private ?CacheInterface $schemaCache = null;
177
    private bool $enableQueryCache = true;
178
    private ?CacheInterface $queryCache = null;
179
    private ?string $charset = null;
180
    private ?bool $emulatePrepare = null;
181
    private string $tablePrefix = '';
182
    private array $queryCacheInfo = [];
183
    private bool $enableSavepoint = true;
184
    private int $serverRetryInterval = 600;
185
    private bool $enableSlaves = true;
186
    private array $slaves = [];
187
    private array $masters = [];
188
    private bool $shuffleMasters = true;
189
    private bool $enableLogging = true;
190
    private bool $enableProfiling = true;
191
    private int $queryCacheDuration = 3600;
192
    private array $quotedTableNames = [];
193
    private array $quotedColumnNames = [];
194
    private ?Connection $master = null;
195
    private ?Connection $slave = null;
196
    private ?LoggerInterface $logger = null;
197
    private ?Profiler $profiler = null;
198
    private ?Transaction $transaction = null;
199
    private ?Schema $schema = null;
200
201
    public function __construct(CacheInterface $cache, LoggerInterface $logger, Profiler $profiler, string $dsn)
202
    {
203
        $this->schemaCache = $cache;
204
        $this->logger = $logger;
205
        $this->profiler = $profiler;
206
        $this->dsn = $dsn;
207
    }
208
209
    /**
210
     * Reset the connection after cloning.
211
     */
212
    public function __clone()
213
    {
214
        $this->master = null;
215
        $this->slave = null;
216
        $this->schema = null;
217
        $this->transaction = null;
218
219
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
220
            /* reset PDO connection, unless its sqlite in-memory, which can only have one connection */
221
            $this->pdo = null;
222
        }
223
    }
224
225
    /**
226
     * Close the connection before serializing.
227
     *
228
     * @return array
229
     */
230
    public function __sleep(): array
231
    {
232
        $fields = (array) $this;
233
234
        unset(
235
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
236
            $fields["\000" . __CLASS__ . "\000" . 'master'],
237
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
238
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
239
            $fields["\000" . __CLASS__ . "\000" . 'schema']
240
        );
241
242
        return array_keys($fields);
243
    }
244
245
    /**
246
     * Starts a transaction.
247
     *
248
     * @param string|null $isolationLevel The isolation level to use for this transaction.
249
     *
250
     * {@see Transaction::begin()} for details.
251
     *
252
     * @throws Exception
253 1147
     * @throws InvalidConfigException
254
     * @throws NotSupportedException
255 1147
     *
256 1147
     * @return Transaction the transaction initiated
257 1147
     */
258 1147
    public function beginTransaction($isolationLevel = null): Transaction
259 1147
    {
260
        $this->open();
261
262
        if (($transaction = $this->getTransaction()) === null) {
263
            $transaction = $this->transaction = new Transaction($this, $this->logger);
264 3
        }
265
266 3
        $transaction->begin($isolationLevel);
267 3
268 3
        return $transaction;
269 3
    }
270
271 3
    /**
272
     * Uses query cache for the queries performed with the callable.
273 3
     *
274
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
275 3
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
276
     *
277
     * For example,
278
     *
279
     * ```php
280
     * // The customer will be fetched from cache if available.
281
     * // If not, the query will be made against DB and cached for use next time.
282 4
     * $customer = $db->cache(function (Connection $db) {
283
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
284 4
     * });
285
     * ```
286
     *
287 4
     * Note that query cache is only meaningful for queries that return results. For queries performed with
288 4
     * {@see Command::execute()}, query cache will not be used.
289 4
     *
290 4
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
291 4
     * The signature of the callable is `function (Connection $db)`.
292
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is not set,
293
     * the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will never
294 4
     * expire.
295
     * @param Dependency $dependency the cache dependency associated with the cached query
296
     * results.
297
     *
298
     * @throws \Throwable if there is any exception during query
299
     *
300
     * @return mixed the return result of the callable
301
     *
302
     * {@see setEnableQueryCache()}
303
     * {@see queryCache}
304
     * {@see noCache()}
305
     */
306
    public function cache(callable $callable, $duration = null, $dependency = null)
307
    {
308
        $this->queryCacheInfo[] = [$duration ?? $this->queryCacheDuration, $dependency];
309
310 24
        try {
311
            $result = $callable($this);
312 24
313
            array_pop($this->queryCacheInfo);
314 24
315 24
            return $result;
316
        } catch (\Throwable $e) {
317
            array_pop($this->queryCacheInfo);
318 24
319
            throw $e;
320 24
        }
321
    }
322
323
    public function getAttributes(): array
324
    {
325
        return $this->attributes;
326
    }
327
328
    public function getCharset(): ?string
329
    {
330
        return $this->charset;
331
    }
332
333
    /**
334
     * Returns the name of the DB driver. Based on the the current {@see dsn}, in case it was not set explicitly by an
335
     * end user.
336
     *
337
     * @throws Exception
338
     * @throws InvalidConfigException
339
     *
340
     * @return string|null name of the DB driver
341
     */
342
    public function getDriverName(): ?string
343
    {
344
        if ($this->driverName === null) {
345
            if (($pos = strpos($this->dsn, ':')) !== false) {
346
                $this->driverName = strtolower(substr($this->dsn, 0, $pos));
347
            } else {
348
                $this->driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
349
            }
350
        }
351
352
        return $this->driverName;
353
    }
354
355
    public function getDsn(): ?string
356
    {
357
        return $this->dsn;
358 6
    }
359
360 6
    public function getEmulatePrepare(): ?bool
361
    {
362
        return $this->emulatePrepare;
363 6
    }
364
365 6
    public function isLoggingEnabled(): bool
366
    {
367 6
        return $this->enableLogging;
368
    }
369
370
    public function isProfilingEnabled(): bool
371
    {
372
        return $this->enableProfiling;
373
    }
374
375
    public function isQueryCacheEnabled(): bool
376
    {
377
        return $this->enableQueryCache;
378
    }
379
380
    public function isSavepointEnabled(): bool
381
    {
382
        return $this->enableSavepoint;
383
    }
384
385
    public function isSchemaCacheEnabled(): bool
386 525
    {
387
        return $this->enableSchemaCache;
388 525
    }
389
390 525
    public function areSlavesEnabled(): bool
391 525
    {
392
        return $this->enableSlaves;
393
    }
394
395 525
    /**
396
     * Returns a value indicating whether the DB connection is established.
397 525
     *
398
     * @return bool whether the DB connection is established
399
     */
400
    public function isActive(): bool
401
    {
402
        return $this->pdo !== null;
403
    }
404
405
    /**
406
     * Returns the ID of the last inserted row or sequence value.
407
     *
408
     * @param string $sequenceName name of the sequence object (required by some DBMS)
409
     *
410
     * @throws Exception
411
     * @throws InvalidConfigException
412
     * @throws NotSupportedException
413
     * @throws InvalidCallException
414 918
     *
415
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
416 918
     *
417 918
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
418 918
     */
419
    public function getLastInsertID($sequenceName = ''): string
420
    {
421
        return $this->getSchema()->getLastInsertID($sequenceName);
0 ignored issues
show
Bug introduced by
The method getSchema() does not exist on Yiisoft\Db\Connection\Connection. Did you maybe mean getSchemaCache()? ( Ignorable by Annotation )

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

421
        return $this->/** @scrutinizer ignore-call */ getSchema()->getLastInsertID($sequenceName);

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...
422
    }
423
424 918
    public function getLogger(): LoggerInterface
425
    {
426
        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...
427 462
    }
428
429 462
    /**
430
     * Returns the currently active master connection.
431
     *
432 495
     * If this method is called for the first time, it will try to open a master connection.
433
     *
434 495
     * @throws InvalidConfigException
435
     *
436
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
437 495
     */
438
    public function getMaster(): ?Connection
439 495
    {
440
        if ($this->master === null) {
441
            $this->master = $this->shuffleMasters
442
                ? $this->openFromPool($this->masters)
443
                : $this->openFromPoolSequentially($this->masters);
444
        }
445
446
        return $this->master;
447 6
    }
448
449 6
    /**
450
     * Returns the PDO instance for the currently active master connection.
451
     *
452 443
     * This method will open the master DB connection and then return {@see pdo}.
453
     *
454 443
     * @throws Exception
455
     *
456
     * @return PDO the PDO instance for the currently active master connection.
457 1
     */
458
    public function getMasterPdo(): PDO
459 1
    {
460
        $this->open();
461
462
        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...
463
    }
464
465
    public function getPassword(): ?string
466
    {
467 31
        return $this->password;
468
    }
469 31
470
    /**
471
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
472
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
473
     * it will be null.
474
     *
475
     * @return PDO|null
476
     *
477
     * {@see pdoClass}
478
     */
479
    public function getPDO(): ?PDO
480
    {
481
        return $this->pdo;
482
    }
483
484
    public function getProfiler(): profiler
485
    {
486
        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...
487
    }
488
489
    /**
490
     * Returns the query builder for the current DB connection.
491
     *
492
     * @throws Exception
493
     * @throws InvalidConfigException
494
     * @throws NotSupportedException
495
     *
496
     * @return QueryBuilder the query builder for the current DB connection.
497
     */
498
    public function getQueryBuilder(): QueryBuilder
499
    {
500 9
        return $this->getSchema()->getQueryBuilder();
501
    }
502 9
503 9
    public function getQueryCacheDuration(): ?int
504 5
    {
505 7
        return $this->queryCacheDuration;
506
    }
507
508 9
    /**
509
     * Returns the current query cache information.
510
     *
511
     * This method is used internally by {@see Command}.
512
     *
513
     * @param int|null $duration the preferred caching duration. If null, it will be ignored.
514
     * @param Dependency|null $dependency the preferred caching dependency. If null, it will be
515
     * ignored.
516
     *
517
     * @return array|null the current query cache information, or null if query cache is not enabled.
518
     */
519
    public function getQueryCacheInfo(?int $duration, ?Dependency $dependency): ?array
520 540
    {
521
        $result = null;
522 540
523
        if ($this->enableQueryCache) {
524 540
            $info = \end($this->queryCacheInfo);
525
526
            if (\is_array($info)) {
527 6
                if ($duration === null) {
528
                    $duration = $info[0];
529 6
                }
530
531
                if ($dependency === null) {
532
                    $dependency = $info[1];
533
                }
534
            }
535
536
            if ($duration === 0 || $duration > 0) {
537
                if ($this->schemaCache instanceof CacheInterface) {
538
                    $result = [$this->schemaCache, $duration, $dependency];
539
                }
540
            }
541 111
        }
542
543 111
        return $result;
544
    }
545
546
    public function getSchemaCache(): CacheInterface
547
    {
548
        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...
549
    }
550
551
    public function getSchemaCacheDuration(): int
552
    {
553
        return $this->schemaCacheDuration;
554
    }
555 179
556
    public function getSchemaCacheExclude(): array
557 179
    {
558
        return $this->schemaCacheExclude;
559
    }
560 6
561
    /**
562 6
     * Returns a server version as a string comparable by {@see \version_compare()}.
563
     *
564
     * @throws Exception
565
     * @throws InvalidConfigException
566
     * @throws NotSupportedException
567
     *
568
     * @return string server version as a string.
569
     */
570
    public function getServerVersion(): string
571
    {
572
        return $this->getSchema()->getServerVersion();
573
    }
574
575
    /**
576 477
     * Returns the currently active slave connection.
577
     *
578 477
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
579
     * is true.
580 477
     *
581 477
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
582
     * available.
583 477
     *
584 6
     * @throws InvalidConfigException
585 6
     *
586
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
587
     * `$fallbackToMaster` is false.
588 6
     */
589 6
    public function getSlave(bool $fallbackToMaster = true): ?Connection
590
    {
591
        if (!$this->enableSlaves) {
592
            return $fallbackToMaster ? $this : null;
593 477
        }
594 6
595 6
        if ($this->slave === null) {
596
            $this->slave = $this->openFromPool($this->slaves);
597
        }
598
599
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
600 477
    }
601
602
    /**
603
     * Returns the PDO instance for the currently active slave connection.
604
     *
605
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
606
     * returned by this method.
607
     *
608
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
609
     *
610
     * @throws Exception
611
     * @throws InvalidConfigException
612 899
     *
613
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
614 899
     * is available and `$fallbackToMaster` is false.
615 594
     */
616
    public function getSlavePdo(bool $fallbackToMaster = true): PDO
617
    {
618 899
        $db = $this->getSlave(false);
619
620 899
        if ($db === null) {
621 899
            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...
622
        }
623 899
624
        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...
625
    }
626
627
    public function getTablePrefix(): string
628
    {
629 900
        return $this->tablePrefix;
630
    }
631 900
632
    /**
633
     * Obtains the schema information for the named table.
634 395
     *
635
     * @param string $name table name.
636 395
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
637
     *
638
     * @throws Exception
639 443
     * @throws InvalidConfigException
640
     * @throws NotSupportedException
641 443
     *
642
     * @return TableSchema
643
     */
644
    public function getTableSchema($name, $refresh = false): ?TableSchema
645
    {
646
        return $this->getSchema()->getTableSchema($name, $refresh);
647
    }
648
649
    /**
650
     * Returns the currently active transaction.
651
     *
652
     * @return Transaction|null the currently active transaction. Null if no active transaction.
653 116
     */
654
    public function getTransaction(): ?Transaction
655 116
    {
656
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
657
    }
658
659
    public function getUsername(): ?string
660
    {
661
        return $this->username;
662
    }
663
664
    /**
665
     * Disables query cache temporarily.
666
     *
667
     * Queries performed within the callable will not use query cache at all. For example,
668
     *
669
     * ```php
670
     * $db->cache(function (Connection $db) {
671
     *
672 530
     *     // ... queries that use query cache ...
673
     *
674 530
     *     return $db->noCache(function (Connection $db) {
675 2
     *         // this query will not use query cache
676
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
677
     *     });
678 530
     * });
679 530
     * ```
680
     *
681
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
682 530
     * of the callable is `function (Connection $db)`.
683
     *
684
     * @throws Throwable if there is any exception during query
685
     *
686
     * @return mixed the return result of the callable
687
     *
688
     * {@see enableQueryCache}
689
     * {@see queryCache}
690
     * {@see cache()}
691
     */
692
    public function noCache(callable $callable)
693
    {
694
        $this->queryCacheInfo[] = false;
695
696
        try {
697
            $result = $callable($this);
698
            array_pop($this->queryCacheInfo);
699 528
700
            return $result;
701 528
        } catch (Throwable $e) {
702
            array_pop($this->queryCacheInfo);
703 528
704 525
            throw $e;
705
        }
706
    }
707 4
708
    /**
709
     * Establishes a DB connection.
710 69
     *
711
     * It does nothing if a DB connection has already been established.
712 69
     *
713
     * @throws Exception if connection fails
714
     * @throws InvalidArgumentException
715
     */
716
    public function open()
717
    {
718
        if (!empty($this->pdo)) {
719
            return null;
720
        }
721
722
        if (!empty($this->masters)) {
723
            $db = $this->getMaster();
724
725
            if ($db !== null) {
726
                $this->pdo = $db->getPDO();
727 53
728
                return null;
729 53
            }
730
731
            throw new InvalidConfigException('None of the master DB servers is available.');
732
        }
733
734
        if (empty($this->dsn)) {
735
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
736
        }
737 504
738
        $token = 'Opening DB connection: ' . $this->dsn;
739 504
740
        try {
741
            if ($this->enableLogging) {
742 455
                $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

742
                $this->logger->/** @scrutinizer ignore-call */ 
743
                               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...
743
            }
744 455
745
            if ($this->enableProfiling) {
746
                $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

746
                $this->profiler->/** @scrutinizer ignore-call */ 
747
                                 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...
747
            }
748
749
            $this->pdo = $this->createPdoInstance();
0 ignored issues
show
introduced by
The method createPdoInstance() does not exist on Yiisoft\Db\Connection\Connection. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

749
            /** @scrutinizer ignore-call */ 
750
            $this->pdo = $this->createPdoInstance();
Loading history...
750
751
            $this->initConnection();
0 ignored issues
show
introduced by
The method initConnection() does not exist on Yiisoft\Db\Connection\Connection. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

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

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

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