Passed
Pull Request — master (#240)
by Wilmer
12:51
created

Connection::setSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
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\LogLevel;
10
use Psr\Log\LoggerInterface;
11
use Throwable;
12
use Yiisoft\Cache\Dependency\Dependency;
13
use Yiisoft\Db\Cache\QueryCache;
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\ProfilerInterface;
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 setMasters()} and {@see setSlaves()}. 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(
50
 *     $cache,
51
 *     $logger,
52
 *     $profiler,
53
 *     $dsn
54
 * );
55
 * $connection->open();
56
 * ```
57
 *
58
 * After the DB connection is established, one can execute SQL statements like the following:
59
 *
60
 * ```php
61
 * $command = $connection->createCommand('SELECT * FROM post');
62
 * $posts = $command->queryAll();
63
 * $command = $connection->createCommand('UPDATE post SET status=1');
64
 * $command->execute();
65
 * ```
66
 *
67
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
68
 * When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The
69
 * following is an example:
70
 *
71
 * ```php
72
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
73
 * $command->bindValue(':id', $_GET['id']);
74
 * $post = $command->query();
75
 * ```
76
 *
77
 * For more information about how to perform various DB queries, please refer to {@see Command}.
78
 *
79
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
80
 *
81
 * ```php
82
 * $transaction = $connection->beginTransaction();
83
 * try {
84
 *     $connection->createCommand($sql1)->execute();
85
 *     $connection->createCommand($sql2)->execute();
86
 *     // ... executing other SQL statements ...
87
 *     $transaction->commit();
88
 * } catch (Exceptions $e) {
89
 *     $transaction->rollBack();
90
 * }
91
 * ```
92
 *
93
 * You also can use shortcut for the above like the following:
94
 *
95
 * ```php
96
 * $connection->transaction(function () {
97
 *     $order = new Order($customer);
98
 *     $order->save();
99
 *     $order->addItems($items);
100
 * });
101
 * ```
102
 *
103
 * If needed you can pass transaction isolation level as a second parameter:
104
 *
105
 * ```php
106
 * $connection->transaction(function (Connection $db) {
107
 *     //return $db->...
108
 * }, Transaction::READ_UNCOMMITTED);
109
 * ```
110
 *
111
 * Connection is often used as an application component and configured in the container-di configuration like the
112
 * following:
113
 *
114
 * ```php
115
 * Connection::class => static function (ContainerInterface $container) {
116
 *     $connection = new Connection(
117
 *         $container->get(CacheInterface::class),
118
 *         $container->get(LoggerInterface::class),
119
 *         $container->get(Profiler::class),
120
 *         'mysql:host=127.0.0.1;dbname=demo;charset=utf8'
121
 *     );
122
 *
123
 *     $connection->setUsername(root);
124
 *     $connection->setPassword('');
125
 *
126
 *     return $connection;
127
 * },
128
 * ```
129
 *
130
 * The {@see dsn} property can be defined via configuration {@see \Yiisoft\Db\Connection\Dsn}:
131
 *
132
 * ```php
133
 * Connection::class => static function (ContainerInterface $container) {
134
 *     $dsn = new Dsn('mysql', '127.0.0.1', 'yiitest', '3306');
135
 *
136
 *     $connection = new Connection(
137
 *         $container->get(CacheInterface::class),
138
 *         $container->get(LoggerInterface::class),
139
 *         $container->get(Profiler::class),
140
 *         $dsn->getDsn()
141
 *     );
142
 *
143
 *     $connection->setUsername(root);
144
 *     $connection->setPassword('');
145
 *
146
 *     return $connection;
147
 * },
