Completed
Push — master ( 8a6f58...915c78 )
by Alexander
14:59
created

framework/db/Connection.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use PDO;
11
use Yii;
12
use yii\base\Component;
13
use yii\base\InvalidConfigException;
14
use yii\base\NotSupportedException;
15
use yii\caching\CacheInterface;
16
17
/**
18
 * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
19
 *
20
 * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
21
 * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
22
 * of the [PDO PHP extension](http://php.net/manual/en/book.pdo.php).
23
 *
24
 * Connection supports database replication and read-write splitting. In particular, a Connection component
25
 * can be configured with multiple [[masters]] and [[slaves]]. It will do load balancing and failover by choosing
26
 * appropriate servers. It will also automatically direct read operations to the slaves and write operations to
27
 * the masters.
28
 *
29
 * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
30
 * call [[open()]] to connect to the database server. The current state of the connection can be checked using [[$isActive]].
31
 *
32
 * The following example shows how to create a Connection instance and establish
33
 * the DB connection:
34
 *
35
 * ```php
36
 * $connection = new \yii\db\Connection([
37
 *     'dsn' => $dsn,
38
 *     'username' => $username,
39
 *     'password' => $password,
40
 * ]);
41
 * $connection->open();
42
 * ```
43
 *
44
 * After the DB connection is established, one can execute SQL statements like the following:
45
 *
46
 * ```php
47
 * $command = $connection->createCommand('SELECT * FROM post');
48
 * $posts = $command->queryAll();
49
 * $command = $connection->createCommand('UPDATE post SET status=1');
50
 * $command->execute();
51
 * ```
52
 *
53
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
54
 * When the parameters are coming from user input, you should use this approach
55
 * to prevent SQL injection attacks. The following is an example:
56
 *
57
 * ```php
58
 * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
59
 * $command->bindValue(':id', $_GET['id']);
60
 * $post = $command->query();
61
 * ```
62
 *
63
 * For more information about how to perform various DB queries, please refer to [[Command]].
64
 *
65
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries
66
 * like the following:
67
 *
68
 * ```php
69
 * $transaction = $connection->beginTransaction();
70
 * try {
71
 *     $connection->createCommand($sql1)->execute();
72
 *     $connection->createCommand($sql2)->execute();
73
 *     // ... executing other SQL statements ...
74
 *     $transaction->commit();
75
 * } catch (Exception $e) {
76
 *     $transaction->rollBack();
77
 * }
78
 * ```
79
 *
80
 * You also can use shortcut for the above like the following:
81
 *
82
 * ```php
83
 * $connection->transaction(function () {
84
 *     $order = new Order($customer);
85
 *     $order->save();
86
 *     $order->addItems($items);
87
 * });
88
 * ```
89
 *
90
 * If needed you can pass transaction isolation level as a second parameter:
91
 *
92
 * ```php
93
 * $connection->transaction(function (Connection $db) {
94
 *     //return $db->...
95
 * }, Transaction::READ_UNCOMMITTED);
96
 * ```
97
 *
98
 * Connection is often used as an application component and configured in the application
99
 * configuration like the following:
100
 *
101
 * ```php
102
 * 'components' => [
103
 *     'db' => [
104
 *         'class' => '\yii\db\Connection',
105
 *         'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
106
 *         'username' => 'root',
107
 *         'password' => '',
108
 *         'charset' => 'utf8',
109
 *     ],
110
 * ],
111
 * ```
112
 *
113
 * @property string $driverName Name of the DB driver.
114
 * @property bool $isActive Whether the DB connection is established. This property is read-only.
115
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
116
 * sequence object. This property is read-only.
117
 * @property Connection $master The currently active master connection. `null` is returned if there is no
118
 * master available. This property is read-only.
119
 * @property PDO $masterPdo The PDO instance for the currently active master connection. This property is
120
 * read-only.
121
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is
122
 * read-only.
123
 * @property Schema $schema The schema information for the database opened by this connection. This property
124
 * is read-only.
125
 * @property Connection $slave The currently active slave connection. `null` is returned if there is no slave
126
 * available and `$fallbackToMaster` is false. This property is read-only.
127
 * @property PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned if
128
 * no slave connection is available and `$fallbackToMaster` is false. This property is read-only.
129
 * @property Transaction $transaction The currently active transaction. Null if no active transaction. This
130
 * property is read-only.
131
 *
132
 * @author Qiang Xue <[email protected]>
133
 * @since 2.0
134
 */
