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

975 lines
36KB

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