Passed
Pull Request — master (#256)
by Wilmer
15:21
created

Connection   F

Complexity

Total Complexity 98

Size/Duplication

Total Lines 883
Duplicated Lines 0 %

Test Coverage

Coverage 91.21%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 201
dl 0
loc 883
ccs 218
cts 239
cp 0.9121
rs 2
c 3
b 0
f 0
wmc 98

51 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setShuffleMasters() 0 3 1
A setUsername() 0 3 1
A transaction() 0 19 4
A setSlave() 0 3 1
A setQueryBuilder() 0 6 2
A setServerRetryInterval() 0 3 1
A useMaster() 0 18 3
A setTablePrefix() 0 3 1
A getAttributes() 0 3 1
A getEmulatePrepare() 0 3 1
A cache() 0 8 1
A isSavepointEnabled() 0 3 1
A areSlavesEnabled() 0 3 1
A getLastInsertID() 0 3 1
A __clone() 0 9 2
A beginTransaction() 0 14 3
A getDsn() 0 3 1
A getCharset() 0 3 1
A isActive() 0 3 1
A __sleep() 0 13 1
A quoteTableName() 0 4 1
A setEmulatePrepare() 0 3 1
A noCache() 0 7 1
A setAttributes() 0 3 1
A getMasterPdo() 0 4 1
B openFromPoolSequentially() 0 39 8
A getUsername() 0 3 1
A quoteValue() 0 3 1
A getServerVersion() 0 3 1
A getSlave() 0 11 6
A getMaster() 0 9 3
A getSlavePdo() 0 9 3
A getTransaction() 0 3 3
A setEnableSlaves() 0 3 1
A openFromPool() 0 4 1
A quoteSql() 0 12 2
A setPassword() 0 3 1
A getTablePrefix() 0 3 1
A getPDO() 0 3 1
A setPDO() 0 3 1
A quoteColumnName() 0 4 1
B open() 0 48 11
A getQueryBuilder() 0 3 1
A rollbackTransactionOnLevel() 0 11 5
A getTableSchema() 0 3 1
A getPassword() 0 3 1
A setEnableSavepoint() 0 3 1
A close() 0 24 6
A setMaster() 0 3 1
A setCharset() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.

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