135
class Connection extends Component
136
{
137
    /**
138
     * @event Event an event that is triggered after a DB connection is established
139
     */
140
    const EVENT_AFTER_OPEN = 'afterOpen';
141
    /**
142
     * @event Event an event that is triggered right before a top-level transaction is started
143
     */
144
    const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
145
    /**
146
     * @event Event an event that is triggered right after a top-level transaction is committed
147
     */
148
    const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
149
    /**
150
     * @event Event an event that is triggered right after a top-level transaction is rolled back
151
     */
152
    const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
153
154
    /**
155
     * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
156
     * Please refer to the [PHP manual](http://php.net/manual/en/pdo.construct.php) on
157
     * the format of the DSN string.
158
     *
159
     * For [SQLite](http://php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](guide:concept-aliases)
160
     * for specifying the database path, e.g. `sqlite:@app/data/db.sql`.
161
     *
162
     * @see charset
163
     */
164
    public $dsn;
165
    /**
166
     * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
167
     */
168
    public $username;
169
    /**
170
     * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
171
     */
172
    public $password;
173
    /**
174
     * @var array PDO attributes (name => value) that should be set when calling [[open()]]
175
     * to establish a DB connection. Please refer to the
176
     * [PHP manual](http://php.net/manual/en/pdo.setattribute.php) for
177
     * details about available attributes.
178
     */
179
    public $attributes;
180
    /**
181
     * @var PDO the PHP PDO instance associated with this DB connection.
182
     * This property is mainly managed by [[open()]] and [[close()]] methods.
183
     * When a DB connection is active, this property will represent a PDO instance;
184
     * otherwise, it will be null.
185
     * @see pdoClass
186
     */
187
    public $pdo;
188
    /**
189
     * @var bool whether to enable schema caching.
190
     * Note that in order to enable truly schema caching, a valid cache component as specified
191
     * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
192
     * @see schemaCacheDuration
193
     * @see schemaCacheExclude
194
     * @see schemaCache
195
     */
196
    public $enableSchemaCache = false;
197
    /**
198
     * @var int number of seconds that table metadata can remain valid in cache.
199
     * Use 0 to indicate that the cached data will never expire.
200
     * @see enableSchemaCache
201
     */
202
    public $schemaCacheDuration = 3600;
203
    /**
204
     * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
205
     * The table names may contain schema prefix, if any. Do not quote the table names.
206
     * @see enableSchemaCache
207
     */
208
    public $schemaCacheExclude = [];
209
    /**
210
     * @var CacheInterface|string the cache object or the ID of the cache application component that
211
     * is used to cache the table metadata.
212
     * @see enableSchemaCache
213
     */
214
    public $schemaCache = 'cache';
215
    /**
216
     * @var bool whether to enable query caching.
217
     * Note that in order to enable query caching, a valid cache component as specified
218
     * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
219
     * Also, only the results of the queries enclosed within [[cache()]] will be cached.
220
     * @see queryCache
221
     * @see cache()
222
     * @see noCache()
223
     */
224
    public $enableQueryCache = true;
225
    /**
226
     * @var int the default number of seconds that query results can remain valid in cache.
227
     * Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
228
     * The value of this property will be used when [[cache()]] is called without a cache duration.
229
     * @see enableQueryCache
230
     * @see cache()
231
     */
232
    public $queryCacheDuration = 3600;
233
    /**
234
     * @var CacheInterface|string the cache object or the ID of the cache application component
235
     * that is used for query caching.
236
     * @see enableQueryCache
237
     */
238
    public $queryCache = 'cache';
239
    /**
240
     * @var string the charset used for database connection. The property is only used
241
     * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
242
     * as configured by the database.
243
     *
244
     * For Oracle Database, the charset must be specified in the [[dsn]], for example for UTF-8 by appending `;charset=UTF-8`
245
     * to the DSN string.
246
     *
247
     * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to
248
     * specify charset via [[dsn]] like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
249
     */
250
    public $charset;
251
    /**
252
     * @var bool whether to turn on prepare emulation. Defaults to false, meaning PDO
253
     * will use the native prepare support if available. For some databases (such as MySQL),
254
     * this may need to be set true so that PDO can emulate the prepare support to bypass
255
     * the buggy native prepare support.
256
     * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
257
     */
258
    public $emulatePrepare;
259
    /**
260
     * @var string the common prefix or suffix for table names. If a table name is given
261
     * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
262
     * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
263
     */
264
    public $tablePrefix = '';
265
    /**
266
     * @var array mapping between PDO driver names and [[Schema]] classes.
267
     * The keys of the array are PDO driver names while the values the corresponding
268
     * schema class name or configuration. Please refer to [[Yii::createObject()]] for
269
     * details on how to specify a configuration.
270
     *
271
     * This property is mainly used by [[getSchema()]] when fetching the database schema information.
272
     * You normally do not need to set this property unless you want to use your own
273
     * [[Schema]] class to support DBMS that is not supported by Yii.
274
     */
275
    public $schemaMap = [
276
        'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
277
        'mysqli' => 'yii\db\mysql\Schema', // MySQL
278
        'mysql' => 'yii\db\mysql\Schema', // MySQL
279
        'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
280
        'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
281
        'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
282
        'oci' => 'yii\db\oci\Schema', // Oracle driver
283
        'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
284
        'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
285
        'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
286
    ];
287
    /**
288
     * @var string Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
289
     * @see pdo
290
     */
291
    public $pdoClass;
292
    /**
293
     * @var string the class used to create new database [[Command]] objects. If you want to extend the [[Command]] class,
294
     * you may configure this property to use your extended version of the class.
295
     * @see createCommand
296
     * @since 2.0.7
297
     */
298
    public $commandClass = 'yii\db\Command';
299
    /**
300
     * @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
301
     * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
302
     */
303
    public $enableSavepoint = true;
304
    /**
305
     * @var CacheInterface|string the cache object or the ID of the cache application component that is used to store
306
     * the health status of the DB servers specified in [[masters]] and [[slaves]].
307
     * This is used only when read/write splitting is enabled or [[masters]] is not empty.
308
     */
309
    public $serverStatusCache = 'cache';
310
    /**
311
     * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
312
     * This is used together with [[serverStatusCache]].
313
     */
314
    public $serverRetryInterval = 600;
315
    /**
316
     * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
317
     * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
318
     */
319
    public $enableSlaves = true;
320
    /**
321
     * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
322
     * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
323
     * for performing read queries only.
324
     * @see enableSlaves
325
     * @see slaveConfig
326
     */
327
    public $slaves = [];
328
    /**
329
     * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
330
     * For example,
331
     *
332
     * ```php
333
     * [
334
     *     'username' => 'slave',
335
     *     'password' => 'slave',
336
     *     'attributes' => [
337
     *         // use a smaller connection timeout
338
     *         PDO::ATTR_TIMEOUT => 10,
339
     *     ],
340
     * ]
341
     * ```
342
     */
343
    public $slaveConfig = [];
344
    /**
345
     * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
346
     * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
347
     * which will be used by this object.
348
     * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
349
     * be ignored.
350
     * @see masterConfig
351
     * @see shuffleMasters
352
     */
353
    public $masters = [];
354
    /**
355
     * @var array the configuration that should be merged with every master configuration listed in [[masters]].
356
     * For example,
357
     *
358
     * ```php
359
     * [
360
     *     'username' => 'master',
361
     *     'password' => 'master',
362
     *     'attributes' => [
363
     *         // use a smaller connection timeout
364
     *         PDO::ATTR_TIMEOUT => 10,
365
     *     ],
366
     * ]
367
     * ```
368
     */
369
    public $masterConfig = [];
370
    /**
371
     * @var bool whether to shuffle [[masters]] before getting one.
372
     * @since 2.0.11
373
     * @see masters
374
     */
375
    public $shuffleMasters = true;
376
    /**
377
     * @var bool whether to enable logging of database queries. Defaults to true.
378
     * You may want to disable this option in a production environment to gain performance
379
     * if you do not need the information being logged.
380
     * @since 2.0.12
381
     * @see enableProfiling
382
     */
383
    public $enableLogging = true;
384
    /**
385
     * @var bool whether to enable profiling of database queries. Defaults to true.
386
     * You may want to disable this option in a production environment to gain performance
387
     * if you do not need the information being logged.
388
     * @since 2.0.12
389
     * @see enableLogging
390
     */
391
    public $enableProfiling = true;
392
393
    /**
394
     * @var Transaction the currently active transaction
395
     */
396
    private $_transaction;
397
    /**
398
     * @var Schema the database schema
399
     */
400
    private $_schema;
401
    /**
402
     * @var string driver name
403
     */
404
    private $_driverName;
405
    /**
406
     * @var Connection|false the currently active master connection
407
     */
408
    private $_master = false;
409
    /**
410
     * @var Connection|false the currently active slave connection
411
     */
412
    private $_slave = false;
413
    /**
414
     * @var array query cache parameters for the [[cache()]] calls
415
     */
416
    private $_queryCacheInfo = [];
417
418
419
    /**
420
     * Returns a value indicating whether the DB connection is established.
421
     * @return bool whether the DB connection is established
422
     */
423 204
    public function getIsActive()
424
    {
425 204
        return $this->pdo !== null;
426
    }
427
428
    /**
429
     * Uses query cache for the queries performed with the callable.
430
     * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
431
     * queries performed within the callable will be cached and their results will be fetched from cache if available.
432
     * For example,
433
     *
434
     * ```php
435
     * // The customer will be fetched from cache if available.
436
     * // If not, the query will be made against DB and cached for use next time.
437
     * $customer = $db->cache(function (Connection $db) {
438
     *     return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
439
     * });
440
     * ```
441
     *
442
     * Note that query cache is only meaningful for queries that return results. For queries performed with
443
     * [[Command::execute()]], query cache will not be used.
444
     *
445
     * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
446
     * The signature of the callable is `function (Connection $db)`.
447
     * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
448
     * not set, the value of [[queryCacheDuration]] will be used instead.
449
     * Use 0 to indicate that the cached data will never expire.
450
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
451
     * @return mixed the return result of the callable
452
     * @throws \Exception|\Throwable if there is any exception during query
453
     * @see enableQueryCache
454
     * @see queryCache
455
     * @see noCache()
456
     */
457 3
    public function cache(callable $callable, $duration = null, $dependency = null)
458
    {
459 3
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
460
        try {
461 3
            $result = call_user_func($callable, $this);
462 3
            array_pop($this->_queryCacheInfo);
463 3
            return $result;
464
        } catch (\Exception $e) {
465
            array_pop($this->_queryCacheInfo);
466
            throw $e;
467
        } catch (\Throwable $e) {
468
            array_pop($this->_queryCacheInfo);
469
            throw $e;
470
        }
471
    }
472
473
    /**
474
     * Disables query cache temporarily.
475
     * Queries performed within the callable will not use query cache at all. For example,
476
     *
477
     * ```php
478
     * $db->cache(function (Connection $db) {
479
     *
480
     *     // ... queries that use query cache ...
481
     *
482
     *     return $db->noCache(function (Connection $db) {
483
     *         // this query will not use query cache
484
     *         return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
485
     *     });
486
     * });
487
     * ```
488
     *
489
     * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
490
     * The signature of the callable is `function (Connection $db)`.
491
     * @return mixed the return result of the callable
492
     * @throws \Exception|\Throwable if there is any exception during query
493
     * @see enableQueryCache
494
     * @see queryCache
495
     * @see cache()
496
     */
497 19
    public function noCache(callable $callable)
498
    {
499 19
        $this->_queryCacheInfo[] = false;
500
        try {
501 19
            $result = call_user_func($callable, $this);
502 19
            array_pop($this->_queryCacheInfo);
503 19
            return $result;
504 3
        } catch (\Exception $e) {
505 3
            array_pop($this->_queryCacheInfo);
506 3
            throw $e;
507
        } catch (\Throwable $e) {
508
            array_pop($this->_queryCacheInfo);
509
            throw $e;
510
        }
511
    }
512
513
    /**
514
     * Returns the current query cache information.
515
     * This method is used internally by [[Command]].
516
     * @param int $duration the preferred caching duration. If null, it will be ignored.
517
     * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
518
     * @return array the current query cache information, or null if query cache is not enabled.
519
     * @internal
520
     */
521 933
    public function getQueryCacheInfo($duration, $dependency)
522
    {
523 933
        if (!$this->enableQueryCache) {
524 23
            return null;
525
        }
526
527 932
        $info = end($this->_queryCacheInfo);
528 932
        if (is_array($info)) {
529 3
            if ($duration === null) {
530 3
                $duration = $info[0];
531
            }
532 3
            if ($dependency === null) {
533 3
                $dependency = $info[1];
534
            }
535
        }
536
537 932
        if ($duration === 0 || $duration > 0) {
538 3
            if (is_string($this->queryCache) && Yii::$app) {
539
                $cache = Yii::$app->get($this->queryCache, false);
540
            } else {
541 3
                $cache = $this->queryCache;
542
            }
543 3
            if ($cache instanceof CacheInterface) {
544 3
                return [$cache, $duration, $dependency];
545
            }
546
        }
547
548 932
        return null;
549
    }
550
551
    /**
552
     * Establishes a DB connection.
553
     * It does nothing if a DB connection has already been established.
554
     * @throws Exception if connection fails
555
     */
556 1213
    public function open()
557
    {
558 1213
        if ($this->pdo !== null) {
559 1004
            return;
560
        }
561
562 1182
        if (!empty($this->masters)) {
563 1
            $db = $this->getMaster();
564 1
            if ($db !== null) {
565 1
                $this->pdo = $db->pdo;
566 1
                return;
567
            }
568
569
            throw new InvalidConfigException('None of the master DB servers is available.');
570
        }
571
572 1182
        if (empty($this->dsn)) {
573
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
574
        }
575 1182
        $token = 'Opening DB connection: ' . $this->dsn;
576
        try {
577 1182
            Yii::info($token, __METHOD__);
578 1182
            Yii::beginProfile($token, __METHOD__);
579 1182
            $this->pdo = $this->createPdoInstance();
580 1182
            $this->initConnection();
581 1182
            Yii::endProfile($token, __METHOD__);
582 4
        } catch (\PDOException $e) {
583 4
            Yii::endProfile($token, __METHOD__);
584 4
            throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
585
        }
586 1182
    }
587
588
    /**
589
     * Closes the currently active DB connection.
590
     * It does nothing if the connection is already closed.
591
     */
592 1458
    public function close()
593
    {
594 1458
        if ($this->_master) {
595
            if ($this->pdo === $this->_master->pdo) {
596
                $this->pdo = null;
597
            }
598
599
            $this->_master->close();
600
            $this->_master = false;
601
        }
602
603 1458
        if ($this->pdo !== null) {
604 1127
            Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
605 1127
            $this->pdo = null;
606 1127
            $this->_schema = null;
607 1127
            $this->_transaction = null;
608
        }
609
610 1458
        if ($this->_slave) {
611 4
            $this->_slave->close();
612 4
            $this->_slave = false;
613
        }
614 1458
    }
615
616
    /**
617
     * Creates the PDO instance.
618
     * This method is called by [[open]] to establish a DB connection.
619
     * The default implementation will create a PHP PDO instance.
620
     * You may override this method if the default PDO needs to be adapted for certain DBMS.
621
     * @return PDO the pdo instance
622
     */
623 1182
    protected function createPdoInstance()
624
    {
625 1182
        $pdoClass = $this->pdoClass;
626 1182
        if ($pdoClass === null) {
627 1182
            $pdoClass = 'PDO';
628 1182
            if ($this->_driverName !== null) {
629 100
                $driver = $this->_driverName;
630 1084
            } elseif (($pos = strpos($this->dsn, ':')) !== false) {
631 1084
                $driver = strtolower(substr($this->dsn, 0, $pos));
632
            }
633 1182
            if (isset($driver)) {
634 1182
                if ($driver === 'mssql' || $driver === 'dblib') {
635
                    $pdoClass = 'yii\db\mssql\PDO';
636 1182
                } elseif ($driver === 'sqlsrv') {
637
                    $pdoClass = 'yii\db\mssql\SqlsrvPDO';
638
                }
639
            }
640
        }
641
642 1182
        $dsn = $this->dsn;
643 1182
        if (strncmp('sqlite:@', $dsn, 8) === 0) {
644 1
            $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
645
        }
646 1182
        return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
647
    }
648
649
    /**
650
     * Initializes the DB connection.
651
     * This method is invoked right after the DB connection is established.
652
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
653
     * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
654
     * It then triggers an [[EVENT_AFTER_OPEN]] event.
655
     */
656 1182
    protected function initConnection()
657
    {
658 1182
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
659 1182
        if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
660
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
661
        }
662 1182
        if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
663
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
664
        }
