Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

937 lines
35KB

  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](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]](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 be true.
  28. *
  29. * The following example shows how to create a Connection instance and establish
  30. * the DB connection:
  31. *
  32. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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. * ~~~
  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 boolean $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 PDO $masterPdo The PDO instance for the currently active master connection. This property is
  115. * read-only.
  116. * @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is
  117. * read-only.
  118. * @property Schema $schema The schema information for the database opened by this connection. This property
  119. * is read-only.
  120. * @property Connection $slave The currently active slave connection. Null is returned if there is slave
  121. * available and `$fallbackToMaster` is false. This property is read-only.
  122. * @property PDO $slavePdo The PDO instance for the currently active slave connection. Null is returned if no
  123. * slave connection is available and `$fallbackToMaster` is false. This property is read-only.
  124. * @property Transaction $transaction The currently active transaction. Null if no active transaction. This
  125. * property is read-only.
  126. *
  127. * @author Qiang Xue <qiang.xue@gmail.com>
  128. * @since 2.0
  129. */
  130. class Connection extends Component
  131. {
  132. /**
  133. * @event Event an event that is triggered after a DB connection is established
  134. */
  135. const EVENT_AFTER_OPEN = 'afterOpen';
  136. /**
  137. * @event Event an event that is triggered right before a top-level transaction is started
  138. */
  139. const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
  140. /**
  141. * @event Event an event that is triggered right after a top-level transaction is committed
  142. */
  143. const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
  144. /**
  145. * @event Event an event that is triggered right after a top-level transaction is rolled back
  146. */
  147. const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
  148. /**
  149. * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
  150. * Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) on
  151. * the format of the DSN string.
  152. * @see charset
  153. */
  154. public $dsn;
  155. /**
  156. * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
  157. */
  158. public $username;
  159. /**
  160. * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
  161. */
  162. public $password;
  163. /**
  164. * @var array PDO attributes (name => value) that should be set when calling [[open()]]
  165. * to establish a DB connection. Please refer to the
  166. * [PHP manual](http://www.php.net/manual/en/function.PDO-setAttribute.php) for
  167. * details about available attributes.
  168. */
  169. public $attributes;
  170. /**
  171. * @var PDO the PHP PDO instance associated with this DB connection.
  172. * This property is mainly managed by [[open()]] and [[close()]] methods.
  173. * When a DB connection is active, this property will represent a PDO instance;
  174. * otherwise, it will be null.
  175. */
  176. public $pdo;
  177. /**
  178. * @var boolean whether to enable schema caching.
  179. * Note that in order to enable truly schema caching, a valid cache component as specified
  180. * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
  181. * @see schemaCacheDuration
  182. * @see schemaCacheExclude
  183. * @see schemaCache
  184. */
  185. public $enableSchemaCache = false;
  186. /**
  187. * @var integer number of seconds that table metadata can remain valid in cache.
  188. * Use 0 to indicate that the cached data will never expire.
  189. * @see enableSchemaCache
  190. */
  191. public $schemaCacheDuration = 3600;
  192. /**
  193. * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
  194. * The table names may contain schema prefix, if any. Do not quote the table names.
  195. * @see enableSchemaCache
  196. */
  197. public $schemaCacheExclude = [];
  198. /**
  199. * @var Cache|string the cache object or the ID of the cache application component that
  200. * is used to cache the table metadata.
  201. * @see enableSchemaCache
  202. */
  203. public $schemaCache = 'cache';
  204. /**
  205. * @var boolean whether to enable query caching.
  206. * Note that in order to enable query caching, a valid cache component as specified
  207. * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
  208. * Also, only the results of the queries enclosed within [[cache()]] will be cached.
  209. * @see queryCache
  210. * @see cache()
  211. * @see noCache()
  212. */
  213. public $enableQueryCache = true;
  214. /**
  215. * @var integer the default number of seconds that query results can remain valid in cache.
  216. * Use 0 to indicate that the cached data will never expire.
  217. * Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
  218. * The value of this property will be used when [[cache()]] is called without a cache duration.
  219. * @see enableQueryCache
  220. * @see cache()
  221. */
  222. public $queryCacheDuration = 3600;
  223. /**
  224. * @var Cache|string the cache object or the ID of the cache application component
  225. * that is used for query caching.
  226. * @see enableQueryCache
  227. */
  228. public $queryCache = 'cache';
  229. /**
  230. * @var string the charset used for database connection. The property is only used
  231. * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
  232. * as specified by the database.
  233. *
  234. * Note that if you're using GBK or BIG5 then it's highly recommended to
  235. * specify charset via DSN like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
  236. */
  237. public $charset;
  238. /**
  239. * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
  240. * will use the native prepare support if available. For some databases (such as MySQL),
  241. * this may need to be set true so that PDO can emulate the prepare support to bypass
  242. * the buggy native prepare support.
  243. * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
  244. */
  245. public $emulatePrepare;
  246. /**
  247. * @var string the common prefix or suffix for table names. If a table name is given
  248. * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
  249. * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
  250. */
  251. public $tablePrefix = '';
  252. /**
  253. * @var array mapping between PDO driver names and [[Schema]] classes.
  254. * The keys of the array are PDO driver names while the values the corresponding
  255. * schema class name or configuration. Please refer to [[Yii::createObject()]] for
  256. * details on how to specify a configuration.
  257. *
  258. * This property is mainly used by [[getSchema()]] when fetching the database schema information.
  259. * You normally do not need to set this property unless you want to use your own
  260. * [[Schema]] class to support DBMS that is not supported by Yii.
  261. */
  262. public $schemaMap = [
  263. 'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
  264. 'mysqli' => 'yii\db\mysql\Schema', // MySQL
  265. 'mysql' => 'yii\db\mysql\Schema', // MySQL
  266. 'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
  267. 'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
  268. 'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
  269. 'oci' => 'yii\db\oci\Schema', // Oracle driver
  270. 'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
  271. 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
  272. 'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
  273. ];
  274. /**
  275. * @var string Custom PDO wrapper class. If not set, it will use "PDO" or "yii\db\mssql\PDO" when MSSQL is used.
  276. */
  277. public $pdoClass;
  278. /**
  279. * @var boolean whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
  280. * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
  281. */
  282. public $enableSavepoint = true;
  283. /**
  284. * @var Cache|string the cache object or the ID of the cache application component that is used to store
  285. * the health status of the DB servers specified in [[masters]] and [[slaves]].
  286. * This is used only when read/write splitting is enabled or [[masters]] is not empty.
  287. */
  288. public $serverStatusCache = 'cache';
  289. /**
  290. * @var integer the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
  291. * This is used together with [[serverStatusCache]].
  292. */
  293. public $serverRetryInterval = 600;
  294. /**
  295. * @var boolean whether to enable read/write splitting by using [[slaves]] to read data.
  296. * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
  297. */
  298. public $enableSlaves = true;
  299. /**
  300. * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
  301. * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
  302. * for performing read queries only.
  303. * @see enableSlaves
  304. * @see slaveConfig
  305. */
  306. public $slaves = [];
  307. /**
  308. * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
  309. * For example,
  310. *
  311. * ```php
  312. * [
  313. * 'username' => 'slave',
  314. * 'password' => 'slave',
  315. * 'attributes' => [
  316. * // use a smaller connection timeout
  317. * PDO::ATTR_TIMEOUT => 10,
  318. * ],
  319. * ]
  320. * ```
  321. */
  322. public $slaveConfig = [];
  323. /**
  324. * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
  325. * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
  326. * which will be used by this object.
  327. * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
  328. * be ignored.
  329. * @see masterConfig
  330. */
  331. public $masters = [];
  332. /**
  333. * @var array the configuration that should be merged with every master configuration listed in [[masters]].
  334. * For example,
  335. *
  336. * ```php
  337. * [
  338. * 'username' => 'master',
  339. * 'password' => 'master',
  340. * 'attributes' => [
  341. * // use a smaller connection timeout
  342. * PDO::ATTR_TIMEOUT => 10,
  343. * ],
  344. * ]
  345. * ```
  346. */
  347. public $masterConfig = [];
  348. /**
  349. * @var Transaction the currently active transaction
  350. */
  351. private $_transaction;
  352. /**
  353. * @var Schema the database schema
  354. */
  355. private $_schema;
  356. /**
  357. * @var string driver name
  358. */
  359. private $_driverName;
  360. /**
  361. * @var Connection the currently active slave connection
  362. */
  363. private $_slave = false;
  364. /**
  365. * @var array query cache parameters for the [[cache()]] calls
  366. */
  367. private $_queryCacheInfo = [];
  368. /**
  369. * Returns a value indicating whether the DB connection is established.
  370. * @return boolean whether the DB connection is established
  371. */
  372. public function getIsActive()
  373. {
  374. return $this->pdo !== null;
  375. }
  376. /**
  377. * Uses query cache for the queries performed with the callable.
  378. * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
  379. * queries performed within the callable will be cached and their results will be fetched from cache if available.
  380. * For example,
  381. *
  382. * ```php
  383. * // The customer will be fetched from cache if available.
  384. * // If not, the query will be made against DB and cached for use next time.
  385. * $customer = $db->cache(function (Connection $db) {
  386. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  387. * });
  388. * ```
  389. *
  390. * Note that query cache is only meaningful for queries that return results. For queries performed with
  391. * [[Command::execute()]], query cache will not be used.
  392. *
  393. * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
  394. * The signature of the callable is `function (Connection $db)`.
  395. * @param integer $duration the number of seconds that query results can remain valid in the cache. If this is
  396. * not set, the value of [[queryCacheDuration]] will be used instead.
  397. * Use 0 to indicate that the cached data will never expire.
  398. * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
  399. * @return mixed the return result of the callable
  400. * @throws \Exception if there is any exception during query
  401. * @see enableQueryCache
  402. * @see queryCache
  403. * @see noCache()
  404. */
  405. public function cache(callable $callable, $duration = null, $dependency = null)
  406. {
  407. $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
  408. try {
  409. $result = call_user_func($callable, $this);
  410. array_pop($this->_queryCacheInfo);
  411. return $result;
  412. } catch (\Exception $e) {
  413. array_pop($this->_queryCacheInfo);
  414. throw $e;
  415. }
  416. }
  417. /**
  418. * Disables query cache temporarily.
  419. * Queries performed within the callable will not use query cache at all. For example,
  420. *
  421. * ```php
  422. * $db->cache(function (Connection $db) {
  423. *
  424. * // ... queries that use query cache ...
  425. *
  426. * return $db->noCache(function (Connection $db) {
  427. * // this query will not use query cache
  428. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  429. * });
  430. * });
  431. * ```
  432. *
  433. * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
  434. * The signature of the callable is `function (Connection $db)`.
  435. * @return mixed the return result of the callable
  436. * @throws \Exception if there is any exception during query
  437. * @see enableQueryCache
  438. * @see queryCache
  439. * @see cache()
  440. */
  441. public function noCache(callable $callable)
  442. {
  443. $this->_queryCacheInfo[] = false;
  444. try {
  445. $result = call_user_func($callable, $this);
  446. array_pop($this->_queryCacheInfo);
  447. return $result;
  448. } catch (\Exception $e) {
  449. array_pop($this->_queryCacheInfo);
  450. throw $e;
  451. }
  452. }
  453. /**
  454. * Returns the current query cache information.
  455. * This method is used internally by [[Command]].
  456. * @param integer $duration the preferred caching duration. If null, it will be ignored.
  457. * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
  458. * @return array the current query cache information, or null if query cache is not enabled.
  459. * @internal
  460. */
  461. public function getQueryCacheInfo($duration, $dependency)
  462. {
  463. if (!$this->enableQueryCache) {
  464. return null;
  465. }
  466. $info = end($this->_queryCacheInfo);
  467. if (is_array($info)) {
  468. if ($duration === null) {
  469. $duration = $info[0];
  470. }
  471. if ($dependency === null) {
  472. $dependency = $info[1];
  473. }
  474. }
  475. if ($duration === 0 || $duration > 0) {
  476. if (is_string($this->queryCache) && Yii::$app) {
  477. $cache = Yii::$app->get($this->queryCache, false);
  478. } else {
  479. $cache = $this->queryCache;
  480. }
  481. if ($cache instanceof Cache) {
  482. return [$cache, $duration, $dependency];
  483. }
  484. }
  485. return null;
  486. }
  487. /**
  488. * Establishes a DB connection.
  489. * It does nothing if a DB connection has already been established.
  490. * @throws Exception if connection fails
  491. */
  492. public function open()
  493. {
  494. if ($this->pdo !== null) {
  495. return;
  496. }
  497. if (!empty($this->masters)) {
  498. $db = $this->openFromPool($this->masters, $this->masterConfig);
  499. if ($db !== null) {
  500. $this->pdo = $db->pdo;
  501. return;
  502. } else {
  503. throw new InvalidConfigException('None of the master DB servers is available.');
  504. }
  505. }
  506. if (empty($this->dsn)) {
  507. throw new InvalidConfigException('Connection::dsn cannot be empty.');
  508. }
  509. $token = 'Opening DB connection: ' . $this->dsn;
  510. try {
  511. Yii::info($token, __METHOD__);
  512. Yii::beginProfile($token, __METHOD__);
  513. $this->pdo = $this->createPdoInstance();
  514. $this->initConnection();
  515. Yii::endProfile($token, __METHOD__);
  516. } catch (\PDOException $e) {
  517. Yii::endProfile($token, __METHOD__);
  518. throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
  519. }
  520. }
  521. /**
  522. * Closes the currently active DB connection.
  523. * It does nothing if the connection is already closed.
  524. */
  525. public function close()
  526. {
  527. if ($this->pdo !== null) {
  528. Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
  529. $this->pdo = null;
  530. $this->_schema = null;
  531. $this->_transaction = null;
  532. }
  533. if ($this->_slave) {
  534. $this->_slave->close();
  535. $this->_slave = null;
  536. }
  537. }
  538. /**
  539. * Creates the PDO instance.
  540. * This method is called by [[open]] to establish a DB connection.
  541. * The default implementation will create a PHP PDO instance.
  542. * You may override this method if the default PDO needs to be adapted for certain DBMS.
  543. * @return PDO the pdo instance
  544. */
  545. protected function createPdoInstance()
  546. {
  547. $pdoClass = $this->pdoClass;
  548. if ($pdoClass === null) {
  549. $pdoClass = 'PDO';
  550. if ($this->_driverName !== null) {
  551. $driver = $this->_driverName;
  552. } elseif (($pos = strpos($this->dsn, ':')) !== false) {
  553. $driver = strtolower(substr($this->dsn, 0, $pos));
  554. }
  555. if (isset($driver) && ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv')) {
  556. $pdoClass = 'yii\db\mssql\PDO';
  557. }
  558. }
  559. return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes);
  560. }
  561. /**
  562. * Initializes the DB connection.
  563. * This method is invoked right after the DB connection is established.
  564. * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
  565. * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
  566. * It then triggers an [[EVENT_AFTER_OPEN]] event.
  567. */
  568. protected function initConnection()
  569. {
  570. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  571. if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
  572. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
  573. }
  574. if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'])) {
  575. $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
  576. }
  577. $this->trigger(self::EVENT_AFTER_OPEN);
  578. }
  579. /**
  580. * Creates a command for execution.
  581. * @param string $sql the SQL statement to be executed
  582. * @param array $params the parameters to be bound to the SQL statement
  583. * @return Command the DB command
  584. */
  585. public function createCommand($sql = null, $params = [])
  586. {
  587. $command = new Command([
  588. 'db' => $this,
  589. 'sql' => $sql,
  590. ]);
  591. return $command->bindValues($params);
  592. }
  593. /**
  594. * Returns the currently active transaction.
  595. * @return Transaction the currently active transaction. Null if no active transaction.
  596. */
  597. public function getTransaction()
  598. {
  599. return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
  600. }
  601. /**
  602. * Starts a transaction.
  603. * @param string|null $isolationLevel The isolation level to use for this transaction.
  604. * See [[Transaction::begin()]] for details.
  605. * @return Transaction the transaction initiated
  606. */
  607. public function beginTransaction($isolationLevel = null)
  608. {
  609. $this->open();
  610. if (($transaction = $this->getTransaction()) === null) {
  611. $transaction = $this->_transaction = new Transaction(['db' => $this]);
  612. }
  613. $transaction->begin($isolationLevel);
  614. return $transaction;
  615. }
  616. /**
  617. * Executes callback provided in a transaction.
  618. *
  619. * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
  620. * @param string|null $isolationLevel The isolation level to use for this transaction.
  621. * See [[Transaction::begin()]] for details.
  622. * @throws \Exception
  623. * @return mixed result of callback function
  624. */
  625. public function transaction(callable $callback, $isolationLevel = null)
  626. {
  627. $transaction = $this->beginTransaction($isolationLevel);
  628. try {
  629. $result = call_user_func($callback, $this);
  630. if ($transaction->isActive) {
  631. $transaction->commit();
  632. }
  633. } catch (\Exception $e) {
  634. $transaction->rollBack();
  635. throw $e;
  636. }
  637. return $result;
  638. }
  639. /**
  640. * Returns the schema information for the database opened by this connection.
  641. * @return Schema the schema information for the database opened by this connection.
  642. * @throws NotSupportedException if there is no support for the current driver type
  643. */
  644. public function getSchema()
  645. {
  646. if ($this->_schema !== null) {
  647. return $this->_schema;
  648. } else {
  649. $driver = $this->getDriverName();
  650. if (isset($this->schemaMap[$driver])) {
  651. $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
  652. $config['db'] = $this;
  653. return $this->_schema = Yii::createObject($config);
  654. } else {
  655. throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
  656. }
  657. }
  658. }
  659. /**
  660. * Returns the query builder for the current DB connection.
  661. * @return QueryBuilder the query builder for the current DB connection.
  662. */
  663. public function getQueryBuilder()
  664. {
  665. return $this->getSchema()->getQueryBuilder();
  666. }
  667. /**
  668. * Obtains the schema information for the named table.
  669. * @param string $name table name.
  670. * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
  671. * @return TableSchema table schema information. Null if the named table does not exist.
  672. */
  673. public function getTableSchema($name, $refresh = false)
  674. {
  675. return $this->getSchema()->getTableSchema($name, $refresh);
  676. }
  677. /**
  678. * Returns the ID of the last inserted row or sequence value.
  679. * @param string $sequenceName name of the sequence object (required by some DBMS)
  680. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  681. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
  682. */
  683. public function getLastInsertID($sequenceName = '')
  684. {
  685. return $this->getSchema()->getLastInsertID($sequenceName);
  686. }
  687. /**
  688. * Quotes a string value for use in a query.
  689. * Note that if the parameter is not a string, it will be returned without change.
  690. * @param string $value string to be quoted
  691. * @return string the properly quoted string
  692. * @see http://www.php.net/manual/en/function.PDO-quote.php
  693. */
  694. public function quoteValue($value)
  695. {
  696. return $this->getSchema()->quoteValue($value);
  697. }
  698. /**
  699. * Quotes a table name for use in a query.
  700. * If the table name contains schema prefix, the prefix will also be properly quoted.
  701. * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
  702. * then this method will do nothing.
  703. * @param string $name table name
  704. * @return string the properly quoted table name
  705. */
  706. public function quoteTableName($name)
  707. {
  708. return $this->getSchema()->quoteTableName($name);
  709. }
  710. /**
  711. * Quotes a column name for use in a query.
  712. * If the column name contains prefix, the prefix will also be properly quoted.
  713. * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
  714. * then this method will do nothing.
  715. * @param string $name column name
  716. * @return string the properly quoted column name
  717. */
  718. public function quoteColumnName($name)
  719. {
  720. return $this->getSchema()->quoteColumnName($name);
  721. }
  722. /**
  723. * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
  724. * Tokens enclosed within double curly brackets are treated as table names, while
  725. * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
  726. * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
  727. * with [[tablePrefix]].
  728. * @param string $sql the SQL to be quoted
  729. * @return string the quoted SQL
  730. */
  731. public function quoteSql($sql)
  732. {
  733. return preg_replace_callback(
  734. '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
  735. function ($matches) {
  736. if (isset($matches[3])) {
  737. return $this->quoteColumnName($matches[3]);
  738. } else {
  739. return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
  740. }
  741. },
  742. $sql
  743. );
  744. }
  745. /**
  746. * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
  747. * by an end user.
  748. * @return string name of the DB driver
  749. */
  750. public function getDriverName()
  751. {
  752. if ($this->_driverName === null) {
  753. if (($pos = strpos($this->dsn, ':')) !== false) {
  754. $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
  755. } else {
  756. $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
  757. }
  758. }
  759. return $this->_driverName;
  760. }
  761. /**
  762. * Changes the current driver name.
  763. * @param string $driverName name of the DB driver
  764. */
  765. public function setDriverName($driverName)
  766. {
  767. $this->_driverName = strtolower($driverName);
  768. }
  769. /**
  770. * Returns the PDO instance for the currently active slave connection.
  771. * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
  772. * will be returned by this method.
  773. * @param boolean $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
  774. * @return PDO the PDO instance for the currently active slave connection. Null is returned if no slave connection
  775. * is available and `$fallbackToMaster` is false.
  776. */
  777. public function getSlavePdo($fallbackToMaster = true)
  778. {
  779. $db = $this->getSlave(false);
  780. if ($db === null) {
  781. return $fallbackToMaster ? $this->getMasterPdo() : null;
  782. } else {
  783. return $db->pdo;
  784. }
  785. }
  786. /**
  787. * Returns the PDO instance for the currently active master connection.
  788. * This method will open the master DB connection and then return [[pdo]].
  789. * @return PDO the PDO instance for the currently active master connection.
  790. */
  791. public function getMasterPdo()
  792. {
  793. $this->open();
  794. return $this->pdo;
  795. }
  796. /**
  797. * Returns the currently active slave connection.
  798. * If this method is called the first time, it will try to open a slave connection when [[enableSlaves]] is true.
  799. * @param boolean $fallbackToMaster whether to return a master connection in case there is no slave connection available.
  800. * @return Connection the currently active slave connection. Null is returned if there is slave available and
  801. * `$fallbackToMaster` is false.
  802. */
  803. public function getSlave($fallbackToMaster = true)
  804. {
  805. if (!$this->enableSlaves) {
  806. return $fallbackToMaster ? $this : null;
  807. }
  808. if ($this->_slave === false) {
  809. $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
  810. }
  811. return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
  812. }
  813. /**
  814. * Executes the provided callback by using the master connection.
  815. *
  816. * This method is provided so that you can temporarily force using the master connection to perform
  817. * DB operations even if they are read queries. For example,
  818. *
  819. * ```php
  820. * $result = $db->useMaster(function ($db) {
  821. * return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
  822. * });
  823. * ```
  824. *
  825. * @param callable $callback a PHP callable to be executed by this method. Its signature is
  826. * `function (Connection $db)`. Its return value will be returned by this method.
  827. * @return mixed the return value of the callback
  828. */
  829. public function useMaster(callable $callback)
  830. {
  831. $enableSlave = $this->enableSlaves;
  832. $this->enableSlaves = false;
  833. $result = call_user_func($callback, $this);
  834. $this->enableSlaves = $enableSlave;
  835. return $result;
  836. }
  837. /**
  838. * Opens the connection to a server in the pool.
  839. * This method implements the load balancing among the given list of the servers.
  840. * @param array $pool the list of connection configurations in the server pool
  841. * @param array $sharedConfig the configuration common to those given in `$pool`.
  842. * @return Connection the opened DB connection, or null if no server is available
  843. * @throws InvalidConfigException if a configuration does not specify "dsn"
  844. */
  845. protected function openFromPool(array $pool, array $sharedConfig)
  846. {
  847. if (empty($pool)) {
  848. return null;
  849. }
  850. if (!isset($sharedConfig['class'])) {
  851. $sharedConfig['class'] = get_class($this);
  852. }
  853. $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
  854. shuffle($pool);
  855. foreach ($pool as $config) {
  856. $config = array_merge($sharedConfig, $config);
  857. if (empty($config['dsn'])) {
  858. throw new InvalidConfigException('The "dsn" option must be specified.');
  859. }
  860. $key = [__METHOD__, $config['dsn']];
  861. if ($cache instanceof Cache && $cache->get($key)) {
  862. // should not try this dead server now
  863. continue;
  864. }
  865. /* @var $db Connection */
  866. $db = Yii::createObject($config);
  867. try {
  868. $db->open();
  869. return $db;
  870. } catch (\Exception $e) {
  871. Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
  872. if ($cache instanceof Cache) {
  873. // mark this server as dead and only retry it after the specified interval
  874. $cache->set($key, 1, $this->serverRetryInterval);
  875. }
  876. }
  877. }
  878. return null;
  879. }
  880. }