Completed
Push — 2.1 ( e4285c...a0b3e2 )
by Alexander
31:54 queued 21s
created

Connection::getSchema()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.0218

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 9
cp 0.8889
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 0
crap 4.0218
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::class,
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 $transaction The currently active transaction. Null if no active transaction. This
131
 * 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 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 and PostgreSQL databases. Defaults to null, meaning using default charset
243
     * as configured by the database.
244
     *
245
     * For Oracle Database, the charset must be specified in the [[dsn]], for example for UTF-8 by appending `;charset=UTF-8`
246
     * to the DSN string.
247
     *
248
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to
249
     * specify charset via [[dsn]] like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
250
     */
251
    public $charset;
252
    /**
253
     * @var bool 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' => pgsql\Schema::class, // PostgreSQL
278
        'mysqli' => mysql\Schema::class, // MySQL
279
        'mysql' => mysql\Schema::class, // MySQL
280
        'sqlite' => sqlite\Schema::class, // sqlite 3
281
        'sqlite2' => sqlite\Schema::class, // sqlite 2
282
    ];
283
    /**
284
     * @var string Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
285
     * @see pdo
286
     */
287
    public $pdoClass;
288
    /**
289
     * @var array mapping between PDO driver names and [[Command]] classes.
290
     * The keys of the array are PDO driver names while the values are either the corresponding
291
     * command class names or configurations. Please refer to [[Yii::createObject()]] for
292
     * details on how to specify a configuration.
293
     *
294
     * This property is mainly used by [[createCommand()]] to create new database [[Command]] objects.
295
     * You normally do not need to set this property unless you want to use your own
296
     * [[Command]] class or support DBMS that is not supported by Yii.
297
     * @since 2.0.14
298
     */
299
    public $commandMap = [
300
        'pgsql' => 'yii\db\Command', // PostgreSQL
301
        'mysqli' => 'yii\db\Command', // MySQL
302
        'mysql' => 'yii\db\Command', // MySQL
303
        'sqlite' => 'yii\db\sqlite\Command', // sqlite 3
304
        'sqlite2' => 'yii\db\sqlite\Command', // sqlite 2
305
        'sqlsrv' => 'yii\db\Command', // newer MSSQL driver on MS Windows hosts
306
        'oci' => 'yii\db\Command', // Oracle driver
307
        'mssql' => 'yii\db\Command', // older MSSQL driver on MS Windows hosts
308
        'dblib' => 'yii\db\Command', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
309
    ];
310
    /**
311
     * @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
312
     * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
313
     */
314
    public $enableSavepoint = true;
315
    /**
316
     * @var CacheInterface|string the cache object or the ID of the cache application component that is used to store
317
     * the health status of the DB servers specified in [[masters]] and [[slaves]].
318
     * This is used only when read/write splitting is enabled or [[masters]] is not empty.
319
     */
320
    public $serverStatusCache = 'cache';
321
    /**
322
     * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
323
     * This is used together with [[serverStatusCache]].
324
     */
325
    public $serverRetryInterval = 600;
326
    /**
327
     * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
328
     * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
329
     */
330
    public $enableSlaves = true;
331
    /**
332
     * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
333
     * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
334
     * for performing read queries only.
335
     * @see enableSlaves
336
     * @see slaveConfig
337
     */
338
    public $slaves = [];
339
    /**
340
     * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
341
     * For example,
342
     *
343
     * ```php
344
     * [
345
     *     'username' => 'slave',
346
     *     'password' => 'slave',
347
     *     'attributes' => [
348
     *         // use a smaller connection timeout
349
     *         PDO::ATTR_TIMEOUT => 10,
350
     *     ],
351
     * ]
352
     * ```
353
     */
354
    public $slaveConfig = [];
355
    /**
356
     * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
357
     * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
358
     * which will be used by this object.
359
     * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
360
     * be ignored.
361
     * @see masterConfig
362
     * @see shuffleMasters
363
     */
364
    public $masters = [];