665 1182
        $this->trigger(self::EVENT_AFTER_OPEN);
666 1182
    }
667
668
    /**
669
     * Creates a command for execution.
670
     * @param string $sql the SQL statement to be executed
671
     * @param array $params the parameters to be bound to the SQL statement
672
     * @return Command the DB command
673
     */
674 996
    public function createCommand($sql = null, $params = [])
675
    {
676
        /** @var Command $command */
677 996
        $command = new $this->commandClass([
678 996
            'db' => $this,
679 996
            'sql' => $sql,
680
        ]);
681
682 996
        return $command->bindValues($params);
683
    }
684
685
    /**
686
     * Returns the currently active transaction.
687
     * @return Transaction the currently active transaction. Null if no active transaction.
688
     */
689 970
    public function getTransaction()
690
    {
691 970
        return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
692
    }
693
694
    /**
695
     * Starts a transaction.
696
     * @param string|null $isolationLevel The isolation level to use for this transaction.
697
     * See [[Transaction::begin()]] for details.
698
     * @return Transaction the transaction initiated
699
     */
700 32
    public function beginTransaction($isolationLevel = null)
701
    {
702 32
        $this->open();
703
704 32
        if (($transaction = $this->getTransaction()) === null) {
705 32
            $transaction = $this->_transaction = new Transaction(['db' => $this]);
706
        }
707 32
        $transaction->begin($isolationLevel);
708
709 32
        return $transaction;
710
    }
