Completed
Push — master ( 7aef17...e93aa7 )
by Alexander
02:36
created

Connection   F

Complexity

Total Complexity 113

Size/Duplication

Total Lines 1060
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 9

Test Coverage

Coverage 42.06%

Importance

Changes 0
Metric Value
wmc 113
lcom 2
cbo 9
dl 0
loc 1060
ccs 106
cts 252
cp 0.4206
rs 1.36
c 0
b 0
f 0

36 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A getIsActive() 0 4 1
A cache() 0 12 3
A noCache() 0 12 2
B getQueryCacheInfo() 0 29 10
B open() 0 42 9
A close() 0 23 5
B createPdoInstance() 0 26 9
A initConnection() 0 11 5
A createCommand() 0 13 3
A getTransaction() 0 4 3
A beginTransaction() 0 11 2
A transaction() 0 17 4
A rollbackTransactionOnLevel() 0 12 4
A getSchema() 0 15 3
A getQueryBuilder() 0 4 1
A setQueryBuilder() 0 7 2
A getTableSchema() 0 4 1
A getLastInsertID() 0 4 1
A quoteValue() 0 4 1
A quoteTableName() 0 4 1
A quoteColumnName() 0 4 1
A quoteSql() 0 14 2
A getDriverName() 0 12 3
A setDriverName() 0 4 1
A getServerVersion() 0 4 1
A getSlavePdo() 0 9 3
A getMasterPdo() 0 5 1
A getSlave() 0 12 6
A getMaster() 0 10 3
A useMaster() 0 18 3
A openFromPool() 0 5 1
B openFromPoolSequentially() 0 41 10
A buildDSN() 0 15 3
A __sleep() 0 12 1
A __clone() 0 13 2

How to fix   Complexity   

Complex Class

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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

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

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use PDO;
11
use yii\base\Component;
12
use yii\exceptions\InvalidConfigException;
13
use yii\exceptions\NotSupportedException;
14
use yii\cache\CacheInterface;
15
use yii\helpers\Yii;
16
17
/**
18
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
19
 *
20
 * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
21
 * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
22
 * of the [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
23
 *
24
 * Connection supports database replication and read-write splitting. In particular, a Connection component
25
 * can be configured with multiple [[masters]] and [[slaves]]. It will do load balancing and failover by choosing
26
 * appropriate servers. It will also automatically direct read operations to the slaves and write operations to
27
 * the masters.
28
 *
29
 * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
30
 * call [[open()]] to connect to the database server. The current state of the connection can be checked using [[$isActive]].
31
 *
32
 * The following example shows how to create a Connection instance and establish
33
 * the DB connection:
34
 *
35
 * ```php
36
 * $connection = new \yii\db\Connection([
37
 *     'dsn' => $dsn,
38
 *     'username' => $username,
39
 *     'password' => $password,
40
 * ]);
41
 * $connection->open();
42
 * ```
43
 *
44
 * After the DB connection is established, one can execute SQL statements like the following:
45
 *
46
 * ```php
47
 * $command = $connection->createCommand('SELECT * FROM post');
48
 * $posts = $command->queryAll();
49
 * $command = $connection->createCommand('UPDATE post SET status=1');
50
 * $command->execute();
51
 * ```
52
 *
53
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
54
 * When the parameters are coming from user input, you should use this approach
55
 * to prevent SQL injection attacks. The following is an example:
56
 *
57
 * ```php
58
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
59
 * $command->bindValue(':id', $_GET['id']);
60
 * $post = $command->query();
61
 * ```
62
 *
63
 * For more information about how to perform various DB queries, please refer to [[Command]].
64
 *
65
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries
66
 * like the following:
67
 *
68
 * ```php
69
 * $transaction = $connection->beginTransaction();
70
 * try {
71
 *     $connection->createCommand($sql1)->execute();
72
 *     $connection->createCommand($sql2)->execute();
73
 *     // ... executing other SQL statements ...
74
 *     $transaction->commit();
75
 * } catch (Exception $e) {
76
 *     $transaction->rollBack();
77
 * }
78
 * ```
79
 *
80
 * You also can use shortcut for the above like the following:
81
 *
82
 * ```php
83
 * $connection->transaction(function () {
84
 *     $order = new Order($customer);
85
 *     $order->save();
86
 *     $order->addItems($items);
87
 * });
88
 * ```
89
 *
90
 * If needed you can pass transaction isolation level as a second parameter:
91
 *
92
 * ```php
93
 * $connection->transaction(function (Connection $db) {
94
 *     //return $db->...
95
 * }, Transaction::READ_UNCOMMITTED);
96
 * ```
97
 *
98
 * Connection is often used as an application component and configured in the application
99
 * configuration like the following:
100
 *
101
 * ```php
102
 * 'components' => [
103
 *     'db' => [
104
 *         '__class' => \yii\db\Connection::class,
105
 *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo;charset=utf8',
106
 *         'username' => 'root',
107
 *         'password' => '',
108
 *     ],
109
 * ],
110
 * ```
111
 *
112
 * The [[dsn]] property can be defined via configuration array:
113
 *
114
 * ```php
115
 * 'components' => [
116
 *     'db' => [
117
 *         '__class' => \yii\db\Connection::class,
118
 *         'dsn' => [
119
 *             'driver' => 'mysql',
120
 *             'host' => '127.0.0.1',
121
 *             'dbname' => 'demo',
122
 *             'charset' => 'utf8',
123
 *          ],
124
 *         'username' => 'root',
125
 *         'password' => '',
126
 *     ],
127
 * ],
128
 * ```
129
 *
130
 * @property string $driverName Name of the DB driver.
131
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
132
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
133
 * sequence object. This property is read-only.
134
 * @property Connection $master The currently active master connection. `null` is returned if there is no
135
 * master available. This property is read-only.
136
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is
137
 * read-only.
138
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of
139
 * this property differs in getter and setter. See [[getQueryBuilder()]] and [[setQueryBuilder()]] for details.
140
 * @property Schema $schema The schema information for the database opened by this connection. This property
141
 * is read-only.
142
 * @property string $serverVersion Server version as a string. This property is read-only.
143
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
144
 * available and `$fallbackToMaster` is false. This property is read-only.
145
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if
146
 * no slave connection is available and `$fallbackToMaster` is false. This property is read-only.
147
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction.
148
 * This property is read-only.
149
 *
150
 * @author Qiang Xue <[email protected]>
151
 * @since 2.0
152
 */