365
    /**
366
     * @var array the configuration that should be merged with every master configuration listed in [[masters]].
367
     * For example,
368
     *
369
     * ```php
370
     * [
371
     *     'username' => 'master',
372
     *     'password' => 'master',
373
     *     'attributes' => [
374
     *         // use a smaller connection timeout
375
     *         PDO::ATTR_TIMEOUT => 10,
376
     *     ],
377
     * ]
378
     * ```
379
     */
380
    public $masterConfig = [];
381
    /**
382
     * @var bool whether to shuffle [[masters]] before getting one.
383
     * @since 2.0.11
384
     * @see masters
385
     */
386
    public $shuffleMasters = true;
387
    /**
388
     * @var bool whether to enable logging of database queries. Defaults to true.
389
     * You may want to disable this option in a production environment to gain performance
390
     * if you do not need the information being logged.
391
     * @since 2.0.12
392
     * @see enableProfiling
393
     */
394
    public $enableLogging = true;
395
    /**
396
     * @var bool whether to enable profiling of opening database connection and database queries. Defaults to true.
397
     * You may want to disable this option in a production environment to gain performance
398
     * if you do not need the information being logged.
399
     * @since 2.0.12
400
     * @see enableLogging
401
     */
402
    public $enableProfiling = true;
403
404
    /**
405
     * @var Transaction the currently active transaction
406
     */
407
    private $_transaction;
408
    /**
409
     * @var Schema the database schema
410
     */
411
    private $_schema;
412
    /**
413
     * @var string driver name
414
     */
415
    private $_driverName;
416
    /**
417
     * @var Connection|false the currently active master connection
418
     */
419
    private $_master = false;
420
    /**
421
     * @var Connection|false the currently active slave connection
422
     */
423
    private $_slave = false;
424
    /**
425
     * @var array query cache parameters for the [[cache()]] calls
426
     */
427
    private $_queryCacheInfo = [];
428
429
430
    /**
431
     * Returns a value indicating whether the DB connection is established.
432
     * @return bool whether the DB connection is established
433
     */
434 314
    public function getIsActive()
435
    {
436 314
        return $this->pdo !== null;
437
    }
438
439
    /**
440
     * Uses query cache for the queries performed with the callable.
441
     *
442
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
443
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
444
     * For example,
445
     *
446
     * ```php
447
     * // The customer will be fetched from cache if available.
448
     * // If not, the query will be made against DB and cached for use next time.
449
     * $customer = $db->cache(function (Connection $db) {
450
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
451
     * });
452
     * ```
453
     *
454
     * Note that query cache is only meaningful for queries that return results. For queries performed with
455
     * [[Command::execute()]], query cache will not be used.
456
     *
457
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
458
     * The signature of the callable is `function (Connection $db)`.
459
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
460
     * not set, the value of [[queryCacheDuration]] will be used instead.
461
     * Use 0 to indicate that the cached data will never expire.
462
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
463
     * @return mixed the return result of the callable
464
     * @throws \Throwable if there is any exception during query
465
     * @see enableQueryCache
466
     * @see queryCache
467
     * @see noCache()
468
     */
469 6
    public function cache(callable $callable, $duration = null, $dependency = null)
470
    {
471 6
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
472
        try {
473 6
            $result = call_user_func($callable, $this);
474 6
            array_pop($this->_queryCacheInfo);
475 6
            return $result;
476
        } catch (\Throwable $e) {
477
            array_pop($this->_queryCacheInfo);
478
            throw $e;
479
        }
480
    }
481
482
    /**
483
     * Disables query cache temporarily.
484
     *
485
     * Queries performed within the callable will not use query cache at all. For example,
486
     *
487
     * ```php
488
     * $db->cache(function (Connection $db) {
489
     *
490
     *     // ... queries that use query cache ...
491
     *
492
     *     return $db->noCache(function (Connection $db) {
493
     *         // this query will not use query cache
494
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
495
     *     });
496
     * });
497
     * ```
498
     *
499
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
500
     * The signature of the callable is `function (Connection $db)`.
501
     * @return mixed the return result of the callable
502
     * @throws \Throwable if there is any exception during query
503
     * @see enableQueryCache
504
     * @see queryCache
505
     * @see cache()
506
     */