711
712
    /**
713
     * Executes callback provided in a transaction.
714
     *
715
     * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
716
     * @param string|null $isolationLevel The isolation level to use for this transaction.
717
     * See [[Transaction::begin()]] for details.
718
     * @throws \Exception|\Throwable if there is any exception during query. In this case the transaction will be rolled back.
719
     * @return mixed result of callback function
720
     */
721 16
    public function transaction(callable $callback, $isolationLevel = null)
722
    {
723 16
        $transaction = $this->beginTransaction($isolationLevel);
724 16
        $level = $transaction->level;
725
726
        try {
727 16
            $result = call_user_func($callback, $this);
728 12
            if ($transaction->isActive && $transaction->level === $level) {
729 12
                $transaction->commit();
730
            }
731 4
        } catch (\Exception $e) {
732 4
            $this->rollbackTransactionOnLevel($transaction, $level);
733 4
            throw $e;
734
        } catch (\Throwable $e) {
0 ignored issues
show
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...
735
            $this->rollbackTransactionOnLevel($transaction, $level);
736
            throw $e;
737
        }
738
739 12
        return $result;
740
    }
741
742
    /**
743
     * Rolls back given [[Transaction]] object if it's still active and level match.
744
     * In some cases rollback can fail, so this method is fail safe. Exception thrown
745
     * from rollback will be caught and just logged with [[\Yii::error()]].
746
     * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
747
     * @param int $level Transaction level just after [[beginTransaction()]] call.
748
     */
