Passed
Push — master ( f4eeb8...0d22ee )
by Sergei
11:47 queued 01:39
created

Connection::isAutoSlaveForReadQueriesEnabled()   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\Dependency\Dependency;
13
use Yiisoft\Db\AwareTrait\LoggerAwareTrait;
14
use Yiisoft\Db\AwareTrait\ProfilerAwareTrait;
15
use Yiisoft\Db\Cache\QueryCache;
16
use Yiisoft\Db\Command\Command;
17
use Yiisoft\Db\Exception\Exception;
18
use Yiisoft\Db\Exception\InvalidCallException;
19
use Yiisoft\Db\Exception\InvalidConfigException;
20
use Yiisoft\Db\Exception\NotSupportedException;
21
use Yiisoft\Db\Query\QueryBuilder;
22
use Yiisoft\Db\Schema\Schema;
23
use Yiisoft\Db\Schema\TableSchema;
24
use Yiisoft\Db\Transaction\Transaction;
25
26
use function array_keys;
27
use function str_replace;
28
use function strncmp;
29
30
/**
31
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
32
 *
33
 * Connection works together with {@see Command}, {@see DataReader} and {@see Transaction} to provide data access to
34
 * various DBMS in a common set of APIs. They are a thin wrapper of the
35
 * [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
36
 *
37
 * Connection supports database replication and read-write splitting. In particular, a Connection component can be
38
 * configured with multiple {@see setMaster()} and {@see setSlave()}. It will do load balancing and failover by
39
 * choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations
40
 * to the masters.
41
 *
42
 * To establish a DB connection, set {@see dsn}, {@see setUsername()} and {@see setPassword}, and then call
43
 * {@see open()} to connect to the database server. The current state of the connection can be checked using
44
 * {@see $isActive}.
45
 *
46
 * The following example shows how to create a Connection instance and establish the DB connection:
47
 *
48
 * ```php
49
 * $connection = new \Yiisoft\Db\Mysql\Connection($dsn, $queryCache);
50
 * $connection->open();
51
 * ```
52
 *
53
 * After the DB connection is established, one can execute SQL statements like the following:
54
 *
55
 * ```php
56
 * $command = $connection->createCommand('SELECT * FROM post');
57
 * $posts = $command->queryAll();
58
 * $command = $connection->createCommand('UPDATE post SET status=1');
59
 * $command->execute();
60
 * ```
61
 *
62
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
63
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
64
 * following is an example:
65
 *
66
 * ```php
67
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
68
 * $command->bindValue(':id', $_GET['id']);
69
 * $post = $command->query();
70
 * ```
71
 *
72
 * For more information about how to perform various DB queries, please refer to {@see Command}.
73
 *
74
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
75
 *
76
 * ```php
77
 * $transaction = $connection->beginTransaction();
78
 * try {
79
 *     $connection->createCommand($sql1)->execute();
80
 *     $connection->createCommand($sql2)->execute();
81
 *     // ... executing other SQL statements ...
82
 *     $transaction->commit();
83
 * } catch (Exceptions $e) {
84
 *     $transaction->rollBack();
85
 * }
86
 * ```
87
 *
88
 * You also can use shortcut for the above like the following:
89
 *
90
 * ```php
91
 * $connection->transaction(function () {
92
 *     $order = new Order($customer);
93
 *     $order->save();
94
 *     $order->addItems($items);
95
 * });
96
 * ```
97
 *
98
 * If needed you can pass transaction isolation level as a second parameter:
99
 *
100
 * ```php
101
 * $connection->transaction(function (ConnectionInterface $db) {
102
 *     //return $db->...
103
 * }, Transaction::READ_UNCOMMITTED);
104
 * ```
105
 *
106
 * Connection is often used as an application component and configured in the container-di configuration like the
107
 * following:
108
 *
109
 * ```php
110
 * Connection::class => static function (ContainerInterface $container) {
111
 *     $connection = new Connection(
112
 *         $container->get(CacheInterface::class),
113
 *         $container->get(LoggerInterface::class),
114
 *         $container->get(Profiler::class),
115
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
116
 *     );
117
 *
118
 *     $connection->setUsername(root);
119
 *     $connection->setPassword('');
120
 *
121
 *     return $connection;
122
 * },
123
 * ```
124
 *
125
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Connection\Dsn}:
126
 *
127
 * ```php
128
 * Connection::class => static function (ContainerInterface $container) {
129
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
130
 *
131
 *     $connection = new Connection(
132
 *         $container->get(CacheInterface::class),
133
 *         $container->get(LoggerInterface::class),
134
 *         $container->get(Profiler::class),
135
 *         $dsn->getDsn()
136
 *     );
137
 *
138
 *     $connection->setUsername(root);
139
 *     $connection->setPassword('');
140
 *
141
 *     return $connection;
142
 * },
143
 * ```
144
 *
145
 * @property string $driverName Name of the DB driver.
146
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
147
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
148
 * object. This property is read-only.
149
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
150
 * available. This property is read-only.
151
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
152
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
153
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
154
 * @property Schema $schema The schema information for the database opened by this connection. This property is
155
 * read-only.
156
 * @property string $serverVersion Server version as a string. This property is read-only.
157
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
158
 * available and `$fallbackToMaster` is false. This property is read-only.
159
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
160
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
161
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
162
 * property is read-only.
163
 */
