Passed
Pull Request — master (#255)
by Wilmer
14:59
created

Connection   F

Complexity

Total Complexity 98

Size/Duplication

Total Lines 877
Duplicated Lines 0 %

Test Coverage

Coverage 91.53%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 201
dl 0
loc 877
ccs 216
cts 236
cp 0.9153
rs 2
c 3
b 0
f 0
wmc 98

51 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A quoteTableName() 0 4 1
A getAttributes() 0 3 1
A setEmulatePrepare() 0 3 1
A noCache() 0 7 1
A setShuffleMasters() 0 3 1
A getEmulatePrepare() 0 3 1
A setAttributes() 0 3 1
A cache() 0 8 1
A isSavepointEnabled() 0 3 1
A getMasterPdo() 0 4 1
A transaction() 0 19 4
B openFromPoolSequentially() 0 39 8
A areSlavesEnabled() 0 3 1
A getLastInsertID() 0 3 1
A getUsername() 0 3 1
A quoteValue() 0 3 1
A getServerVersion() 0 3 1
A __clone() 0 9 2
A setSlave() 0 3 1
A getSlave() 0 11 6
A getMaster() 0 9 3
A beginTransaction() 0 14 3
A getSlavePdo() 0 9 3
A getTransaction() 0 3 3
A setEnableSlaves() 0 3 1
A getDsn() 0 3 1
A setUsername() 0 3 1
A getCharset() 0 3 1
A setQueryBuilder() 0 6 2
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 setServerRetryInterval() 0 3 1
A quoteColumnName() 0 4 1
B open() 0 48 11
A getQueryBuilder() 0 3 1
A rollbackTransactionOnLevel() 0 11 5
A PDO() 0 3 1
A isActive() 0 3 1
A getTableSchema() 0 3 1
A useMaster() 0 18 3
A getPassword() 0 3 1
A setEnableSavepoint() 0 3 1
A setTablePrefix() 0 3 1
A close() 0 24 6
A __sleep() 0 13 1
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 ?ConnectionInterface $master = null;
185
    private ?ConnectionInterface $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
     * Creates the PDO instance and 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 ConnectionInterface the currently active master connection. `null` is returned if there is no master
398
     * available.
399 10
     */
400
    public function getMaster(): ?ConnectionInterface
401
    {
402
        if ($this->master === null) {
403
            $this->master = $this->shuffleMasters
404
                ? $this->openFromPool($this->masters)
405
                : $this->openFromPoolSequentially($this->masters);
406
        }
407
408
        return $this->master;
409 13
    }
410
411 13
    /**
412 13
     * Returns the PDO instance for the currently active master connection.
413 7
     *
414 8
     * This method will open the master DB connection and then return {@see pdo}.
415
     *
416
     * @throws Exception
417 13
     *
418
     * @return PDO|null the PDO instance for the currently active master connection.
419
     */
420
    public function getMasterPdo(): ?PDO
421
    {
422
        $this->open();
423
        return $this->pdo;
424
    }
425
426
    public function getPassword(): ?string
427
    {
428
        return $this->password;
429 1830
    }
430
431 1830
    /**
432 1830
     * The PHP PDO instance associated with this DB connection. This property is mainly managed by {@see open()} and
433
     * {@see close()} methods. When a DB connection is active, this property will represent a PDO instance; otherwise,
434
     * it will be null.
435 1866
     *
436
     * @return PDO|null
437 1866
     *
438
     * {@see pdoClass}
439
     */
440
    public function getPDO(): ?PDO
441
    {
442
        return $this->pdo;
443
    }
444
445
    /**
446
     * Returns the query builder for the current DB connection.
447
     *
448
     * @return QueryBuilder the query builder for the current DB connection.
449 1866
     */
450
    public function getQueryBuilder(): QueryBuilder
451 1866
    {
452
        return $this->getSchema()->getQueryBuilder();
453
    }
454
455
    public function getServerVersion(): string
456
    {
457
        return $this->getSchema()->getServerVersion();
458
    }
459 963
460
    /**
461 963
     * Returns the currently active slave connection.
462
     *
463
     * If this method is called for the first time, it will try to open a slave connection when {@see setEnableSlaves()}
464 315
     * is true.
465
     *
466 315
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection
467
     * available.
468
     *
469
     * @return ConnectionInterface the currently active slave connection. `null` is returned if there is no slave
470
     * available and `$fallbackToMaster` is false.
471
     */
472
    public function getSlave(bool $fallbackToMaster = true): ?ConnectionInterface
473
    {
474
        if (!$this->enableSlaves) {
475
            return $fallbackToMaster ? $this : null;
476
        }
477
478
        if ($this->slave === null) {
479
            $this->slave = $this->openFromPool($this->slaves);
480
        }
481 1812
482
        return $this->slave === null && $fallbackToMaster ? $this : $this->slave;
483 1812
    }
484 6
485
    /**
486
     * Returns the PDO instance for the currently active slave connection.
487 1811
     *
488 1811
     * When {@see enableSlaves} is true, one of the slaves will be used for read queries, and its PDO instance will be
489
     * returned by this method.
490
     *
491 1811
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
492
     *
493
     * @throws Exception
494
     *
495
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
496
     * is available and `$fallbackToMaster` is false.
497
     */
498
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
499
    {
500
        $db = $this->getSlave(false);
501
502
        if ($db === null) {
503
            return $fallbackToMaster ? $this->getMasterPdo() : null;
504
        }
505
506
        return $db->getPdo();
0 ignored issues
show
Bug introduced by
The method getPdo() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

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

506
        return $db->/** @scrutinizer ignore-call */ getPdo();
Loading history...
507 1810
    }
508
509 1810
    public function getTablePrefix(): string
510
    {
511 1810
        return $this->tablePrefix;
512 1805
    }
513
514
    public function getTableSchema(string $name, $refresh = false): ?TableSchema
515 6
    {
516
        return $this->getSchema()->getTableSchema($name, $refresh);
517
    }
518 130
519
    /**
520 130
     * Returns the currently active transaction.
521
     *
522
     * @return Transaction|null the currently active transaction. Null if no active transaction.
523 200
     */
524
    public function getTransaction(): ?Transaction
525 200
    {
526
        return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
527
    }
528
529
    public function getUsername(): ?string
530
    {
531
        return $this->username;
532
    }
533 1745
534
    /**
535 1745
     * Disables query cache temporarily.
536
     *
537
     * Queries performed within the callable will not use query cache at all. For example,
538 1990
     *
539
     * ```php
540 1990
     * $db->cache(function (ConnectionInterface $db) {
541
     *
542
     *     // ... queries that use query cache ...
543
     *
544
     *     return $db->noCache(function (ConnectionInterface $db) {
545
     *         // this query will not use query cache
546
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
547
     *     });
548
     * });
549
     * ```
550
     *
551
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache. The signature
552
     * of the callable is `function (ConnectionInterface $db)`.
553
     *
554
     * @throws Throwable if there is any exception during query
555
     *
556
     * @return mixed the return result of the callable
557
     *
558
     * {@see enableQueryCache}
559
     * {@see queryCache}
560
     * {@see cache()}
561
     */
562
    public function noCache(callable $callable)
563
    {
564
        $queryCache = $this->queryCache;
565
        $queryCache->setInfo(false);
566
        $result = $callable($this);
567
        $queryCache->removeLastInfo();
568
        return $result;
569
    }
570
571 10
    /**
572
     * Establishes a DB connection.
573 10
     *
574 10
     * It does nothing if a DB connection has already been established.
575 10
     *
576 10
     * @throws Exception|InvalidConfigException if connection fails
577 10
     */
578
    public function open(): void
579
    {
580
        if (!empty($this->pdo)) {
581
            return;
582
        }
583
584
        if (!empty($this->masters)) {
585
            $db = $this->getMaster();
586
587 1866
            if ($db !== null) {
588
                $this->pdo = $db->getPDO();
0 ignored issues
show
Bug introduced by
The method getPDO() does not exist on Yiisoft\Db\Connection\ConnectionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Db\Connection\ConnectionInterface. ( Ignorable by Annotation )

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

588
                /** @scrutinizer ignore-call */ 
589
                $this->pdo = $db->getPDO();
Loading history...
589 1866
590 1697
                return;
591
            }
592
593 1866
            throw new InvalidConfigException('None of the master DB servers is available.');
594 11
        }
595
596 11
        if (empty($this->dsn)) {
597 8
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
598
        }
599 8
600
        $token = 'Opening DB connection: ' . $this->dsn;
601
602 10
        try {
603
            if ($this->logger !== null) {
604
                $this->logger->log(LogLevel::INFO, $token);
605 1866
            }
606
607
            if ($this->profiler !== null) {
608
                $this->profiler->begin($token, [__METHOD__]);
609 1866
            }
610
611
            $this->initConnection();
612 1866
613 1004
            if ($this->profiler !== null) {
614
                $this->profiler->end($token, [__METHOD__]);
615
            }
616 1866
        } catch (PDOException $e) {
617 1004
            if ($this->profiler !== null) {
618
                $this->profiler->end($token, [__METHOD__]);
619
            }
620 1866
621
            if ($this->logger !== null) {
622 1866
                $this->logger->log(LogLevel::ERROR, $token);
623
            }
624 1866
625 1866
            throw new Exception($e->getMessage(), $e->errorInfo, $e);
626
        }
627 15
    }
628 15
629 15
    /**
630
     * Closes the currently active DB connection.
631
     *
632 15
     * It does nothing if the connection is already closed.
633 15
     */
634
    public function close(): void
635
    {
636 15
        if (!empty($this->master)) {
637
            if ($this->pdo === $this->master->getPDO()) {
638 1866
                $this->pdo = null;
639
            }
640
641
            $this->master->close();
642
643
            $this->master = null;
644
        }
645 2935
646
        if ($this->pdo !== null) {
647 2935
            if ($this->logger !== null) {
648 7
                $this->logger->log(LogLevel::DEBUG, 'Closing DB connection: ' . $this->dsn . ' ' . __METHOD__);
649 7
            }
650
651
            $this->pdo = null;
652 7
            $this->transaction = null;
653
        }
654 7
655
        if (!empty($this->slave)) {
656
            $this->slave->close();
657 2935
            $this->slave = null;
658 1866
        }
659 994
    }
660
661
    public function PDO(PDO $value): void
662 1866
    {
663 1866
        $this->pdo = $value;
664
    }
665
666 2935
    /**
667 5
     * Rolls back given {@see Transaction} object if it's still active and level match. In some cases rollback can fail,
668 5
     * so this method is fail safe. Exceptions thrown from rollback will be caught and just logged with
669
     * {@see logger->log()}.
670 2935
     *
671
     * @param Transaction $transaction Transaction object given from {@see beginTransaction()}.
672
     * @param int $level Transaction level just after {@see beginTransaction()} call.
673
     */
674
    private function rollbackTransactionOnLevel(Transaction $transaction, int $level): void
675
    {
676
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
677
            /**
678
             * {@see https://github.com/yiisoft/yii2/pull/13347}
679
             */
680 10
            try {
681
                $transaction->rollBack();
682 10
            } catch (Exception $e) {
683
                if ($this->logger !== null) {
684
                    $this->logger->log(LogLevel::ERROR, $e, [__METHOD__]);
685
                    /** hide this exception to be able to continue throwing original exception outside */
686
                }
687 10
            }
688
        }
689
    }