148
 * ```
149
 *
150
 * @property string $driverName Name of the DB driver.
151
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
152
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
153
 * object. This property is read-only.
154
 * @property Connection $master The currently active master connection. `null` is returned if there is no master
155
 * available. This property is read-only.
156
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is read-only.
157
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of this
158
 * property differs in getter and setter. See {@see getQueryBuilder()} and {@see setQueryBuilder()} for details.
159
 * @property Schema $schema The schema information for the database opened by this connection. This property is
160
 * read-only.
161
 * @property string $serverVersion Server version as a string. This property is read-only.
162
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
163
 * available and `$fallbackToMaster` is false. This property is read-only.
164
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if no slave
165
 * connection is available and `$fallbackToMaster` is false. This property is read-only.
166
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction. This
167
 * property is read-only.
168
 */
169
abstract class Connection implements ConnectionInterface
170
{
171
    private string $dsn;
172
    private ?string $username = null;
173
    private ?string $password = null;
174
    private array $attributes = [];
175
    private ?string $charset = null;
176
    private ?bool $emulatePrepare = null;
177
    private string $tablePrefix = '';
178
    private bool $enableSavepoint = true;
179
    private int $serverRetryInterval = 600;
180
    private bool $enableSlaves = true;
181
    private array $slaves = [];
182
    private array $masters = [];
183
    private bool $shuffleMasters = true;
184
    private array $quotedTableNames = [];
185
    private array $quotedColumnNames = [];
186
    private ?Connection $master = null;
187
    private ?Connection $slave = null;
188
    private ?LoggerInterface $logger = null;
189
    private ?PDO $pdo = null;
190
    private ?ProfilerInterface $profiler = null;
191
    private QueryCache $queryCache;
192
    protected ?Schema $schema = null;
193
    private ?Transaction $transaction = null;
194
195
    public function __construct(string $dsn, QueryCache $queryCache)
196 3016
    {
197
        $this->dsn = $dsn;
198 3016
        $this->queryCache = $queryCache;
199 3016
    }
200 3016
201
    /**
202
     * Creates a command for execution.
203
     *
204
     * @param string|null $sql the SQL statement to be executed
205
     * @param array $params the parameters to be bound to the SQL statement
206
     *
207
     * @throws Exception|InvalidConfigException
208
     *
209
     * @return Command the DB command
210
     */
211
    abstract public function createCommand(?string $sql = null, array $params = []): Command;
212
213
    /**
214
     * Returns the schema information for the database opened by this connection.
215
     *
216
     * @return Schema the schema information for the database opened by this connection.
217
     */
218
    abstract public function getSchema(): Schema;
219
220
    /**
221
     * Creates the PDO instance.
222
     *
223
     * This method is called by {@see open} to establish a DB connection. The default implementation will create a PHP
224
     * PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
225
     *
226
     * @return PDO the pdo instance
227
     */
228
    abstract protected function createPdoInstance(): PDO;
229
230
    /**
231
     * Initializes the DB connection.
232
     *
233
     * This method is invoked right after the DB connection is established.
234
     *
235
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
236
     *
237
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
238
     *
239
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
240
     */
241
    abstract protected function initConnection(): void;
242
243
    /**
244
     * Reset the connection after cloning.
245
     */
246
    public function __clone()
247 10
    {
248
        $this->master = null;
249 10
        $this->slave = null;
250 10
        $this->schema = null;
251 10
        $this->transaction = null;
252 10
253
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
254 10
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
255
            $this->pdo = null;
256 10
        }
257
    }
258 10
259
    /**
260
     * Close the connection before serializing.
261
     *
262
     * @return array
263
     */
264
    public function __sleep(): array
265 6
    {
266
        $fields = (array) $this;
267 6
268
        unset(
269
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
270 6
            $fields["\000" . __CLASS__ . "\000" . 'master'],
271 6
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
272 6
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
273 6
            $fields["\000" . __CLASS__ . "\000" . 'schema']
274 6
        );
275
276
        return array_keys($fields);
277 6
    }
278
279
    /**
280
     * Starts a transaction.
281
     *
282
     * @param string|null $isolationLevel The isolation level to use for this transaction.
283
     *
284
     * {@see Transaction::begin()} for details.
285
     *
286
     * @throws Exception|InvalidConfigException|NotSupportedException|Throwable
287
     *
288
     * @return Transaction the transaction initiated
289
     */
290
    public function beginTransaction($isolationLevel = null): Transaction
291 40
    {
292
        $this->open();
293 40
294
        if (($transaction = $this->getTransaction()) === null) {
295 40
            $transaction = $this->transaction = new Transaction($this);
296 40
        }
297
298
        $transaction->begin($isolationLevel);
299 40
300
        return $transaction;
301 40
    }
302
303
    /**
304
     * Uses query cache for the queries performed with the callable.
305
     *
306
     * When query caching is enabled ({@see enableQueryCache} is true and {@see queryCache} refers to a valid cache),
307
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
308
     *
309
     * For example,
310
     *
311
     * ```php
312
     * // The customer will be fetched from cache if available.