749 4
    private function rollbackTransactionOnLevel($transaction, $level)
750
    {
751 4
        if ($transaction->isActive && $transaction->level === $level) {
752
            // https://github.com/yiisoft/yii2/pull/13347
753
            try {
754 4
                $transaction->rollBack();
755
            } catch (\Exception $e) {
756
                \Yii::error($e, __METHOD__);
757
                // hide this exception to be able to continue throwing original exception outside
758
            }
759
        }
760 4
    }
761
762
    /**
763
     * Returns the schema information for the database opened by this connection.
764
     * @return Schema the schema information for the database opened by this connection.
765
     * @throws NotSupportedException if there is no support for the current driver type
766
     */
767 1291
    public function getSchema()
768
    {
769 1291
        if ($this->_schema !== null) {
770 1045
            return $this->_schema;
771
        }
772
773 1260
        $driver = $this->getDriverName();
774 1260
        if (isset($this->schemaMap[$driver])) {
775 1260
            $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
776 1260
            $config['db'] = $this;
777
778 1260
            return $this->_schema = Yii::createObject($config);
779
        }
780
781
        throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
782
    }
783
784
    /**
785
     * Returns the query builder for the current DB connection.
786
     * @return QueryBuilder the query builder for the current DB connection.
787
     */
788 716
    public function getQueryBuilder()
