Passed
Push — fix-tests ( 6dd538...727178 )
by Alexander
195:41 queued 192:18
created

Connection::open()   B

Complexity

Conditions 10
Paths 42

Size

Total Lines 43
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 10.0064

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 25
c 1
b 0
f 0
nc 42
nop 0
dl 0
loc 43
ccs 24
cts 25
cp 0.96
crap 10.0064
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

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

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

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

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

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

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

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