Passed
Push — master ( 9607e5...058f8b )
by Wilmer
09:15
created

Connection::getEmulatePrepare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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