690
691
    /**
692
     * Opens the connection to a server in the pool.
693
     *
694
     * This method implements the load balancing among the given list of the servers.
695 10
     *
696
     * Connections will be tried in random order.
697
     *
698
     * @param array $pool the list of connection configurations in the server pool
699
     *
700
     * @return ConnectionInterface|null the opened DB connection, or `null` if no server is available
701
     */
702
    protected function openFromPool(array $pool): ?ConnectionInterface
703
    {
704
        shuffle($pool);
705
        return $this->openFromPoolSequentially($pool);
706
    }
707
708 1816
    /**
709
     * Opens the connection to a server in the pool.
710 1816
     *
711 1816
     * This method implements the load balancing among the given list of the servers.
712
     *
713
     * Connections will be tried in sequential order.
714
     *
715
     * @param array $pool
716
     *
717
     * @return ConnectionInterface|null the opened DB connection, or `null` if no server is available
718
     */
719
    protected function openFromPoolSequentially(array $pool): ?ConnectionInterface
720
    {
721
        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...
722
            return null;
723
        }
724
725 1821
        foreach ($pool as $poolConnetion) {
726
            $key = [__METHOD__, $poolConnetion->getDsn()];
727 1821
728 1804
            if (
729
                $this->getSchema()->getSchemaCache()->isEnabled() &&
730
                $this->getSchema()->getSchemaCache()->getOrSet($key, null, $this->serverRetryInterval)
731 18
            ) {
732 18
                /** should not try this dead server now */
733
                continue;
734
            }
735 18
736 18
            try {
737
                $poolConnetion->open();
738
739
                return $poolConnetion;
740
            } catch (Exception $e) {
741
                if ($this->logger !== null) {
742
                    $this->logger->log(
743 18
                        LogLevel::WARNING,
744
                        "Connection ({$poolConnetion->getDsn()}) failed: " . $e->getMessage() . ' ' . __METHOD__
745 15
                    );
746 10
                }
747 10
748 10
                if ($this->getSchema()->getSchemaCache()->isEnabled()) {
749 10
                    /** mark this server as dead and only retry it after the specified interval */
750 10
                    $this->getSchema()->getSchemaCache()->set($key, 1, $this->serverRetryInterval);
751
                }
752
753
                return null;
754 10
            }
755
        }
