Completed
Push — 2.1 ( c12e66...b57633 )
by Alexander
12:31
created

Connection::buildDSN()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
crap 3
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
    * {@inheritdoc}
431
    */
432 1936
    public function init()
433
    {
434 1936
       if (is_array($this->dsn)) {
435 4
           $this->dsn = $this->buildDSN($this->dsn);
436
       }
437 1936
    }
438
439
    /**
440
     * Returns a value indicating whether the DB connection is established.
441
     * @return bool whether the DB connection is established
442
     */
443 314
    public function getIsActive()
444
    {
445 314
        return $this->pdo !== null;
446
    }
447
448
    /**
449
     * Uses query cache for the queries performed with the callable.
450
     *
451
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
452
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
453
     * For example,
454
     *
455
     * ```php
456
     * // The customer will be fetched from cache if available.
457
     * // If not, the query will be made against DB and cached for use next time.
458
     * $customer = $db->cache(function (Connection $db) {
459
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
460
     * });
461
     * ```
462
     *
463
     * Note that query cache is only meaningful for queries that return results. For queries performed with
464
     * [[Command::execute()]], query cache will not be used.
465
     *
466
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
467
     * The signature of the callable is `function (Connection $db)`.
468
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
469
     * not set, the value of [[queryCacheDuration]] will be used instead.
470
     * Use 0 to indicate that the cached data will never expire.
471
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
472
     * @return mixed the return result of the callable
473
     * @throws \Throwable if there is any exception during query
474
     * @see enableQueryCache
475
     * @see queryCache
476
     * @see noCache()
477
     */
478 6
    public function cache(callable $callable, $duration = null, $dependency = null)
479
    {
480 6
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
481
        try {
482 6
            $result = call_user_func($callable, $this);
483 6
            array_pop($this->_queryCacheInfo);
484 6
            return $result;
485
        } catch (\Throwable $e) {
486
            array_pop($this->_queryCacheInfo);
487
            throw $e;
488
        }
489
    }
490
491
    /**
492
     * Disables query cache temporarily.
493
     *
494
     * Queries performed within the callable will not use query cache at all. For example,
495
     *
496
     * ```php
497
     * $db->cache(function (Connection $db) {
498
     *
499
     *     // ... queries that use query cache ...
500
     *
501
     *     return $db->noCache(function (Connection $db) {
502
     *         // this query will not use query cache
503
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
504
     *     });
505
     * });
506
     * ```
507
     *
508
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
509
     * The signature of the callable is `function (Connection $db)`.
510
     * @return mixed the return result of the callable
511
     * @throws \Throwable if there is any exception during query
512
     * @see enableQueryCache
513
     * @see queryCache
514
     * @see cache()
515
     */
516 38
    public function noCache(callable $callable)
517
    {
518 38
        $this->_queryCacheInfo[] = false;
519
        try {
520 38
            $result = call_user_func($callable, $this);
521 38
            array_pop($this->_queryCacheInfo);
522 38
            return $result;
523
        } catch (\Throwable $e) {
524
            array_pop($this->_queryCacheInfo);
525
            throw $e;
526
        }
527
    }
528
529
    /**
530
     * Returns the current query cache information.
531
     * This method is used internally by [[Command]].
532
     * @param int $duration the preferred caching duration. If null, it will be ignored.
533
     * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
534
     * @return array the current query cache information, or null if query cache is not enabled.
535
     * @internal
536
     */
537 1269
    public function getQueryCacheInfo($duration, $dependency)
538
    {
539 1269
        if (!$this->enableQueryCache) {
540 42
            return null;
541
        }
542
543 1267
        $info = end($this->_queryCacheInfo);
544 1267
        if (is_array($info)) {
545 6
            if ($duration === null) {
546 6
                $duration = $info[0];
547
            }
548 6
            if ($dependency === null) {
549 6
                $dependency = $info[1];
550
            }
551
        }
552
553 1267
        if ($duration === 0 || $duration > 0) {
554 6
            if (is_string($this->queryCache) && Yii::$app) {
555
                $cache = Yii::$app->get($this->queryCache, false);
556
            } else {
557 6
                $cache = $this->queryCache;
558
            }
559 6
            if ($cache instanceof CacheInterface) {
560 6
                return [$cache, $duration, $dependency];
561
            }
562
        }
563
564 1267
        return null;
565
    }
