Passed
Pull Request — master (#161)
by Wilmer
10:34
created

Connection::open()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 9.0076

Importance

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

824
            $this->logger->/** @scrutinizer ignore-call */ 
825
                           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...
825 1124
826
            if ($this->enableProfiling) {
827 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

827
                $this->profiler->/** @scrutinizer ignore-call */ 
828
                                 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...
828
            }
829 1124
830 1124
            $this->pdo = $this->createPdoInstance();
831
832 9
            $this->initConnection();
833 9
834 9
            if ($this->enableProfiling) {
835 9
                $this->profiler->end($token, [__METHOD__]);
836
            }
837
        } catch (\PDOException $e) {
838 9
            if ($this->enableProfiling) {
839
                $this->logger->log(LogLevel::ERROR, $token);
840 1124
                $this->profiler->end($token, [__METHOD__]);
841
            }
842
843
            throw new Exception($e->getMessage(), $e->errorInfo, (string) $e->getCode(), $e);
844
        }
845
    }
846
847 1145
    /**
848
     * Closes the currently active DB connection.
849 1145
     *
850 9
     * It does nothing if the connection is already closed.
851 7
     */
852
    public function close(): void
853
    {
854 9
        if ($this->master) {
855
            if ($this->pdo === $this->master->getPDO()) {
856 9
                $this->pdo = null;
857
            }
858
859 1145
            $this->master->close();
860 738
861
            $this->master = null;
862 738
        }
863 738
864 738
        if ($this->pdo !== null) {
865
            $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
866
867 1145
            $this->pdo = null;
868 6
            $this->schema = null;
869 6
            $this->transaction = null;
870
        }
871 1145
872
        if ($this->slave) {
873
            $this->slave->close();
874
            $this->slave = null;
875
        }
876
    }
877
878
    /**
879
     * Creates the PDO instance.
880
     *
881 1124
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
882
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
883 1124
     *
884
     * @return PDO the pdo instance
885 1124
     */
886 1124
    protected function createPdoInstance(): PDO
887
    {
888 1124
        $pdoClass = $this->pdoClass;
889 64
890 1064
        if ($pdoClass === null) {
891 1064
            $pdoClass = 'PDO';
892
893
            if ($this->driverName !== null) {
894 1124
                $driver = $this->driverName;
895 1124
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
896
                $driver = strtolower(substr($this->dsn, 0, $pos));
897 1124
            }
898
899
            if (isset($driver)) {
900
                if ($driver === 'mssql' || $driver === 'dblib') {
901
                    $pdoClass = Yiisoft\Db\Mssql\Pdo\PDO::class;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\Yiisoft\Db\Mssql\Pdo\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...
902
                } 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...
903 1124
                    $pdoClass = Yiisoft\Db\Mssql\Pdo\SqlsrvPDO::class;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\Yi...\Db\Mssql\Pdo\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...
904
                }
905 1124
            }
906
        }
907
908
        $dsn = $this->dsn;
909 1124
910
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
911
            $dsn = 'sqlite:' . substr($dsn, 7);
912
        }
913
914
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
915
    }
916
917
    /**
918 1124
     * Initializes the DB connection.
919
     *
920 1124
     * This method is invoked right after the DB connection is established. The default implementation turns on
921
     * `PDO::ATTR_EMULATE_PREPARES` if {@see emulatePrepare} is true. It then triggers an {@see EVENT_AFTER_OPEN} event.
922 1124
     */
923
    protected function initConnection(): void
924
    {
925
        $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

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

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