Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

Connection::getServerVersion()   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
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\db;
10
11
use PDO;
12
use Yii;
13
use yii\base\Component;
14
use yii\base\InvalidConfigException;
15
use yii\base\NotSupportedException;
16
use yii\caching\CacheInterface;
17
18
/**
19
 * Connection represents a connection to a database via [PDO](https://www.php.net/manual/en/book.pdo.php).
20
 *
21
 * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
22
 * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
23
 * of the [PDO PHP extension](https://www.php.net/manual/en/book.pdo.php).
24
 *
25
 * Connection supports database replication and read-write splitting. In particular, a Connection component
26
 * can be configured with multiple [[masters]] and [[slaves]]. It will do load balancing and failover by choosing
27
 * appropriate servers. It will also automatically direct read operations to the slaves and write operations to
28
 * the masters.
29
 *
30
 * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
31
 * call [[open()]] to connect to the database server. The current state of the connection can be checked using [[$isActive]].
32
 *
33
 * The following example shows how to create a Connection instance and establish
34
 * the DB connection:
35
 *
36
 * ```php
37
 * $connection = new \yii\db\Connection([
38
 *     'dsn' => $dsn,
39
 *     'username' => $username,
40
 *     'password' => $password,
41
 * ]);
42
 * $connection->open();
43
 * ```
44
 *
45
 * After the DB connection is established, one can execute SQL statements like the following:
46
 *
47
 * ```php
48
 * $command = $connection->createCommand('SELECT * FROM post');
49
 * $posts = $command->queryAll();
50
 * $command = $connection->createCommand('UPDATE post SET status=1');
51
 * $command->execute();
52
 * ```
53
 *
54
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
55
 * When the parameters are coming from user input, you should use this approach
56
 * to prevent SQL injection attacks. The following is an example:
57
 *
58
 * ```php
59
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
60
 * $command->bindValue(':id', $_GET['id']);
61
 * $post = $command->query();
62
 * ```
63
 *
64
 * For more information about how to perform various DB queries, please refer to [[Command]].
65
 *
66
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries
67
 * like the following:
68
 *
69
 * ```php
70
 * $transaction = $connection->beginTransaction();
71
 * try {
72
 *     $connection->createCommand($sql1)->execute();
73
 *     $connection->createCommand($sql2)->execute();
74
 *     // ... executing other SQL statements ...
75
 *     $transaction->commit();
76
 * } catch (Exception $e) {
77
 *     $transaction->rollBack();
78
 * }
79
 * ```
80
 *
81
 * You also can use shortcut for the above like the following:
82
 *
83
 * ```php
84
 * $connection->transaction(function () {
85
 *     $order = new Order($customer);
86
 *     $order->save();
87
 *     $order->addItems($items);
88
 * });
89
 * ```
90
 *
91
 * If needed you can pass transaction isolation level as a second parameter:
92
 *
93
 * ```php
94
 * $connection->transaction(function (Connection $db) {
95
 *     //return $db->...
96
 * }, Transaction::READ_UNCOMMITTED);
97
 * ```
98
 *
99
 * Connection is often used as an application component and configured in the application
100
 * configuration like the following:
101
 *
102
 * ```php
103
 * 'components' => [
104
 *     'db' => [
105
 *         'class' => '\yii\db\Connection',
106
 *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
107
 *         'username' => 'root',
108
 *         'password' => '',
109
 *         'charset' => 'utf8',
110
 *     ],
111
 * ],
112
 * ```
113
 *
114
 * @property string|null $driverName Name of the DB driver. Note that the type of this property differs in
115
 * getter and setter. See [[getDriverName()]] and [[setDriverName()]] for details.
116
 * @property-read bool $isActive Whether the DB connection is established.
117
 * @property-read string $lastInsertID The row ID of the last row inserted, or the last value retrieved from
118
 * the sequence object.
119
 * @property-read Connection|null $master The currently active master connection. `null` is returned if there
120
 * is no master available.
121
 * @property-read PDO $masterPdo The PDO instance for the currently active master connection.
122
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of
123
 * this property differs in getter and setter. See [[getQueryBuilder()]] and [[setQueryBuilder()]] for details.
124
 * @property-read Schema $schema The schema information for the database opened by this connection.
125
 * @property-read string $serverVersion Server version as a string.
126
 * @property-read Connection|null $slave The currently active slave connection. `null` is returned if there is
127
 * no slave available and `$fallbackToMaster` is false.
128
 * @property-read PDO|null $slavePdo The PDO instance for the currently active slave connection. `null` is
129
 * returned if no slave connection is available and `$fallbackToMaster` is false.
130
 * @property-read Transaction|null $transaction The currently active transaction. Null if no active
131
 * transaction.
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://www.php.net/manual/en/pdo.construct.php) on
158
     * the format of the DSN string.
159
     *
160
     * For [SQLite](https://www.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|null the username for establishing DB connection. Defaults to `null` meaning no username to use.
168
     */