313
     * // If not, the query will be made against DB and cached for use next time.
314
     * $customer = $db->cache(function (Connection $db) {
315
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
316
     * });
317
     * ```
318
     *
319
     * Note that query cache is only meaningful for queries that return results. For queries performed with
320
     * {@see Command::execute()}, query cache will not be used.
321
     *
322
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
323
     * The signature of the callable is `function (Connection $db)`.
324
     * @param int|null $duration the number of seconds that query results can remain valid in the cache. If this is not
325
     * set, the value of {@see queryCacheDuration} will be used instead. Use 0 to indicate that the cached data will
326
     * never expire.
327
     * @param Dependency|null $dependency the cache dependency associated with the cached query
328
     * results.
329
     *
330
     * @throws Throwable if there is any exception during query
331
     *
332
     * @return mixed the return result of the callable
333
     *
334
     * {@see setEnableQueryCache()}
335
     * {@see queryCache}
336
     * {@see noCache()}
337
     */
338
    public function cache(callable $callable, int $duration = null, Dependency $dependency = null)
339 10
    {
340
        $this->queryCache->setInfo(
341 10
            [$duration ?? $this->queryCache->getDuration(), $dependency]
342 10
        );
343
344
        $result = $callable($this);
345 10
346
        $this->queryCache->removeLastInfo();
347 10
348
        return $result;
349 10
    }
350
351
    public function getAttributes(): array
352 1853
    {
353
        return $this->attributes;
354 1853
    }
355
356
    public function getCharset(): ?string
357 754
    {
358
        return $this->charset;
359 754
    }
360
361
    public function getDsn(): string
362 1878
    {
363
        return $this->dsn;
364 1878
    }
365
366
    public function getEmulatePrepare(): ?bool
367 1484
    {
368
        return $this->emulatePrepare;
369 1484
    }
370
371
    public function isSavepointEnabled(): bool
372 1717
    {
373
        return $this->enableSavepoint;
374 1717
    }
375
376
    public function areSlavesEnabled(): bool
377 1853
    {
378
        return $this->enableSlaves;
379 1853
    }
380
381
    /**
382 10
     * Returns a value indicating whether the DB connection is established.
383
     *
384 10
     * @return bool whether the DB connection is established
385
     */
386
    public function isActive(): bool
387 1
    {
388
        return $this->pdo !== null;
389 1
    }
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 193
     * @throws InvalidCallException
398
     *
399 193
     * @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
    public function getLastInsertID($sequenceName = ''): string
404
    {
405
        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 10
     */
415
    public function getMaster(): ?self
416 10
    {
417
        if ($this->master === null) {
418
            $this->master = $this->shuffleMasters
419
                ? $this->openFromPool($this->masters)
420
                : $this->openFromPoolSequentially($this->masters);
421
        }
422
423
        return $this->master;
424
    }
425
426 13
    /**
427
     * Returns the PDO instance for the currently active master connection.
428 13
     *
429 13
     * This method will open the master DB connection and then return {@see pdo}.
430 7
     *
431 8
     * @throws Exception
432
     *
433
     * @return PDO the PDO instance for the currently active master connection.
434 13
     */
435
    public function getMasterPdo(): PDO
436
    {
437
        $this->open();
438
439
        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...
440
    }
441
442
    public function getPassword(): ?string
443
    {
444
        return $this->password;
445
    }
446 1817
447
    /**
448 1817
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
449
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
450 1817
     * it will be null.
451
     *
452
     * @return PDO|null
453 1853
     *
454
     * {@see pdoClass}
455 1853
     */
456
    public function getPDO(): ?PDO
457
    {
458
        return $this->pdo;
459
    }
460
461
    /**
462
     * Returns the query builder for the current DB connection.
463
     *
464
     * @return QueryBuilder the query builder for the current DB connection.
465
     */
466
    public function getQueryBuilder(): QueryBuilder
467 1853
    {
468
        return $this->getSchema()->getQueryBuilder();
469 1853
    }
470
471
    /**
472
     * Returns a server version as a string comparable by {@see \version_compare()}.
473
     *
474
     * @throws Exception
475
     *
476
     * @return string server version as a string.
477 955
     */
478
    public function getServerVersion(): string
479 955
    {
480
        return $this->getSchema()->getServerVersion();
481
    }
482
483
    /**
484
     * Returns the currently active slave connection.
485
     *
486
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
487
     * is true.
488
     *
489 314
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
490
     * available.
491 314
     *
492
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
493
     * `$fallbackToMaster` is false.
494
     */
495
    public function getSlave(bool $fallbackToMaster = true): ?self
496
    {
497
        if (!$this->enableSlaves) {
498
            return $fallbackToMaster ? $this : null;
499
        }
500
501
        if ($this->slave === null) {
502
            $this->slave = $this->openFromPool($this->slaves);
503
        }
504
505
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
506 1799
    }
507
508 1799
    /**
509 6
     * Returns the PDO instance for the currently active slave connection.
510
     *
511
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
512 1798
     * returned by this method.
513 1798
     *
514
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
515
     *
516 1798
     * @throws Exception
517
     *
518
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
519
     * is available and `$fallbackToMaster` is false.
520
     */
521
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
522
    {
523
        $db = $this->getSlave(false);
524
525
        if ($db === null) {
526
            return $fallbackToMaster ? $this->getMasterPdo() : null;
527
        }
528
529
        return $db->getPdo();
530
    }
531
532 1797
    public function getTablePrefix(): string
533
    {
534 1797
        return $this->tablePrefix;
535
    }
536 1797
537 1792
    /**
538
     * Obtains the schema information for the named table.
539
     *
540 6
     * @param string $name table name.
541
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
542
     *
543 130
     * @return TableSchema
544
     */
545 130
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
546
    {
547
        return $this->getSchema()->getTableSchema($name, $refresh);
548
    }
549
550
    /**
551
     * Returns the currently active transaction.
552
     *
553
     * @return Transaction|null the currently active transaction. Null if no active transaction.
554
     */
555
    public function getTransaction(): ?Transaction
556 196
    {
557
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
558 196
    }
559
560
    public function getUsername(): ?string
561
    {
562
        return $this->username;
563
    }
564
565
    /**
566 1732
     * Disables query cache temporarily.
567
     *
568 1732
     * Queries performed within the callable will not use query cache at all. For example,
569
     *
570
     * ```php
