Passed
Push — master ( 7be875...4e97ca )
by Alexander
02:16
created

Connection::getMasterPdo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
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 Psr\Log\LoggerInterface;
9
use Psr\Log\LogLevel;
10
use Yiisoft\Cache\CacheInterface;
11
use Yiisoft\Cache\Dependency\Dependency;
12
use Yiisoft\Db\Command\Command;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidCallException;
15
use Yiisoft\Db\Exception\InvalidConfigException;
16
use Yiisoft\Db\Exception\NotSupportedException;
17
use Yiisoft\Db\Factory\DatabaseFactory;
18
use Yiisoft\Db\Query\QueryBuilder;
19
use Yiisoft\Db\Schema\Schema;
20
use Yiisoft\Db\Schema\TableSchema;
21
use Yiisoft\Db\Transaction\Transaction;
22
use Yiisoft\Profiler\Profiler;
23
24
/**
25
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
26
 *
27
 * Connection works together with {@see Command}, {@see DataReader} and {@see Transaction} to provide data access to
28
 * various DBMS in a common set of APIs. They are a thin wrapper of the
29
 * [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
30
 *
31
 * Connection supports database replication and read-write splitting. In particular, a Connection component can be
32
 * configured with multiple {@see setMasters()} and {@see setSlaves()}. It will do load balancing and failover by
33
 * choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations
34
 * to the masters.
35
 *
36
 * To establish a DB connection, set {@see dsn}, {@see setUsername()} and {@see setPassword}, and then call
37
 * {@see open()} to connect to the database server. The current state of the connection can be checked using
38
 * {@see $isActive}.
39
 *
40
 * The following example shows how to create a Connection instance and establish the DB connection:
41
 *
42
 * ```php
43
 * $connection = new \Yiisoft\Db\Connection\Connection(
44
 *     $cache,
45
 *     $logger,
46
 *     $profiler,
47
 *     $dsn
48
 * );
49
 * $connection->open();
50
 * ```
51
 *
52
 * After the DB connection is established, one can execute SQL statements like the following:
53
 *
54
 * ```php
55
 * $command = $connection->createCommand('SELECT * FROM post');
56
 * $posts = $command->queryAll();
57
 * $command = $connection->createCommand('UPDATE post SET status=1');
58
 * $command->execute();
59
 * ```
60
 *
61
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
62
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
63
 * following is an example:
64
 *
65
 * ```php
66
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
67
 * $command->bindValue(':id', $_GET['id']);
68
 * $post = $command->query();
69
 * ```
70
 *
71
 * For more information about how to perform various DB queries, please refer to {@see Command}.
72
 *
73
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
74
 *
75
 * ```php
76
 * $transaction = $connection->beginTransaction();
77
 * try {
78
 *     $connection->createCommand($sql1)->execute();
79
 *     $connection->createCommand($sql2)->execute();
80
 *     // ... executing other SQL statements ...
81
 *     $transaction->commit();
82
 * } catch (Exceptions $e) {
83
 *     $transaction->rollBack();
84
 * }
85
 * ```
86
 *
87
 * You also can use shortcut for the above like the following:
88
 *
89
 * ```php
90
 * $connection->transaction(function () {
91
 *     $order = new Order($customer);
92
 *     $order->save();
93
 *     $order->addItems($items);
94
 * });
95
 * ```
96
 *
97
 * If needed you can pass transaction isolation level as a second parameter:
98
 *
99
 * ```php
100
 * $connection->transaction(function (Connection $db) {
101
 *     //return $db->...
102
 * }, Transaction::READ_UNCOMMITTED);
103
 * ```
104
 *
105
 * Connection is often used as an application component and configured in the container-di configuration like the
106
 * following:
107
 *
108
 * ```php
109
 * Connection::class => static function (ContainerInterface $container) {
110
 *     $connection = new Connection(
111
 *         $container->get(CacheInterface::class),
112
 *         $container->get(LoggerInterface::class),
113
 *         $container->get(Profiler::class),
114
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
115
 *     );
116
 *
117
 *     $connection->setUsername(root);
118
 *     $connection->setPassword('');
119
 *
120
 *     return $connection;
121
 * },
122
 * ```
123
 *
124
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Helper\Dsn}:
125
 *
126
 * ```php
127
 * Connection::class => static function (ContainerInterface $container) {
128
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
129
 *
130
 *     $connection = new Connection(
131
 *         $container->get(CacheInterface::class),
132
 *         $container->get(LoggerInterface::class),
133
 *         $container->get(Profiler::class),
134
 *         $dsn->getDsn()
135
 *     );
136
 *
137
 *     $connection->setUsername(root);
138
 *     $connection->setPassword('');
139
 *
140
 *     return $connection;
141
 * },
142
 * ```
143
 *
144
 * @property string $driverName Name of the DB driver.
145
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
146
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
147
 * object. This property is read-only.
148
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
149
 * available. This property is read-only.
150
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
151
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
152
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
153
 * @property Schema $schema The schema information for the database opened by this connection. This property is
154
 * read-only.
155
 * @property string $serverVersion Server version as a string. This property is read-only.
156
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
157
 * available and `$fallbackToMaster` is false. This property is read-only.
158
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
159
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
160
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
161
 * property is read-only.
162
 */