789
    {
790 716
        return $this->getSchema()->getQueryBuilder();
791
    }
792
793
    /**
794
     * Obtains the schema information for the named table.
795
     * @param string $name table name.
796
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
797
     * @return TableSchema table schema information. Null if the named table does not exist.
798
     */
799 111
    public function getTableSchema($name, $refresh = false)
800
    {
801 111
        return $this->getSchema()->getTableSchema($name, $refresh);
802
    }
803
804
    /**
805
     * Returns the ID of the last inserted row or sequence value.
806
     * @param string $sequenceName name of the sequence object (required by some DBMS)
807
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
808
     * @see http://php.net/manual/en/pdo.lastinsertid.php
809
     */
810
    public function getLastInsertID($sequenceName = '')
811
    {
812
        return $this->getSchema()->getLastInsertID($sequenceName);
813
    }
814
815
    /**
816
     * Quotes a string value for use in a query.
817
     * Note that if the parameter is not a string, it will be returned without change.
818
     * @param string $value string to be quoted
819
     * @return string the properly quoted string
820
     * @see http://php.net/manual/en/pdo.quote.php
821
     */
822 678
    public function quoteValue($value)
823
    {
824 678
        return $this->getSchema()->quoteValue($value);
825
    }
826
827
    /**
828
     * Quotes a table name for use in a query.
829
     * If the table name contains schema prefix, the prefix will also be properly quoted.
830
     * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
831
     * then this method will do nothing.
832
     * @param string $name table name
833
     * @return string the properly quoted table name
834
     */