756 5
757
        return null;
758
    }
759 10
760
    public function quoteColumnName(string $name): string
761
    {
762
        return $this->quotedColumnNames[$name]
763
            ?? ($this->quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name));
764
    }
765
766 1602
    /**
767
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
768 1602
     *
769 1602
     * Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double
770
     * square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the
771
     * beginning or ending of a table name will be replaced with {@see tablePrefix}.
772
     *
773
     * @param string $sql the SQL to be quoted
774
     *
775
     * @return string the quoted SQL
776
     */
777
    public function quoteSql(string $sql): string
778
    {
779
        return preg_replace_callback(
780
            '/({{(%?[\w\-. ]+%?)}}|\\[\\[([\w\-. ]+)]])/',
781
            function (array $matches) {
782
                if (isset($matches[3])) {
783 1855
                    return $this->quoteColumnName($matches[3]);
784
                }
785 1855
786 1855
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
787 1855
            },
788 689
            $sql
789 569
        );
790
    }
791
792 493
    /**
793 1855
     * Quotes a table name for use in a query.
794
     *
795
     * If the table name contains schema prefix, the prefix will also be properly quoted.
796
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method
797
     * will do nothing.
798
     *
799
     * @param string $name table name
800
     *
801
     * @return string the properly quoted table name
802
     */