163
class Connection
164
{
165
    private ?string $driverName = null;
166
    private ?string $dsn = null;
167
    private ?string $username = null;
168
    private ?string $password = null;
169
    private array $attributes = [];
170
    private ?PDO $pdo = null;
171
    private bool $enableSchemaCache = true;
172
    private int $schemaCacheDuration = 3600;
173
    private array $schemaCacheExclude = [];
174
    private ?CacheInterface $schemaCache = null;
175
    private bool $enableQueryCache = true;
176
    private ?CacheInterface $queryCache = null;
177
    private ?string $charset = null;
178
    private ?bool $emulatePrepare = null;
179
    private string $tablePrefix = '';
180
181
    /**
182
     * @var array mapping between PDO driver names and {@see Schema} classes. The keys of the array are PDO driver names
183
     * while the values are either the corresponding schema class names or configurations.
184
     *
185
     * This property is mainly used by {@see getSchema()} when fetching the database schema information. You normally do
186
     * not need to set this property unless you want to use your own {@see Schema} class to support DBMS that is not
187
     * supported by Yii.
188
     */
189
    private array $schemaMap = [
190
        'pgsql' => \Yiisoft\Db\Pgsql\Schema\Schema::class, // PostgreSQL
191
        'mysqli' => \Yiisoft\Db\Mysql\Schema\Schema::class, // MySQL
192
        'mysql' => \Yiisoft\Db\Mysql\Schema\Schema::class, // MySQL
193
        'sqlite' => \Yiisoft\Db\Sqlite\Schema\Schema::class, // sqlite 3
194
        'sqlite2' => \Yiisoft\Db\Sqlite\Schema\Schema::class, // sqlite 2
195
        'sqlsrv' => \Yiisoft\Db\Mssql\Schema::class, // newer MSSQL driver on MS Windows hosts
196
        'oci' => \Yiisoft\Db\Oci\Schema::class, // Oracle driver
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Oci\Schema was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
197
        'mssql' => \Yiisoft\Db\Mssql\Schema::class, // older MSSQL driver on MS Windows hosts
198
        'dblib' => \Yiisoft\Db\Mssql\Schema::class, // dblib drivers on GNU/Linux (and maybe other OSes) hosts
199
    ];
200
201
    /**
202
     * @var string Custom PDO wrapper class. If not set, it will use {@see PDO} or {@see \Yiisoft\Db\mssql\PDO}
203
     * when MSSQL is used.
204
     *
205
     * @see pdo
206
     */
207
    private ?string $pdoClass = null;
208
209
    /**
210
     * @var array mapping between PDO driver names and {@see Command} classes. The keys of the array are PDO driver
211
     * names while the values are either the corresponding command class names or configurations.
212
     *
213
     * This property is mainly used by {@see createCommand()} to create new database {@see Command} objects. You
214
     * normally do not need to set this property unless you want to use your own {@see Command} class or support
215
     * DBMS that is not supported by Yii.
216
     */
217
    private array $commandMap = [
218
        'pgsql'   => Command::class, // PostgreSQL
219
        'mysqli'  => Command::class, // MySQL
220
        'mysql'   => Command::class, // MySQL
221
        'mariadb' => Command::class, // MySQL
222
        'sqlite'  => \Yiisoft\Db\Sqlite\Command\Command::class, // sqlite 3
223
        'sqlite2' => \Yiisoft\Db\Sqlite\Command\Command::class, // sqlite 2
224
        'sqlsrv'  => Command::class, // newer MSSQL driver on MS Windows hosts
225
        'oci'     => Command::class, // Oracle driver
226
        'mssql'   => Command::class, // older MSSQL driver on MS Windows hosts
227
        'dblib'   => Command::class, // dblib drivers on GNU/Linux (and maybe other OSes) hosts
228
    ];
229
230
    /**
231
     * @var array query cache parameters for the {cache()} calls
232
     */
233
    private array $queryCacheInfo = [];
234
235
    private bool $enableSavepoint = true;
236
    private int $serverRetryInterval = 600;
237
    private bool $enableSlaves = true;
238
    private array $slaves = [];
239
    private array $masters = [];
240
    private bool $shuffleMasters = true;
241
    private bool $enableLogging = true;
242
    private bool $enableProfiling = true;
243
    private int $queryCacheDuration = 3600;
244
    private array $quotedTableNames = [];
245
    private array $quotedColumnNames = [];
246
    private ?Connection $master = null;
247
    private ?Connection $slave = null;
248
    private ?LoggerInterface $logger = null;
249
    private ?Profiler $profiler = null;
250
    private ?Transaction $transaction = null;
251
    private ?Schema $schema = null;
252
253 1147
    public function __construct(?CacheInterface $cache, LoggerInterface $logger, Profiler $profiler, string $dsn)
254
    {
255 1147
        $this->schemaCache = $cache;
256 1147
        $this->logger = $logger;
257 1147
        $this->profiler = $profiler;
258 1147
        $this->dsn = $dsn;
259 1147
    }
260
261
    /**
262
     * Reset the connection after cloning.
263
     */
264 3
    public function __clone()
265
    {
266 3
        $this->master = null;
267 3
        $this->slave = null;
268 3
        $this->schema = null;
269 3
        $this->transaction = null;
270
271 3
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
272
            /* reset PDO connection, unless its sqlite in-memory, which can only have one connection */
273 3
            $this->pdo = null;
274
        }
275 3
    }
276
277
    /**
278
     * Close the connection before serializing.
279
     *
280
     * @return array
281
     */
282 4
    public function __sleep(): array
283
    {
284 4
        $fields = (array) $this;
285
286
        unset(
287 4
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
288 4
            $fields["\000" . __CLASS__ . "\000" . 'master'],
289 4
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
290 4
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
291 4
            $fields["\000" . __CLASS__ . "\000" . 'schema']
292
        );
293
294 4
        return array_keys($fields);
295
    }
296
297
    /**
298
     * Starts a transaction.
299
     *
300
     * @param string|null $isolationLevel The isolation level to use for this transaction.
301
     *
302
     * {@see Transaction::begin()} for details.
303
     *
304
     * @throws Exception
305
     * @throws InvalidConfigException
306
     * @throws NotSupportedException
307
     *
308
     * @return Transaction the transaction initiated
309
     */
310 24
    public function beginTransaction($isolationLevel = null): Transaction
311
    {
312 24
        $this->open();
313
314 24
        if (($transaction = $this->getTransaction()) === null) {
315 24
            $transaction = $this->transaction = new Transaction($this, $this->logger);
316
        }
317
318 24
        $transaction->begin($isolationLevel);
319
320 24
        return $transaction;
321
    }
