Passed
Pull Request — master (#243)
by Wilmer
39:10 queued 23:38
created

Connection::quoteColumnName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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