Passed
Push — master ( 385fe1...5adb55 )
by Alexander
10:01
created

Connection::getEnableReplicas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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;
12
use yii\base\Component;
13
use yii\base\InvalidConfigException;
14
use yii\base\NotSupportedException;
15
use yii\caching\CacheInterface;
16
17
/**
18
 * Connection represents a connection to a database via [PDO](https://secure.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](https://secure.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',
105
 *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
106
 *         'username' => 'root',
107
 *         'password' => '',
108
 *         'charset' => 'utf8',
109
 *     ],
110
 * ],
111
 * ```
112
 *
113
 * @property string $driverName Name of the DB driver.
114
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
115
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
116
 * sequence object. This property is read-only.
117
 * @property Connection $master The currently active master connection. `null` is returned if there is no
118
 * master available. This property is read-only.
119
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is
120
 * read-only.
121
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of
122
 * this property differs in getter and setter. See [[getQueryBuilder()]] and [[setQueryBuilder()]] for details.
123
 * @property Schema $schema The schema information for the database opened by this connection. This property
124
 * is read-only.
125
 * @property string $serverVersion Server version as a string. This property is read-only.
126
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
127
 * available and `$fallbackToMaster` is false. This property is read-only.
128
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if
129
 * no slave connection is available and `$fallbackToMaster` is false. This property is read-only.
130
 * @property Transaction|null $transaction The currently active transaction. Null if no active transaction.
131
 * This property is read-only.
132
 *
133
 * @author Qiang Xue <[email protected]>
134
 * @since 2.0
135
 */