153
class Connection extends Component implements ConnectionInterface
154
{
155
    /**
156
     * @event [[yii\base\Event|Event]] an event that is triggered after a DB connection is established
157
     */
158
    const EVENT_AFTER_OPEN = 'afterOpen';
159
    /**
160
     * @event [[yii\base\Event|Event]] an event that is triggered right before a top-level transaction is started
161
     */
162
    const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
163
    /**
164
     * @event [[yii\base\Event|Event]] an event that is triggered right after a top-level transaction is committed
165
     */
166
    const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
167
    /**
168
     * @event [[yii\base\Event|Event]] an event that is triggered right after a top-level transaction is rolled back
169
     */
170
    const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
171
172
    /**
173
     * @var string|array the Data Source Name, or DSN, contains the information required to connect to the database.
174
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.construct.php) on
175
     * the format of the DSN string.
176
     *
177
     * For [SQLite](http://php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](guide:concept-aliases)
178
     * for specifying the database path, e.g. `sqlite:@app/data/db.sql`.
179
     *
180
     * Since version 3.0.0 an array can be passed to contruct a DSN string.
181
     * The `driver` array key is used as the driver prefix of the DSN,
182
     * all further key-value pairs are rendered as `key=value` and concatenated by `;`. For example:
183
     *
184
     * ```php
185
     * 'dsn' => [
186
     *     'driver' => 'mysql',
187
     *     'host' => '127.0.0.1',
188
     *     'dbname' => 'demo',
189
     *     'charset' => 'utf8',
190
     * ],
191
     * ```
192
     *
193
     * Will result in the DSN string `mysql:host=127.0.0.1;dbname=demo`.
194
     */
195
    public $dsn;
196
    /**
197
     * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
198
     */
199
    public $username;
200
    /**
201
     * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
202
     */
203
    public $password;
204
    /**
205
     * @var array PDO attributes (name => value) that should be set when calling [[open()]]
206
     * to establish a DB connection. Please refer to the
207
     * [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for
208
     * details about available attributes.
209
     */
210
    public $attributes;
211
    /**
212
     * @var PDO the PHP PDO instance associated with this DB connection.
213
     * This property is mainly managed by [[open()]] and [[close()]] methods.
214
     * When a DB connection is active, this property will represent a PDO instance;
215
     * otherwise, it will be null.
216
     * @see pdoClass
217
     */
218
    public $pdo;
219
    /**
220
     * @var bool whether to enable schema caching.
221
     * Note that in order to enable truly schema caching, a valid cache component as specified
222
     * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
223
     * @see schemaCacheDuration
224
     * @see schemaCacheExclude
225
     * @see schemaCache
226
     */
227
    public $enableSchemaCache = false;
228
    /**
229
     * @var int number of seconds that table metadata can remain valid in cache.
230
     * Use 0 to indicate that the cached data will never expire.
231
     * @see enableSchemaCache
232
     */
233
    public $schemaCacheDuration = 3600;
234
    /**
235
     * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
236
     * The table names may contain schema prefix, if any. Do not quote the table names.
237
     * @see enableSchemaCache
238
     */
239
    public $schemaCacheExclude = [];
240
    /**
241
     * @var CacheInterface|string the cache object or the ID of the cache application component that
242
     * is used to cache the table metadata.
243
     * @see enableSchemaCache
244
     */
245
    public $schemaCache = 'cache';
246
    /**
247
     * @var bool whether to enable query caching.
248
     * Note that in order to enable query caching, a valid cache component as specified
249
     * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
250
     * Also, only the results of the queries enclosed within [[cache()]] will be cached.
251
     * @see queryCache
252
     * @see cache()
253
     * @see noCache()
254
     */
255
    public $enableQueryCache = true;
256
    /**
257
     * @var int the default number of seconds that query results can remain valid in cache.
258
     * Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
259
     * The value of this property will be used when [[cache()]] is called without a cache duration.
260
     * @see enableQueryCache
261
     * @see cache()
262
     */
263
    public $queryCacheDuration = 3600;
264
    /**
265
     * @var CacheInterface|string the cache object or the ID of the cache application component
266
     * that is used for query caching.
267
     * @see enableQueryCache
268
     */
269
    public $queryCache = 'cache';
270
    /**
271
     * @var string the charset used for database connection. The property is only used
272
     * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
273
     * as configured by the database.
274
     *
275
     * For Oracle Database, the charset must be specified in the [[dsn]], for example for UTF-8 by appending `;charset=UTF-8`
276
     * to the DSN string.
277
     *
278
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to
279
     * specify charset via [[dsn]] like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
280
     */
281
    public $charset;
282
283
    /**
284
     * @var bool whether to turn on prepare emulation. Defaults to false, meaning PDO
285
     * will use the native prepare support if available. For some databases (such as MySQL),
286
     * this may need to be set true so that PDO can emulate the prepare support to bypass
287
     * the buggy native prepare support.
288
     * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
289
     */
290
    public $emulatePrepare;
291
    /**
292
     * @var string the common prefix or suffix for table names. If a table name is given
293
     * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
294
     * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
295
     */
296
    public $tablePrefix = '';
297
    /**
298
     * @var array mapping between PDO driver names and [[Schema]] classes.
299
     * The keys of the array are PDO driver names while the values are either the corresponding
300
     * schema class names or configurations. Please refer to [[Yii::createObject()]] for
301
     * details on how to specify a configuration.
302
     *
303
     * This property is mainly used by [[getSchema()]] when fetching the database schema information.
304
     * You normally do not need to set this property unless you want to use your own
305
     * [[Schema]] class to support DBMS that is not supported by Yii.
306
     */
307
    public $schemaMap = [
308
        'pgsql' => pgsql\Schema::class, // PostgreSQL
309
        'mysqli' => mysql\Schema::class, // MySQL
310
        'mysql' => mysql\Schema::class, // MySQL
311
        'sqlite' => sqlite\Schema::class, // sqlite 3
312
        'sqlite2' => sqlite\Schema::class, // sqlite 2
313
    ];
314
    /**
315
     * @var string Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
316
     * @see pdo
317
     */
318
    public $pdoClass;
319
    /**
320
     * @var array mapping between PDO driver names and [[Command]] classes.
321
     * The keys of the array are PDO driver names while the values are either the corresponding
322
     * command class names or configurations. Please refer to [[Yii::createObject()]] for
323
     * details on how to specify a configuration.
324
     *
325
     * This property is mainly used by [[createCommand()]] to create new database [[Command]] objects.
326
     * You normally do not need to set this property unless you want to use your own
327
     * [[Command]] class or support DBMS that is not supported by Yii.
328
     * @since 2.0.14
329
     */
330
    public $commandMap = [
331
        'pgsql' => 'yii\db\Command', // PostgreSQL
332
        'mysqli' => 'yii\db\Command', // MySQL
333
        'mysql' => 'yii\db\Command', // MySQL
334
        'sqlite' => 'yii\db\sqlite\Command', // sqlite 3
335
        'sqlite2' => 'yii\db\sqlite\Command', // sqlite 2
336
        'sqlsrv' => 'yii\db\Command', // newer MSSQL driver on MS Windows hosts
337
        'oci' => 'yii\db\Command', // Oracle driver
338
        'mssql' => 'yii\db\Command', // older MSSQL driver on MS Windows hosts
339
        'dblib' => 'yii\db\Command', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
340
    ];
341
    /**
342
     * @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
343
     * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
344
     */
345
    public $enableSavepoint = true;
346
    /**
347
     * @var CacheInterface|string|false the cache object or the ID of the cache application component that is used to store
348
     * the health status of the DB servers specified in [[masters]] and [[slaves]].
349
     * This is used only when read/write splitting is enabled or [[masters]] is not empty.
350
     * Set boolean `false` to disabled server status caching.
351
     */
352
    public $serverStatusCache = 'cache';
353
    /**
354
     * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
355
     * This is used together with [[serverStatusCache]].
356
     */
357
    public $serverRetryInterval = 600;
358
    /**
359
     * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
360
     * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
361
     */
362
    public $enableSlaves = true;
363
    /**
364
     * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
365
     * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
366
     * for performing read queries only.
367
     * @see enableSlaves
368
     * @see slaveConfig
369
     */
370
    public $slaves = [];
371
    /**
372
     * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
373
     * For example,
374
     *
375
     * ```php
376
     * [
377
     *     'username' => 'slave',
378
     *     'password' => 'slave',
379
     *     'attributes' => [
380
     *         // use a smaller connection timeout
381
     *         PDO::ATTR_TIMEOUT => 10,
382
     *     ],
383
     * ]
384
     * ```
385
     */
386
    public $slaveConfig = [];
387
    /**
388
     * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
389
     * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
390
     * which will be used by this object.
391
     * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
392
     * be ignored.
393
     * @see masterConfig
394
     * @see shuffleMasters
395
     */
396
    public $masters = [];
397
    /**
398
     * @var array the configuration that should be merged with every master configuration listed in [[masters]].
399
     * For example,
400
     *
401
     * ```php
402
     * [
403
     *     'username' => 'master',
404
     *     'password' => 'master',
405
     *     'attributes' => [
406
     *         // use a smaller connection timeout
407
     *         PDO::ATTR_TIMEOUT => 10,
408
     *     ],
409
     * ]
410
     * ```
411
     */
412
    public $masterConfig = [];
413
    /**
414
     * @var bool whether to shuffle [[masters]] before getting one.
415
     * @since 2.0.11
416
     * @see masters
417
     */
418
    public $shuffleMasters = true;
419
    /**
420
     * @var bool whether to enable logging of database queries. Defaults to true.
421
     * You may want to disable this option in a production environment to gain performance
422
     * if you do not need the information being logged.
423
     * @since 2.0.12
424
     * @see enableProfiling
425
     */
426
    public $enableLogging = true;
427
    /**
428
     * @var bool whether to enable profiling of opening database connection and database queries. Defaults to true.
429
     * You may want to disable this option in a production environment to gain performance
430
     * if you do not need the information being logged.
431
     * @since 2.0.12
432
     * @see enableLogging
433
     */
434
    public $enableProfiling = true;
435
436
    /**
437
     * @var Transaction the currently active transaction
438
     */
439
    private $_transaction;
440
    /**
441
     * @var Schema the database schema
442
     */
443
    private $_schema;
444
    /**
445
     * @var string driver name
446
     */
447
    private $_driverName;
448
    /**
449
     * @var Connection|false the currently active master connection
450
     */
451
    private $_master = false;
452
    /**
453
     * @var Connection|false the currently active slave connection
454
     */
455
    private $_slave = false;
456
    /**
457
     * @var array query cache parameters for the [[cache()]] calls
458
     */
459
    private $_queryCacheInfo = [];
460
461
    /**
462
     * Constructor based on dns info
463
     * @param array dns info
464
     */
465 8
    public function __construct(array $dsn = null)
466
    {
467 8
        if (is_array($dsn)) {
468
            $this->dsn = $this->buildDSN($dsn);
469
        }
470
     }
471
472
    /**
473
     * Returns a value indicating whether the DB connection is established.
474
     * @return bool whether the DB connection is established
475
     */
476 4
    public function getIsActive()
477
    {
478 4
        return $this->pdo !== null;
479
    }
480
481
    /**
482
     * Uses query cache for the queries performed with the callable.
483
     *
484
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
485
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
486
     * For example,
487
     *
488
     * ```php
489
     * // The customer will be fetched from cache if available.
490
     * // If not, the query will be made against DB and cached for use next time.
491
     * $customer = $db->cache(function (Connection $db) {
492
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
493
     * });
494
     * ```
495
     *
496
     * Note that query cache is only meaningful for queries that return results. For queries performed with
497
     * [[Command::execute()]], query cache will not be used.
498
     *
499
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
500
     * The signature of the callable is `function (Connection $db)`.
501
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
502
     * not set, the value of [[queryCacheDuration]] will be used instead.
503
     * Use 0 to indicate that the cached data will never expire.
504
     * @param \yii\cache\dependencies\Dependency $dependency the cache dependency associated with the cached query results.
505
     * @return mixed the return result of the callable
506
     * @throws \Throwable if there is any exception during query
507
     * @see enableQueryCache
508
     * @see queryCache
509
     * @see noCache()
510
     */
511
    public function cache(callable $callable, $duration = null, $dependency = null)
512
    {
513
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
514
        try {
515
            $result = call_user_func($callable, $this);
516
            array_pop($this->_queryCacheInfo);
517
            return $result;
518
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
519
            array_pop($this->_queryCacheInfo);
520
            throw $e;
521
        }
522
    }
523
524
    /**
525
     * Disables query cache temporarily.
526
     *
527
     * Queries performed within the callable will not use query cache at all. For example,
528
     *
529
     * ```php
530
     * $db->cache(function (Connection $db) {
531
     *
532
     *     // ... queries that use query cache ...
533
     *
534
     *     return $db->noCache(function (Connection $db) {
535
     *         // this query will not use query cache
536
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
537
     *     });
538
     * });
539
     * ```
540
     *
541
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
542
     * The signature of the callable is `function (Connection $db)`.
543
     * @return mixed the return result of the callable
544
     * @throws \Throwable if there is any exception during query
545
     * @see enableQueryCache
546
     * @see queryCache
547
     * @see cache()
548
     */
549
    public function noCache(callable $callable)
550
    {
551
        $this->_queryCacheInfo[] = false;
552
        try {
553
            $result = call_user_func($callable, $this);
554
            array_pop($this->_queryCacheInfo);
555
            return $result;
556
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
557
            array_pop($this->_queryCacheInfo);
558
            throw $e;
559
        }
560
    }
561
562
    /**
563
     * Returns the current query cache information.
564
     * This method is used internally by [[Command]].
565
     * @param int $duration the preferred caching duration. If null, it will be ignored.
566
     * @param \yii\cache\dependencies\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
567
     * @return array the current query cache information, or null if query cache is not enabled.
568
     * @internal
569
     */
570 8
    public function getQueryCacheInfo($duration, $dependency)
571
    {
572 8
        if (!$this->enableQueryCache) {
573
            return null;
574
        }
575
576 8
        $info = end($this->_queryCacheInfo);
577 8
        if (is_array($info)) {
578
            if ($duration === null) {
579
                $duration = $info[0];
580
            }
581
            if ($dependency === null) {
582
                $dependency = $info[1];
583
            }
584
        }
585
586 8
        if ($duration === 0 || $duration > 0) {
587
            if (is_string($this->queryCache) && Yii::getApp()) {
0 ignored issues
show
Deprecated Code introduced by
The method yii\helpers\BaseYii::getApp() has been deprecated with message: 3.0.0 Use DI instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
588
                $cache = Yii::getApp()->get($this->queryCache, false);
0 ignored issues
show
Deprecated Code introduced by
The method yii\helpers\BaseYii::getApp() has been deprecated with message: 3.0.0 Use DI instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
589
            } else {
590
                $cache = $this->queryCache;
591
            }
592
            if ($cache instanceof CacheInterface) {
593
                return [$cache, $duration, $dependency];
594
            }
595
        }
596
597 8
        return null;
598
    }
599
600
    /**
601
     * Establishes a DB connection.
602
     * It does nothing if a DB connection has already been established.
603
     * @throws Exception if connection fails
604
     */
605 8
    public function open()
606
    {
607 8
        if ($this->pdo !== null) {
608 8
            return;
609
        }
610
611 8
        if (!empty($this->masters)) {
612
            $db = $this->getMaster();
613
            if ($db !== null) {
614
                $this->pdo = $db->pdo;
615
                return;
616
            }
617
618
            throw new InvalidConfigException('None of the master DB servers is available.');
619
        }
620
621 8
        if (empty($this->dsn)) {
622
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
623
        }
624
625 8
        $token = 'Opening DB connection: ' . $this->dsn;
626 8
        $enableProfiling = $this->enableProfiling;
627
        try {
628 8
            Yii::info($token, __METHOD__);
629 8
            if ($enableProfiling) {
630 8
                Yii::beginProfile($token, __METHOD__);
631
            }
632
633 8
            $this->pdo = $this->createPdoInstance();
634 8
            $this->initConnection();
635
636 8
            if ($enableProfiling) {
637 8
                Yii::endProfile($token, __METHOD__);
638
            }
639
        } catch (\PDOException $e) {
640
            if ($enableProfiling) {
641
                Yii::endProfile($token, __METHOD__);
642
            }
643
644
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
645
        }
646
    }
647
648
    /**
649
     * Closes the currently active DB connection.
650
     * It does nothing if the connection is already closed.
651
     */
652 8
    public function close()
653
    {
654 8
        if ($this->_master) {
655
            if ($this->pdo === $this->_master->pdo) {
656
                $this->pdo = null;
657
            }
658
659
            $this->_master->close();
660
            $this->_master = false;
661
        }
662
663 8
        if ($this->pdo !== null) {
664 8
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
665 8
            $this->pdo = null;
666 8
            $this->_schema = null;
667 8
            $this->_transaction = null;
668
        }
669
670 8
        if ($this->_slave) {
671
            $this->_slave->close();
672
            $this->_slave = false;
673
        }
674
    }
675
676
    /**
677
     * Creates the PDO instance.
678
     * This method is called by [[open]] to establish a DB connection.
679
     * The default implementation will create a PHP PDO instance.
680
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
681
     * @return PDO the pdo instance
682
     */
683 8
    protected function createPdoInstance()
684
    {
685 8
        $pdoClass = $this->pdoClass;
686 8
        if ($pdoClass === null) {
687 8
            $pdoClass = 'PDO';
688 8
            if ($this->_driverName !== null) {
689
                $driver = $this->_driverName;
690 8
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
691 8
                $driver = strtolower(substr($this->dsn, 0, $pos));
692
            }
693 8
            if (isset($driver)) {
694 8
                if ($driver === 'mssql' || $driver === 'dblib') {
695
                    $pdoClass = mssql\PDO::class;
696 8
                } elseif ($driver === 'sqlsrv') {
697
                    $pdoClass = mssql\SqlsrvPDO::class;
698
                }
699
            }
700
        }
701
702 8
        $dsn = $this->dsn;
703 8
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
704
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
0 ignored issues
show
Deprecated Code introduced by
The method yii\helpers\BaseYii::getAlias() has been deprecated with message: 3.0.0 Use [[yii\base\Application::get()|Application::get()]] instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
705
        }
706
707 8
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
708
    }