164
abstract class Connection implements ConnectionInterface
165
{
166
    use LoggerAwareTrait;
167
    use ProfilerAwareTrait;
168
169
    private string $dsn;
170
    private ?string $username = null;
171
    private ?string $password = null;
172
    private array $attributes = [];
173
    private ?string $charset = null;
174
    private ?bool $emulatePrepare = null;
175
    private string $tablePrefix = '';
176
    private bool $enableSavepoint = true;
177
    private int $serverRetryInterval = 600;
178
    private bool $enableSlaves = true;
179
    private bool $enableAutoSlaveForReadQueries = true;
180
    private array $slaves = [];
181
    private array $masters = [];
182
    private bool $shuffleMasters = true;
183
    private array $quotedTableNames = [];
184
    private array $quotedColumnNames = [];
185
    private ?Connection $master = null;
186
    private ?Connection $slave = null;
187
    private ?PDO $pdo = null;
188
    private QueryCache $queryCache;
189
    private ?Transaction $transaction = null;
190
191 3034
    public function __construct(string $dsn, QueryCache $queryCache)
192
    {
193 3034
        $this->dsn = $dsn;
194 3034
        $this->queryCache = $queryCache;
195
    }
196
197
    /**
198
     * Creates a command for execution.
199
     *
200
     * @param string|null $sql the SQL statement to be executed
201
     * @param array $params the parameters to be bound to the SQL statement
202
     *
203
     * @throws Exception|InvalidConfigException
204
     *
205
     * @return Command the DB command
206
     */
207
    abstract public function createCommand(?string $sql = null, array $params = []): Command;
208
209
    /**
210
     * Returns the schema information for the database opened by this connection.
211
     *
212
     * @return Schema the schema information for the database opened by this connection.
213
     */
214
    abstract public function getSchema(): Schema;
215
216
    /**
217
     * Creates the PDO instance.
218
     *
219
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
220
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
221
     *
222
     * @return PDO the pdo instance
223
     */
224
    abstract protected function createPdoInstance(): PDO;
225
226
    /**
227
     * Initializes the DB connection.
228
     *
229
     * This method is invoked right after the DB connection is established.
230
     *
231
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
232
     *
233
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
234
     *
235
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
236
     */
237
    abstract protected function initConnection(): void;
238
239
    /**
240
     * Reset the connection after cloning.
241
     */
242 5
    public function __clone()
243
    {
244 5
        $this->master = null;
245 5
        $this->slave = null;
246 5
        $this->transaction = null;
247
248 5
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
249
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
250 5
            $this->pdo = null;
251
        }
252
    }
253
254
    /**
255
     * Close the connection before serializing.
256
     *
257
     * @return array
258
     */
259 6
    public function __sleep(): array
260
    {
261 6
        $fields = (array) $this;
262
263
        unset(
264 6
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
265 6
            $fields["\000" . __CLASS__ . "\000" . 'master'],
266 6
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
267 6
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
268 6
            $fields["\000" . __CLASS__ . "\000" . 'schema']
269
        );
270
271 6
        return array_keys($fields);
272
    }
273
274
    /**
275
     * Starts a transaction.
276
     *
277
     * @param string|null $isolationLevel The isolation level to use for this transaction.
278
     *
279
     * {@see Transaction::begin()} for details.
280
     *
281
     * @throws Exception|InvalidConfigException|NotSupportedException|Throwable
282
     *
283
     * @return Transaction the transaction initiated
284
     */