803
    public function quoteTableName(string $name): string
804
    {
805
        return $this->quotedTableNames[$name]
806
            ?? ($this->quotedTableNames[$name] = $this->getSchema()->quoteTableName($name));
807
    }
808
809 1396
    /**
810
     * Quotes a string value for use in a query.
811 1396
     *
812 1396
     * Note that if the parameter is not a string, it will be returned without change.
813
     *
814
     * @param int|string $value string to be quoted
815
     *
816
     * @throws Exception
817
     *
818
     * @return int|string the properly quoted string
819
     *
820
     * {@see http://php.net/manual/en/pdo.quote.php}
821
     */
822
    public function quoteValue($value)
823
    {
824
        return $this->getSchema()->quoteValue($value);
825
    }
826
827
    /**
828 1017
     * PDO attributes (name => value) that should be set when calling {@see open()} to establish a DB connection.
829
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for details about available
830 1017
     * attributes.
831
     *
832
     * @param array $value
833
     */
834
    public function setAttributes(array $value): void
835
    {
836
        $this->attributes = $value;
837
    }
838
839
    /**
840
     * The charset used for database connection. The property is only used for MySQL, PostgreSQL databases. Defaults to
841
     * null, meaning using default charset as configured by the database.
842
     *
843
     * For Oracle Database, the charset must be specified in the {@see dsn}, for example for UTF-8 by appending
844
     * `;charset=UTF-8` to the DSN string.
845
     *
846
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify
847
     * charset via {@see dsn} like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
848
     *
849
     * @param string|null $value
850
     */
851
    public function setCharset(?string $value): void
852
    {
853
        $this->charset = $value;
854
    }
855
856
    /**
857 2074
     * Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if
858
     * available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare
859 2074
     * support to bypass the buggy native prepare support. The default value is null, which means the PDO
860 2074
     * ATTR_EMULATE_PREPARES value will not be changed.
861
     *
862
     * @param bool $value
863
     */
864
    public function setEmulatePrepare(bool $value): void
865
    {
866
        $this->emulatePrepare = $value;
867
    }
868
869
    /**
870 7
     * Whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint). Note that if the underlying DBMS does not
871
     * support savepoint, setting this property to be true will have no effect.
872 7
     *
873 7
     * @param bool $value
874
     */
875
    public function setEnableSavepoint(bool $value): void
876
    {
877
        $this->enableSavepoint = $value;
878
    }
879
880
    public function setEnableSlaves(bool $value): void
881 5
    {
882
        $this->enableSlaves = $value;
883 5
    }
884 5
885
    /**
886
     * Set connection for master server, you can specify multiple connections, adding the id for each one.
887
     *
888
     * @param string $key index master connection.
889
     * @param ConnectionInterface $db The connection every master.
890
     */
891
    public function setMaster(string $key, ConnectionInterface $master): void
892
    {
893
        $this->masters[$key] = $master;
894
    }