322
323
    /**
324
     * Uses query cache for the queries performed with the callable.
325
     *
326
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
327
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
328
     *
329
     * For example,
330
     *
331
     * ```php
332
     * // The customer will be fetched from cache if available.
333
     * // If not, the query will be made against DB and cached for use next time.
334
     * $customer = $db->cache(function (Connection $db) {
335
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
336
     * });
337
     * ```
338
     *
339
     * Note that query cache is only meaningful for queries that return results. For queries performed with
340
     * {@see Command::execute()}, query cache will not be used.
341
     *
342
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
343
     * The signature of the callable is `function (Connection $db)`.
344
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is not set,
345
     * the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will never
346
     * expire.
347
     * @param Dependency $dependency the cache dependency associated with the cached query
348
     * results.
349
     *
350
     * @throws \Throwable if there is any exception during query
351
     *
352
     * @return mixed the return result of the callable
353
     *
354
     * {@see setEnableQueryCache()}
355
     * {@see queryCache}
356
     * {@see noCache()}
357
     */
358 6
    public function cache(callable $callable, $duration = null, $dependency = null)
359
    {
360 6
        $this->queryCacheInfo[] = [$duration ?? $this->queryCacheDuration, $dependency];
361
362
        try {
363 6
            $result = $callable($this);
364
365 6
            array_pop($this->queryCacheInfo);
366
367 6
            return $result;
368
        } catch (\Throwable $e) {
369
            array_pop($this->queryCacheInfo);
370
371
            throw $e;
372
        }
373
    }
374
375
    /**
376
     * Creates a command for execution.
377
     *
378
     * @param string $sql the SQL statement to be executed
379
     * @param array $params the parameters to be bound to the SQL statement
380
     *
381
     * @throws Exception
382
     * @throws InvalidConfigException
383
     *
384
     * @return Command the DB command
385
     */
386 525
    public function createCommand($sql = null, $params = []): Command
387
    {
388 525
        $driver = $this->getDriverName();
389
390 525
        if ($sql !== null) {
391 525
            $sql = $this->quoteSql($sql);
392
        }
393
394
        /** @var Command $command */
395 525
        $command = new $this->commandMap[$driver]($this->profiler, $this->logger, $this, $sql);
396
397 525
        return $command->bindValues($params);
398
    }
399
400
    /**
401
     * Returns the name of the DB driver. Based on the the current {@see dsn}, in case it was not set explicitly by an
402
     * end user.
403
     *
404
     * @throws Exception
405
     * @throws InvalidConfigException
406
     *
407
     * @return string name of the DB driver
408
     */
409 918
    public function getDriverName(): string
410
    {
411 918
        if ($this->driverName === null) {
412 918
            if (($pos = strpos($this->dsn, ':')) !== false) {
413 918
                $this->driverName = strtolower(substr($this->dsn, 0, $pos));
414
            } else {
415
                $this->driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
416
            }
417
        }
418
419 918
        return $this->driverName;
420
    }
421
422 462
    public function getDsn(): ?string
423
    {
424 462
        return $this->dsn;
425
    }
426
427 495
    public function isLoggingEnabled(): bool
428
    {
429 495
        return $this->enableLogging;
430
    }
431
432 495
    public function isProfilingEnabled(): bool
433
    {
434 495
        return $this->enableProfiling;
435
    }
436
437
    public function isQueryCacheEnabled(): bool
438
    {
439
        return $this->enableQueryCache;
440
    }
441
442 6
    public function isSavepointEnabled(): bool
443
    {
444 6
        return $this->enableSavepoint;
445
    }
446
447 443
    public function isSchemaCacheEnabled(): bool
448
    {
449 443
        return $this->enableSchemaCache;
450
    }
451
452 1
    public function areSlavesEnabled(): bool
453
    {
454 1
        return $this->enableSlaves;
455
    }
456
457
    /**
458
     * Returns a value indicating whether the DB connection is established.
459
     *
460
     * @return bool whether the DB connection is established
461
     */
462 31
    public function isActive(): bool
463
    {
464 31
        return $this->pdo !== null;
465
    }
466
467
    /**
468
     * Returns the ID of the last inserted row or sequence value.
469
     *
470
     * @param string $sequenceName name of the sequence object (required by some DBMS)
471
     *
472
     * @throws Exception
473
     * @throws InvalidConfigException
474
     * @throws NotSupportedException
475
     * @throws InvalidCallException
476
     *
477
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
478
     *
479
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
480
     */
481
    public function getLastInsertID($sequenceName = ''): string
482
    {
483
        return $this->getSchema()->getLastInsertID($sequenceName);
484
    }
485
486
    /**
487
     * Returns the currently active master connection.
488
     *
489
     * If this method is called for the first time, it will try to open a master connection.
490
     *
491
     * @throws InvalidConfigException
492
     *
493
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
494
     */
495 9
    public function getMaster(): ?Connection
496
    {
497 9
        if ($this->master === null) {
498 9
            $this->master = $this->shuffleMasters
499 5
                ? $this->openFromPool($this->masters)
500 7
                : $this->openFromPoolSequentially($this->masters);
501
        }
502
503 9
        return $this->master;
504
    }
505
506
    /**
507
     * Returns the PDO instance for the currently active master connection.
508
     *
509
     * This method will open the master DB connection and then return {@see pdo}.
510
     *
511
     * @throws Exception
512
     *
513
     * @return PDO the PDO instance for the currently active master connection.
514
     */
515 540
    public function getMasterPdo(): PDO
516
    {
517 540
        $this->open();
518
519 540
        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...
520
    }
521
522 6
    public function getPassword(): ?string
523
    {
524 6
        return $this->password;
525
    }
526
527
    /**
528
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
529
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
530
     * it will be null.
531
     *
532
     * @return PDO|null
533
     *
534
     * {@see pdoClass}
535
     */
536 110
    public function getPDO(): ?PDO
537
    {
538 110
        return $this->pdo;
539
    }
540
541
    /**
542
     * Returns the query builder for the current DB connection.
543
     *
544
     * @throws Exception
545
     * @throws InvalidConfigException
546
     * @throws NotSupportedException
547
     *
548
     * @return QueryBuilder the query builder for the current DB connection.
549
     */