285 40
    public function beginTransaction(string $isolationLevel = null): Transaction
286
    {
287 40
        $this->open();
288
289 40
        if (($transaction = $this->getTransaction()) === null) {
290 40
            $transaction = $this->transaction = new Transaction($this);
291 40
            if ($this->logger !== null) {
292 40
                $transaction->setLogger($this->logger);
293
            }
294
        }
295
296 40
        $transaction->begin($isolationLevel);
297
298 40
        return $transaction;
299
    }
300
301
    /**
302
     * Uses query cache for the queries performed with the callable.
303
     *
304
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
305
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
306
     *
307
     * For example,
308
     *
309
     * ```php
310
     * // The customer will be fetched from cache if available.
311
     * // If not, the query will be made against DB and cached for use next time.
312
     * $customer = $db->cache(function (ConnectionInterface $db) {
313
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
314
     * });
315
     * ```
316
     *
317
     * Note that query cache is only meaningful for queries that return results. For queries performed with
318
     * {@see Command::execute()}, query cache will not be used.
319
     *
320
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
321
     * The signature of the callable is `function (ConnectionInterface $db)`.
322
     * @param int|null $duration the number of seconds that query results can remain valid in the cache. If this is not
323
     * set, the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will
324
     * never expire.
325
     * @param Dependency|null $dependency the cache dependency associated with the cached query
326
     * results.
327
     *
328
     * @throws Throwable if there is any exception during query
329
     *
330
     * @return mixed the return result of the callable
331
     *
332
     * {@see setEnableQueryCache()}
333
     * {@see queryCache}
334
     * {@see noCache()}
335
     */
336 10
    public function cache(callable $callable, int $duration = null, Dependency $dependency = null)
337
    {
338 10
        $this->queryCache->setInfo(
339 10
            [$duration ?? $this->queryCache->getDuration(), $dependency]
340
        );
341 10
        $result = $callable($this);
342 10
        $this->queryCache->removeLastInfo();
343 10
        return $result;
344
    }
345
346 1866
    public function getAttributes(): array
347
    {
348 1866
        return $this->attributes;
349
    }
350
351 756
    public function getCharset(): ?string
352
    {
353 756
        return $this->charset;
354
    }
355
356 1891
    public function getDsn(): string
357
    {
358 1891
        return $this->dsn;
359
    }
360
361 1492
    public function getEmulatePrepare(): ?bool
362
    {
363 1492
        return $this->emulatePrepare;
364
    }
365
366 10
    public function isSavepointEnabled(): bool
367
    {
368 10
        return $this->enableSavepoint;
369
    }
370
371 1
    public function areSlavesEnabled(): bool
372
    {
373 1
        return $this->enableSlaves;
374
    }
375
376 1729
    public function isAutoSlaveForReadQueriesEnabled(): bool
377
    {
378 1729
        return $this->enableAutoSlaveForReadQueries;
379
    }
380
381
    /**
382
     * Returns a value indicating whether the DB connection is established.
383
     *
384
     * @return bool whether the DB connection is established
385
     */
386 193
    public function isActive(): bool
387
    {
388 193
        return $this->pdo !== null;
389
    }
390
391
    /**
392
     * Returns the ID of the last inserted row or sequence value.
393
     *
394
     * @param string $sequenceName name of the sequence object (required by some DBMS)
395
     *
396
     * @throws Exception
397
     * @throws InvalidCallException
398
     *
399
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
400
     *
401
     * {@see http://php.net/manual/en/pdo.lastinsertid.php'>http://php.net/manual/en/pdo.lastinsertid.php}
402
     */
403 10
    public function getLastInsertID(string $sequenceName = ''): string
404
    {
405 10
        return $this->getSchema()->getLastInsertID($sequenceName);
406
    }
407
408
    /**
409
     * Returns the currently active master connection.
410
     *
411
     * If this method is called for the first time, it will try to open a master connection.
412
     *
413
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
414
     */
415 13
    public function getMaster(): ?self