895
896
    /**
897 14
     * The password for establishing DB connection. Defaults to `null` meaning no password to use.
898
     *
899 14
     * @param string|null $value
900 14
     */
901
    public function setPassword(?string $value): void
902
    {
903
        $this->password = $value;
904
    }
905
906
    /**
907 3029
     * Can be used to set {@see QueryBuilder} configuration via Connection configuration array.
908
     *
909 3029
     * @param iterable $config the {@see QueryBuilder} properties to be configured.
910 3029
     */
911
    public function setQueryBuilder(iterable $config): void
912
    {
913
        $builder = $this->getQueryBuilder();
914
915
        foreach ($config as $key => $value) {
916
            $builder->{$key} = $value;
917
        }
918
    }
919
920
    /**
921
     * The retry interval in seconds for dead servers listed in {@see setMaster()} and {@see setSlave()}.
922
     *
923
     * @param int $value
924
     */
925
    public function setServerRetryInterval(int $value): void
926
    {
927
        $this->serverRetryInterval = $value;
928
    }
929
930
    /**
931
     * Whether to shuffle {@see setMaster()} before getting one.
932
     *
933
     * @param bool $value
934
     */
935
    public function setShuffleMasters(bool $value): void
936
    {
937
        $this->shuffleMasters = $value;
938
    }
939
940
    /**
941 12
     * Set connection for master slave, you can specify multiple connections, adding the id for each one.
942
     *
943 12
     * @param string $key index slave connection.
944 12
     * @param ConnectionInterface $slave The connection every slave.
945
     */
946
    public function setSlave(string $key, ConnectionInterface $slave): void
947
    {
948
        $this->slaves[$key] = $slave;
949
    }
950
951
    /**
952 9
     * The common prefix or suffix for table names. If a table name is given as `{{%TableName}}`, then the percentage
953
     * character `%` will be replaced with this property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
954 9
     *
955 9
     * @param string $value
956
     */
957
    public function setTablePrefix(string $value): void
958
    {
959
        $this->tablePrefix = $value;
960
    }
961
962
    /**
963 24
     * The username for establishing DB connection. Defaults to `null` meaning no username to use.
964
     *
965 24
     * @param string|null $value
966 24
     */
967
    public function setUsername(?string $value): void
968
    {
969
        $this->username = $value;
970
    }
971
972
    /**
973 3029
     * Executes callback provided in a transaction.
974
     *
975 3029
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
976 3029
     * @param string|null $isolationLevel The isolation level to use for this transaction. {@see Transaction::begin()}
977
     * for details.
978
     *
979
     *@throws Throwable if there is any exception during query. In this case the transaction will be rolled back.
980
     *
981
     * @return mixed result of callback function
982
     */
983
    public function transaction(callable $callback, string $isolationLevel = null)
984
    {
985
        $transaction = $this->beginTransaction($isolationLevel);
986
987
        $level = $transaction->getLevel();
988
989 25
        try {
990
            $result = $callback($this);
991 25
992
            if ($transaction->isActive() && $transaction->getLevel() === $level) {
993 25
                $transaction->commit();
994
            }
995
        } catch (Throwable $e) {
996 25
            $this->rollbackTransactionOnLevel($transaction, $level);
997
998 15
            throw $e;
999 15
        }
1000
1001 10
        return $result;
1002 10
    }
1003
1004 10
    /**
1005
     * Executes the provided callback by using the master connection.
1006
     *
1007 15
     * This method is provided so that you can temporarily force using the master connection to perform DB operations
1008
     * even if they are read queries. For example,
1009
     *
1010
     * ```php
1011
     * $result = $db->useMaster(function (ConnectionInterface $db) {
1012
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1013
     * });
1014
     * ```
1015
     *
1016
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1017
     * `function (ConnectionInterface $db)`. Its return value will be returned by this method.
1018
     *
1019
     * @throws Throwable if there is any exception thrown from the callback
1020
     *
1021
     * @return mixed the return value of the callback
1022
     */
1023
    public function useMaster(callable $callback)
1024
    {
1025
        if ($this->enableSlaves) {
1026
            $this->enableSlaves = false;
1027
1028
            try {
1029 7
                $result = $callback($this);
1030
            } catch (Throwable $e) {
1031 7
                $this->enableSlaves = true;
1032 7
1033
                throw $e;
1034
            }
1035 7
            $this->enableSlaves = true;
1036 1
        } else {
1037 1
            $result = $callback($this);
1038
        }
1039 1
1040
        return $result;
1041 6
    }
1042
}
1043