566
567
    /**
568
     * Establishes a DB connection.
569
     * It does nothing if a DB connection has already been established.
570
     * @throws Exception if connection fails
571
     */
572 1590
    public function open()
573
    {
574 1590
        if ($this->pdo !== null) {
575 1351
            return;
576
        }
577
578 1535
        if (!empty($this->masters)) {
579 1
            $db = $this->getMaster();
580 1
            if ($db !== null) {
581 1
                $this->pdo = $db->pdo;
582 1
                return;
583
            }
584
585
            throw new InvalidConfigException('None of the master DB servers is available.');
586
        }
587
588 1535
        if (empty($this->dsn)) {
589
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
590
        }
591
592 1535
        $token = 'Opening DB connection: ' . $this->dsn;
593 1535
        $enableProfiling = $this->enableProfiling;
594
        try {
595 1535
            Yii::info($token, __METHOD__);
596 1535
            if ($enableProfiling) {
597 1535
                Yii::beginProfile($token, __METHOD__);
598
            }
599
600 1535
            $this->pdo = $this->createPdoInstance();
601 1535
            $this->initConnection();
602
603 1535
            if ($enableProfiling) {
604 1535
                Yii::endProfile($token, __METHOD__);
605
            }
606 4
        } catch (\PDOException $e) {
607 4
            if ($enableProfiling) {
608 4
                Yii::endProfile($token, __METHOD__);
609
            }
610
611 4
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
612
        }
613 1535
    }
614
615
    /**
616
     * Closes the currently active DB connection.
617
     * It does nothing if the connection is already closed.
618
     */
619 1827
    public function close()
620
    {
621 1827
        if ($this->_master) {
622
            if ($this->pdo === $this->_master->pdo) {
623
                $this->pdo = null;
624
            }
625
626
            $this->_master->close();
627
            $this->_master = false;
628
        }
629
630 1827
        if ($this->pdo !== null) {
631 1421
            Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
632 1421
            $this->pdo = null;
633 1421
            $this->_schema = null;
634 1421
            $this->_transaction = null;
635
        }
636
637 1827
        if ($this->_slave) {
638 4
            $this->_slave->close();
639 4
            $this->_slave = false;
640
        }
641 1827
    }
642
643
    /**
644
     * Creates the PDO instance.
645
     * This method is called by [[open]] to establish a DB connection.
646
     * The default implementation will create a PHP PDO instance.
647
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
648
     * @return PDO the pdo instance
649
     */
650 1535
    protected function createPdoInstance()
651
    {
652 1535
        $pdoClass = $this->pdoClass;
653 1535
        if ($pdoClass === null) {
654 1535
            $pdoClass = 'PDO';
655 1535
            if ($this->_driverName !== null) {
656 181
                $driver = $this->_driverName;
657 1359
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
658 1359
                $driver = strtolower(substr($this->dsn, 0, $pos));
659
            }
660 1535
            if (isset($driver)) {
661 1535
                if ($driver === 'mssql' || $driver === 'dblib') {
662
                    $pdoClass = mssql\PDO::class;
663 1535
                } elseif ($driver === 'sqlsrv') {
664
                    $pdoClass = mssql\SqlsrvPDO::class;
665
                }
666
            }
667
        }
668
669 1535
        $dsn = $this->dsn;
670 1535
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
671 1
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
672
        }
673
674 1535
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
675
    }
676
677
    /**
678
     * Initializes the DB connection.
679
     * This method is invoked right after the DB connection is established.
680
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
681
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
682
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
683
     */