416
    {
417 13
        if ($this->master === null) {
418 13
            $this->master = $this->shuffleMasters
419 7
                ? $this->openFromPool($this->masters)
420 8
                : $this->openFromPoolSequentially($this->masters);
421
        }
422
423 13
        return $this->master;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->master could return the type Yiisoft\Db\Connection\ConnectionInterface which includes types incompatible with the type-hinted return Yiisoft\Db\Connection\Connection|null. Consider adding an additional type-check to rule them out.
Loading history...
424
    }
425
426
    /**
427
     * Returns the PDO instance for the currently active master connection.
428
     *
429
     * This method will open the master DB connection and then return {@see pdo}.
430
     *
431
     * @throws Exception
432
     *
433
     * @return PDO the PDO instance for the currently active master connection.
434
     */
435 1830
    public function getMasterPdo(): PDO
436
    {
437 1830
        $this->open();
438 1830
        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...
439
    }
440
441 1866
    public function getPassword(): ?string
442
    {
443 1866
        return $this->password;
444
    }
445
446
    /**
447
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
448
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
449
     * it will be null.
450
     *
451
     * @return PDO|null
452
     *
453
     * {@see pdoClass}
454
     */
455 1866
    public function getPDO(): ?PDO
456
    {
457 1866
        return $this->pdo;
458
    }
459
460
    /**
461
     * Returns the query builder for the current DB connection.
462
     *
463
     * @return QueryBuilder the query builder for the current DB connection.
464
     */
465 963
    public function getQueryBuilder(): QueryBuilder
466
    {
467 963
        return $this->getSchema()->getQueryBuilder();
468
    }
469
470 315
    public function getServerVersion(): string
471
    {
472 315
        return $this->getSchema()->getServerVersion();
473
    }
474
475
    /**
476
     * Returns the currently active slave connection.
477
     *
478
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
479
     * is true.
480
     *
481
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
482
     * available.
483
     *
484
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
485
     * `$fallbackToMaster` is false.
486
     */
487 1812
    public function getSlave(bool $fallbackToMaster = true): ?self
488
    {
489 1812
        if (!$this->enableSlaves) {
490 6
            return $fallbackToMaster ? $this : null;
491
        }
492
493 1811
        if ($this->slave === null) {
494 1811
            $this->slave = $this->openFromPool($this->slaves);
495
        }
496
497 1811
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
498
    }
499
500
    /**
501
     * Returns the PDO instance for the currently active slave connection.
502
     *
503
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
504
     * returned by this method.
505
     *
506
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
507
     *
508
     * @throws Exception
509
     *
510
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
511
     * is available and `$fallbackToMaster` is false.
512
     */
513 1810
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
514
    {
515 1810
        $db = $this->getSlave(false);
516
517 1810
        if ($db === null) {
518 1805
            return $fallbackToMaster ? $this->getMasterPdo() : null;
519
        }
520
521 6
        return $db->getPdo();
522
    }
523
524 130
    public function getTablePrefix(): string
525
    {
526 130
        return $this->tablePrefix;
527
    }
528
529 200
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
530
    {
531 200
        return $this->getSchema()->getTableSchema($name, $refresh);
532
    }
533
534
    /**
535
     * Returns the currently active transaction.
536
     *
537
     * @return Transaction|null the currently active transaction. Null if no active transaction.
538
     */
539 1745
    public function getTransaction(): ?Transaction
540
    {
541 1745
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
542
    }
543
544 1990
    public function getUsername(): ?string
545
    {
546 1990
        return $this->username;
547
    }
548
549
    /**
550
     * Disables query cache temporarily.
551
     *
552
     * Queries performed within the callable will not use query cache at all. For example,
553
     *
554
     * ```php
555
     * $db->cache(function (ConnectionInterface $db) {
556
     *
557
     *     // ... queries that use query cache ...
558
     *
559
     *     return $db->noCache(function (ConnectionInterface $db) {
560
     *         // this query will not use query cache
561
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
562
     *     });
563
     * });
564
     * ```
565
     *
566
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
567
     * of the callable is `function (ConnectionInterface $db)`.
568
     *
569
     * @throws Throwable if there is any exception during query
570
     *
571
     * @return mixed the return result of the callable
572
     *
573
     * {@see enableQueryCache}
574
     * {@see queryCache}
575
     * {@see cache()}
576
     */
577 10
    public function noCache(callable $callable)
578
    {
579 10
        $queryCache = $this->queryCache;
580 10
        $queryCache->setInfo(false);
581 10
        $result = $callable($this);
582 10
        $queryCache->removeLastInfo();
583 10
        return $result;
584
    }