550 179
    public function getQueryBuilder(): QueryBuilder
551
    {
552 179
        return $this->getSchema()->getQueryBuilder();
553
    }
554
555 6
    public function getQueryCacheDuration(): ?int
556
    {
557 6
        return $this->queryCacheDuration;
558
    }
559
560
    /**
561
     * Returns the current query cache information.
562
     *
563
     * This method is used internally by {@see Command}.
564
     *
565
     * @param int|null $duration the preferred caching duration. If null, it will be ignored.
566
     * @param Dependency|null $dependency the preferred caching dependency. If null, it will be
567
     * ignored.
568
     *
569
     * @return array|null the current query cache information, or null if query cache is not enabled.
570
     */
571 477
    public function getQueryCacheInfo(?int $duration, ?Dependency $dependency): ?array
572
    {
573 477
        $result = null;
574
575 477
        if ($this->enableQueryCache) {
576 477
            $info = \end($this->queryCacheInfo);
577
578 477
            if (\is_array($info)) {
579 6
                if ($duration === null) {
580 6
                    $duration = $info[0];
581
                }
582
583 6
                if ($dependency === null) {
584 6
                    $dependency = $info[1];
585
                }
586
            }
587
588 477
            if ($duration === 0 || $duration > 0) {
589 6
                if ($this->schemaCache instanceof CacheInterface) {
590 6
                    $result = [$this->schemaCache, $duration, $dependency];
591
                }
592
            }
593
        }
594
595 477
        return $result;
596
    }
597
598
    /**
599
     * Returns the schema information for the database opened by this connection.
600
     *
601
     * @throws Exception
602
     * @throws InvalidConfigException
603
     * @throws NotSupportedException if there is no support for the current driver type
604
     *
605
     * @return Schema the schema information for the database opened by this connection.
606
     */
607 899
    public function getSchema(): Schema
608
    {
609 899
        if ($this->schema !== null) {
610 594
            return $this->schema;
611
        }
612
613 899
        $driver = $this->getDriverName();
614
615 899
        if (isset($this->schemaMap[$driver])) {
616 899
            $class = $this->schemaMap[$driver];
617
618 899
            return $this->schema = new $class($this);
619
        }
620
621
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
622
    }
623
624 900
    public function getSchemaCache(): CacheInterface
625
    {
626 900
        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...
627
    }
628
629 395
    public function getSchemaCacheDuration(): int
630
    {
631 395
        return $this->schemaCacheDuration;
632
    }
633
634 443
    public function getSchemaCacheExclude(): array
635
    {
636 443
        return $this->schemaCacheExclude;
637
    }
638
639
    /**
640
     * Returns a server version as a string comparable by {@see \version_compare()}.
641
     *
642
     * @throws Exception
643
     * @throws InvalidConfigException
644
     * @throws NotSupportedException
645
     *
646
     * @return string server version as a string.
647
     */
648 116
    public function getServerVersion(): string
649
    {
650 116
        return $this->getSchema()->getServerVersion();
651
    }
652
653
    /**
654
     * Returns the currently active slave connection.
655
     *
656
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
657
     * is true.
658
     *
659
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
660
     * available.
661
     *
662
     * @throws InvalidConfigException
663
     *
664
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
665
     * `$fallbackToMaster` is false.
666
     */
667 530
    public function getSlave(bool $fallbackToMaster = true): ?Connection
668
    {
669 530
        if (!$this->enableSlaves) {
670 2
            return $fallbackToMaster ? $this : null;
671
        }
672
673 530
        if ($this->slave === null) {
674 530
            $this->slave = $this->openFromPool($this->slaves);
675
        }
676
677 530
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
678
    }
679
680
    /**
681
     * Returns the PDO instance for the currently active slave connection.
682
     *
683
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
684
     * returned by this method.
685
     *
686
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
687
     *
688
     * @throws Exception
689
     * @throws InvalidConfigException
690
     *
691
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
692
     * is available and `$fallbackToMaster` is false.
693
     */
694 528
    public function getSlavePdo(bool $fallbackToMaster = true): PDO
695
    {
696 528
        $db = $this->getSlave(false);
697
698 528
        if ($db === null) {
699 525
            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...
700
        }
701
702 4
        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...
703
    }
704
705 69
    public function getTablePrefix(): string
706
    {
707 69
        return $this->tablePrefix;
708
    }
709
710
    /**
711
     * Obtains the schema information for the named table.
712
     *
713
     * @param string $name table name.
714
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
715
     *
716
     * @throws Exception
717
     * @throws InvalidConfigException
718
     * @throws NotSupportedException
719
     *
720
     * @return TableSchema
721
     */
722 53
    public function getTableSchema($name, $refresh = false): ?TableSchema
723
    {
724 53
        return $this->getSchema()->getTableSchema($name, $refresh);
725
    }
726
727
    /**
728
     * Returns the currently active transaction.
729
     *
730
     * @return Transaction|null the currently active transaction. Null if no active transaction.
731
     */
732 504
    public function getTransaction(): ?Transaction
733
    {
734 504
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
735
    }
736
737 455
    public function getUsername(): ?string
738
    {
739 455
        return $this->username;
740
    }
741
742
    /**
743
     * Disables query cache temporarily.
744
     *
745
     * Queries performed within the callable will not use query cache at all. For example,
746
     *
747
     * ```php
748
     * $db->cache(function (Connection $db) {
749
     *
750
     *     // ... queries that use query cache ...
751
     *
752
     *     return $db->noCache(function (Connection $db) {
753
     *         // this query will not use query cache
754
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
755
     *     });
756
     * });
757
     * ```
758
     *
759
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
760
     * of the callable is `function (Connection $db)`.
761
     *
762
     * @throws \Throwable if there is any exception during query
763
     *
764
     * @return mixed the return result of the callable
765
     *
766
     * {@see enableQueryCache}
767
     * {@see queryCache}
768
     * {@see cache()}
769
     */
770 6
    public function noCache(callable $callable)