136
class Connection extends Component
137
{
138
    /**
139
     * @event yii\base\Event an event that is triggered after a DB connection is established
140
     */
141
    const EVENT_AFTER_OPEN = 'afterOpen';
142
    /**
143
     * @event yii\base\Event an event that is triggered right before a top-level transaction is started
144
     */
145
    const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
146
    /**
147
     * @event yii\base\Event an event that is triggered right after a top-level transaction is committed
148
     */
149
    const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
150
    /**
151
     * @event yii\base\Event an event that is triggered right after a top-level transaction is rolled back
152
     */
153
    const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
154
155
    /**
156
     * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
157
     * Please refer to the [PHP manual](https://secure.php.net/manual/en/pdo.construct.php) on
158
     * the format of the DSN string.
159
     *
160
     * For [SQLite](https://secure.php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](guide:concept-aliases)
161
     * for specifying the database path, e.g. `sqlite:@app/data/db.sql`.
162
     *
163
     * @see charset
164
     */
165
    public $dsn;
166
    /**
167
     * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
168
     */
169
    public $username;
170
    /**
171
     * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
172
     */
173
    public $password;
174
    /**
175
     * @var array PDO attributes (name => value) that should be set when calling [[open()]]
176
     * to establish a DB connection. Please refer to the
177
     * [PHP manual](https://secure.php.net/manual/en/pdo.setattribute.php) for
178
     * details about available attributes.
179
     */
180
    public $attributes;
181
    /**
182
     * @var PDO the PHP PDO instance associated with this DB connection.
183
     * This property is mainly managed by [[open()]] and [[close()]] methods.
184
     * When a DB connection is active, this property will represent a PDO instance;
185
     * otherwise, it will be null.
186
     * @see pdoClass
187
     */
188
    public $pdo;
189
    /**
190
     * @var bool whether to enable schema caching.
191
     * Note that in order to enable truly schema caching, a valid cache component as specified
192
     * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
193
     * @see schemaCacheDuration
194
     * @see schemaCacheExclude
195
     * @see schemaCache
196
     */
197
    public $enableSchemaCache = false;
198
    /**
199
     * @var int number of seconds that table metadata can remain valid in cache.
200
     * Use 0 to indicate that the cached data will never expire.
201
     * @see enableSchemaCache
202
     */
203
    public $schemaCacheDuration = 3600;
204
    /**
205
     * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
206
     * The table names may contain schema prefix, if any. Do not quote the table names.
207
     * @see enableSchemaCache
208
     */
209
    public $schemaCacheExclude = [];
210
    /**
211
     * @var CacheInterface|string the cache object or the ID of the cache application component that
212
     * is used to cache the table metadata.
213
     * @see enableSchemaCache
214
     */
215
    public $schemaCache = 'cache';
216
    /**
217
     * @var bool whether to enable query caching.
218
     * Note that in order to enable query caching, a valid cache component as specified
219
     * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
220
     * Also, only the results of the queries enclosed within [[cache()]] will be cached.
221
     * @see queryCache
222
     * @see cache()
223
     * @see noCache()
224
     */
225
    public $enableQueryCache = true;
226
    /**
227
     * @var int the default number of seconds that query results can remain valid in cache.
228
     * Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
229
     * The value of this property will be used when [[cache()]] is called without a cache duration.
230
     * @see enableQueryCache
231
     * @see cache()
232
     */
233
    public $queryCacheDuration = 3600;
234
    /**
235
     * @var CacheInterface|string the cache object or the ID of the cache application component
236
     * that is used for query caching.
237
     * @see enableQueryCache
238
     */
239
    public $queryCache = 'cache';
240
    /**
241
     * @var string the charset used for database connection. The property is only used
242
     * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
243
     * as configured by the database.
244
     *
245
     * For Oracle Database, the charset must be specified in the [[dsn]], for example for UTF-8 by appending `;charset=UTF-8`
246
     * to the DSN string.
247
     *
248
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to
249
     * specify charset via [[dsn]] like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
250
     */
251
    public $charset;
252
    /**
253
     * @var bool whether to turn on prepare emulation. Defaults to false, meaning PDO
254
     * will use the native prepare support if available. For some databases (such as MySQL),
255
     * this may need to be set true so that PDO can emulate the prepare support to bypass
256
     * the buggy native prepare support.
257
     * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
258
     */
259
    public $emulatePrepare;
260
    /**
261
     * @var string the common prefix or suffix for table names. If a table name is given
262
     * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
263
     * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
264
     */
265
    public $tablePrefix = '';
266
    /**
267
     * @var array mapping between PDO driver names and [[Schema]] classes.
268
     * The keys of the array are PDO driver names while the values are either the corresponding
269
     * schema class names or configurations. Please refer to [[Yii::createObject()]] for
270
     * details on how to specify a configuration.
271
     *
272
     * This property is mainly used by [[getSchema()]] when fetching the database schema information.
273
     * You normally do not need to set this property unless you want to use your own
274
     * [[Schema]] class to support DBMS that is not supported by Yii.
275
     */
276
    public $schemaMap = [
277
        'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
278
        'mysqli' => 'yii\db\mysql\Schema', // MySQL
279
        'mysql' => 'yii\db\mysql\Schema', // MySQL
280
        'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
281
        'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
282
        'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
283
        'oci' => 'yii\db\oci\Schema', // Oracle driver
284
        'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
285
        'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
286
        'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
287
    ];
288
    /**
289
     * @var string Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
290
     * @see pdo
291
     */
292
    public $pdoClass;
293
    /**
294
     * @var string the class used to create new database [[Command]] objects. If you want to extend the [[Command]] class,
295
     * you may configure this property to use your extended version of the class.
296
     * Since version 2.0.14 [[$commandMap]] is used if this property is set to its default value.
297
     * @see createCommand
298
     * @since 2.0.7
299
     * @deprecated since 2.0.14. Use [[$commandMap]] for precise configuration.
300
     */
301
    public $commandClass = 'yii\db\Command';
302
    /**
303
     * @var array mapping between PDO driver names and [[Command]] classes.
304
     * The keys of the array are PDO driver names while the values are either the corresponding
305
     * command class names or configurations. Please refer to [[Yii::createObject()]] for
306
     * details on how to specify a configuration.
307
     *
308
     * This property is mainly used by [[createCommand()]] to create new database [[Command]] objects.
309
     * You normally do not need to set this property unless you want to use your own
310
     * [[Command]] class or support DBMS that is not supported by Yii.
311
     * @since 2.0.14
312
     */
313
    public $commandMap = [
314
        'pgsql' => 'yii\db\Command', // PostgreSQL
315
        'mysqli' => 'yii\db\Command', // MySQL
316
        'mysql' => 'yii\db\Command', // MySQL
317
        'sqlite' => 'yii\db\sqlite\Command', // sqlite 3
318
        'sqlite2' => 'yii\db\sqlite\Command', // sqlite 2
319
        'sqlsrv' => 'yii\db\Command', // newer MSSQL driver on MS Windows hosts
320
        'oci' => 'yii\db\oci\Command', // Oracle driver
321
        'mssql' => 'yii\db\Command', // older MSSQL driver on MS Windows hosts
322
        'dblib' => 'yii\db\Command', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
323
        'cubrid' => 'yii\db\Command', // CUBRID
324
    ];
325
    /**
326
     * @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
327
     * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
328
     */
329
    public $enableSavepoint = true;
330
    /**
331
     * @var CacheInterface|string|false the cache object or the ID of the cache application component that is used to store
332
     * the health status of the DB servers specified in [[masters]] and [[slaves]].
333
     * This is used only when read/write splitting is enabled or [[masters]] is not empty.
334
     * Set boolean `false` to disabled server status caching.
335
     * @see openFromPoolSequentially() for details about the failover behavior.
336
     * @see serverRetryInterval
337
     */
338
    public $serverStatusCache = 'cache';
339
    /**
340
     * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
341
     * This is used together with [[serverStatusCache]].
342
     */
343
    public $serverRetryInterval = 600;
344
    /**
345
     * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
346
     * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
347
     */
348
    public $enableSlaves = true;
349
    /**
350
     * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
351
     * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
352
     * for performing read queries only.
353
     * @see enableSlaves
354
     * @see slaveConfig
355
     */
356
    public $slaves = [];
357
    /**
358
     * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
359
     * For example,
360
     *
361
     * ```php
362
     * [
363
     *     'username' => 'slave',
364
     *     'password' => 'slave',
365
     *     'attributes' => [
366
     *         // use a smaller connection timeout
367
     *         PDO::ATTR_TIMEOUT => 10,
368
     *     ],
369
     * ]
370
     * ```
371
     */
372
    public $slaveConfig = [];
373
    /**
374
     * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
375
     * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
376
     * which will be used by this object.
377
     * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
378
     * be ignored.
379
     * @see masterConfig
380
     * @see shuffleMasters
381
     */
382
    public $masters = [];
383
    /**
384
     * @var array the configuration that should be merged with every master configuration listed in [[masters]].
385
     * For example,
386
     *
387
     * ```php
388
     * [
389
     *     'username' => 'master',
390
     *     'password' => 'master',
391
     *     'attributes' => [
392
     *         // use a smaller connection timeout
393
     *         PDO::ATTR_TIMEOUT => 10,
394
     *     ],
395
     * ]
396
     * ```
397
     */
398
    public $masterConfig = [];
399
    /**
400
     * @var bool whether to shuffle [[masters]] before getting one.
401
     * @since 2.0.11
402
     * @see masters
403
     */
404
    public $shuffleMasters = true;
405
    /**
406
     * @var bool whether to enable logging of database queries. Defaults to true.
407
     * You may want to disable this option in a production environment to gain performance
408
     * if you do not need the information being logged.
409
     * @since 2.0.12
410
     * @see enableProfiling
411
     */
412
    public $enableLogging = true;
413
    /**
414
     * @var bool whether to enable profiling of opening database connection and database queries. Defaults to true.
415
     * You may want to disable this option in a production environment to gain performance
416
     * if you do not need the information being logged.
417
     * @since 2.0.12
418
     * @see enableLogging
419
     */
420
    public $enableProfiling = true;
421
422
    /**
423
     * @var Transaction the currently active transaction
424
     */
425
    private $_transaction;
426
    /**
427
     * @var Schema the database schema
428
     */
429
    private $_schema;
430
    /**
431
     * @var string driver name
432
     */
433
    private $_driverName;
434
    /**
435
     * @var Connection|false the currently active master connection
436
     */
437
    private $_master = false;
438
    /**
439
     * @var Connection|false the currently active slave connection
440
     */
441
    private $_slave = false;
442
    /**
443
     * @var array query cache parameters for the [[cache()]] calls
444
     */
445
    private $_queryCacheInfo = [];
446
    /**
447
     * @var string[] quoted table name cache for [[quoteTableName()]] calls
448
     */
449
    private $_quotedTableNames;
450
    /**
451
     * @var string[] quoted column name cache for [[quoteColumnName()]] calls
452
     */
453
    private $_quotedColumnNames;
454
455
456
    /**
457
     * Returns a value indicating whether the DB connection is established.
458
     * @return bool whether the DB connection is established
459
     */
460 332
    public function getIsActive()
461
    {
462 332
        return $this->pdo !== null;
463
    }
464
465
    /**
466
     * Uses query cache for the queries performed with the callable.
467
     *
468
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
469
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
470
     * For example,
471
     *
472
     * ```php
473
     * // The customer will be fetched from cache if available.
474
     * // If not, the query will be made against DB and cached for use next time.
475
     * $customer = $db->cache(function (Connection $db) {
476
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
477
     * });
478
     * ```
479
     *
480
     * Note that query cache is only meaningful for queries that return results. For queries performed with
481
     * [[Command::execute()]], query cache will not be used.
482
     *
483
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
484
     * The signature of the callable is `function (Connection $db)`.
485
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
486
     * not set, the value of [[queryCacheDuration]] will be used instead.
487
     * Use 0 to indicate that the cached data will never expire.
488
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
489
     * @return mixed the return result of the callable
490
     * @throws \Exception|\Throwable if there is any exception during query
491
     * @see enableQueryCache
492
     * @see queryCache
493
     * @see noCache()
494
     */
495 6
    public function cache(callable $callable, $duration = null, $dependency = null)
496
    {
497 6
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
498
        try {
499 6
            $result = call_user_func($callable, $this);
500 6
            array_pop($this->_queryCacheInfo);
501 6
            return $result;
502
        } catch (\Exception $e) {
503
            array_pop($this->_queryCacheInfo);
504
            throw $e;
505
        } catch (\Throwable $e) {
506
            array_pop($this->_queryCacheInfo);
507
            throw $e;
508
        }
509
    }
510
511
    /**
512
     * Disables query cache temporarily.
513
     *
514
     * Queries performed within the callable will not use query cache at all. For example,
515
     *
516
     * ```php
517
     * $db->cache(function (Connection $db) {
518
     *
519
     *     // ... queries that use query cache ...
520
     *
521
     *     return $db->noCache(function (Connection $db) {
522
     *         // this query will not use query cache
523
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
524
     *     });
525
     * });
526
     * ```
527
     *
528
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
529
     * The signature of the callable is `function (Connection $db)`.
530
     * @return mixed the return result of the callable
531
     * @throws \Exception|\Throwable if there is any exception during query
532
     * @see enableQueryCache
533
     * @see queryCache
534
     * @see cache()
535
     */
536 40
    public function noCache(callable $callable)
537
    {
538 40
        $this->_queryCacheInfo[] = false;
539
        try {
540 40
            $result = call_user_func($callable, $this);
541 40
            array_pop($this->_queryCacheInfo);
542 40
            return $result;
543 4
        } catch (\Exception $e) {
544 4
            array_pop($this->_queryCacheInfo);
545 4
            throw $e;
546
        } catch (\Throwable $e) {
547
            array_pop($this->_queryCacheInfo);
548
            throw $e;
549
        }
550
    }
551
552
    /**
553
     * Returns the current query cache information.
554
     * This method is used internally by [[Command]].
555
     * @param int $duration the preferred caching duration. If null, it will be ignored.
556
     * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
557
     * @return array the current query cache information, or null if query cache is not enabled.
558
     * @internal
559
     */
560 1505
    public function getQueryCacheInfo($duration, $dependency)
561
    {
562 1505
        if (!$this->enableQueryCache) {
563 44
            return null;
564
        }
565
566 1503
        $info = end($this->_queryCacheInfo);
567 1503
        if (is_array($info)) {
568 6
            if ($duration === null) {
0 ignored issues
show
introduced by
The condition $duration === null is always false.
Loading history...
569 6
                $duration = $info[0];
570
            }
571 6
            if ($dependency === null) {
572 6
                $dependency = $info[1];
573
            }
574
        }
575
576 1503
        if ($duration === 0 || $duration > 0) {
577 6
            if (is_string($this->queryCache) && Yii::$app) {
578
                $cache = Yii::$app->get($this->queryCache, false);
579
            } else {
580 6
                $cache = $this->queryCache;
581
            }
582 6
            if ($cache instanceof CacheInterface) {
583 6
                return [$cache, $duration, $dependency];
584
            }
585
        }
586
587 1503
        return null;
588
    }
589
590
    /**
591
     * Establishes a DB connection.
592
     * It does nothing if a DB connection has already been established.
593
     * @throws Exception if connection fails
594
     */
595 2034
    public function open()
596
    {
597 2034
        if ($this->pdo !== null) {
598 1615
            return;
599
        }
600
601 1979
        if (!empty($this->masters)) {
602 9
            $db = $this->getMaster();
603 9
            if ($db !== null) {
604 9
                $this->pdo = $db->pdo;
605 9
                return;
606
            }
607
608 8
            throw new InvalidConfigException('None of the master DB servers is available.');
609
        }
610
611 1979
        if (empty($this->dsn)) {
612
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
613
        }
614
615 1979
        $token = 'Opening DB connection: ' . $this->dsn;
616 1979
        $enableProfiling = $this->enableProfiling;
617
        try {
618 1979
            if ($this->enableLogging) {
619 1979
                Yii::info($token, __METHOD__);
620
            }
621
622 1979
            if ($enableProfiling) {
623 1979
                Yii::beginProfile($token, __METHOD__);
624
            }
625
626 1979
            $this->pdo = $this->createPdoInstance();
627 1979
            $this->initConnection();
628
629 1979
            if ($enableProfiling) {
630 1979
                Yii::endProfile($token, __METHOD__);
631
            }
632 12
        } catch (\PDOException $e) {
633 12
            if ($enableProfiling) {
634 12
                Yii::endProfile($token, __METHOD__);
635
            }
636
637 12
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
638
        }
639 1979
    }
640
641
    /**
642
     * Closes the currently active DB connection.
643
     * It does nothing if the connection is already closed.
644
     */
645 2131
    public function close()
646
    {
647 2131
        if ($this->_master) {
648 8
            if ($this->pdo === $this->_master->pdo) {
649 8
                $this->pdo = null;
650
            }
651
652 8
            $this->_master->close();
653 8
            $this->_master = false;
654
        }
655
656 2131
        if ($this->pdo !== null) {
657 1784
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
658 1784
            $this->pdo = null;
659
        }
660
661 2131
        if ($this->_slave) {
662 4
            $this->_slave->close();
663 4
            $this->_slave = false;
664
        }
665
666 2131
        $this->_schema = null;
667 2131
        $this->_transaction = null;
668 2131
        $this->_driverName = null;
669 2131
        $this->_queryCacheInfo = [];
670 2131
        $this->_quotedTableNames = null;
671 2131
        $this->_quotedColumnNames = null;
672 2131
    }
673
674
    /**
675
     * Creates the PDO instance.
676
     * This method is called by [[open]] to establish a DB connection.
677
     * The default implementation will create a PHP PDO instance.
678
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
679
     * @return PDO the pdo instance
680
     */
681 1979
    protected function createPdoInstance()
682
    {
683 1979
        $pdoClass = $this->pdoClass;
684 1979
        if ($pdoClass === null) {
0 ignored issues
show
introduced by
The condition $pdoClass === null is always false.
Loading history...
685 1979
            $pdoClass = 'PDO';
686 1979
            if ($this->_driverName !== null) {
687 239
                $driver = $this->_driverName;
688 1745
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
689 1745
                $driver = strtolower(substr($this->dsn, 0, $pos));
690
            }
691 1979
            if (isset($driver)) {
692 1979
                if ($driver === 'mssql' || $driver === 'dblib') {
693
                    $pdoClass = 'yii\db\mssql\PDO';
694 1979
                } elseif ($driver === 'sqlsrv') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $driver does not seem to be defined for all execution paths leading up to this point.
Loading history...
695
                    $pdoClass = 'yii\db\mssql\SqlsrvPDO';
696
                }
697
            }
698
        }
699
700 1979
        $dsn = $this->dsn;
701 1979
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
702 1
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
703
        }