585
586
    /**
587
     * Establishes a DB connection.
588
     *
589
     * It does nothing if a DB connection has already been established.
590
     *
591
     * @throws Exception|InvalidConfigException if connection fails
592
     */
593 1866
    public function open(): void
594
    {
595 1866
        if (!empty($this->pdo)) {
596 1697
            return;
597
        }
598
599 1866
        if (!empty($this->masters)) {
600 11
            $db = $this->getMaster();
601
602 11
            if ($db !== null) {
603 8
                $this->pdo = $db->getPDO();
604
605 8
                return;
606
            }
607
608 10
            throw new InvalidConfigException('None of the master DB servers is available.');
609
        }
610
611 1866
        if (empty($this->dsn)) {
612
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
613
        }
614
615 1866
        $token = 'Opening DB connection: ' . $this->dsn;
616
617
        try {
618 1866
            if ($this->logger !== null) {
619 1004
                $this->logger->log(LogLevel::INFO, $token);
620
            }
621
622 1866
            if ($this->profiler !== null) {
623 1004
                $this->profiler->begin($token, [__METHOD__]);
624
            }
625
626 1866
            $this->pdo = $this->createPdoInstance();
627
628 1866
            $this->initConnection();
629
630 1866
            if ($this->profiler !== null) {
631 1866
                $this->profiler->end($token, [__METHOD__]);
632
            }
633 15
        } catch (PDOException $e) {
634 15
            if ($this->profiler !== null) {
635 15
                $this->profiler->end($token, [__METHOD__]);
636
            }
637
638 15
            if ($this->logger !== null) {
639 15
                $this->logger->log(LogLevel::ERROR, $token);
640
            }
641
642 15
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
643
        }
644
    }
645
646
    /**
647
     * Closes the currently active DB connection.
648
     *
649
     * It does nothing if the connection is already closed.
650
     */
651 2940
    public function close(): void
652
    {
653 2940
        if ($this->master) {
654 7
            if ($this->pdo === $this->master->getPDO()) {
655 7
                $this->pdo = null;
656
            }
657
658 7
            $this->master->close();
659
660 7
            $this->master = null;
661
        }
662
663 2940
        if ($this->pdo !== null) {
664 1866
            if ($this->logger !== null) {
665 994
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
666
            }
667
668 1866
            $this->pdo = null;
669 1866
            $this->transaction = null;
670
        }
671
672 2940
        if ($this->slave) {
673 5
            $this->slave->close();
674 5
            $this->slave = null;
675
        }
676
    }
677
678
    /**
679
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
680
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
681
     * {@see logger->log()}.
682
     *
683
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
684
     * @param int $level Transaction level just after {@see beginTransaction()} call.
685
     */
686 10
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
687
    {
688 10
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
689
            /**
690
             * {@see https://github.com/yiisoft/yii2/pull/13347}
691
             */
692
            try {
693 10
                $transaction->rollBack();
694
            } catch (Exception $e) {
695
                if ($this->logger !== null) {
696
                    $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
697
                    /** hide this exception to be able to continue throwing original exception outside */
698
                }
699
            }
700
        }
701
    }
702
703
    /**
704
     * Opens the connection to a server in the pool.
705
     *
706
     * This method implements the load balancing among the given list of the servers.
707
     *
708
     * Connections will be tried in random order.
709
     *
710
     * @param array $pool the list of connection configurations in the server pool
711
     *
712
     * @return Connection|null the opened DB connection, or `null` if no server is available
713
     */
714 1816
    protected function openFromPool(array $pool): ?self
715
    {
716 1816
        shuffle($pool);
717 1816
        return $this->openFromPoolSequentially($pool);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->openFromPoolSequentially($pool) could return the type Yiisoft\Db\Connection\ConnectionInterface which includes types incompatible with the type-hinted return Yiisoft\Db\Connection\Connection|null. Consider adding an additional type-check to rule them out.
Loading history...
718
    }
719
720
    /**
721
     * Opens the connection to a server in the pool.
722
     *
723
     * This method implements the load balancing among the given list of the servers.
724
     *
725
     * Connections will be tried in sequential order.
726
     *
727
     * @param array $pool
728
     *
729
     * @return ConnectionInterface|null the opened DB connection, or `null` if no server is available
730
     */