169
    public $username;
170
    /**
171
     * @var string|null 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://www.php.net/manual/en/pdo.setattribute.php) for
178
     * details about available attributes.
179
     */
180
    public $attributes;
181
    /**
182
     * @var PDO|null 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|null the charset used for database connection. The property is only used
242
     * for MySQL and PostgreSQL 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|null 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
    ];
287
    /**
288
     * @var string|null Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
289
     * @see pdo
290
     */
291
    public $pdoClass;
292
    /**
293
     * @var array mapping between PDO driver names and [[Command]] classes.
294
     * The keys of the array are PDO driver names while the values are either the corresponding
295
     * command class names or configurations. Please refer to [[Yii::createObject()]] for
296
     * details on how to specify a configuration.
297
     *
298
     * This property is mainly used by [[createCommand()]] to create new database [[Command]] objects.
299
     * You normally do not need to set this property unless you want to use your own
300
     * [[Command]] class or support DBMS that is not supported by Yii.
301
     * @since 2.0.14
302
     */
303
    public $commandMap = [
304
        'pgsql' => 'yii\db\Command', // PostgreSQL
305
        'mysqli' => 'yii\db\Command', // MySQL
306
        'mysql' => 'yii\db\Command', // MySQL
307
        'sqlite' => 'yii\db\sqlite\Command', // sqlite 3
308
        'sqlite2' => 'yii\db\sqlite\Command', // sqlite 2
309
        'sqlsrv' => 'yii\db\Command', // newer MSSQL driver on MS Windows hosts
310
        'oci' => 'yii\db\oci\Command', // Oracle driver
311
        'mssql' => 'yii\db\Command', // older MSSQL driver on MS Windows hosts
312
        'dblib' => 'yii\db\Command', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
313
    ];
314
    /**
315
     * @var bool whether to enable [savepoint](https://en.wikipedia.org/wiki/Savepoint).
316
     * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
317
     */
318
    public $enableSavepoint = true;
319
    /**
320
     * @var CacheInterface|string|false the cache object or the ID of the cache application component that is used to store
321
     * the health status of the DB servers specified in [[masters]] and [[slaves]].
322
     * This is used only when read/write splitting is enabled or [[masters]] is not empty.
323
     * Set boolean `false` to disabled server status caching.
324
     * @see openFromPoolSequentially() for details about the failover behavior.
325
     * @see serverRetryInterval
326
     */
327
    public $serverStatusCache = 'cache';
328
    /**
329
     * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
330
     * This is used together with [[serverStatusCache]].
331
     */
332
    public $serverRetryInterval = 600;
333
    /**
334
     * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
335
     * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
336
     */
337
    public $enableSlaves = true;
338
    /**
339
     * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
340
     * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
341
     * for performing read queries only.
342
     * @see enableSlaves
343
     * @see slaveConfig
344
     */
345
    public $slaves = [];