507 38
    public function noCache(callable $callable)
508
    {
509 38
        $this->_queryCacheInfo[] = false;
510
        try {
511 38
            $result = call_user_func($callable, $this);
512 38
            array_pop($this->_queryCacheInfo);
513 38
            return $result;
514
        } catch (\Throwable $e) {
515
            array_pop($this->_queryCacheInfo);
516
            throw $e;
517
        }
518
    }
519
520
    /**
521
     * Returns the current query cache information.
522
     * This method is used internally by [[Command]].
523
     * @param int $duration the preferred caching duration. If null, it will be ignored.
524
     * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
525
     * @return array the current query cache information, or null if query cache is not enabled.
526
     * @internal
527
     */
528 1263
    public function getQueryCacheInfo($duration, $dependency)
529
    {
530 1263
        if (!$this->enableQueryCache) {
531 42
            return null;
532
        }
533
534 1261
        $info = end($this->_queryCacheInfo);
535 1261
        if (is_array($info)) {
536 6
            if ($duration === null) {
537 6
                $duration = $info[0];
538
            }
539 6
            if ($dependency === null) {
540 6
                $dependency = $info[1];
541
            }
542
        }
543
544 1261
        if ($duration === 0 || $duration > 0) {
545 6
            if (is_string($this->queryCache) && Yii::$app) {
546
                $cache = Yii::$app->get($this->queryCache, false);
547
            } else {
548 6
                $cache = $this->queryCache;
549
            }
550 6
            if ($cache instanceof CacheInterface) {
551 6
                return [$cache, $duration, $dependency];
552
            }
553
        }
554
555 1261
        return null;
556
    }
557
558
    /**
559
     * Establishes a DB connection.
560
     * It does nothing if a DB connection has already been established.
561
     * @throws Exception if connection fails
562
     */
563 1584
    public function open()
564
    {
565 1584
        if ($this->pdo !== null) {
566 1345
            return;
567
        }
568
569 1529
        if (!empty($this->masters)) {
570 1
            $db = $this->getMaster();
571 1
            if ($db !== null) {
572 1
                $this->pdo = $db->pdo;
573 1
                return;
574
            }
575
576
            throw new InvalidConfigException('None of the master DB servers is available.');
577
        }
578
579 1529
        if (empty($this->dsn)) {
580
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
581
        }
582
583 1529
        $token = 'Opening DB connection: ' . $this->dsn;
584 1529
        $enableProfiling = $this->enableProfiling;
585
        try {
586 1529
            Yii::info($token, __METHOD__);
587 1529
            if ($enableProfiling) {
588 1529
                Yii::beginProfile($token, __METHOD__);
589
            }
590
591 1529
            $this->pdo = $this->createPdoInstance();
592 1529
            $this->initConnection();
593
594 1529
            if ($enableProfiling) {
595 1529
                Yii::endProfile($token, __METHOD__);
596
            }
597 4
        } catch (\PDOException $e) {
598 4
            if ($enableProfiling) {
599 4
                Yii::endProfile($token, __METHOD__);
600
            }
601
602 4
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
603
        }
604 1529
    }
605
606
    /**
607
     * Closes the currently active DB connection.
608
     * It does nothing if the connection is already closed.
609
     */
610 1821
    public function close()
611
    {
612 1821
        if ($this->_master) {
613
            if ($this->pdo === $this->_master->pdo) {
614
                $this->pdo = null;
615
            }
616
617
            $this->_master->close();
618
            $this->_master = false;
619
        }
620
621 1821
        if ($this->pdo !== null) {
622 1415
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
623 1415
            $this->pdo = null;
624 1415
            $this->_schema = null;
625 1415
            $this->_transaction = null;
626
        }
627
628 1821
        if ($this->_slave) {
629 4
            $this->_slave->close();
630 4
            $this->_slave = false;
631
        }
632 1821
    }
633
634
    /**
635
     * Creates the PDO instance.
636
     * This method is called by [[open]] to establish a DB connection.
637
     * The default implementation will create a PHP PDO instance.
638
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
639
     * @return PDO the pdo instance
640
     */
