Passed
Push — master ( 6bbfff...4d4eb6 )
by Alexander
06:37 queued 04:34
created

Connection::getServerVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

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