Completed
Pull Request — master (#37)
by
unknown
02:22
created

Connection::buildDSN()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

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

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

Loading history...
507
            array_pop($this->_queryCacheInfo);
508
            throw $e;
509
        }
510
    }
511
512
    /**
513
     * Disables query cache temporarily.
514
     *
515
     * Queries performed within the callable will not use query cache at all. For example,
516
     *
517
     * ```php
518
     * $db->cache(function (Connection $db) {
519
     *
520
     *     // ... queries that use query cache ...
521
     *
522
     *     return $db->noCache(function (Connection $db) {
523
     *         // this query will not use query cache
524
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
525
     *     });
526
     * });
527
     * ```
528
     *
529
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
530
     * The signature of the callable is `function (Connection $db)`.
531
     * @return mixed the return result of the callable
532
     * @throws \Throwable if there is any exception during query
533
     * @see enableQueryCache
534
     * @see queryCache
535
     * @see cache()
536
     */
537
    public function noCache(callable $callable)
538
    {
539
        $this->_queryCacheInfo[] = false;
540
        try {
541
            $result = call_user_func($callable, $this);
542
            array_pop($this->_queryCacheInfo);
543
            return $result;
544
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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