571 1977
     * $db->cache(function (Connection $db) {
572
     *
573 1977
     *     // ... queries that use query cache ...
574
     *
575
     *     return $db->noCache(function (Connection $db) {
576
     *         // this query will not use query cache
577
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
578
     *     });
579
     * });
580
     * ```
581
     *
582
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
583
     * of the callable is `function (Connection $db)`.
584
     *
585
     * @throws Throwable if there is any exception during query
586
     *
587
     * @return mixed the return result of the callable
588
     *
589
     * {@see enableQueryCache}
590
     * {@see queryCache}
591
     * {@see cache()}
592
     */
593
    public function noCache(callable $callable)
594
    {
595
        $queryCache = $this->queryCache;
596
597
        $queryCache->setInfo(false);
598
599
        $result = $callable($this);
600
601
        $queryCache->removeLastInfo();
602
603
        return $result;
604 10
    }
605
606 10
    /**
607
     * Establishes a DB connection.
608 10
     *
609
     * It does nothing if a DB connection has already been established.
610 10
     *
611
     * @throws Exception|InvalidConfigException if connection fails
612 10
     */
613
    public function open(): void
614 10
    {
615
        if (!empty($this->pdo)) {
616
            return;
617
        }
618
619
        if (!empty($this->masters)) {
620
            $db = $this->getMaster();
621
622
            if ($db !== null) {
623
                $this->pdo = $db->getPDO();
624 1853
625
                return;
626 1853
            }
627 1685
628
            throw new InvalidConfigException('None of the master DB servers is available.');
629
        }
630 1853
631 11
        if (empty($this->dsn)) {
632
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
633 11
        }
634 8
635
        $token = 'Opening DB connection: ' . $this->dsn;
636 8
637
        try {
638
            if ($this->logger !== null) {
639 10
                $this->logger->log(LogLevel::INFO, $token);
640
            }
641
642 1853
            if ($this->profiler !== null) {
643
                $this->profiler->begin($token, [__METHOD__]);
644
            }
645
646 1853
            $this->pdo = $this->createPdoInstance();
647
648
            $this->initConnection();
649 1853
650 1853
            if ($this->profiler !== null) {
651
                $this->profiler->end($token, [__METHOD__]);
652
            }
653 1853
        } catch (PDOException $e) {
654 1853
            if ($this->profiler !== null) {
655
                $this->profiler->end($token, [__METHOD__]);
656
            }
657 1853
658
            if ($this->logger !== null) {
659 1853
                $this->logger->log(LogLevel::ERROR, $token);
660
            }
661 1853
662 1853
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
663
        }
664 15
    }
665 15
666 15
    /**
667
     * Closes the currently active DB connection.
668
     *
669 15
     * It does nothing if the connection is already closed.
670 15
     */
671
    public function close(): void
672
    {
673 15
        if ($this->master) {
674
            if ($this->pdo === $this->master->getPDO()) {
675 1853
                $this->pdo = null;
676
            }
677
678
            $this->master->close();
679
680
            $this->master = null;
681
        }
682 2922
683
        if ($this->pdo !== null) {
684 2922
            if ($this->logger !== null) {
685 7
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
686 7
            }
687
688
            $this->pdo = null;
689 7
            $this->schema = null;
690
            $this->transaction = null;
691 7
        }
692
693
        if ($this->slave) {
694 2922
            $this->slave->close();
695 1853
            $this->slave = null;
696 1843
        }
697
    }
698
699 1853
    /**
700 1853
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
701 1853
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
702
     * {@see logger->log()}.
703
     *
704 2922
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
705 5
     * @param int $level Transaction level just after {@see beginTransaction()} call.
706 5
     */
707
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
708 2922
    {
709
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
710
            /**
711
             * {@see https://github.com/yiisoft/yii2/pull/13347}
712
             */
713
            try {
714
                $transaction->rollBack();
715
            } catch (Exception $e) {
716
                $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
0 ignored issues
show
Bug introduced by
The method log() does not exist on null. ( Ignorable by Annotation )

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

716
                $this->logger->/** @scrutinizer ignore-call */ 
717
                               log(LogLevel::ERROR, $e, [__METHOD__]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
717
                /** hide this exception to be able to continue throwing original exception outside */
718 10
            }
719
        }
720 10
    }
721
722
    /**
723
     * Opens the connection to a server in the pool.
724
     *
725 10
     * This method implements the load balancing among the given list of the servers.
726
     *
727
     * Connections will be tried in random order.
728
     *
729
     * @param array $pool the list of connection configurations in the server pool
730
     *
731 10
     * @return Connection|null the opened DB connection, or `null` if no server is available
732
     */
733
    protected function openFromPool(array $pool): ?self
734
    {
735
        shuffle($pool);
736
737
        return $this->openFromPoolSequentially($pool);
738
    }
739
740
    /**
741
     * Opens the connection to a server in the pool.
742
     *
743
     * This method implements the load balancing among the given list of the servers.
744 1803
     *
745
     * Connections will be tried in sequential order.
746 1803
     *
747
     * @param array $pool
748 1803
     *
749
     * @return Connection|null the opened DB connection, or `null` if no server is available
750
     */
751
    protected function openFromPoolSequentially(array $pool): ?self
752
    {
753
        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...
754
            return null;
755
        }
756
757
        foreach ($pool as $config) {
758
            /* @var $db Connection */
759
            $db = DatabaseFactory::connection($config);
760
761
            $key = [__METHOD__, $db->getDsn()];
762 1808
763
            if (
764 1808
                $this->getSchema()->getSchemaCache()->isEnabled() &&
765 1791
                $this->getSchema()->getSchemaCache()->getOrSet($key, null, $this->serverRetryInterval)
766
            ) {
767
                /** should not try this dead server now */
768 18
                continue;
769
            }
770 18
771
            try {
772 18
                $db->open();
773
774
                return $db;
775 18
            } catch (Exception $e) {
776 18
                if ($this->logger !== null) {
777
                    $this->logger->log(
778
                        LogLevel::WARNING,
779
                        "Connection ({$db->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
780
                    );
781
                }
782
783 18
                if ($this->getSchema()->getSchemaCache()->isEnabled()) {
784
                    /** mark this server as dead and only retry it after the specified interval */
785 15
                    $this->getSchema()->getSchemaCache()->set($key, 1, $this->serverRetryInterval);
786 10
                }
787 10
788 10
                return null;
789 10
            }
790 10
        }
791
792
        return null;
793
    }
794 10
795
    /**
796 5
     * Quotes a column name for use in a query.
797
     *
798
     * If the column name contains prefix, the prefix will also be properly quoted.
799 10
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this
800
     * method will do nothing.
801
     *
802
     * @param string $name column name
803
     *
804
     * @return string the properly quoted column name
805
     */
806
    public function quoteColumnName(string $name): string
807
    {
808
        return $this->quotedColumnNames[$name]
809
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
810
    }
811
812
    /**
813
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
814
     *
815
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
816
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
817 1594
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
818
     *
819 1594
     * @param string $sql the SQL to be quoted
820 1594
     *
821
     * @return string the quoted SQL
822
     */
823
    public function quoteSql(string $sql): string
824
    {
825
        return preg_replace_callback(
826
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
827
            function ($matches) {
828
                if (isset($matches[3])) {
829
                    return $this->quoteColumnName($matches[3]);
830
                }
831
832
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
833
            },
834 1842
            $sql
835
        );
836 1842
    }
837 1842
838 1842
    /**
839 689
     * Quotes a table name for use in a query.
840 569
     *
841
     * If the table name contains schema prefix, the prefix will also be properly quoted.
842
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
843 493
     * will do nothing.
844 1842
     *
845
     * @param string $name table name
846
     *
847
     * @return string the properly quoted table name
848
     */
849
    public function quoteTableName(string $name): string
850
    {
851
        return $this->quotedTableNames[$name]
852
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
853
    }
854
855
    /**
856
     * Quotes a string value for use in a query.
857
     *
858
     * Note that if the parameter is not a string, it will be returned without change.
859
     *
860 1388
     * @param int|string $value string to be quoted
861
     *
862 1388
     * @throws Exception
863 1388
     *
864
     * @return int|string the properly quoted string
865
     *
866
     * {@see http://php.net/manual/en/pdo.quote.php}
867
     */
868
    public function quoteValue($value)
869
    {
870
        return $this->getSchema()->quoteValue($value);
871
    }
872
873
    /**
874
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
875
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
876
     * attributes.
877
     *
878
     * @param array $value
879 1370
     */
880
    public function setAttributes(array $value): void
881 1370
    {
882
        $this->attributes = $value;
883
    }
884
885
    /**
886
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
887
     * null, meaning using default charset as configured by the database.
888
     *
889
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
890
     * `;charset=UTF-8` to the DSN string.
891
     *
892
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
893
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
894
     *
895
     * @param string|null $value
896
     */
897
    public function setCharset(?string $value): void
898
    {
899
        $this->charset = $value;
900
    }
901
902
    /**
903
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
904
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
905
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
906
     * ATTR_EMULATE_PREPARES value will not be changed.
907
     *
908 885
     * @param bool $value
909
     */
910 885
    public function setEmulatePrepare(bool $value): void
911 885
    {
912
        $this->emulatePrepare = $value;
913
    }
914
915
    /**
916
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
917
     * support savepoint, setting this property to be true will have no effect.
918
     *
919
     * @param bool $value
920 10
     */
921
    public function setEnableSavepoint(bool $value): void
922 10
    {
923 10
        $this->enableSavepoint = $value;
924
    }
925
926
    /**
927
     * Whether to enable read/write splitting by using {@see setSlaves()} to read data. Note that if {@see setSlaves()}
928
     * is empty, read/write splitting will NOT be enabled no matter what value this property takes.
929
     *
930
     * @param bool $value
931
     */
932
    public function setEnableSlaves(bool $value): void
933 7
    {
934
        $this->enableSlaves = $value;
935 7
    }
936 7
937
    /**
938
     * List of master connection. Each DSN is used to create a master DB connection. When {@see open()} is called, one
939
     * of these configurations will be chosen and used to create a DB connection which will be used by this object.
940
     *
941
     * @param string $key index master connection.
942
     * @param array $config The configuration that should be merged with every master configuration
943
     */
944 10
    public function setMasters(string $key, array $config = []): void
945
    {
946 10
        $this->masters[$key] = $config;
947 10
    }
948
949
    /**
950
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
951
     *
952
     * @param string|null $value
953
     */
954
    public function setPassword(?string $value): void
955 5
    {
956
        $this->password = $value;
957 5
    }
958 5
959
    /**
960
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
961
     *
962
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
963
     */
964
    public function setQueryBuilder(iterable $config): void
965
    {
966
        $builder = $this->getQueryBuilder();
967
968
        foreach ($config as $key => $value) {
969
            $builder->{$key} = $value;
970
        }
971
    }
972
973
    /**
974
     * The retry interval in seconds for dead servers listed in {@see setMasters()} and {@see setSlaves()}.
975
     *
976
     * @param int $value
977
     */
978 14
    public function setServerRetryInterval(int $value): void
979
    {
980 14
        $this->serverRetryInterval = $value;
981 14
    }
982
983
    /**
984
     * Whether to shuffle {@see setMasters()} before getting one.
985
     *
986
     * @param bool $value
987
     */
988 2631
    public function setShuffleMasters(bool $value): void
989
    {
990 2631
        $this->shuffleMasters = $value;
991 2631
    }
992
993
    /**
994
     * List of slave connection. Each DSN is used to create a slave DB connection. When {@see enableSlaves} is true,
995
     * one of these configurations will be chosen and used to create a DB connection for performing read queries only.
996
     *
997
     * @param string $key index slave connection.
998
     * @param array $config The configuration that should be merged with every slave configuration
999
     */
1000
    public function setSlaves(string $key, array $config = []): void
1001
    {
1002
        $this->slaves[$key] = $config;
1003
    }
1004
1005
    /**
1006
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
1007
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
1008
     *
1009
     * @param string $value
1010
     */
1011
    public function setTablePrefix(string $value): void
1012
    {
1013
        $this->tablePrefix = $value;
1014
    }
1015
1016
    /**
1017
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
1018
     *
1019
     * @param string|null $value
1020
     */
1021
    public function setUsername(?string $value): void
1022 12
    {
1023
        $this->username = $value;
1024 12
    }
1025 12
1026
    /**
1027
     * Executes callback provided in a transaction.
1028
     *
1029
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
1030
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
1031
     * for details.
1032
     *
1033
     * @throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
1034 9
     *
1035
     * @return mixed result of callback function
1036 9
     */
1037 9
    public function transaction(callable $callback, $isolationLevel = null)
1038
    {
1039
        $transaction = $this->beginTransaction($isolationLevel);
1040
1041
        $level = $transaction->getLevel();
1042
1043
        try {
1044
            $result = $callback($this);
1045 24
1046
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
1047 24
                $transaction->commit();
1048 24
            }
1049
        } catch (Throwable $e) {
1050
            $this->rollbackTransactionOnLevel($transaction, $level);
1051
1052
            throw $e;
1053
        }
1054
1055 2631
        return $result;
1056
    }
1057 2631
1058 2631
    /**
1059
     * Executes the provided callback by using the master connection.
1060
     *
1061
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1062
     * even if they are read queries. For example,
1063
     *
1064
     * ```php