771
    {
772 6
        $this->queryCacheInfo[] = false;
773
774
        try {
775 6
            $result = $callable($this);
776 6
            array_pop($this->queryCacheInfo);
777
778 6
            return $result;
779
        } catch (\Throwable $e) {
780
            array_pop($this->queryCacheInfo);
781
782
            throw $e;
783
        }
784
    }
785
786
    /**
787
     * Establishes a DB connection.
788
     *
789
     * It does nothing if a DB connection has already been established.
790
     *
791
     * @throws Exception if connection fails
792
     * @throws InvalidArgumentException
793
     */
794 1124
    public function open()
795
    {
796 1124
        if (!empty($this->pdo)) {
797 538
            return null;
798
        }
799
800 1124
        if (!empty($this->masters)) {
801 7
            $db = $this->getMaster();
802
803 7
            if ($db !== null) {
804 7
                $this->pdo = $db->getPDO();
805
806 7
                return null;
807
            }
808
809 6
            throw new InvalidConfigException('None of the master DB servers is available.');
810
        }
811
812 1124
        if (empty($this->dsn)) {
813
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
814
        }
815
816 1124
        $token = 'Opening DB connection: ' . $this->dsn;
817
818
        try {
819 1124
            $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

819
            $this->logger->/** @scrutinizer ignore-call */ 
820
                           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...
820
821 1124
            if ($this->enableProfiling) {
822 1124
                $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

822
                $this->profiler->/** @scrutinizer ignore-call */ 
823
                                 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...
823
            }
824
825 1124
            $this->pdo = $this->createPdoInstance();
826
827 1124
            $this->initConnection();
828
829 1124
            if ($this->enableProfiling) {
830 1124
                $this->profiler->end($token, [__METHOD__]);
831
            }
832 9
        } catch (\PDOException $e) {
833 9
            if ($this->enableProfiling) {
834 9
                $this->logger->log(LogLevel::ERROR, $token);
835 9
                $this->profiler->end($token, [__METHOD__]);
836
            }
837
838 9
            throw new Exception($e->getMessage(), $e->errorInfo, (string) $e->getCode(), $e);
839
        }
840 1124
    }
841
842
    /**
843
     * Closes the currently active DB connection.
844
     *
845
     * It does nothing if the connection is already closed.
846
     */
847 1145
    public function close(): void
848
    {
849 1145
        if ($this->master) {
850 9
            if ($this->pdo === $this->master->getPDO()) {
851 7
                $this->pdo = null;
852
            }
853
854 9
            $this->master->close();
855
856 9
            $this->master = null;
857
        }
858
859 1145
        if ($this->pdo !== null) {
860 738
            $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
861
862 738
            $this->pdo = null;
863 738
            $this->schema = null;
864 738
            $this->transaction = null;
865
        }
866
867 1145
        if ($this->slave) {
868 6
            $this->slave->close();
869 6
            $this->slave = null;
870
        }
871 1145
    }
872
873
    /**
874
     * Creates the PDO instance.
875
     *
876
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
877
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
878
     *
879
     * @return PDO the pdo instance
880
     */
881 1124
    protected function createPdoInstance(): PDO
882
    {
883 1124
        $pdoClass = $this->pdoClass;
884
885 1124
        if ($pdoClass === null) {
886 1124
            $pdoClass = 'PDO';
887
888 1124
            if ($this->driverName !== null) {
889 64
                $driver = $this->driverName;
890 1064
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
891 1064
                $driver = strtolower(substr($this->dsn, 0, $pos));
892
            }
893
894 1124
            if (isset($driver)) {
895 1124
                if ($driver === 'mssql' || $driver === 'dblib') {
896
                    $pdoClass = mssql\PDO::class;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\mssql\PDO was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
897 1124
                } elseif ($driver === 'sqlsrv') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $driver does not seem to be defined for all execution paths leading up to this point.
Loading history...
898
                    $pdoClass = mssql\SqlsrvPDO::class;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\mssql\SqlsrvPDO was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
899
                }
900
            }
901
        }
902
903 1124
        $dsn = $this->dsn;
904
905 1124
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
906
            $dsn = 'sqlite:' . substr($dsn, 7);
907
        }
908
909 1124
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
910
    }
911
912
    /**
913
     * Initializes the DB connection.
914
     *
915
     * This method is invoked right after the DB connection is established. The default implementation turns on
916
     * `PDO::ATTR_EMULATE_PREPARES` if {@see emulatePrepare} is true. It then triggers an {@see EVENT_AFTER_OPEN} event.
917
     */
918 1124
    protected function initConnection(): void
919
    {
920 1124
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
0 ignored issues
show
Bug introduced by
The method setAttribute() 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

920
        $this->pdo->/** @scrutinizer ignore-call */ 
921
                    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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...
921
922 1124
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
923
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
924
        }
925
926 1124
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid', 'mariadb'], true)) {
927
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
928
        }
929
930
        //$this->trigger(self::EVENT_AFTER_OPEN);
931 1124
    }
932
933
    /**
934
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
935
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
936
     * {@see logger->log()}.
937
     *
938
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
939
     * @param int $level Transaction level just after {@see beginTransaction()} call.
940
     *
941
     * @return void
942
     */
943 3
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
944
    {
945 3
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
946
            /* https://github.com/yiisoft/yii2/pull/13347 */
947
            try {
948 3
                $transaction->rollBack();
949
            } catch (Exception $e) {
950
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
951
                /* hide this exception to be able to continue throwing original exception outside */
952
            }
953
        }
954 3
    }
955
956
    /**
957
     * Opens the connection to a server in the pool.
958
     *
959
     * This method implements the load balancing among the given list of the servers.
960
     *
961
     * Connections will be tried in random order.
962
     *
963
     * @param array $pool the list of connection configurations in the server pool
964
     * @param array $sharedConfig the configuration common to those given in `$pool`.
965
     *
966
     * @throws InvalidConfigException
967
     *
968
     * @return Connection|null the opened DB connection, or `null` if no server is available
969
     */
970 533
    protected function openFromPool(array $pool): ?Connection