684 1535
    protected function initConnection()
685
    {
686 1535
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
687 1535
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
688
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
689
        }
690 1535
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli'], true)) {
691
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
692
        }
693 1535
        $this->trigger(self::EVENT_AFTER_OPEN);
694 1535
    }
695
696
    /**
697
     * Creates a command for execution.
698
     * @param string $sql the SQL statement to be executed
699
     * @param array $params the parameters to be bound to the SQL statement
700
     * @return Command the DB command
701
     */
702 1354
    public function createCommand($sql = null, $params = [])
703
    {
704 1354
        $driver = $this->getDriverName();
705 1354
        $config = ['__class' => Command::class];
706 1354
        if (isset($this->commandMap[$driver])) {
707 1354
            $config = !is_array($this->commandMap[$driver]) ? ['__class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
708
        }
709 1354
        $config['db'] = $this;
710 1354
        $config['sql'] = $sql;
711
        /** @var Command $command */
712 1354
        $command = Yii::createObject($config);
713 1354
        return $command->bindValues($params);
714
    }
715
716
    /**
717
     * Returns the currently active transaction.
718
     * @return Transaction the currently active transaction. Null if no active transaction.
719
     */
720 1325
    public function getTransaction()
721
    {
722 1325
        return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
723
    }
724
725
    /**
726
     * Starts a transaction.
727
     * @param string|null $isolationLevel The isolation level to use for this transaction.
728
     * See [[Transaction::begin()]] for details.
729
     * @return Transaction the transaction initiated
730
     */
731 35
    public function beginTransaction($isolationLevel = null)
732
    {
733 35
        $this->open();
734
735 35
        if (($transaction = $this->getTransaction()) === null) {
736 35
            $transaction = $this->_transaction = new Transaction(['db' => $this]);
737
        }
738 35
        $transaction->begin($isolationLevel);
739
740 35
        return $transaction;
741
    }
742
743
    /**
744
     * Executes callback provided in a transaction.
745
     *
746
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
747
     * @param string|null $isolationLevel The isolation level to use for this transaction.
748
     * See [[Transaction::begin()]] for details.
749
     * @throws \Throwable if there is any exception during query. In this case the transaction will be rolled back.
750
     * @return mixed result of callback function
751
     */
752 19
    public function transaction(callable $callback, $isolationLevel = null)
753
    {
754 19
        $transaction = $this->beginTransaction($isolationLevel);
755 19
        $level = $transaction->level;
756
757
        try {
758 19
            $result = call_user_func($callback, $this);
759 15
            if ($transaction->isActive && $transaction->level === $level) {
760 15
                $transaction->commit();
761
            }
762 4
        } catch (\Throwable $e) {
763 4
            $this->rollbackTransactionOnLevel($transaction, $level);
764 4
            throw $e;
765
        }
766
767 15
        return $result;
768
    }
769
770
    /**
771
     * Rolls back given [[Transaction]] object if it's still active and level match.
772
     * In some cases rollback can fail, so this method is fail safe. Exception thrown
773
     * from rollback will be caught and just logged with [[\Yii::error()]].
774
     * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
775
     * @param int $level Transaction level just after [[beginTransaction()]] call.
776
     */
777 4
    private function rollbackTransactionOnLevel($transaction, $level)
778
    {
779 4
        if ($transaction->isActive && $transaction->level === $level) {
780
            // https://github.com/yiisoft/yii2/pull/13347
781
            try {
782 4
                $transaction->rollBack();
783
            } catch (\Exception $e) {
784
                \Yii::error($e, __METHOD__);
785
                // hide this exception to be able to continue throwing original exception outside
786
            }
787
        }
788 4
    }
789
790
    /**
791
     * Returns the schema information for the database opened by this connection.
792
     * @return Schema the schema information for the database opened by this connection.
793
     * @throws NotSupportedException if there is no support for the current driver type
794
     */
795 1731
    public function getSchema()
796
    {
797 1731
        if ($this->_schema !== null) {
798 1439
            return $this->_schema;
799
        }
800
801 1668
        $driver = $this->getDriverName();
802 1668
        if (isset($this->schemaMap[$driver])) {
803 1668
            $config = !is_array($this->schemaMap[$driver]) ? ['__class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
804 1668
            $config['db'] = $this;
805
806 1668
            return $this->_schema = Yii::createObject($config);
807
        }
808
809
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
810
    }
811
812
    /**
813
     * Returns the query builder for the current DB connection.
814
     * @return QueryBuilder the query builder for the current DB connection.
815
     */
816 981
    public function getQueryBuilder()
817
    {
818 981
        return $this->getSchema()->getQueryBuilder();
819
    }
820
821
    /**
822
     * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
823
     *
824
     * @param array $value the [[QueryBuilder]] properties to be configured.
825
     * @since 2.0.14
826
     */
827
    public function setQueryBuilder($value)
828
    {
829
        Yii::configure($this->getQueryBuilder(), $value);
830
    }
831
832
    /**
833
     * Obtains the schema information for the named table.
834
     * @param string $name table name.
835
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
836
     * @return TableSchema table schema information. Null if the named table does not exist.
837
     */
838 201
    public function getTableSchema($name, $refresh = false)
839
    {
840 201
        return $this->getSchema()->getTableSchema($name, $refresh);
841
    }
842
843
    /**
844
     * Returns the ID of the last inserted row or sequence value.
845
     * @param string $sequenceName name of the sequence object (required by some DBMS)
846
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
847
     * @see http://php.net/manual/en/pdo.lastinsertid.php
848
     */
849
    public function getLastInsertID($sequenceName = '')
850
    {
851
        return $this->getSchema()->getLastInsertID($sequenceName);
852
    }
853
854
    /**
855
     * Quotes a string value for use in a query.
856
     * Note that if the parameter is not a string, it will be returned without change.
857
     * @param string $value string to be quoted
858
     * @return string the properly quoted string
859
     * @see http://php.net/manual/en/pdo.quote.php
860
     */
861 957
    public function quoteValue($value)
862
    {
863 957
        return $this->getSchema()->quoteValue($value);
864
    }
865
866
    /**
867
     * Quotes a table name for use in a query.
868
     * If the table name contains schema prefix, the prefix will also be properly quoted.
869
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
870
     * then this method will do nothing.
871
     * @param string $name table name
872
     * @return string the properly quoted table name
873
     */
874 1193
    public function quoteTableName($name)
875
    {
876 1193
        return $this->getSchema()->quoteTableName($name);
877
    }
878
879
    /**
880
     * Quotes a column name for use in a query.
881
     * If the column name contains prefix, the prefix will also be properly quoted.
882
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
883
     * then this method will do nothing.
884
     * @param string $name column name
885
     * @return string the properly quoted column name
886
     */
887 1216
    public function quoteColumnName($name)
888
    {
889 1216
        return $this->getSchema()->quoteColumnName($name);
890
    }
891
892
    /**
893
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
894
     * Tokens enclosed within double curly brackets are treated as table names, while
895
     * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
896
     * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
897
     * with [[tablePrefix]].
898
     * @param string $sql the SQL to be quoted
899
     * @return string the quoted SQL
900
     */
901 1397
    public function quoteSql($sql)
902
    {
903 1397
        return preg_replace_callback(
904 1397
            '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
905 1397
            function ($matches) {
906 692
                if (isset($matches[3])) {
907 485
                    return $this->quoteColumnName($matches[3]);
908
                }
909
910 651
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
911 1397
            },
912 1397
            $sql
913
        );
914
    }
915
916
    /**
917
     * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
918
     * by an end user.
919
     * @return string name of the DB driver
920
     */
921 1739
    public function getDriverName()
922
    {
923 1739
        if ($this->_driverName === null) {
924 1667
            if (($pos = strpos($this->dsn, ':')) !== false) {
925 1667
                $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
926
            } else {
927
                $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
928
            }
929
        }
930
931 1739
        return $this->_driverName;
932
    }
933
934
    /**
935
     * Changes the current driver name.
936
     * @param string $driverName name of the DB driver
937
     */
938
    public function setDriverName($driverName)
939
    {
940
        $this->_driverName = strtolower($driverName);
941
    }
942
943
    /**
944
     * Returns a server version as a string comparable by [[\version_compare()]].
945
     * @return string server version as a string.
946
     * @since 2.0.14
947
     */
948 48
    public function getServerVersion()
949
    {
950 48
        return $this->getSchema()->getServerVersion();
951
    }
952
953
    /**
954
     * Returns the PDO instance for the currently active slave connection.
955
     * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
956
     * will be returned by this method.
957
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
958
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
959
     * is available and `$fallbackToMaster` is false.
960
     */
961 1328
    public function getSlavePdo($fallbackToMaster = true)
962
    {
963 1328
        $db = $this->getSlave(false);
964 1328
        if ($db === null) {
965 1324
            return $fallbackToMaster ? $this->getMasterPdo() : null;
966
        }
967
968 5
        return $db->pdo;
969
    }
970
971
    /**
972
     * Returns the PDO instance for the currently active master connection.
973
     * This method will open the master DB connection and then return [[pdo]].
974
     * @return PDO the PDO instance for the currently active master connection.
975
     */
976 1366
    public function getMasterPdo()
977
    {
978 1366
        $this->open();
979 1366
        return $this->pdo;
980
    }
981
982
    /**
983
     * Returns the currently active slave connection.
984
     * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
985
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
986
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
987
     * `$fallbackToMaster` is false.
988
     */
989 1330
    public function getSlave($fallbackToMaster = true)
990
    {
991 1330
        if (!$this->enableSlaves) {
992 191
            return $fallbackToMaster ? $this : null;
993
        }
994
995 1243
        if ($this->_slave === false) {
996 1243
            $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
997
        }
998
999 1237
        return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
1000
    }
1001
1002
    /**
1003
     * Returns the currently active master connection.
1004
     * If this method is called for the first time, it will try to open a master connection.
1005
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
1006
     * @since 2.0.11
1007
     */
1008 3
    public function getMaster()
1009
    {
1010 3
        if ($this->_master === false) {
1011 3
            $this->_master = ($this->shuffleMasters)
1012 2
                ? $this->openFromPool($this->masters, $this->masterConfig)
1013 1
                : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
1014
        }
1015
1016 3
        return $this->_master;
1017
    }
1018
1019
    /**
1020
     * Executes the provided callback by using the master connection.
1021
     *
1022
     * This method is provided so that you can temporarily force using the master connection to perform
1023
     * DB operations even if they are read queries. For example,
1024
     *
1025
     * ```php
1026
     * $result = $db->useMaster(function ($db) {
1027
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
1028
     * });
1029
     * ```
1030
     *
1031
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
1032
     * `function (Connection $db)`. Its return value will be returned by this method.
1033
     * @return mixed the return value of the callback
1034
     * @throws \Throwable if there is any exception thrown from the callback
1035
     */
1036 87
    public function useMaster(callable $callback)
1037
    {
1038 87
        if ($this->enableSlaves) {
1039 87
            $this->enableSlaves = false;
1040
            try {
1041 87
                $result = call_user_func($callback, $this);
1042 4
            } catch (\Throwable $e) {
1043 4
                $this->enableSlaves = true;
1044 4
                throw $e;
1045
            }
1046
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
1047 83
            $this->enableSlaves = true;
1048
        } else {
1049
            $result = call_user_func($callback, $this);
1050
        }
1051
1052 83
        return $result;
1053
    }
1054
1055
    /**
1056
     * Opens the connection to a server in the pool.
1057
     * This method implements the load balancing among the given list of the servers.
1058
     * Connections will be tried in random order.
1059
     * @param array $pool the list of connection configurations in the server pool
1060
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1061
     * @return Connection the opened DB connection, or `null` if no server is available
1062
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1063
     */
1064 1243
    protected function openFromPool(array $pool, array $sharedConfig)
1065
    {
1066 1243
        shuffle($pool);
1067 1243
        return $this->openFromPoolSequentially($pool, $sharedConfig);
1068
    }
1069
1070
    /**
1071
     * Opens the connection to a server in the pool.
1072
     * This method implements the load balancing among the given list of the servers.
1073
     * Connections will be tried in sequential order.
1074
     * @param array $pool the list of connection configurations in the server pool
1075
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1076
     * @return Connection the opened DB connection, or `null` if no server is available
1077
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1078
     * @since 2.0.11
1079
     */
1080 1243
    protected function openFromPoolSequentially(array $pool, array $sharedConfig)
1081
    {
1082 1243
        if (empty($pool)) {
1083 1231
            return null;
1084
        }
1085
1086 13
        if (!isset($sharedConfig['__class'])) {
1087 13
            $sharedConfig['__class'] = get_class($this);
1088
        }
1089
1090 13
        $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
1091
1092 13
        foreach ($pool as $config) {
1093 13
            $config = array_merge($sharedConfig, $config);
1094 13
            if (empty($config['dsn'])) {
1095 6
                throw new InvalidConfigException('The "dsn" option must be specified.');
1096
            }
1097
1098 7
            $key = [__METHOD__, $config['dsn']];
1099 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...
1100
                // should not try this dead server now
1101
                continue;
1102
            }
1103
1104
            /* @var $db Connection */
1105 7
            $db = Yii::createObject($config);
1106
1107
            try {
1108 7
                $db->open();
1109 7
                return $db;
1110
            } catch (\Exception $e) {
1111
                Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1112
                if ($cache instanceof CacheInterface) {
1113
                    // mark this server as dead and only retry it after the specified interval
1114
                    $cache->set($key, 1, $this->serverRetryInterval);
1115
                }
1116
            }
1117
        }
1118
1119
        return null;
1120
    }
1121
1122
    /**
1123
     * Build the Data Source Name or DSN
1124
     * @param array $config the DSN configurations
1125
     * @return string the formated DSN
1126
     * @throws InvalidConfigException if 'driver' key was not defined
1127
     */
1128 4
    private function buildDSN(array $config)
1129
    {
1130 4
        if (isset($config['driver'])) {
1131 4
            $parts = [];
1132 4
            $driver = $config['driver'];
1133 4
            unset($config['driver']);
1134
1135 4
            foreach ($config as $key => $value) {
1136 4
                $parts[] = "$key=$value";
1137
            }
1138
1139 4
            return "$driver:" . implode(';', $parts);
1140
        } else {
1141 4
            throw new InvalidConfigException("Connection 'driver' must be set.");
1142
        }
1143
    }
1144
1145
    /**
1146
     * Close the connection before serializing.
1147
     * @return array
1148
     */
1149 17
    public function __sleep()
1150
    {
1151 17
        $fields = (array) $this;
1152
1153 17
        unset($fields['pdo']);
1154 17
        unset($fields["\000" . __CLASS__ . "\000" . '_master']);
1155 17
        unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
1156 17
        unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
1157 17
        unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
1158
1159 17
        return array_keys($fields);
1160
    }
1161
1162
    /**
1163
     * Reset the connection after cloning.
1164
     */
1165 7
    public function __clone()
1166
    {
1167 7
        parent::__clone();
1168
1169 7
        $this->_master = false;
1170 7
        $this->_slave = false;
1171 7
        $this->_schema = null;
1172 7
        $this->_transaction = null;
1173 7
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
1174
            // reset PDO connection, unless its sqlite in-memory, which can only have one connection
1175 6
            $this->pdo = null;
1176
        }
1177 7
    }
1178
}
1179