641 1529
    protected function createPdoInstance()
642
    {
643 1529
        $pdoClass = $this->pdoClass;
644 1529
        if ($pdoClass === null) {
645 1529
            $pdoClass = 'PDO';
646 1529
            if ($this->_driverName !== null) {
647 181
                $driver = $this->_driverName;
648 1353
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
649 1353
                $driver = strtolower(substr($this->dsn, 0, $pos));
650
            }
651 1529
            if (isset($driver)) {
652 1529
                if ($driver === 'mssql' || $driver === 'dblib') {
653
                    $pdoClass = mssql\PDO::class;
654 1529
                } elseif ($driver === 'sqlsrv') {
655
                    $pdoClass = mssql\SqlsrvPDO::class;
656
                }
657
            }
658
        }
659
660 1529
        $dsn = $this->dsn;
661 1529
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
662 1
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
663
        }
664
665 1529
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
666
    }
667
668
    /**
669
     * Initializes the DB connection.
670
     * This method is invoked right after the DB connection is established.
671
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
672
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
673
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
674
     */
675 1529
    protected function initConnection()
676
    {
677 1529
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
678 1529
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
679
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
680
        }
681 1529
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli'], true)) {
682
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
683
        }
684 1529
        $this->trigger(self::EVENT_AFTER_OPEN);
685 1529
    }
686
687
    /**
688
     * Creates a command for execution.
689
     * @param string $sql the SQL statement to be executed
690
     * @param array $params the parameters to be bound to the SQL statement
691
     * @return Command the DB command
692
     */
693 1348
    public function createCommand($sql = null, $params = [])