971
    {
972 533
        shuffle($pool);
973
974 533
        return $this->openFromPoolSequentially($pool);
975
    }
976
977
    /**
978
     * Opens the connection to a server in the pool.
979
     *
980
     * This method implements the load balancing among the given list of the servers.
981
     *
982
     * Connections will be tried in sequential order.
983
     *
984
     * @param array $pool
985
     *
986
     * @throws InvalidConfigException if a configuration does not specify "dsn"
987
     *
988
     * @return Connection|null the opened DB connection, or `null` if no server is available
989
     */
990 536
    protected function openFromPoolSequentially(array $pool): ?Connection
991
    {
992 536
        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...
993 525
            return null;
994
        }
995
996 12
        foreach ($pool as $config) {
997 12
            if (empty($config['dsn'])) {
998
                throw new InvalidConfigException('The "dsn" option must be specified.');
999
            }
1000
1001 12
            $dsn = $config['dsn'];
1002
1003 12
            unset($config['dsn']);
1004
1005 12
            $key = [__METHOD__, $dsn];
1006
1007 12
            $config = array_merge(
1008
                [
1009
                    '__class' => Connection::class,
1010
                    '__construct()' => [
1011 12
                        $this->schemaCache,
1012 12
                        $this->logger,
1013 12
                        $this->profiler,
1014 12
                        $dsn
1015
                    ]
1016
                ],
1017
                $config
1018
            );
1019
1020
            /* @var $db Connection */
1021 12
            $db = DatabaseFactory::createClass($config);
1022
1023 12
            if ($this->schemaCache instanceof CacheInterface && $this->schemaCache->get($key)) {
0 ignored issues
show
Bug introduced by
$key of type array<integer,mixed|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

1023
            if ($this->schemaCache instanceof CacheInterface && $this->schemaCache->get(/** @scrutinizer ignore-type */ $key)) {
Loading history...
1024
                // should not try this dead server now
1025
                continue;
1026
            }
1027
1028
            try {
1029 12
                $db->open();
1030
1031 12
                return $db;
1032 6
            } catch (Exception $e) {
1033 6
                $this->logger->log(
1034 6
                    LogLevel::WARNING,
1035 6
                    "Connection ({$dsn}) failed: " . $e->getMessage() . ' ' . __METHOD__
1036
                );
1037
1038 6
                if ($this->schemaCache instanceof CacheInterface) {
1039
                    // mark this server as dead and only retry it after the specified interval
1040 3
                    $this->schemaCache->set($key, 1, $this->serverRetryInterval);
1041
                }
1042
1043 6
                return null;
1044
            }
1045
        }
1046
    }
1047
1048
    /**
1049
     * Quotes a column name for use in a query.
1050
     *
1051
     * If the column name contains prefix, the prefix will also be properly quoted.
1052
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
1053
     * method will do nothing.
1054
     *
1055
     * @param string $name column name
1056
     *
1057
     * @throws Exception
1058
     * @throws InvalidConfigException
1059
     * @throws NotSupportedException
1060
     * @throws InvalidArgumentException
1061
     *
1062
     * @return string the properly quoted column name
1063
     */
1064 510
    public function quoteColumnName(string $name): string
1065
    {
1066 510
        if (isset($this->quotedColumnNames[$name])) {
1067 187
            return $this->quotedColumnNames[$name];
1068
        }
1069
1070 510
        return $this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
1071
    }
1072
1073
    /**
1074
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
1075
     *
1076
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
1077
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
1078
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
1079
     *
1080
     * @param string $sql the SQL to be quoted
1081
     *
1082
     * @return string the quoted SQL
1083
     */
1084 567
    public function quoteSql(string $sql): string
1085
    {
1086 567
        return preg_replace_callback(
1087 567
            '/(\\{\\{(%?[\w\-\. ]+%?)}}|\\[\\[([\w\-\. ]+)]])/',
1088 567
            function ($matches) {
1089 172
                if (isset($matches[3])) {
1090 142
                    return $this->quoteColumnName($matches[3]);
1091
                }
1092
1093 161
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
1094 567
            },
1095
            $sql
1096
        );
1097
    }
1098
1099
    /**
1100
     * Quotes a table name for use in a query.
1101
     *
1102
     * If the table name contains schema prefix, the prefix will also be properly quoted.
1103
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
1104
     * will do nothing.
1105
     *
1106
     * @param string $name table name
1107
     *
1108
     * @return string the properly quoted table name
1109
     *
1110
     * @throws Exception
1111
     * @throws InvalidConfigException
1112
     * @throws NotSupportedException
1113
     * @throws InvalidArgumentException
1114
     */
1115 395
    public function quoteTableName(string $name): string
1116
    {
1117 395
        if (isset($this->quotedTableNames[$name])) {
1118 194
            return $this->quotedTableNames[$name];
1119
        }
1120
1121 395
        return $this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
1122
    }
1123
1124
    /**
1125
     * Quotes a string value for use in a query.
1126
     *
1127
     * Note that if the parameter is not a string, it will be returned without change.
1128
     *
1129
     * @param string|int $value string to be quoted
1130
     *
1131
     * @throws Exception
1132
     * @throws InvalidConfigException
1133
     * @throws NotSupportedException
1134
     *
1135
     * @return string|int the properly quoted string
1136
     *
1137
     * {@see http://php.net/manual/en/pdo.quote.php}
1138
     */
1139 318
    public function quoteValue($value)
1140
    {
1141 318
        return $this->getSchema()->quoteValue($value);
1142
    }
1143
1144
    /**
1145
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
1146
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
1147
     * attributes.
1148
     *
1149
     * @param array $value
1150
     *
1151
     * @return void
1152
     */
1153
    public function setAttributes(array $value): void
1154
    {
1155
        $this->attributes = $value;
1156
    }
1157
1158
    /**
1159
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
1160
     * null, meaning using default charset as configured by the database.
1161
     *
1162
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
1163
     * `;charset=UTF-8` to the DSN string.
1164
     *
1165
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
1166
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
1167
     *
1168
     * @param string $value
1169
     *
1170
     * @return void
1171
     */
