Completed
Push — master ( 1d5850...f37f83 )
by Andrii
08:50
created

Connection   F

Complexity

Total Complexity 111

Size/Duplication

Total Lines 1045
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 9

Test Coverage

Coverage 38.8%

Importance

Changes 0
Metric Value
wmc 111
lcom 2
cbo 9
dl 0
loc 1045
ccs 97
cts 250
cp 0.388
rs 1.42
c 0
b 0
f 0

36 Methods

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

How to fix   Complexity   

Complex Class

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

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

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

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

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

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

Loading history...
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 (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1111
1112
        foreach ($pool as $config) {
1113
            $config = array_merge($sharedConfig, $config);
1114
            if (empty($config['dsn'])) {
1115
                throw new InvalidConfigException('The "dsn" option must be specified.');
1116
            }
1117
1118
            $key = [__METHOD__, $config['dsn']];
1119
            if ($cache instanceof CacheInterface && $cache->get($key)) {
0 ignored issues
show
Documentation introduced by
$key is of type array<integer,?,{"0":"string","1":"?"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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