346
    /**
347
     * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
348
     * For example,
349
     *
350
     * ```php
351
     * [
352
     *     'username' => 'slave',
353
     *     'password' => 'slave',
354
     *     'attributes' => [
355
     *         // use a smaller connection timeout
356
     *         PDO::ATTR_TIMEOUT => 10,
357
     *     ],
358
     * ]
359
     * ```
360
     */
361
    public $slaveConfig = [];
362
    /**
363
     * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
364
     * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
365
     * which will be used by this object.
366
     * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
367
     * be ignored.
368
     * @see masterConfig
369
     * @see shuffleMasters
370
     */
371
    public $masters = [];
372
    /**
373
     * @var array the configuration that should be merged with every master configuration listed in [[masters]].
374
     * For example,
375
     *
376
     * ```php
377
     * [
378
     *     'username' => 'master',
379
     *     'password' => 'master',
380
     *     'attributes' => [
381
     *         // use a smaller connection timeout
382
     *         PDO::ATTR_TIMEOUT => 10,
383
     *     ],
384
     * ]
385
     * ```
386
     */
387
    public $masterConfig = [];
388
    /**
389
     * @var bool whether to shuffle [[masters]] before getting one.
390
     * @since 2.0.11
391
     * @see masters
392
     */
393
    public $shuffleMasters = true;
394
    /**
395
     * @var bool whether to enable logging of database queries. Defaults to true.
396
     * You may want to disable this option in a production environment to gain performance
397
     * if you do not need the information being logged.
398
     * @since 2.0.12
399
     * @see enableProfiling
400
     */
401
    public $enableLogging = true;
402
    /**
403
     * @var bool whether to enable profiling of opening database connection and database queries. Defaults to true.
404
     * You may want to disable this option in a production environment to gain performance
405
     * if you do not need the information being logged.
406
     * @since 2.0.12
407
     * @see enableLogging
408
     */
409
    public $enableProfiling = true;
410
    /**
411
     * @var bool If the database connected via pdo_dblib is SyBase.
412
     * @since 2.0.38
413
     */
414
    public $isSybase = false;
415
416
    /**
417
     * @var array An array of [[setQueryBuilder()]] calls, holding the passed arguments.
418
     * Is used to restore a QueryBuilder configuration after the connection close/open cycle.
419
     *
420
     * @see restoreQueryBuilderConfiguration()
421
     */
422
    private $_queryBuilderConfigurations = [];
423
    /**
424
     * @var Transaction the currently active transaction
425
     */
426
    private $_transaction;
427
    /**
428
     * @var Schema the database schema
429
     */
430
    private $_schema;
431
    /**
432
     * @var string driver name
433
     */
434
    private $_driverName;
435
    /**
436
     * @var Connection|false the currently active master connection
437
     */
438
    private $_master = false;
439
    /**
440
     * @var Connection|false the currently active slave connection
441
     */
442
    private $_slave = false;
443
    /**
444
     * @var array query cache parameters for the [[cache()]] calls
445
     */
446
    private $_queryCacheInfo = [];
447
    /**
448
     * @var string[] quoted table name cache for [[quoteTableName()]] calls
449
     */
450
    private $_quotedTableNames;
451
    /**
452
     * @var string[] quoted column name cache for [[quoteColumnName()]] calls
453
     */
454
    private $_quotedColumnNames;
455
456
457
    /**
458
     * Returns a value indicating whether the DB connection is established.
459
     * @return bool whether the DB connection is established
460
     */
461 24
    public function getIsActive()
462
    {
463 24
        return $this->pdo !== null;
464
    }
