Completed
Pull Request — master (#16074)
by Leandro
13:14
created

Connection::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 0
crap 2
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](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',
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|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|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|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|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|array the Data Source Name, or DSN, contains the information required to connect to the database.
157
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.construct.php) on
158
     * the format of the DSN string.
159
     *
160
     * For [SQLite](http://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](http://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\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
    /**
446
     * {@inheritdoc}
447
     */
448 1970
    public function init()
449
    {
450 1970
        if (is_array($this->dsn)) {
451 4
            $this->dsn = $this->buildDSN($this->dsn);
452
        }
453 1970
    }
454
455
    /**
456
     * Returns a value indicating whether the DB connection is established.
457
     * @return bool whether the DB connection is established
458
     */
459 314
    public function getIsActive()
460
    {
461 314
        return $this->pdo !== null;
462
    }
463
464
    /**
465
     * Uses query cache for the queries performed with the callable.
466
     *
467
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
468
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
469
     * For example,
470
     *
471
     * ```php
472
     * // The customer will be fetched from cache if available.
473
     * // If not, the query will be made against DB and cached for use next time.
474
     * $customer = $db->cache(function (Connection $db) {
475
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
476
     * });
477
     * ```
478
     *
479
     * Note that query cache is only meaningful for queries that return results. For queries performed with
480
     * [[Command::execute()]], query cache will not be used.
481
     *
482
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
483
     * The signature of the callable is `function (Connection $db)`.
484
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
485
     * not set, the value of [[queryCacheDuration]] will be used instead.
486
     * Use 0 to indicate that the cached data will never expire.
487
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
488
     * @return mixed the return result of the callable
489
     * @throws \Exception|\Throwable if there is any exception during query
490
     * @see enableQueryCache
491
     * @see queryCache
492
     * @see noCache()
493
     */
494 6
    public function cache(callable $callable, $duration = null, $dependency = null)
495
    {
496 6
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
497
        try {
498 6
            $result = call_user_func($callable, $this);
499 6
            array_pop($this->_queryCacheInfo);
500 6
            return $result;
501
        } catch (\Exception $e) {
502
            array_pop($this->_queryCacheInfo);
503
            throw $e;
504
        } 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...
505
            array_pop($this->_queryCacheInfo);
506
            throw $e;
507
        }
508
    }
509
510
    /**
511
     * Disables query cache temporarily.
512
     *
513
     * Queries performed within the callable will not use query cache at all. For example,
514
     *
515
     * ```php
516
     * $db->cache(function (Connection $db) {
517
     *
518
     *     // ... queries that use query cache ...
519
     *
520
     *     return $db->noCache(function (Connection $db) {
521
     *         // this query will not use query cache
522
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
523
     *     });
524
     * });
525
     * ```
526
     *
527
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
528
     * The signature of the callable is `function (Connection $db)`.
529
     * @return mixed the return result of the callable
530
     * @throws \Exception|\Throwable if there is any exception during query
531
     * @see enableQueryCache
532
     * @see queryCache
533
     * @see cache()
534
     */
535 40
    public function noCache(callable $callable)
536
    {
537 40
        $this->_queryCacheInfo[] = false;
538
        try {
539 40
            $result = call_user_func($callable, $this);
540 40
            array_pop($this->_queryCacheInfo);
541 40
            return $result;
542 4
        } catch (\Exception $e) {
543 4
            array_pop($this->_queryCacheInfo);
544 4
            throw $e;
545
        } 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...
546
            array_pop($this->_queryCacheInfo);
547
            throw $e;
548
        }
549
    }
550
551
    /**
552
     * Returns the current query cache information.
553
     * This method is used internally by [[Command]].
554
     * @param int $duration the preferred caching duration. If null, it will be ignored.
555
     * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
556
     * @return array the current query cache information, or null if query cache is not enabled.
557
     * @internal
558
     */
559 1291
    public function getQueryCacheInfo($duration, $dependency)
560
    {
561 1291
        if (!$this->enableQueryCache) {
562 44
            return null;
563
        }
564
565 1289
        $info = end($this->_queryCacheInfo);
566 1289
        if (is_array($info)) {
567 6
            if ($duration === null) {
568 6
                $duration = $info[0];
569
            }
570 6
            if ($dependency === null) {
571 6
                $dependency = $info[1];
572
            }
573
        }
574
575 1289
        if ($duration === 0 || $duration > 0) {
576 6
            if (is_string($this->queryCache) && Yii::$app) {
577
                $cache = Yii::$app->get($this->queryCache, false);
578
            } else {
579 6
                $cache = $this->queryCache;
580
            }
581 6
            if ($cache instanceof CacheInterface) {
582 6
                return [$cache, $duration, $dependency];
583
            }
584
        }
585
586 1289
        return null;
587
    }