709
710
    /**
711
     * Initializes the DB connection.
712
     * This method is invoked right after the DB connection is established.
713
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
714
     * if [[emulatePrepare]] is true.
715
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
716
     */
717 8
    protected function initConnection()
718
    {
719 8
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
720 8
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
721
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
722
        }
723 8
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
724
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
725
        }
726 8
        $this->trigger(self::EVENT_AFTER_OPEN);
727
    }
728
729
    /**
730
     * Creates a command for execution.
731
     * @param string $sql the SQL statement to be executed
732
     * @param array $params the parameters to be bound to the SQL statement
733
     * @return Command the DB command
734
     */
735 8
    public function createCommand($sql = null, $params = [])
736
    {
737 8
        $driver = $this->getDriverName();
738 8
        $config = ['__class' => Command::class];
739 8
        if (isset($this->commandMap[$driver])) {
740 8
            $config = !is_array($this->commandMap[$driver]) ? ['__class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
741
        }
742 8
        $config['db'] = $this;
743 8
        $config['sql'] = $sql;
744
        /** @var Command $command */
745 8
        $command = Yii::createObject($config);
746 8
        return $command->bindValues($params);
747
    }
748
749
    /**
750
     * Returns the currently active transaction.
751
     * @return Transaction|null the currently active transaction. Null if no active transaction.
752
     */
753 8
    public function getTransaction()
754
    {
755 8
        return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
756
    }
757
758
    /**
759
     * Starts a transaction.
760
     * @param string|null $isolationLevel The isolation level to use for this transaction.
761
     * See [[Transaction::begin()]] for details.
762
     * @return Transaction the transaction initiated
763
     */
764
    public function beginTransaction($isolationLevel = null)
765
    {
766
        $this->open();
767
768
        if (($transaction = $this->getTransaction()) === null) {
769
            $transaction = $this->_transaction = new Transaction($this);
770
        }
771
        $transaction->begin($isolationLevel);
772
773
        return $transaction;
774
    }
775
776
    /**
777
     * Executes callback provided in a transaction.
778
     *
779
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
780
     * @param string|null $isolationLevel The isolation level to use for this transaction.
781
     * See [[Transaction::begin()]] for details.
782
     * @throws \Throwable if there is any exception during query. In this case the transaction will be rolled back.
783
     * @return mixed result of callback function
784
     */
785
    public function transaction(callable $callback, $isolationLevel = null)
786
    {
787
        $transaction = $this->beginTransaction($isolationLevel);
788
        $level = $transaction->level;
789
790
        try {
791
            $result = call_user_func($callback, $this);
792
            if ($transaction->isActive && $transaction->level === $level) {
793
                $transaction->commit();
794
            }
795
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
796
            $this->rollbackTransactionOnLevel($transaction, $level);
797
            throw $e;
798
        }
799
800
        return $result;
801
    }
802
803
    /**
804
     * Rolls back given [[Transaction]] object if it's still active and level match.
805
     * In some cases rollback can fail, so this method is fail safe. Exception thrown
806
     * from rollback will be caught and just logged with [[\Yii::error()]].
807
     * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
808
     * @param int $level Transaction level just after [[beginTransaction()]] call.
809
     */
810
    private function rollbackTransactionOnLevel($transaction, $level)
811
    {
812
        if ($transaction->isActive && $transaction->level === $level) {
813
            // https://github.com/yiisoft/yii2/pull/13347
814
            try {
815
                $transaction->rollBack();
816
            } catch (\Exception $e) {
817
                Yii::error($e, __METHOD__);
818
                // hide this exception to be able to continue throwing original exception outside
819
            }
820
        }
821
    }
822
823
    /**
824
     * Returns the schema information for the database opened by this connection.
825
     * @return Schema the schema information for the database opened by this connection.
826
     * @throws NotSupportedException if there is no support for the current driver type
827
     */
828 8
    public function getSchema()
829
    {
830 8
        if ($this->_schema !== null) {
831 8
            return $this->_schema;
832
        }
833
834 8
        $driver = $this->getDriverName();
835 8
        if (isset($this->schemaMap[$driver])) {
836 8
            $class = $this->schemaMap[$driver];
837
838 8
            return $this->_schema = new $class($this);
839
        }
840
841
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
842
    }
843
844
    /**
845
     * Returns the query builder for the current DB connection.
846
     * @return QueryBuilder the query builder for the current DB connection.
847
     */
848 8
    public function getQueryBuilder()
849
    {
850 8
        return $this->getSchema()->getQueryBuilder();
851
    }
852
853
    /**
854
     * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
855
     *
856
     * @param iterable $config the [[QueryBuilder]] properties to be configured.
857
     * @since 2.0.14
858
     */
859
    public function setQueryBuilder(iterable $config)
860
    {
861
        $builder = $this->getQueryBuilder();
862
        foreach ($config as $key => $value) {
863
            $builder->{$key} = $value;
864
        }
865
    }
866
867
    /**
868
     * Obtains the schema information for the named table.
869
     * @param string $name table name.
870
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
871
     * @return TableSchema table schema information. Null if the named table does not exist.
872
     */
873 5
    public function getTableSchema($name, $refresh = false)
874
    {
875 5
        return $this->getSchema()->getTableSchema($name, $refresh);
876
    }
877
878
    /**
879
     * Returns the ID of the last inserted row or sequence value.
880
     * @param string $sequenceName name of the sequence object (required by some DBMS)
881
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
882
     * @see http://php.net/manual/en/pdo.lastinsertid.php
883
     */
884
    public function getLastInsertID($sequenceName = '')
885
    {
886
        return $this->getSchema()->getLastInsertID($sequenceName);
887
    }
888
889
    /**
890
     * Quotes a string value for use in a query.
891
     * Note that if the parameter is not a string, it will be returned without change.
892
     * @param string $value string to be quoted
893
     * @return string the properly quoted string
894
     * @see http://php.net/manual/en/pdo.quote.php
895
     */
896 5
    public function quoteValue($value)
897
    {
898 5
        return $this->getSchema()->quoteValue($value);
899
    }
900
901
    /**
902
     * Quotes a table name for use in a query.
903
     * If the table name contains schema prefix, the prefix will also be properly quoted.
904
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
905
     * then this method will do nothing.
906
     * @param string $name table name
907
     * @return string the properly quoted table name
908
     */
909 8
    public function quoteTableName($name)
910
    {
911 8
        return $this->getSchema()->quoteTableName($name);
912
    }
913
914
    /**
915
     * Quotes a column name for use in a query.
916
     * If the column name contains prefix, the prefix will also be properly quoted.
917
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
918
     * then this method will do nothing.
919
     * @param string $name column name
920
     * @return string the properly quoted column name
921
     */
922 3
    public function quoteColumnName($name)
923
    {
924 3
        return $this->getSchema()->quoteColumnName($name);
925
    }
926
927
    /**
928
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
929
     * Tokens enclosed within double curly brackets are treated as table names, while
930
     * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
931
     * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
932
     * with [[tablePrefix]].
933
     * @param string $sql the SQL to be quoted
934
     * @return string the quoted SQL
935
     */
936 8
    public function quoteSql($sql)
937
    {
938 8
        return preg_replace_callback(
939 8
            '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
940
            function ($matches) {
941
                if (isset($matches[3])) {
942
                    return $this->quoteColumnName($matches[3]);
943
                }
944
945
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
946 8
            },
947 8
            $sql
948
        );
949
    }
950
951
    /**
952
     * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
953
     * by an end user.
954
     * @return string name of the DB driver
955
     */
956 8
    public function getDriverName()
957
    {
958 8
        if ($this->_driverName === null) {
959 8
            if (($pos = strpos($this->dsn, ':')) !== false) {
960 8
                $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
961
            } else {
962
                $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
963
            }
964
        }
965
966 8
        return $this->_driverName;
967
    }
968
969
    /**
970
     * Changes the current driver name.
971
     * @param string $driverName name of the DB driver
972
     */
973
    public function setDriverName($driverName)
974
    {
975
        $this->_driverName = strtolower($driverName);
976
    }
977
978
    /**
979
     * Returns a server version as a string comparable by [[\version_compare()]].
980
     * @return string server version as a string.
981
     * @since 2.0.14
982
     */
983
    public function getServerVersion()
984
    {
985
        return $this->getSchema()->getServerVersion();
986
    }
987
988
    /**
989
     * Returns the PDO instance for the currently active slave connection.
990
     * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
991
     * will be returned by this method.
992
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
993
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
994
     * is available and `$fallbackToMaster` is false.
995
     */
996 8
    public function getSlavePdo($fallbackToMaster = true)
997
    {
998 8
        $db = $this->getSlave(false);
999 8
        if ($db === null) {
1000 8
            return $fallbackToMaster ? $this->getMasterPdo() : null;
1001
        }
1002
1003
        return $db->pdo;
1004
    }
1005
1006
    /**
1007
     * Returns the PDO instance for the currently active master connection.
1008
     * This method will open the master DB connection and then return [[pdo]].
1009
     * @return PDO the PDO instance for the currently active master connection.
1010
     */
1011 8
    public function getMasterPdo()
1012
    {
1013 8
        $this->open();
1014 8
        return $this->pdo;
1015
    }
1016
1017
    /**
1018
     * Returns the currently active slave connection.
1019
     * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
1020
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
1021
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
1022
     * `$fallbackToMaster` is false.
1023
     */
1024 8
    public function getSlave($fallbackToMaster = true)
1025
    {
1026 8
        if (!$this->enableSlaves) {
1027
            return $fallbackToMaster ? $this : null;
1028
        }
1029
1030 8
        if ($this->_slave === false) {
1031 8
            $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
1032
        }
1033
1034 8
        return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
1035
    }
1036
1037
    /**
1038
     * Returns the currently active master connection.
1039
     * If this method is called for the first time, it will try to open a master connection.
1040
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
1041
     * @since 2.0.11
1042
     */
1043
    public function getMaster()
1044
    {
1045
        if ($this->_master === false) {
1046
            $this->_master = $this->shuffleMasters
1047
                ? $this->openFromPool($this->masters, $this->masterConfig)
1048
                : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
1049
        }
1050
1051
        return $this->_master;
1052
    }
1053
1054
    /**
1055
     * Executes the provided callback by using the master connection.
1056
     *
1057
     * This method is provided so that you can temporarily force using the master connection to perform
1058
     * DB operations even if they are read queries. For example,
1059
     *
1060
     * ```php
1061
     * $result = $db->useMaster(function ($db) {
1062
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1063
     * });
1064
     * ```
1065
     *
1066
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1067
     * `function (Connection $db)`. Its return value will be returned by this method.
1068
     * @return mixed the return value of the callback
1069
     * @throws \Throwable if there is any exception thrown from the callback
1070
     */
1071
    public function useMaster(callable $callback)
1072
    {
1073
        if ($this->enableSlaves) {
1074
            $this->enableSlaves = false;
1075
            try {
1076
                $result = call_user_func($callback, $this);
1077
            } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
1078
                $this->enableSlaves = true;
1079
                throw $e;
1080
            }
1081
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
1082
            $this->enableSlaves = true;
1083
        } else {
1084
            $result = call_user_func($callback, $this);
1085
        }
1086
1087
        return $result;
1088
    }