835 822
    public function quoteTableName($name)
836
    {
837 822
        return $this->getSchema()->quoteTableName($name);
838
    }
839
840
    /**
841
     * Quotes a column name for use in a query.
842
     * If the column name contains prefix, the prefix will also be properly quoted.
843
     * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
844
     * then this method will do nothing.
845
     * @param string $name column name
846
     * @return string the properly quoted column name
847
     */
848 873
    public function quoteColumnName($name)
849
    {
850 873
        return $this->getSchema()->quoteColumnName($name);
851
    }
852
853
    /**
854
     * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
855
     * Tokens enclosed within double curly brackets are treated as table names, while
856
     * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
857
     * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
858
     * with [[tablePrefix]].
859
     * @param string $sql the SQL to be quoted
860
     * @return string the quoted SQL
861
     */
862 1039
    public function quoteSql($sql)
863
    {
864 1039
        return preg_replace_callback(
865 1039
            '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
866 1039
            function ($matches) {
867 447
                if (isset($matches[3])) {
868 375
                    return $this->quoteColumnName($matches[3]);
869
                }
870
871 406
                return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
872 1039
            },
873 1039
            $sql
874
        );
875
    }
876
877
    /**
878
     * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
879
     * by an end user.
880
     * @return string name of the DB driver
881
     */
882 1270
    public function getDriverName()
883
    {
884 1270
        if ($this->_driverName === null) {
885 1249
            if (($pos = strpos($this->dsn, ':')) !== false) {
886 1249
                $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
887
            } else {
888
                $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
889
            }
890
        }
891 1270
        return $this->_driverName;
892
    }
893
894
    /**
895
     * Changes the current driver name.
896
     * @param string $driverName name of the DB driver
897
     */
898
    public function setDriverName($driverName)
899
    {
900
        $this->_driverName = strtolower($driverName);
901
    }
902
903
    /**
904
     * Returns the PDO instance for the currently active slave connection.
905
     * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
906
     * will be returned by this method.
907
     * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
908
     * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
909
     * is available and `$fallbackToMaster` is false.
910
     */
911 984
    public function getSlavePdo($fallbackToMaster = true)
912
    {
913 984
        $db = $this->getSlave(false);
914 984
        if ($db === null) {
915 980
            return $fallbackToMaster ? $this->getMasterPdo() : null;
916
        }
917
918 5
        return $db->pdo;
919
    }
920
921
    /**
922
     * Returns the PDO instance for the currently active master connection.
923
     * This method will open the master DB connection and then return [[pdo]].
924
     * @return PDO the PDO instance for the currently active master connection.
925
     */
926 1011
    public function getMasterPdo()
927
    {
928 1011
        $this->open();
929 1011
        return $this->pdo;
930
    }
931
932
    /**
933
     * Returns the currently active slave connection.
934
     * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
935
     * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
936
     * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
937
     * `$fallbackToMaster` is false.
938
     */
939 986
    public function getSlave($fallbackToMaster = true)
940
    {
941 986
        if (!$this->enableSlaves) {
942 66
            return $fallbackToMaster ? $this : null;
943
        }
944
945 938
        if ($this->_slave === false) {
946 938
            $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
947
        }
948
949 938
        return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
950
    }
951
952
    /**
953
     * Returns the currently active master connection.
954
     * If this method is called for the first time, it will try to open a master connection.
955
     * @return Connection the currently active master connection. `null` is returned if there is no master available.
956
     * @since 2.0.11
957
     */
958 3
    public function getMaster()
959
    {
960 3
        if ($this->_master === false) {
961 3
            $this->_master = ($this->shuffleMasters)
962 2
                ? $this->openFromPool($this->masters, $this->masterConfig)
963 1
                : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
964
        }
965
966 3
        return $this->_master;
967
    }