704
705 1979
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
706
    }
707
708
    /**
709
     * Initializes the DB connection.
710
     * This method is invoked right after the DB connection is established.
711
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
712
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
713
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
714
     */
715 1979
    protected function initConnection()
716
    {
717 1979
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
718 1979
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
719
            if ($this->driverName !== 'sqlsrv') {
720
                $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
721
            }
722
        }
723 1979
        if (in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
724
            $this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
725
        }
726 1979
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
727
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
728
        }
729 1979
        $this->trigger(self::EVENT_AFTER_OPEN);
730 1979
    }
731
732
    /**
733
     * Creates a command for execution.
734
     * @param string $sql the SQL statement to be executed
735
     * @param array $params the parameters to be bound to the SQL statement
736
     * @return Command the DB command
737
     */
738 1596
    public function createCommand($sql = null, $params = [])
739
    {
740 1596
        $driver = $this->getDriverName();
741 1596
        $config = ['class' => 'yii\db\Command'];
742 1596
        if ($this->commandClass !== $config['class']) {
0 ignored issues
show
Deprecated Code introduced by
The property yii\db\Connection::$commandClass has been deprecated: since 2.0.14. Use [[$commandMap]] for precise configuration. ( Ignorable by Annotation )

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

742
        if (/** @scrutinizer ignore-deprecated */ $this->commandClass !== $config['class']) {

This property 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 property will be removed from the class and what other property to use instead.

Loading history...
743
            $config['class'] = $this->commandClass;
0 ignored issues
show
Deprecated Code introduced by
The property yii\db\Connection::$commandClass has been deprecated: since 2.0.14. Use [[$commandMap]] for precise configuration. ( Ignorable by Annotation )

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

743
            $config['class'] = /** @scrutinizer ignore-deprecated */ $this->commandClass;

This property 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 property will be removed from the class and what other property to use instead.

Loading history...
744 1596
        } elseif (isset($this->commandMap[$driver])) {
745 1596
            $config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
746
        }
747 1596
        $config['db'] = $this;
748 1596
        $config['sql'] = $sql;
749
        /** @var Command $command */
750 1596
        $command = Yii::createObject($config);
751 1596
        return $command->bindValues($params);
752
    }
753
754
    /**
755
     * Returns the currently active transaction.
756
     * @return Transaction|null the currently active transaction. Null if no active transaction.
757
     */
758 1565
    public function getTransaction()
759
    {
760 1565
        return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
761
    }
762
763
    /**
764
     * Starts a transaction.
765
     * @param string|null $isolationLevel The isolation level to use for this transaction.
766
     * See [[Transaction::begin()]] for details.
767
     * @return Transaction the transaction initiated
768
     */
769 39
    public function beginTransaction($isolationLevel = null)
770
    {
771 39
        $this->open();
772
773 39
        if (($transaction = $this->getTransaction()) === null) {
774 39
            $transaction = $this->_transaction = new Transaction(['db' => $this]);
775
        }
776 39
        $transaction->begin($isolationLevel);
777
778 39
        return $transaction;
779
    }
780
781
    /**
782
     * Executes callback provided in a transaction.
783
     *
784
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
785
     * @param string|null $isolationLevel The isolation level to use for this transaction.
786
     * See [[Transaction::begin()]] for details.
787
     * @throws \Exception|\Throwable if there is any exception during query. In this case the transaction will be rolled back.
788
     * @return mixed result of callback function
789
     */
790 23
    public function transaction(callable $callback, $isolationLevel = null)
791
    {
792 23
        $transaction = $this->beginTransaction($isolationLevel);
793 23
        $level = $transaction->level;
794
795
        try {
796 23
            $result = call_user_func($callback, $this);
797 15
            if ($transaction->isActive && $transaction->level === $level) {
798 15
                $transaction->commit();
799
            }
800 8
        } catch (\Exception $e) {
801 8
            $this->rollbackTransactionOnLevel($transaction, $level);
802 8
            throw $e;
803
        } catch (\Throwable $e) {
804
            $this->rollbackTransactionOnLevel($transaction, $level);
805
            throw $e;
806
        }
807
808 15
        return $result;
809
    }
810
811
    /**
812
     * Rolls back given [[Transaction]] object if it's still active and level match.
813
     * In some cases rollback can fail, so this method is fail safe. Exception thrown
814
     * from rollback will be caught and just logged with [[\Yii::error()]].
815
     * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
816
     * @param int $level Transaction level just after [[beginTransaction()]] call.
817
     */
818 8
    private function rollbackTransactionOnLevel($transaction, $level)
819
    {
820 8
        if ($transaction->isActive && $transaction->level === $level) {
821
            // https://github.com/yiisoft/yii2/pull/13347
822
            try {
823 8
                $transaction->rollBack();
824
            } catch (\Exception $e) {
825
                \Yii::error($e, __METHOD__);
826
                // hide this exception to be able to continue throwing original exception outside
827
            }
828
        }
829 8
    }
830
831
    /**
832
     * Returns the schema information for the database opened by this connection.
833
     * @return Schema the schema information for the database opened by this connection.
834
     * @throws NotSupportedException if there is no support for the current driver type
835
     */
836 2065
    public function getSchema()
837
    {
838 2065
        if ($this->_schema !== null) {
839 1687
            return $this->_schema;
840
        }
841
842 2010
        $driver = $this->getDriverName();
843 2010
        if (isset($this->schemaMap[$driver])) {
844 2010
            $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
845 2010
            $config['db'] = $this;
846
847 2010
            return $this->_schema = Yii::createObject($config);
848
        }
849
850
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
851
    }
852
853
    /**
854
     * Returns the query builder for the current DB connection.
855
     * @return QueryBuilder the query builder for the current DB connection.
856
     */
857 1100
    public function getQueryBuilder()
858
    {
859 1100
        return $this->getSchema()->getQueryBuilder();
860
    }
861
862
    /**
863
     * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
864
     *
865
     * @param array $value the [[QueryBuilder]] properties to be configured.
866
     * @since 2.0.14
867
     */
868
    public function setQueryBuilder($value)
869
    {
870
        Yii::configure($this->getQueryBuilder(), $value);
871
    }
872
873
    /**
874
     * Obtains the schema information for the named table.
875
     * @param string $name table name.
876
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
877
     * @return TableSchema table schema information. Null if the named table does not exist.
878
     */
879 242
    public function getTableSchema($name, $refresh = false)
880
    {
881 242
        return $this->getSchema()->getTableSchema($name, $refresh);
882
    }
883
884
    /**
885
     * Returns the ID of the last inserted row or sequence value.
886
     * @param string $sequenceName name of the sequence object (required by some DBMS)
887
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
888
     * @see https://secure.php.net/manual/en/pdo.lastinsertid.php
889
     */
890 6
    public function getLastInsertID($sequenceName = '')
891
    {
892 6
        return $this->getSchema()->getLastInsertID($sequenceName);
893
    }
894
895
    /**
896
     * Quotes a string value for use in a query.
897
     * Note that if the parameter is not a string, it will be returned without change.
898
     * @param string $value string to be quoted
899
     * @return string the properly quoted string
900
     * @see https://secure.php.net/manual/en/pdo.quote.php
901
     */
902 1075
    public function quoteValue($value)
903
    {
904 1075
        return $this->getSchema()->quoteValue($value);
905
    }
906
907
    /**
908
     * Quotes a table name for use in a query.
909
     * If the table name contains schema prefix, the prefix will also be properly quoted.
910
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
911
     * then this method will do nothing.
912
     * @param string $name table name
913
     * @return string the properly quoted table name
914
     */
915 1361
    public function quoteTableName($name)
916
    {
917 1361
        if (isset($this->_quotedTableNames[$name])) {
918 1002
            return $this->_quotedTableNames[$name];
919
        }
920 1295
        return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
921
    }
922
923
    /**
924
     * Quotes a column name for use in a query.
925
     * If the column name contains prefix, the prefix will also be properly quoted.
926
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
927
     * then this method will do nothing.
928
     * @param string $name column name
929
     * @return string the properly quoted column name
930
     */
931 1416
    public function quoteColumnName($name)
932
    {
933 1416
        if (isset($this->_quotedColumnNames[$name])) {
934 875
            return $this->_quotedColumnNames[$name];
935
        }
936 1361
        return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
937
    }
938
939
    /**
940
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
941
     * Tokens enclosed within double curly brackets are treated as table names, while
942
     * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
943
     * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
944
     * with [[tablePrefix]].
945
     * @param string $sql the SQL to be quoted
946
     * @return string the quoted SQL
947
     */
948 1640
    public function quoteSql($sql)
949
    {
950 1640
        return preg_replace_callback(
951 1640
            '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
952 1640
            function ($matches) {
953 817
                if (isset($matches[3])) {
954 601
                    return $this->quoteColumnName($matches[3]);
955
                }
956
957 713
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
958 1640
            },
959 1640
            $sql
960
        );
961
    }
962
963
    /**
964
     * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
965
     * by an end user.
966
     * @return string name of the DB driver
967
     */
968 2298
    public function getDriverName()
969
    {
970 2298
        if ($this->_driverName === null) {
971 2229
            if (($pos = strpos($this->dsn, ':')) !== false) {
972 2229
                $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
973
            } else {
974
                $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
975
            }
976
        }
977
978 2298
        return $this->_driverName;
979
    }
980
981
    /**
982
     * Changes the current driver name.
983
     * @param string $driverName name of the DB driver
984
     */
985
    public function setDriverName($driverName)
986
    {
987
        $this->_driverName = strtolower($driverName);
988
    }
989
990
    /**
991
     * Returns a server version as a string comparable by [[\version_compare()]].
992
     * @return string server version as a string.
993
     * @since 2.0.14
994
     */
995 411
    public function getServerVersion()
996
    {
997 411
        return $this->getSchema()->getServerVersion();
998
    }
999
1000
    /**
1001
     * Returns the PDO instance for the currently active slave connection.
1002
     * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
1003
     * will be returned by this method.
1004
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
1005
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
1006
     * is available and `$fallbackToMaster` is false.
1007
     */
1008 1748
    public function getSlavePdo($fallbackToMaster = true)
1009
    {
1010 1748
        $db = $this->getSlave(false);
1011 1748
        if ($db === null) {
1012 1744
            return $fallbackToMaster ? $this->getMasterPdo() : null;
1013
        }
1014
1015 5
        return $db->pdo;
1016
    }
1017
1018
    /**
1019
     * Returns the PDO instance for the currently active master connection.
1020
     * This method will open the master DB connection and then return [[pdo]].
1021
     * @return PDO the PDO instance for the currently active master connection.
1022
     */
1023 1778
    public function getMasterPdo()
1024
    {
1025 1778
        $this->open();
1026 1778
        return $this->pdo;
1027
    }
1028
1029
    /**
1030
     * Returns the currently active slave connection.
1031
     * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
1032
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
1033
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
1034
     * `$fallbackToMaster` is false.
1035
     */
1036 1750
    public function getSlave($fallbackToMaster = true)
1037
    {
1038 1750
        if (!$this->enableSlaves) {
1039 209
            return $fallbackToMaster ? $this : null;
1040
        }
1041
1042 1651
        if ($this->_slave === false) {
1043 1651
            $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
1044
        }
1045
1046 1645
        return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_slave ===...? $this : $this->_slave also could return the type true which is incompatible with the documented return type yii\db\Connection.
Loading history...
1047
    }
1048
1049
    /**
1050
     * Returns the currently active master connection.
1051
     * If this method is called for the first time, it will try to open a master connection.
1052
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
1053
     * @since 2.0.11
1054
     */
1055 11
    public function getMaster()
1056
    {
1057 11
        if ($this->_master === false) {
1058 11
            $this->_master = $this->shuffleMasters
1059 2
                ? $this->openFromPool($this->masters, $this->masterConfig)
1060 9
                : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
1061
        }
1062
1063 11
        return $this->_master;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_master also could return the type true which is incompatible with the documented return type yii\db\Connection.
Loading history...
1064
    }
1065
1066
    /**
1067
     * Executes the provided callback by using the master connection.
1068
     *
1069
     * This method is provided so that you can temporarily force using the master connection to perform
1070
     * DB operations even if they are read queries. For example,
1071
     *
1072
     * ```php
1073
     * $result = $db->useMaster(function ($db) {
1074
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1075
     * });
1076
     * ```
1077
     *
1078
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1079
     * `function (Connection $db)`. Its return value will be returned by this method.
1080
     * @return mixed the return value of the callback
1081
     * @throws \Exception|\Throwable if there is any exception thrown from the callback
1082
     */
1083 100
    public function useMaster(callable $callback)
1084
    {
1085 100
        if ($this->enableSlaves) {
1086 100
            $this->enableSlaves = false;
1087
            try {
1088 100
                $result = call_user_func($callback, $this);
1089 4
            } catch (\Exception $e) {
1090 4
                $this->enableSlaves = true;
1091 4
                throw $e;
1092
            } catch (\Throwable $e) {
1093
                $this->enableSlaves = true;
1094
                throw $e;
1095
            }
1096
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
1097 96
            $this->enableSlaves = true;
1098
        } else {
1099
            $result = call_user_func($callback, $this);
1100
        }
1101
1102 96
        return $result;
1103
    }
1104
1105
    /**
1106
     * Opens the connection to a server in the pool.
1107
     *
1108
     * This method implements load balancing and failover among the given list of the servers.
1109
     * Connections will be tried in random order.
1110
     * For details about the failover behavior, see [[openFromPoolSequentially]].
1111
     *
1112
     * @param array $pool the list of connection configurations in the server pool
1113
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1114
     * @return Connection the opened DB connection, or `null` if no server is available
1115
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1116
     * @see openFromPoolSequentially
1117
     */
1118 1651
    protected function openFromPool(array $pool, array $sharedConfig)
1119
    {
1120 1651
        shuffle($pool);
1121 1651
        return $this->openFromPoolSequentially($pool, $sharedConfig);
1122
    }
1123
1124
    /**
1125
     * Opens the connection to a server in the pool.
1126
     *
1127
     * This method implements failover among the given list of servers.
1128
     * Connections will be tried in sequential order. The first successful connection will return.
1129
     *
1130
     * If [[serverStatusCache]] is configured, this method will cache information about
1131
     * unreachable servers and does not try to connect to these for the time configured in [[serverRetryInterval]].
1132
     * This helps to keep the application stable when some servers are unavailable. Avoiding
1133
     * connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
1134
     *
1135
     * If none of the servers are available the status cache is ignored and connection attempts are made to all
1136
     * servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time.
1137
     * After a successful connection attempt the server is marked as avaiable again.
1138
     *
1139
     * @param array $pool the list of connection configurations in the server pool
1140
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1141
     * @return Connection the opened DB connection, or `null` if no server is available
1142
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1143
     * @since 2.0.11
1144
     * @see openFromPool
1145
     * @see serverStatusCache
1146
     */
1147 1659
    protected function openFromPoolSequentially(array $pool, array $sharedConfig)
1148
    {
1149 1659
        if (empty($pool)) {
1150 1639
            return null;
1151
        }
1152
1153 21
        if (!isset($sharedConfig['class'])) {
1154 21
            $sharedConfig['class'] = get_class($this);
1155
        }
1156
1157 21
        $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
1158
1159 21
        foreach ($pool as $i => $config) {
1160 21
            $pool[$i] = $config = array_merge($sharedConfig, $config);
1161 21
            if (empty($config['dsn'])) {
1162 6
                throw new InvalidConfigException('The "dsn" option must be specified.');
1163
            }
1164
1165 15
            $key = [__METHOD__, $config['dsn']];
1166 15
            if ($cache instanceof CacheInterface && $cache->get($key)) {
1167
                // should not try this dead server now
1168
                continue;
1169
            }
1170
1171
            /* @var $db Connection */
1172 15
            $db = Yii::createObject($config);
1173
1174
            try {
1175 15
                $db->open();
1176 15
                return $db;
1177 8
            } catch (\Exception $e) {
1178 8
                Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1179 8
                if ($cache instanceof CacheInterface) {
1180
                    // mark this server as dead and only retry it after the specified interval
1181 4
                    $cache->set($key, 1, $this->serverRetryInterval);
1182
                }
1183
                // exclude server from retry below
1184 8
                unset($pool[$i]);
1185
            }
1186
        }
1187
1188 8
        if ($cache instanceof CacheInterface) {
1189
            // if server status cache is enabled and no server is available
1190
            // ignore the cache and try to connect anyway
1191
            // $pool now only contains servers we did not already try in the loop above
1192 4
            foreach ($pool as $config) {
1193
1194
                /* @var $db Connection */
1195
                $db = Yii::createObject($config);
1196
                try {
1197
                    $db->open();
1198
                } catch (\Exception $e) {
1199
                    Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1200
                    continue;
1201
                }
1202
1203
                // mark this server as available again after successful connection
1204
                $cache->delete([__METHOD__, $config['dsn']]);
1205
1206
                return $db;
1207
            }
1208
        }
1209
1210 8
        return null;
1211
    }
1212
1213
    /**
1214
     * Close the connection before serializing.
1215
     * @return array
1216
     */
1217 19
    public function __sleep()
1218
    {
1219 19
        $fields = (array) $this;
1220
1221 19
        unset($fields['pdo']);
1222 19
        unset($fields["\000" . __CLASS__ . "\000" . '_master']);
1223 19
        unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
1224 19
        unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
1225 19
        unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
1226
1227 19
        return array_keys($fields);
1228
    }
1229
1230
    /**
1231
     * Reset the connection after cloning.
1232
     */
1233 7
    public function __clone()
1234
    {
1235 7
        parent::__clone();
1236
1237 7
        $this->_master = false;
1238 7
        $this->_slave = false;
1239 7
        $this->_schema = null;
1240 7
        $this->_transaction = null;
1241 7
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
1242
            // reset PDO connection, unless its sqlite in-memory, which can only have one connection
1243 6
            $this->pdo = null;
1244
        }
1245 7
    }
1246
}
1247