465
466
    /**
467
     * Uses query cache for the queries performed with the callable.
468
     *
469
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
470
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
471
     * For example,
472
     *
473
     * ```php
474
     * // The customer will be fetched from cache if available.
475
     * // If not, the query will be made against DB and cached for use next time.
476
     * $customer = $db->cache(function (Connection $db) {
477
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
478
     * });
479
     * ```
480
     *
481
     * Note that query cache is only meaningful for queries that return results. For queries performed with
482
     * [[Command::execute()]], query cache will not be used.
483
     *
484
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
485
     * The signature of the callable is `function (Connection $db)`.
486
     * @param int|null $duration the number of seconds that query results can remain valid in the cache. If this is
487
     * not set, the value of [[queryCacheDuration]] will be used instead.
488
     * Use 0 to indicate that the cached data will never expire.
489
     * @param \yii\caching\Dependency|null $dependency the cache dependency associated with the cached query results.
490
     * @return mixed the return result of the callable
491
     * @throws \Throwable if there is any exception during query
492
     * @see enableQueryCache
493
     * @see queryCache
494
     * @see noCache()
495
     */
496
    public function cache(callable $callable, $duration = null, $dependency = null)
497
    {
498
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
499
        try {
500
            $result = call_user_func($callable, $this);
501
            array_pop($this->_queryCacheInfo);
502
            return $result;
503
        } catch (\Exception $e) {
504
            array_pop($this->_queryCacheInfo);
505
            throw $e;
506
        } catch (\Throwable $e) {
507
            array_pop($this->_queryCacheInfo);
508
            throw $e;
509
        }
510
    }
511
512
    /**
513
     * Disables query cache temporarily.
514
     *
515
     * Queries performed within the callable will not use query cache at all. For example,
516
     *
517
     * ```php
518
     * $db->cache(function (Connection $db) {
519
     *
520
     *     // ... queries that use query cache ...
521
     *
522
     *     return $db->noCache(function (Connection $db) {
523
     *         // this query will not use query cache
524
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
525
     *     });
526
     * });
527
     * ```
528
     *
529
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
530
     * The signature of the callable is `function (Connection $db)`.
531
     * @return mixed the return result of the callable
532
     * @throws \Throwable if there is any exception during query
533
     * @see enableQueryCache
534
     * @see queryCache
535
     * @see cache()
536
     */
537
    public function noCache(callable $callable)
538
    {
539
        $this->_queryCacheInfo[] = false;
540
        try {
541
            $result = call_user_func($callable, $this);
542
            array_pop($this->_queryCacheInfo);
543
            return $result;
544
        } catch (\Exception $e) {
545
            array_pop($this->_queryCacheInfo);
546
            throw $e;
547
        } catch (\Throwable $e) {
548
            array_pop($this->_queryCacheInfo);
549
            throw $e;
550
        }
551
    }
552
553
    /**
554
     * Returns the current query cache information.
555
     * This method is used internally by [[Command]].
556
     * @param int|null $duration the preferred caching duration. If null, it will be ignored.
557
     * @param \yii\caching\Dependency|null $dependency the preferred caching dependency. If null, it will be ignored.
558
     * @return array|null the current query cache information, or null if query cache is not enabled.
559
     * @internal
560
     */
561 77
    public function getQueryCacheInfo($duration, $dependency)
562
    {
563 77
        if (!$this->enableQueryCache) {
564 6
            return null;
565
        }
566
567 77
        $info = end($this->_queryCacheInfo);
568 77
        if (is_array($info)) {
569
            if ($duration === null) {
570
                $duration = $info[0];
571
            }
572
            if ($dependency === null) {
573
                $dependency = $info[1];
574
            }
575
        }
576
577 77
        if ($duration === 0 || $duration > 0) {
578
            if (is_string($this->queryCache) && Yii::$app) {
579
                $cache = Yii::$app->get($this->queryCache, false);
580
            } else {
581
                $cache = $this->queryCache;
582
            }
583
            if ($cache instanceof CacheInterface) {
584
                return [$cache, $duration, $dependency];
585
            }
586
        }
587
588 77
        return null;
589
    }
590
591
    /**
592
     * Establishes a DB connection.
593
     * It does nothing if a DB connection has already been established.
594
     * @throws Exception if connection fails
595
     */
596 84
    public function open()