1172
    public function setCharset(?string $value): void
1173
    {
1174
        $this->charset = $value;
1175
    }
1176
1177
    /**
1178
     * Changes the current driver name.
1179
     *
1180
     * @param string $driverName name of the DB driver
1181
     */
1182
    public function setDriverName(string $driverName): void
1183
    {
1184
        $this->driverName = strtolower($driverName);
1185
    }
1186
1187
    /**
1188
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
1189
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
1190
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
1191
     * ATTR_EMULATE_PREPARES value will not be changed.
1192
     *
1193
     * @param bool $value
1194
     *
1195
     * @return void
1196
     */
1197 2
    public function setEmulatePrepare(bool $value): void
1198
    {
1199 2
        $this->emulatePrepare = $value;
1200 2
    }
1201
1202
    /**
1203
     * Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a
1204
     * production environment to gain performance if you do not need the information being logged.
1205
     *
1206
     * @param bool $value
1207
     *
1208
     * @return void
1209
     *
1210
     * {@see setEnableProfiling()}
1211
     */
1212 2
    public function setEnableLogging(bool $value): void
1213
    {
1214 2
        $this->enableLogging = $value;
1215 2
    }
1216
1217
    /**
1218
     * Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want
1219
     * to disable this option in a production environment to gain performance if you do not need the information being
1220
     * logged.
1221
     *
1222
     * @param bool $value
1223
     *
1224
     * @return void
1225
     *
1226
     * {@see setEnableLogging()}
1227
     */
1228 2
    public function setEnableProfiling(bool $value): void
1229
    {
1230 2
        $this->enableProfiling = $value;
1231 2
    }
1232
1233
    /**
1234
     * Whether to enable query caching. Note that in order to enable query caching, a valid cache component as specified
1235
     * by {@see setQueryCache()} must be enabled and {@see enableQueryCache} must be set true. Also, only the results of
1236
     * the queries enclosed within {@see cache()} will be cached.
1237
     *
1238
     * @param bool $value
1239
     *
1240
     * @return void
1241
     *
1242
     * {@see setQueryCache()}
1243
     * {@see cache()}
1244
     * {@see noCache()}
1245
     */
1246 6
    public function setEnableQueryCache(bool $value): void
1247
    {
1248 6
        $this->enableQueryCache = $value;
1249 6
    }
1250
1251
    /**
1252
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
1253
     * support savepoint, setting this property to be true will have no effect.
1254
     *
1255
     * @param bool $value
1256
     *
1257
     * @return void
1258
     */
1259 3
    public function setEnableSavepoint(bool $value): void
1260
    {
1261 3
        $this->enableSavepoint = $value;
1262 3
    }
1263
1264
    /**
1265
     * Whether to enable schema caching. Note that in order to enable truly schema caching, a valid cache component as
1266
     * specified by {@see setSchemaCache()} must be enabled and {@see setEnableSchemaCache()} must be set true.
1267
     *
1268
     * @param bool $value
1269
     *
1270
     * @return void
1271
     *
1272
     * {@see setSchemaCacheDuration()}
1273
     * {@see setSchemaCacheExclude()}
1274
     * {@see setSchemaCache()}
1275
     */
1276 24
    public function setEnableSchemaCache(bool $value): void
1277
    {
1278 24
        $this->enableSchemaCache = $value;
1279 24
    }
1280
1281
    /**
1282
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
1283
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
1284
     *
1285
     * @param bool $value
1286
     *
1287
     * @return void
1288
     */
1289
    public function setEnableSlaves(bool $value): void
1290
    {
1291
        $this->enableSlaves = $value;
1292
    }
1293
1294
    /**
1295
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
1296
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
1297
     *
1298
     * @param string $key index master connection.
1299
     * @param string $dsn the Data Source Name, or DSN, contains the information required to connect to the database
1300
     * @param array $config The configuration that should be merged with every master configuration
1301
     *
1302
     * @return void
1303
     *
1304
     * For example,
1305
     *
1306
     * ```php
1307
     * $connection->setMasters(
1308
     *     '1',
1309
     *     'mysql:host=127.0.0.1;dbname=yiitest;port=3306',
1310
     *     [
1311
     *         'setUsername()' => [$connection->getUsername()],
1312
     *         'setPassword()' => [$connection->getPassword()],
1313
     *     ]
1314
     * );
1315
     * ```
1316
     *
1317
     * {@see setShuffleMasters()}
1318
     */
1319 10
    public function setMasters(string $key, string $dsn, array $config = []): void
1320
    {
1321 10
        $this->masters[$key] = array_merge(['dsn' => $dsn], $config);
1322 10
    }
1323
1324
    /**
1325
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
1326
     *
1327
     * @param string|null $value
1328
     *
1329
     * @return void
1330
     */
1331 795
    public function setPassword(?string $value): void
1332
    {
1333 795
        $this->password = $value;
1334 795
    }
1335
1336
    /**
1337
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
1338
     *
1339
     * @throws Exception
1340
     * @throws InvalidConfigException
1341
     * @throws NotSupportedException
1342
     *
1343
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
1344
     *
1345
     * @return void
1346
     */
1347
    public function setQueryBuilder(iterable $config): void
1348
    {
1349
        $builder = $this->getQueryBuilder();
1350
1351
        foreach ($config as $key => $value) {
1352
            $builder->{$key} = $value;
1353
        }
1354
    }
1355
1356
    /**
1357
     * The cache object or the ID of the cache application component that is used for query caching.
1358
     *
1359
     * @param CacheInterface $value
1360
     *
1361
     * @return void
1362
     *
1363
     * {@see setEnableQueryCache()}
1364
     */
1365 6
    public function setQueryCache(CacheInterface $value): void
1366
    {
1367 6
        $this->queryCache = $value;
1368 6
    }
