Completed
Push — master ( b39e50...55dd16 )
by Alexander
40:37
created

Connection::rollbackTransactionOnLevel()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

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