588
589
    /**
590
     * Establishes a DB connection.
591
     * It does nothing if a DB connection has already been established.
592
     * @throws Exception if connection fails
593
     */
594 1622
    public function open()
595
    {
596 1622
        if ($this->pdo !== null) {
597 1372
            return;
598
        }
599
600 1567
        if (!empty($this->masters)) {
601 9
            $db = $this->getMaster();
602 9
            if ($db !== null) {
603 9
                $this->pdo = $db->pdo;
604 9
                return;
605
            }
606
607 8
            throw new InvalidConfigException('None of the master DB servers is available.');
608
        }
609
610 1567
        if (empty($this->dsn)) {
611
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
612
        }
613
614 1567
        $token = 'Opening DB connection: ' . $this->dsn;
615 1567
        $enableProfiling = $this->enableProfiling;
616
        try {
617 1567
            Yii::info($token, __METHOD__);
618 1567
            if ($enableProfiling) {
619 1567
                Yii::beginProfile($token, __METHOD__);
620
            }
621
622 1567
            $this->pdo = $this->createPdoInstance();
623 1567
            $this->initConnection();
624
625 1567
            if ($enableProfiling) {
626 1567
                Yii::endProfile($token, __METHOD__);
627
            }
628 12
        } catch (\PDOException $e) {
629 12
            if ($enableProfiling) {
630 12
                Yii::endProfile($token, __METHOD__);
631
            }
632
633 12
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
634
        }
635 1567
    }
636
637
    /**
638
     * Closes the currently active DB connection.
639
     * It does nothing if the connection is already closed.
640
     */
641 1859
    public function close()
642
    {
643 1859
        if ($this->_master) {
644 8
            if ($this->pdo === $this->_master->pdo) {
645 8
                $this->pdo = null;
646
            }
647
648 8
            $this->_master->close();
649 8
            $this->_master = false;
650
        }
651
652 1859
        if ($this->pdo !== null) {
653 1451
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
654 1451
            $this->pdo = null;
655 1451
            $this->_schema = null;
656 1451
            $this->_transaction = null;
657
        }
658
659 1859
        if ($this->_slave) {
660 4
            $this->_slave->close();
661 4
            $this->_slave = false;
662
        }
663 1859
    }
664
665
    /**
666
     * Creates the PDO instance.
667
     * This method is called by [[open]] to establish a DB connection.
668
     * The default implementation will create a PHP PDO instance.
669
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
670
     * @return PDO the pdo instance
671
     */
672 1567
    protected function createPdoInstance()
673
    {
674 1567
        $pdoClass = $this->pdoClass;
675 1567
        if ($pdoClass === null) {
676 1567
            $pdoClass = 'PDO';
677 1567
            if ($this->_driverName !== null) {
678 181
                $driver = $this->_driverName;
679 1391
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
680 1391
                $driver = strtolower(substr($this->dsn, 0, $pos));
681
            }
682 1567
            if (isset($driver)) {
683 1567
                if ($driver === 'mssql' || $driver === 'dblib') {
684
                    $pdoClass = 'yii\db\mssql\PDO';
685 1567
                } elseif ($driver === 'sqlsrv') {
686
                    $pdoClass = 'yii\db\mssql\SqlsrvPDO';
687
                }
688
            }
689
        }
690
691 1567
        $dsn = $this->dsn;
692 1567
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
693 1
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
694
        }
695
696 1567
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
697
    }
698
699
    /**
700
     * Initializes the DB connection.
701
     * This method is invoked right after the DB connection is established.
702
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
703
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
704
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
705
     */
706 1567
    protected function initConnection()
707
    {
708 1567
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
709 1567
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
710
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
711
        }
712 1567
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
713
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
714
        }
715 1567
        $this->trigger(self::EVENT_AFTER_OPEN);
716 1567
    }
717
718
    /**
719
     * Creates a command for execution.
720
     * @param string $sql the SQL statement to be executed
721
     * @param array $params the parameters to be bound to the SQL statement
722
     * @return Command the DB command
723
     */
724 1379
    public function createCommand($sql = null, $params = [])
725
    {
726 1379
        $driver = $this->getDriverName();
727 1379
        $config = ['class' => 'yii\db\Command'];
728 1379
        if ($this->commandClass !== $config['class']) {
0 ignored issues
show
Deprecated Code introduced by
The property yii\db\Connection::$commandClass has been deprecated with message: since 2.0.14. Use [[$commandMap]] for precise configuration.

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...
729
            $config['class'] = $this->commandClass;
0 ignored issues
show
Deprecated Code introduced by
The property yii\db\Connection::$commandClass has been deprecated with message: since 2.0.14. Use [[$commandMap]] for precise configuration.

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