1369
1370
    /**
1371
     * The default number of seconds that query results can remain valid in cache. Defaults to 3600, meaning 3600
1372
     * seconds, or one hour. Use 0 to indicate that the cached data will never expire. The value of this property will
1373
     * be used when {@see cache()} is called without a cache duration.
1374
     *
1375
     * @param int $value
1376
     *
1377
     * @return void
1378
     *
1379
     * {@see setEnableQueryCache()}
1380
     * {@see cache()}
1381
     */
1382
    public function setQueryCacheDuration(int $value): void
1383
    {
1384
        $this->queryCacheDuration = $value;
1385
    }
1386
1387
    /**
1388
     * The cache object or the ID of the cache application component that is used to cache the table metadata.
1389
     *
1390
     * @param $value
1391
     *
1392
     * @return void
1393
     *
1394
     * {@see setEnableSchemaCache()}
1395
     */
1396 27
    public function setSchemaCache(?CacheInterface $value): void
1397
    {
1398 27
        $this->schemaCache = $value;
1399 27
    }
1400
1401
    /**
1402
     * Number of seconds that table metadata can remain valid in cache. Use 0 to indicate that the cached data will
1403
     * never expire.
1404
     *
1405
     * @param int $value
1406
     *
1407
     * @return void
1408
     *
1409
     * {@see setEnableSchemaCache()}
1410
     */
1411
    public function setSchemaCacheDuration(int $value): void
1412
    {
1413
        $this->schemaCacheDuration = $value;
1414
    }
1415
1416
    /**
1417
     * List of tables whose metadata should NOT be cached. Defaults to empty array. The table names may contain schema
1418
     * prefix, if any. Do not quote the table names.
1419
     *
1420
     * @param array $value
1421
     *
1422
     * @return void
1423
     *
1424
     * {@see setEnableSchemaCache()}
1425
     */
1426
    public function setSchemaCacheExclude(array $value): void
1427
    {
1428
        $this->schemaCacheExclude = $value;
1429
    }
1430
1431
    /**
1432
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
1433
     *
1434
     * @param int $value
1435
     *
1436
     * @return void
1437
     */
1438
    public function setServerRetryInterval(int $value): void
1439
    {
1440
        $this->serverRetryInterval = $value;
1441
    }
1442
1443
    /**
1444
     * Whether to shuffle {@see setMasters()} before getting one.
1445
     *
1446
     * @param bool $value
1447
     *
1448
     * @return void
1449
     *
1450
     * {@see setMasters()}
1451
     */
1452 8
    public function setShuffleMasters(bool $value): void
1453
    {
1454 8
        $this->shuffleMasters = $value;
1455 8
    }
1456
1457
    /**
1458
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
1459
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
1460
     *
1461
     * @param string $key index slave connection.
1462
     * @param string $dsn the Data Source Name, or DSN, contains the information required to connect to the database
1463
     * @param array $config The configuration that should be merged with every slave configuration
1464
     *
1465
     * @return void
1466
     *
1467
     * For example,
1468
     *
1469
     * ```php
1470
     * $connection->setSlaves(
1471
     *     '1',
1472
     *     'mysql:host=127.0.0.1;dbname=yiitest;port=3306',
1473
     *     [
1474
     *         'setUsername()' => [$connection->getUsername()],
1475
     *         'setPassword()' => [$connection->getPassword()],
1476
     *     ]
1477
     * );
1478
     * ```
1479
     *
1480
     * {@see setEnableSlaves()}
1481
     */
1482 7
    public function setSlaves(string $key, string $dsn, array $config = []): void
1483
    {
1484 7
        $this->slaves[$key] = array_merge(['dsn' => $dsn], $config);
1485 7
    }
1486
1487
    /**
1488
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1489
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1490
     *
1491
     * @param string $value
1492
     *
1493
     * @return void
1494
     */
1495 18
    public function setTablePrefix(string $value): void
1496
    {
1497 18
        $this->tablePrefix = $value;
1498 18
    }
1499
1500
    /**
1501
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1502
     *
1503
     * @param string|null $value
1504
     *
1505
     * @return void
1506
     */
1507 795
    public function setUsername(?string $value): void
1508
    {
1509 795
        $this->username = $value;
1510 795
    }
1511
1512
    /**
1513
     * Executes callback provided in a transaction.
1514
     *
1515
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1516
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1517
     * for details.
1518
     *
1519
     * @throws \Throwable if there is any exception during query. In this case the transaction will be rolled back.
1520
     *
1521
     * @return mixed result of callback function
1522
     */
1523 15
    public function transaction(callable $callback, $isolationLevel = null)
1524
    {
1525 15
        $transaction = $this->beginTransaction($isolationLevel);
1526
1527 15
        $level = $transaction->getLevel();
1528
1529
        try {
1530 15
            $result = $callback($this);
1531
1532 12
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1533 12
                $transaction->commit();
1534
            }
1535 3
        } catch (\Throwable $e) {
1536 3
            $this->rollbackTransactionOnLevel($transaction, $level);
1537
1538 3
            throw $e;
1539
        }
1540
1541 12
        return $result;
1542
    }
1543
1544
    /**
1545
     * Executes the provided callback by using the master connection.
1546
     *
1547
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1548
     * even if they are read queries. For example,
1549
     *
1550
     * ```php
1551
     * $result = $db->useMaster(function ($db) {
1552
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1553
     * });
1554
     * ```
1555
     *
1556
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1557
     * `function (Connection $db)`. Its return value will be returned by this method.
1558
     *
1559
     * @throws \Throwable if there is any exception thrown from the callback
1560
     *
1561
     * @return mixed the return value of the callback
1562
     */
1563 3
    public function useMaster(callable $callback)
1564
    {
1565 3
        if ($this->enableSlaves) {
1566 3
            $this->enableSlaves = false;
1567
1568
            try {
1569 3
                $result = $callback($this);
1570 1
            } catch (\Throwable $e) {
1571 1
                $this->enableSlaves = true;
1572
1573 1
                throw $e;
1574
            }
1575 2
            $this->enableSlaves = true;
1576
        } else {
1577
            $result = $callback($this);
1578
        }
1579
1580 2
        return $result;
1581
    }
1582
}
1583