Connection.php 39 KB

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