1089
1090
    /**
1091
     * Opens the connection to a server in the pool.
1092
     * This method implements the load balancing among the given list of the servers.
1093
     * Connections will be tried in random order.
1094
     * @param array $pool the list of connection configurations in the server pool
1095
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1096
     * @return Connection the opened DB connection, or `null` if no server is available
1097
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1098
     */
1099 8
    protected function openFromPool(array $pool, array $sharedConfig)
1100
    {
1101 8
        shuffle($pool);
1102 8
        return $this->openFromPoolSequentially($pool, $sharedConfig);
1103
    }
1104
1105
    /**
1106
     * Opens the connection to a server in the pool.
1107
     * This method implements the load balancing among the given list of the servers.
1108
     * Connections will be tried in sequential order.
1109
     * @param array $pool the list of connection configurations in the server pool
1110
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1111
     * @return Connection the opened DB connection, or `null` if no server is available
1112
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1113
     * @since 2.0.11
1114
     */
1115 8
    protected function openFromPoolSequentially(array $pool, array $sharedConfig)
1116
    {
1117 8
        if (empty($pool)) {
1118 8
            return null;
1119
        }
1120
1121
        if (!isset($sharedConfig['__class'])) {
1122
            $sharedConfig['__class'] = get_class($this);
1123
        }
1124
1125
        $cache = is_string($this->serverStatusCache) ? Yii::getApp()->get($this->serverStatusCache, false) : $this->serverStatusCache;
0 ignored issues
show
Deprecated Code introduced by
The method yii\helpers\BaseYii::getApp() has been deprecated with message: 3.0.0 Use DI instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1126
1127
        foreach ($pool as $config) {
1128
            $config = array_merge($sharedConfig, $config);
1129
            if (empty($config['dsn'])) {
1130
                throw new InvalidConfigException('The "dsn" option must be specified.');
1131
            }
1132
1133
            $key = [__METHOD__, $config['dsn']];
1134
            if ($cache instanceof CacheInterface && $cache->get($key)) {
0 ignored issues
show
Documentation introduced by
$key is of type array<integer,?,{"0":"string","1":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1135
                // should not try this dead server now
1136
                continue;
1137
            }
1138
1139
            /* @var $db Connection */
1140
            $db = Yii::createObject($config);
1141
1142
            try {
1143
                $db->open();
1144
                return $db;
1145
            } catch (\Exception $e) {
1146
                Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1147
                if ($cache instanceof CacheInterface) {
1148
                    // mark this server as dead and only retry it after the specified interval
1149
                    $cache->set($key, 1, $this->serverRetryInterval);
1150
                }
1151
            }
1152
        }
1153
1154
        return null;
1155
    }
1156
1157
    /**
1158
     * Build the Data Source Name or DSN
1159
     * @param array $config the DSN configurations
1160
     * @return string the formated DSN
1161
     * @throws InvalidConfigException if 'driver' key was not defined
1162
     */
1163
    private function buildDSN(array $config)
1164
    {
1165
        if (isset($config['driver'])) {
1166
            $driver = $config['driver'];
1167
            unset($config['driver']);
1168
1169
            $parts = [];
1170
            foreach ($config as $key => $value) {
1171
                $parts[] = "$key=$value";
1172
            }
1173
1174
            return "$driver:" . implode(';', $parts);
1175
        }
1176
        throw new InvalidConfigException("Connection DSN 'driver' must be set.");
1177
    }
1178
1179
    /**
1180
     * Close the connection before serializing.
1181
     * @return array
1182
     */
1183
    public function __sleep()
1184
    {
1185
        $fields = (array) $this;
1186
1187
        unset($fields['pdo']);
1188
        unset($fields["\000" . __CLASS__ . "\000" . '_master']);
1189
        unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
1190
        unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
1191
        unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
1192
1193
        return array_keys($fields);
1194
    }
1195
1196
    /**
1197
     * Reset the connection after cloning.
1198
     */
1199
    public function __clone()
1200
    {
1201
        parent::__clone();
1202
1203
        $this->_master = false;
1204
        $this->_slave = false;
1205
        $this->_schema = null;
1206
        $this->_transaction = null;
1207
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
1208
            // reset PDO connection, unless its sqlite in-memory, which can only have one connection
1209
            $this->pdo = null;
1210
        }
1211
    }
1212
}
1213