Passed
Pull Request — master (#197)
by Wilmer
15:35
created

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