731 1821
    protected function openFromPoolSequentially(array $pool): ?ConnectionInterface
732
    {
733 1821
        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...
734 1804
            return null;
735
        }
736
737 18
        foreach ($pool as $poolConnetion) {
738 18
            $key = [__METHOD__, $poolConnetion->getDsn()];
739
740
            if (
741 18
                $this->getSchema()->getSchemaCache()->isEnabled() &&
742 18
                $this->getSchema()->getSchemaCache()->getOrSet($key, null, $this->serverRetryInterval)
743
            ) {
744
                /** should not try this dead server now */
745
                continue;
746
            }
747
748
            try {
749 18
                $poolConnetion->open();
750
751 15
                return $poolConnetion;
752 10
            } catch (Exception $e) {
753 10
                if ($this->logger !== null) {
754 10
                    $this->logger->log(
755
                        LogLevel::WARNING,
756 10
                        "Connection ({$poolConnetion->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
757
                    );
758
                }
759
760 10
                if ($this->getSchema()->getSchemaCache()->isEnabled()) {
761
                    /** mark this server as dead and only retry it after the specified interval */
762 5
                    $this->getSchema()->getSchemaCache()->set($key, 1, $this->serverRetryInterval);
763
                }
764
765 10
                return null;
766
            }
767
        }
768
769
        return null;
770
    }
771
772 1602
    public function quoteColumnName(string $name): string
773
    {
774 1602
        return $this->quotedColumnNames[$name]
775 1602
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
776
    }
777
778
    /**
779
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
780
     *
781
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
782
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
783
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
784
     *
785
     * @param string $sql the SQL to be quoted
786
     *
787
     * @return string the quoted SQL
788
     */
789 1855
    public function quoteSql(string $sql): string
790
    {
791 1855
        return preg_replace_callback(
792
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
793 1855
            function ($matches) {
794 689
                if (isset($matches[3])) {
795 569
                    return $this->quoteColumnName($matches[3]);
796
                }
797
798 493
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
799
            },
800
            $sql
801
        );
802
    }
803
804
    /**
805
     * Quotes a table name for use in a query.
806
     *
807
     * If the table name contains schema prefix, the prefix will also be properly quoted.
808
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
809
     * will do nothing.
810
     *
811
     * @param string $name table name
812
     *
813
     * @return string the properly quoted table name
814
     */
815 1396
    public function quoteTableName(string $name): string
816
    {
817 1396
        return $this->quotedTableNames[$name]
818 1396
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
819
    }
820
821
    /**
822
     * Quotes a string value for use in a query.
823
     *
824
     * Note that if the parameter is not a string, it will be returned without change.
825
     *
826
     * @param int|string $value string to be quoted
827
     *
828
     * @throws Exception
829
     *
830
     * @return int|string the properly quoted string
831
     *
832
     * {@see http://php.net/manual/en/pdo.quote.php}
833
     */
834 1017
    public function quoteValue($value)
835
    {
836 1017
        return $this->getSchema()->quoteValue($value);
837
    }
838
839
    /**
840
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
841
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
842
     * attributes.
843
     *
844
     * @param array $value
845
     */
846
    public function setAttributes(array $value): void
847
    {
848
        $this->attributes = $value;
849
    }
850
851
    /**
852
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
853
     * null, meaning using default charset as configured by the database.
854
     *
855
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
856
     * `;charset=UTF-8` to the DSN string.
857
     *
858
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
859
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
860
     *
861
     * @param string|null $value
862
     */
863 2079
    public function setCharset(?string $value): void
864
    {
865 2079
        $this->charset = $value;
866
    }
867
868
    /**
869
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
870
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
871
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
872
     * ATTR_EMULATE_PREPARES value will not be changed.
873
     *
874
     * @param bool $value
875
     */
876 7
    public function setEmulatePrepare(bool $value): void
877
    {
878 7
        $this->emulatePrepare = $value;
879
    }
880
881
    /**
882
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
883
     * support savepoint, setting this property to be true will have no effect.
884
     *
885
     * @param bool $value
886
     */
887 5
    public function setEnableSavepoint(bool $value): void
888
    {
889 5
        $this->enableSavepoint = $value;
890
    }
891
892
    public function setEnableSlaves(bool $value): void
893
    {
894
        $this->enableSlaves = $value;
895
    }