694
    {
695 1348
        $driver = $this->getDriverName();
696 1348
        $config = ['__class' => Command::class];
697 1348
        if (isset($this->commandMap[$driver])) {
698 1348
            $config = !is_array($this->commandMap[$driver]) ? ['__class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
699
        }
700 1348
        $config['db'] = $this;
701 1348
        $config['sql'] = $sql;
702
        /** @var Command $command */
703 1348
        $command = Yii::createObject($config);
704 1348
        return $command->bindValues($params);
705
    }
706
707
    /**
708
     * Returns the currently active transaction.
709
     * @return Transaction the currently active transaction. Null if no active transaction.
710
     */
711 1319
    public function getTransaction()
712
    {
713 1319
        return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
714
    }
715
716
    /**
717
     * Starts a transaction.
718
     * @param string|null $isolationLevel The isolation level to use for this transaction.
719
     * See [[Transaction::begin()]] for details.
720
     * @return Transaction the transaction initiated
721
     */
722 35
    public function beginTransaction($isolationLevel = null)
723
    {
724 35
        $this->open();
725
726 35
        if (($transaction = $this->getTransaction()) === null) {
727 35
            $transaction = $this->_transaction = new Transaction(['db' => $this]);
728
        }
729 35
        $transaction->begin($isolationLevel);
730
731 35
        return $transaction;
732
    }
733
734
    /**
735
     * Executes callback provided in a transaction.
736
     *
737
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
738
     * @param string|null $isolationLevel The isolation level to use for this transaction.
739
     * See [[Transaction::begin()]] for details.
740
     * @throws \Throwable if there is any exception during query. In this case the transaction will be rolled back.
741
     * @return mixed result of callback function
742
     */
743 19
    public function transaction(callable $callback, $isolationLevel = null)
744
    {
745 19
        $transaction = $this->beginTransaction($isolationLevel);
746 19
        $level = $transaction->level;
747
748
        try {
749 19
            $result = call_user_func($callback, $this);
750 15
            if ($transaction->isActive && $transaction->level === $level) {
751 15
                $transaction->commit();
752
            }
753 4
        } catch (\Throwable $e) {
754 4
            $this->rollbackTransactionOnLevel($transaction, $level);
755 4
            throw $e;
756
        }
757
758 15
        return $result;
759
    }
760
761
    /**
762
     * Rolls back given [[Transaction]] object if it's still active and level match.
763
     * In some cases rollback can fail, so this method is fail safe. Exception thrown
764
     * from rollback will be caught and just logged with [[\Yii::error()]].
765
     * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
766
     * @param int $level Transaction level just after [[beginTransaction()]] call.
767
     */
768 4
    private function rollbackTransactionOnLevel($transaction, $level)
769
    {
770 4
        if ($transaction->isActive && $transaction->level === $level) {
771
            // https://github.com/yiisoft/yii2/pull/13347
772
            try {
773 4
                $transaction->rollBack();
774
            } catch (\Exception $e) {
775
                \Yii::error($e, __METHOD__);
776
                // hide this exception to be able to continue throwing original exception outside
777
            }
778
        }
779 4
    }
780
781
    /**
782
     * Returns the schema information for the database opened by this connection.
783
     * @return Schema the schema information for the database opened by this connection.
784
     * @throws NotSupportedException if there is no support for the current driver type
785
     */
786 1725
    public function getSchema()
787
    {
788 1725
        if ($this->_schema !== null) {
789 1434
            return $this->_schema;
790
        }
791
792 1662
        $driver = $this->getDriverName();
793 1662
        if (isset($this->schemaMap[$driver])) {
794 1662
            $config = !is_array($this->schemaMap[$driver]) ? ['__class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
795 1662
            $config['db'] = $this;
796
797 1662
            return $this->_schema = Yii::createObject($config);
798
        }
799
800
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
801
    }
802
803
    /**
804
     * Returns the query builder for the current DB connection.
805
     * @return QueryBuilder the query builder for the current DB connection.
806
     */
807 981
    public function getQueryBuilder()
808
    {
809 981
        return $this->getSchema()->getQueryBuilder();
810
    }
811
812
    /**
813
     * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
814
     *
815
     * @param array $value the [[QueryBuilder]] properties to be configured.
816
     * @since 2.0.14
817
     */
818
    public function setQueryBuilder($value)
819
    {
820
        Yii::configure($this->getQueryBuilder(), $value);
821
    }
822
823
    /**
824
     * Obtains the schema information for the named table.
825
     * @param string $name table name.
826
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
827
     * @return TableSchema table schema information. Null if the named table does not exist.
828
     */
829 201
    public function getTableSchema($name, $refresh = false)
830
    {
831 201
        return $this->getSchema()->getTableSchema($name, $refresh);
832
    }
833
834
    /**
835
     * Returns the ID of the last inserted row or sequence value.
836
     * @param string $sequenceName name of the sequence object (required by some DBMS)
837
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
838
     * @see http://php.net/manual/en/pdo.lastinsertid.php
839
     */
840
    public function getLastInsertID($sequenceName = '')
841
    {
842
        return $this->getSchema()->getLastInsertID($sequenceName);
843
    }
844
845
    /**
846
     * Quotes a string value for use in a query.
847
     * Note that if the parameter is not a string, it will be returned without change.
848
     * @param string $value string to be quoted
849
     * @return string the properly quoted string
850
     * @see http://php.net/manual/en/pdo.quote.php
851
     */
852 954
    public function quoteValue($value)
853
    {
854 954
        return $this->getSchema()->quoteValue($value);
855
    }
856
857
    /**
858
     * Quotes a table name for use in a query.
859
     * If the table name contains schema prefix, the prefix will also be properly quoted.
860
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
861
     * then this method will do nothing.
862
     * @param string $name table name
863
     * @return string the properly quoted table name
864
     */
865 1193
    public function quoteTableName($name)
866
    {
867 1193
        return $this->getSchema()->quoteTableName($name);
868
    }
869
870
    /**
871
     * Quotes a column name for use in a query.
872
     * If the column name contains prefix, the prefix will also be properly quoted.
873
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
874
     * then this method will do nothing.
875
     * @param string $name column name
876
     * @return string the properly quoted column name
877
     */
878 1216
    public function quoteColumnName($name)
879
    {
880 1216
        return $this->getSchema()->quoteColumnName($name);
881
    }
882
883
    /**
884
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
885
     * Tokens enclosed within double curly brackets are treated as table names, while
886
     * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
887
     * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
888
     * with [[tablePrefix]].
889
     * @param string $sql the SQL to be quoted
890
     * @return string the quoted SQL
891
     */
892 1391
    public function quoteSql($sql)
893
    {
894 1391
        return preg_replace_callback(
895 1391
            '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
896 1391
            function ($matches) {
897 692
                if (isset($matches[3])) {
898 485
                    return $this->quoteColumnName($matches[3]);
899
                }
900
901 651
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
902 1391
            },
903 1391
            $sql
904
        );
905
    }
906
907
    /**
908
     * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
909
     * by an end user.
910
     * @return string name of the DB driver
911
     */
912 1733
    public function getDriverName()
913
    {
914 1733
        if ($this->_driverName === null) {
915 1661
            if (($pos = strpos($this->dsn, ':')) !== false) {
916 1661
                $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
917
            } else {
918
                $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
919
            }
920
        }
921
922 1733
        return $this->_driverName;
923
    }
924
925
    /**
926
     * Changes the current driver name.
927
     * @param string $driverName name of the DB driver
928
     */
929
    public function setDriverName($driverName)
930
    {
931
        $this->_driverName = strtolower($driverName);
932
    }
933
934
    /**
935
     * Returns a server version as a string comparable by [[\version_compare()]].
936
     * @return string server version as a string.
937
     * @since 2.0.14
938
     */
939 48
    public function getServerVersion()
940
    {
941 48
        return $this->getSchema()->getServerVersion();
942
    }
943
944
    /**
945
     * Returns the PDO instance for the currently active slave connection.
946
     * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
947
     * will be returned by this method.
948
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
949
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
950
     * is available and `$fallbackToMaster` is false.
951
     */
952 1322
    public function getSlavePdo($fallbackToMaster = true)
953
    {
954 1322
        $db = $this->getSlave(false);
955 1322
        if ($db === null) {
956 1318
            return $fallbackToMaster ? $this->getMasterPdo() : null;
957
        }
958
959 5
        return $db->pdo;
960
    }
961
962
    /**
963
     * Returns the PDO instance for the currently active master connection.
964
     * This method will open the master DB connection and then return [[pdo]].
965
     * @return PDO the PDO instance for the currently active master connection.
966
     */
967 1360
    public function getMasterPdo()
968
    {
969 1360
        $this->open();
970 1360
        return $this->pdo;
971
    }
972
973
    /**
974
     * Returns the currently active slave connection.
975
     * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
976
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
977
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
978
     * `$fallbackToMaster` is false.
979
     */
980 1324
    public function getSlave($fallbackToMaster = true)
981
    {
982 1324
        if (!$this->enableSlaves) {
983 185
            return $fallbackToMaster ? $this : null;
984
        }
985
986 1243
        if ($this->_slave === false) {
987 1243
            $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
988
        }
989
990 1237
        return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
991
    }
992
993
    /**
994
     * Returns the currently active master connection.
995
     * If this method is called for the first time, it will try to open a master connection.
996
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
997
     * @since 2.0.11
998
     */
999 3
    public function getMaster()
1000
    {
1001 3
        if ($this->_master === false) {
1002 3
            $this->_master = ($this->shuffleMasters)
1003 2
                ? $this->openFromPool($this->masters, $this->masterConfig)
1004 1
                : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
1005
        }
1006
1007 3
        return $this->_master;
1008
    }
1009
1010
    /**
1011
     * Executes the provided callback by using the master connection.
1012
     *
1013
     * This method is provided so that you can temporarily force using the master connection to perform
1014
     * DB operations even if they are read queries. For example,
1015
     *
1016
     * ```php
1017
     * $result = $db->useMaster(function ($db) {
1018
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1019
     * });
1020
     * ```
1021
     *
1022
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1023
     * `function (Connection $db)`. Its return value will be returned by this method.
1024
     * @return mixed the return value of the callback
1025
     * @throws \Throwable if there is any exception thrown from the callback
1026
     */
1027 81
    public function useMaster(callable $callback)
1028
    {
1029 81
        if ($this->enableSlaves) {
1030 81
            $this->enableSlaves = false;
1031
            try {
1032 81
                $result = call_user_func($callback, $this);
1033 4
            } catch (\Throwable $e) {
1034 4
                $this->enableSlaves = true;
1035 4
                throw $e;
1036
            }
1037
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
1038 77
            $this->enableSlaves = true;
1039
        } else {
1040
            $result = call_user_func($callback, $this);
1041
        }
1042
1043 77
        return $result;
1044
    }
1045
1046
    /**
1047
     * Opens the connection to a server in the pool.
1048
     * This method implements the load balancing among the given list of the servers.
1049
     * Connections will be tried in random order.
1050
     * @param array $pool the list of connection configurations in the server pool
1051
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1052
     * @return Connection the opened DB connection, or `null` if no server is available
1053
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1054
     */
1055 1243
    protected function openFromPool(array $pool, array $sharedConfig)
1056
    {
1057 1243
        shuffle($pool);
1058 1243
        return $this->openFromPoolSequentially($pool, $sharedConfig);
1059
    }
1060
1061
    /**
1062
     * Opens the connection to a server in the pool.
1063
     * This method implements the load balancing among the given list of the servers.
1064
     * Connections will be tried in sequential order.
1065
     * @param array $pool the list of connection configurations in the server pool
1066
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1067
     * @return Connection the opened DB connection, or `null` if no server is available
1068
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1069
     * @since 2.0.11
1070
     */
1071 1243
    protected function openFromPoolSequentially(array $pool, array $sharedConfig)
1072
    {
1073 1243
        if (empty($pool)) {
1074 1231
            return null;
1075
        }
1076
1077 13
        if (!isset($sharedConfig['__class'])) {
1078 13
            $sharedConfig['__class'] = get_class($this);
1079
        }
1080
1081 13
        $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
1082
1083 13
        foreach ($pool as $config) {
1084 13
            $config = array_merge($sharedConfig, $config);
1085 13
            if (empty($config['dsn'])) {
1086 6
                throw new InvalidConfigException('The "dsn" option must be specified.');
1087
            }
1088
1089 7
            $key = [__METHOD__, $config['dsn']];
1090 7
            if ($cache instanceof CacheInterface && $cache->get($key)) {
0 ignored issues
show
Documentation introduced by
$key is of type array<integer,?,{"0":"string","1":"?"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1091
                // should not try this dead server now
1092
                continue;
1093
            }
1094
1095
            /* @var $db Connection */
1096 7
            $db = Yii::createObject($config);
1097
1098
            try {
1099 7
                $db->open();
1100 7
                return $db;
1101
            } catch (\Exception $e) {
1102
                Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1103
                if ($cache instanceof CacheInterface) {
1104
                    // mark this server as dead and only retry it after the specified interval
1105
                    $cache->set($key, 1, $this->serverRetryInterval);
1106
                }
1107
            }
1108
        }
1109
1110
        return null;
1111
    }
1112
1113
    /**
1114
     * Close the connection before serializing.
1115
     * @return array
1116
     */
1117 17
    public function __sleep()
1118
    {
1119 17
        $fields = (array) $this;
1120
1121 17
        unset($fields['pdo']);
1122 17
        unset($fields["\000" . __CLASS__ . "\000" . '_master']);
1123 17
        unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
1124 17
        unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
1125 17
        unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
1126
1127 17
        return array_keys($fields);
1128
    }
1129
1130
    /**
1131
     * Reset the connection after cloning.
1132
     */
1133 7
    public function __clone()
1134
    {
1135 7
        parent::__clone();
1136
1137 7
        $this->_master = false;
1138 7
        $this->_slave = false;
1139 7
        $this->_schema = null;
1140 7
        $this->_transaction = null;
1141 7
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
1142
            // reset PDO connection, unless its sqlite in-memory, which can only have one connection
1143 6
            $this->pdo = null;
1144
        }
1145 7
    }
1146
}
1147