您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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