1065
     * $result = $db->useMaster(function ($db) {
1066
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1067
     * });
1068
     * ```
1069
     *
1070
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1071 25
     * `function (Connection $db)`. Its return value will be returned by this method.
1072
     *
1073 25
     * @throws Throwable if there is any exception thrown from the callback
1074
     *
1075 25
     * @return mixed the return value of the callback
1076
     */
1077
    public function useMaster(callable $callback)
1078 25
    {
1079
        if ($this->enableSlaves) {
1080 15
            $this->enableSlaves = false;
1081 15
1082
            try {
1083 10
                $result = $callback($this);
1084 10
            } catch (Throwable $e) {
1085
                $this->enableSlaves = true;
1086 10
1087
                throw $e;
1088
            }
1089 15
            $this->enableSlaves = true;
1090
        } else {
1091
            $result = $callback($this);
1092
        }
1093
1094
        return $result;
1095
    }
1096
1097
    public function setLogger(LoggerInterface $logger = null): void
1098
    {
1099
        $this->logger = $logger;
1100
    }
1101
1102
    public function setProfiler(ProfilerInterface $profiler = null): void
1103
    {
1104
        $this->profiler = $profiler;
1105
    }
1106
1107
    public function setSchema(Schema $schema): ?LoggerInterface
1108
    {
1109
        $this->schema = $schema;
1110
    }
1111 7
1112
    public function getLogger(): ?LoggerInterface
1113 7
    {
1114 7
        return $this->logger;
1115
    }
1116
1117 7
    public function getProfiler(): ?ProfilerInterface
1118 1
    {
1119 1
        return $this->profiler;
1120
    }
1121 1
1122
    public function getQueryCache(): QueryCache
1123 6
    {
1124
        return $this->queryCache;
1125
    }
1126
}
1127