968
969
    /**
970
     * Executes the provided callback by using the master connection.
971
     *
972
     * This method is provided so that you can temporarily force using the master connection to perform
973
     * DB operations even if they are read queries. For example,
974
     *
975
     * ```php
976
     * $result = $db->useMaster(function ($db) {
977
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
978
     * });
979
     * ```
980
     *
981
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
982
     * `function (Connection $db)`. Its return value will be returned by this method.
983
     * @return mixed the return value of the callback
984
     * @throws \Exception|\Throwable if there is any exception thrown from the callback
985
     */
986 7
    public function useMaster(callable $callback)
987
    {
988 7
        if ($this->enableSlaves) {
989 7
            $this->enableSlaves = false;
990
            try {
991 7
                $result = call_user_func($callback, $this);
992 1
            } catch (\Exception $e) {
993 1
                $this->enableSlaves = true;
994 1
                throw $e;
995
            } catch (\Throwable $e) {
996
                $this->enableSlaves = true;
997
                throw $e;
998
            }
999
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
1000 6
            $this->enableSlaves = true;
1001
        } else {
1002
            $result = call_user_func($callback, $this);
1003
        }
1004
1005 6
        return $result;
1006
    }
1007
1008
    /**
1009
     * Opens the connection to a server in the pool.
1010
     * This method implements the load balancing among the given list of the servers.
1011
     * Connections will be tried in random order.
1012
     * @param array $pool the list of connection configurations in the server pool
1013
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1014
     * @return Connection the opened DB connection, or `null` if no server is available
1015
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1016
     */
1017 938
    protected function openFromPool(array $pool, array $sharedConfig)
1018
    {
1019 938
        shuffle($pool);
1020 938
        return $this->openFromPoolSequentially($pool, $sharedConfig);
1021
    }
1022
1023
    /**
1024
     * Opens the connection to a server in the pool.
1025
     * This method implements the load balancing among the given list of the servers.
1026
     * Connections will be tried in sequential order.
1027
     * @param array $pool the list of connection configurations in the server pool
1028
     * @param array $sharedConfig the configuration common to those given in `$pool`.
1029
     * @return Connection the opened DB connection, or `null` if no server is available
1030
     * @throws InvalidConfigException if a configuration does not specify "dsn"
1031
     * @since 2.0.11
1032
     */
1033 938
    protected function openFromPoolSequentially(array $pool, array $sharedConfig)
1034
    {
1035 938
        if (empty($pool)) {
1036 932
            return null;
1037
        }
1038
1039 7
        if (!isset($sharedConfig['class'])) {
1040 7
            $sharedConfig['class'] = get_class($this);
1041
        }
1042
1043 7
        $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
1044
1045 7
        foreach ($pool as $config) {
1046 7
            $config = array_merge($sharedConfig, $config);
1047 7
            if (empty($config['dsn'])) {
1048
                throw new InvalidConfigException('The "dsn" option must be specified.');
1049
            }
1050
1051 7
            $key = [__METHOD__, $config['dsn']];
1052 7
            if ($cache instanceof CacheInterface && $cache->get($key)) {
1053
                // should not try this dead server now
1054
                continue;
1055
            }
1056
1057
            /* @var $db Connection */
1058 7
            $db = Yii::createObject($config);
1059
1060
            try {
1061 7
                $db->open();
1062 7
                return $db;
1063
            } catch (\Exception $e) {
1064
                Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
1065
                if ($cache instanceof CacheInterface) {
1066
                    // mark this server as dead and only retry it after the specified interval
1067
                    $cache->set($key, 1, $this->serverRetryInterval);
1068
                }
1069
            }
1070
        }
1071
1072
        return null;
1073
    }
1074
1075
    /**
1076
     * Close the connection before serializing.
1077
     * @return array
1078
     */
1079 15
    public function __sleep()
1080
    {
1081 15
        $this->close();
1082 15
        return array_keys((array) $this);
1083
    }
1084
1085
    /**
1086
     * Reset the connection after cloning.
1087
     */
1088 7
    public function __clone()
1089
    {
1090 7
        parent::__clone();
1091
1092 7
        $this->_master = false;
1093 7
        $this->_slave = false;
1094 7
        $this->_schema = null;
1095 7
        $this->_transaction = null;
1096 7
        if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
1097
            // reset PDO connection, unless its sqlite in-memory, which can only have one connection
1098 6
            $this->pdo = null;
1099
        }
1100 7
    }
1101
}
1102