896
897 5
    public function setEnableAutoSlaveForReadQueries(bool $value): void
898
    {
899 5
        $this->enableAutoSlaveForReadQueries = $value;
900
    }
901
902
    /**
903
     * Set connection for master server, you can specify multiple connections, adding the id for each one.
904
     *
905
     * @param string $key index master connection.
906
     * @param ConnectionInterface $db The connection every master.
907
     */
908 14
    public function setMaster(string $key, ConnectionInterface $master): void
909
    {
910 14
        $this->masters[$key] = $master;
911
    }
912
913
    /**
914
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
915
     *
916
     * @param string|null $value
917
     */
918 3034
    public function setPassword(?string $value): void
919
    {
920 3034
        $this->password = $value;
921
    }
922
923
    /**
924
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
925
     *
926
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
927
     */
928
    public function setQueryBuilder(iterable $config): void
929
    {
930
        $builder = $this->getQueryBuilder();
931
932
        foreach ($config as $key => $value) {
933
            $builder->{$key} = $value;
934
        }
935
    }
936
937
    /**
938
     * The retry interval in seconds for dead servers listed in {@see setMaster()} and {@see setSlave()}.
939
     *
940
     * @param int $value
941
     */
942
    public function setServerRetryInterval(int $value): void
943
    {
944
        $this->serverRetryInterval = $value;
945
    }
946
947
    /**
948
     * Whether to shuffle {@see setMaster()} before getting one.
949
     *
950
     * @param bool $value
951
     */
952 12
    public function setShuffleMasters(bool $value): void
953
    {
954 12
        $this->shuffleMasters = $value;
955
    }
956
957
    /**
958
     * Set connection for master slave, you can specify multiple connections, adding the id for each one.
959
     *
960
     * @param string $key index slave connection.
961
     * @param ConnectionInterface $slave The connection every slave.
962
     */
963 9
    public function setSlave(string $key, ConnectionInterface $slave): void
964
    {
965 9
        $this->slaves[$key] = $slave;
966
    }
967
968
    /**
969
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
970
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
971
     *
972
     * @param string $value
973
     */
974 24
    public function setTablePrefix(string $value): void
975
    {
976 24
        $this->tablePrefix = $value;
977
    }
978
979
    /**
980
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
981
     *
982
     * @param string|null $value
983
     */
984 3034
    public function setUsername(?string $value): void
985
    {
986 3034
        $this->username = $value;
987
    }
988
989
    /**
990
     * Executes callback provided in a transaction.
991
     *
992
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
993
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
994
     * for details.
995
     *
996
     *@throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
997
     *
998
     * @return mixed result of callback function
999
     */
1000 25
    public function transaction(callable $callback, string $isolationLevel = null)
1001
    {
1002 25
        $transaction = $this->beginTransaction($isolationLevel);
1003
1004 25
        $level = $transaction->getLevel();
1005
1006
        try {
1007 25
            $result = $callback($this);
1008
1009 15
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1010 15
                $transaction->commit();
1011
            }
1012 10
        } catch (Throwable $e) {
1013 10
            $this->rollbackTransactionOnLevel($transaction, $level);
1014
1015 10
            throw $e;
1016
        }
1017
1018 15
        return $result;
1019
    }
1020
1021
    /**
1022
     * Executes the provided callback by using the master connection.
1023
     *
1024
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1025
     * even if they are read queries. For example,
1026
     *
1027
     * ```php
1028
     * $result = $db->useMaster(function (ConnectionInterface $db) {
1029
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1030
     * });
1031
     * ```
1032
     *
1033
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1034
     * `function (ConnectionInterface $db)`. Its return value will be returned by this method.
1035
     *
1036
     * @throws Throwable if there is any exception thrown from the callback
1037
     *
1038
     * @return mixed the return value of the callback
1039
     */
1040 7
    public function useMaster(callable $callback)
1041
    {
1042 7
        if ($this->enableSlaves) {
1043 7
            $this->enableSlaves = false;
1044
1045
            try {
1046 7
                $result = $callback($this);
1047 1
            } catch (Throwable $e) {
1048 1
                $this->enableSlaves = true;
1049
1050 1
                throw $e;
1051
            }
1052 6
            $this->enableSlaves = true;
1053
        } else {
1054
            $result = $callback($this);
1055
        }
1056
1057 6
        return $result;
1058
    }
1059
}
1060