597
    {
598 84
        if ($this->pdo !== null) {
599 78
            return;
600
        }
601
602 84
        if (!empty($this->masters)) {
603
            $db = $this->getMaster();
604
            if ($db !== null) {
605
                $this->pdo = $db->pdo;
606
                return;
607
            }
608
609
            throw new InvalidConfigException('None of the master DB servers is available.');
610
        }
611
612 84
        if (empty($this->dsn)) {
613
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
614
        }
615
616 84
        $token = 'Opening DB connection: ' . $this->dsn;
617 84
        $enableProfiling = $this->enableProfiling;
618
        try {
619 84
            if ($this->enableLogging) {
620 84
                Yii::info($token, __METHOD__);
621
            }
622
623 84
            if ($enableProfiling) {
624 84
                Yii::beginProfile($token, __METHOD__);
625
            }
626
627 84
            $this->pdo = $this->createPdoInstance();
628 84
            $this->initConnection();
629
630 84
            if ($enableProfiling) {
631 84
                Yii::endProfile($token, __METHOD__);
632
            }
633
        } catch (\PDOException $e) {
634
            if ($enableProfiling) {
635
                Yii::endProfile($token, __METHOD__);
636
            }
637
638
            throw new Exception($e->getMessage(), $e->errorInfo, $e->getCode(), $e);
639
        }
640
    }
641
642
    /**
643
     * Closes the currently active DB connection.
644
     * It does nothing if the connection is already closed.
645
     */
646 62
    public function close()
647
    {
648 62
        if ($this->_master) {
649
            if ($this->pdo === $this->_master->pdo) {
650
                $this->pdo = null;
651
            }
652
653
            $this->_master->close();
654
            $this->_master = false;
655
        }
656
657 62
        if ($this->pdo !== null) {
658 62
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
659 62
            $this->pdo = null;
660
        }
661
662 62
        if ($this->_slave) {
663
            $this->_slave->close();
664
            $this->_slave = false;
665
        }
666
667 62
        $this->_schema = null;
668 62
        $this->_transaction = null;
669 62
        $this->_driverName = null;
670 62
        $this->_queryCacheInfo = [];
671 62
        $this->_quotedTableNames = null;
672 62
        $this->_quotedColumnNames = null;
673
    }
674
675
    /**
676
     * Creates the PDO instance.
677
     * This method is called by [[open]] to establish a DB connection.
678
     * The default implementation will create a PHP PDO instance.
679
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
680
     * @return PDO the pdo instance
681
     */
682 84
    protected function createPdoInstance()
683
    {
684 84
        $pdoClass = $this->pdoClass;
685 84
        if ($pdoClass === null) {
686 84
            $driver = null;
687 84
            if ($this->_driverName !== null) {
688 66
                $driver = $this->_driverName;
689 18
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
690 18
                $driver = strtolower(substr($this->dsn, 0, $pos));
691
            }
692
            switch ($driver) {
693 84
                case 'mssql':
694
                    $pdoClass = 'yii\db\mssql\PDO';
695
                    break;
696 84
                case 'dblib':
697
                    $pdoClass = 'yii\db\mssql\DBLibPDO';
698
                    break;
699 84
                case 'sqlsrv':
700
                    $pdoClass = 'yii\db\mssql\SqlsrvPDO';
701
                    break;
702
                default:
703 84
                    $pdoClass = 'PDO';
704
            }
705
        }
706
707 84
        $dsn = $this->dsn;
708 84
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
709
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
0 ignored issues
show
Bug introduced by
Are you sure Yii::getAlias(substr($dsn, 7)) of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

709
            $dsn = 'sqlite:' . /** @scrutinizer ignore-type */ Yii::getAlias(substr($dsn, 7));
Loading history...
710
        }
711
712 84
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
713
    }
714
715
    /**
716
     * Initializes the DB connection.
717
     * This method is invoked right after the DB connection is established.
718
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
719
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
720
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
721
     */
722 84
    protected function initConnection()
723
    {
724 84
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
0 ignored issues
show
Bug introduced by
The method setAttribute() does not exist on null. ( Ignorable by Annotation )

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

724
        $this->pdo->/** @scrutinizer ignore-call */ 
725
                    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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