Connection.php 41 KB

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