Connection.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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://www.php.net/manual/en/ref.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://www.php.net/manual/en/ref.pdo.php).
  20. *
  21. * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
  22. * call [[open()]] to be true.
  23. *
  24. * The following example shows how to create a Connection instance and establish
  25. * the DB connection:
  26. *
  27. * ~~~
  28. * $connection = new \yii\db\Connection([
  29. * 'dsn' => $dsn,
  30. * 'username' => $username,
  31. * 'password' => $password,
  32. * ]);
  33. * $connection->open();
  34. * ~~~
  35. *
  36. * After the DB connection is established, one can execute SQL statements like the following:
  37. *
  38. * ~~~
  39. * $command = $connection->createCommand('SELECT * FROM tbl_post');
  40. * $posts = $command->queryAll();
  41. * $command = $connection->createCommand('UPDATE tbl_post SET status=1');
  42. * $command->execute();
  43. * ~~~
  44. *
  45. * One can also do prepared SQL execution and bind parameters to the prepared SQL.
  46. * When the parameters are coming from user input, you should use this approach
  47. * to prevent SQL injection attacks. The following is an example:
  48. *
  49. * ~~~
  50. * $command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id');
  51. * $command->bindValue(':id', $_GET['id']);
  52. * $post = $command->query();
  53. * ~~~
  54. *
  55. * For more information about how to perform various DB queries, please refer to [[Command]].
  56. *
  57. * If the underlying DBMS supports transactions, you can perform transactional SQL queries
  58. * like the following:
  59. *
  60. * ~~~
  61. * $transaction = $connection->beginTransaction();
  62. * try {
  63. * $connection->createCommand($sql1)->execute();
  64. * $connection->createCommand($sql2)->execute();
  65. * // ... executing other SQL statements ...
  66. * $transaction->commit();
  67. * } catch(Exception $e) {
  68. * $transaction->rollback();
  69. * }
  70. * ~~~
  71. *
  72. * Connection is often used as an application component and configured in the application
  73. * configuration like the following:
  74. *
  75. * ~~~
  76. * [
  77. * 'components' => [
  78. * 'db' => [
  79. * 'class' => '\yii\db\Connection',
  80. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  81. * 'username' => 'root',
  82. * 'password' => '',
  83. * 'charset' => 'utf8',
  84. * ],
  85. * ],
  86. * ]
  87. * ~~~
  88. *
  89. * @property string $driverName Name of the DB driver. This property is read-only.
  90. * @property boolean $isActive Whether the DB connection is established. This property is read-only.
  91. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
  92. * sequence object. This property is read-only.
  93. * @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is
  94. * read-only.
  95. * @property Schema $schema The schema information for the database opened by this connection. This property
  96. * is read-only.
  97. * @property Transaction $transaction The currently active transaction. Null if no active transaction. This
  98. * property is read-only.
  99. *
  100. * @author Qiang Xue <[email protected]>
  101. * @since 2.0
  102. */
  103. class Connection extends Component
  104. {
  105. /**
  106. * @event Event an event that is triggered after a DB connection is established
  107. */
  108. const EVENT_AFTER_OPEN = 'afterOpen';
  109. /**
  110. * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
  111. * Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) on
  112. * the format of the DSN string.
  113. * @see charset
  114. */
  115. public $dsn;
  116. /**
  117. * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
  118. */
  119. public $username;
  120. /**
  121. * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
  122. */
  123. public $password;
  124. /**
  125. * @var array PDO attributes (name => value) that should be set when calling [[open()]]
  126. * to establish a DB connection. Please refer to the
  127. * [PHP manual](http://www.php.net/manual/en/function.PDO-setAttribute.php) for
  128. * details about available attributes.
  129. */
  130. public $attributes;
  131. /**
  132. * @var PDO the PHP PDO instance associated with this DB connection.
  133. * This property is mainly managed by [[open()]] and [[close()]] methods.
  134. * When a DB connection is active, this property will represent a PDO instance;
  135. * otherwise, it will be null.
  136. */
  137. public $pdo;
  138. /**
  139. * @var boolean whether to enable schema caching.
  140. * Note that in order to enable truly schema caching, a valid cache component as specified
  141. * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
  142. * @see schemaCacheDuration
  143. * @see schemaCacheExclude
  144. * @see schemaCache
  145. */
  146. public $enableSchemaCache = false;
  147. /**
  148. * @var integer number of seconds that table metadata can remain valid in cache.
  149. * Use 0 to indicate that the cached data will never expire.
  150. * @see enableSchemaCache
  151. */
  152. public $schemaCacheDuration = 3600;
  153. /**
  154. * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
  155. * The table names may contain schema prefix, if any. Do not quote the table names.
  156. * @see enableSchemaCache
  157. */
  158. public $schemaCacheExclude = [];
  159. /**
  160. * @var Cache|string the cache object or the ID of the cache application component that
  161. * is used to cache the table metadata.
  162. * @see enableSchemaCache
  163. */
  164. public $schemaCache = 'cache';
  165. /**
  166. * @var boolean whether to enable query caching.
  167. * Note that in order to enable query caching, a valid cache component as specified
  168. * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
  169. *
  170. * Methods [[beginCache()]] and [[endCache()]] can be used as shortcuts to turn on
  171. * and off query caching on the fly.
  172. * @see queryCacheDuration
  173. * @see queryCache
  174. * @see queryCacheDependency
  175. * @see beginCache()
  176. * @see endCache()
  177. */
  178. public $enableQueryCache = false;
  179. /**
  180. * @var integer number of seconds that query results can remain valid in cache.
  181. * Defaults to 3600, meaning 3600 seconds, or one hour.
  182. * Use 0 to indicate that the cached data will never expire.
  183. * @see enableQueryCache
  184. */
  185. public $queryCacheDuration = 3600;
  186. /**
  187. * @var \yii\caching\Dependency the dependency that will be used when saving query results into cache.
  188. * Defaults to null, meaning no dependency.
  189. * @see enableQueryCache
  190. */
  191. public $queryCacheDependency;
  192. /**
  193. * @var Cache|string the cache object or the ID of the cache application component
  194. * that is used for query caching.
  195. * @see enableQueryCache
  196. */
  197. public $queryCache = 'cache';
  198. /**
  199. * @var string the charset used for database connection. The property is only used
  200. * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
  201. * as specified by the database.
  202. *
  203. * Note that if you're using GBK or BIG5 then it's highly recommended to
  204. * specify charset via DSN like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
  205. */
  206. public $charset;
  207. /**
  208. * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
  209. * will use the native prepare support if available. For some databases (such as MySQL),
  210. * this may need to be set true so that PDO can emulate the prepare support to bypass
  211. * the buggy native prepare support.
  212. * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
  213. */
  214. public $emulatePrepare;
  215. /**
  216. * @var string the common prefix or suffix for table names. If a table name is given
  217. * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
  218. * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
  219. */
  220. public $tablePrefix = 'tbl_';
  221. /**
  222. * @var array mapping between PDO driver names and [[Schema]] classes.
  223. * The keys of the array are PDO driver names while the values the corresponding
  224. * schema class name or configuration. Please refer to [[Yii::createObject()]] for
  225. * details on how to specify a configuration.
  226. *
  227. * This property is mainly used by [[getSchema()]] when fetching the database schema information.
  228. * You normally do not need to set this property unless you want to use your own
  229. * [[Schema]] class to support DBMS that is not supported by Yii.
  230. */
  231. public $schemaMap = [
  232. 'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
  233. 'mysqli' => 'yii\db\mysql\Schema', // MySQL
  234. 'mysql' => 'yii\db\mysql\Schema', // MySQL
  235. 'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
  236. 'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
  237. 'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
  238. 'oci' => 'yii\db\oci\Schema', // Oracle driver
  239. 'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
  240. 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
  241. 'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
  242. ];
  243. /**
  244. * @var string Custom PDO wrapper class. If not set, it will use "PDO" or "yii\db\mssql\PDO" when MSSQL is used.
  245. */
  246. public $pdoClass;
  247. /**
  248. * @var Transaction the currently active transaction
  249. */
  250. private $_transaction;
  251. /**
  252. * @var Schema the database schema
  253. */
  254. private $_schema;
  255. /**
  256. * Returns a value indicating whether the DB connection is established.
  257. * @return boolean whether the DB connection is established
  258. */
  259. public function getIsActive()
  260. {
  261. return $this->pdo !== null;
  262. }
  263. /**
  264. * Turns on query caching.
  265. * This method is provided as a shortcut to setting two properties that are related
  266. * with query caching: [[queryCacheDuration]] and [[queryCacheDependency]].
  267. * @param integer $duration the number of seconds that query results may remain valid in cache.
  268. * If not set, it will use the value of [[queryCacheDuration]]. See [[queryCacheDuration]] for more details.
  269. * @param \yii\caching\Dependency $dependency the dependency for the cached query result.
  270. * See [[queryCacheDependency]] for more details.
  271. */
  272. public function beginCache($duration = null, $dependency = null)
  273. {
  274. $this->enableQueryCache = true;
  275. if ($duration !== null) {
  276. $this->queryCacheDuration = $duration;
  277. }
  278. $this->queryCacheDependency = $dependency;
  279. }
  280. /**
  281. * Turns off query caching.
  282. */
  283. public function endCache()
  284. {
  285. $this->enableQueryCache = false;
  286. }
  287. /**
  288. * Establishes a DB connection.
  289. * It does nothing if a DB connection has already been established.
  290. * @throws Exception if connection fails
  291. */
  292. public function open()
  293. {
  294. if ($this->pdo === null) {
  295. if (empty($this->dsn)) {
  296. throw new InvalidConfigException('Connection::dsn cannot be empty.');
  297. }
  298. $token = 'Opening DB connection: ' . $this->dsn;
  299. try {
  300. Yii::trace($token, __METHOD__);
  301. Yii::beginProfile($token, __METHOD__);
  302. $this->pdo = $this->createPdoInstance();
  303. $this->initConnection();
  304. Yii::endProfile($token, __METHOD__);
  305. } catch (\PDOException $e) {
  306. Yii::endProfile($token, __METHOD__);
  307. throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
  308. }
  309. }
  310. }
  311. /**
  312. * Closes the currently active DB connection.
  313. * It does nothing if the connection is already closed.
  314. */
  315. public function close()
  316. {
  317. if ($this->pdo !== null) {
  318. Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
  319. $this->pdo = null;
  320. $this->_schema = null;
  321. $this->_transaction = null;
  322. }
  323. }
  324. /**
  325. * Creates the PDO instance.
  326. * This method is called by [[open]] to establish a DB connection.
  327. * The default implementation will create a PHP PDO instance.
  328. * You may override this method if the default PDO needs to be adapted for certain DBMS.
  329. * @return PDO the pdo instance
  330. */
  331. protected function createPdoInstance()
  332. {
  333. $pdoClass = $this->pdoClass;
  334. if ($pdoClass === null) {
  335. $pdoClass = 'PDO';
  336. if (($pos = strpos($this->dsn, ':')) !== false) {
  337. $driver = strtolower(substr($this->dsn, 0, $pos));
  338. if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') {
  339. $pdoClass = 'yii\db\mssql\PDO';
  340. }
  341. }
  342. }
  343. return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes);
  344. }
  345. /**
  346. * Initializes the DB connection.
  347. * This method is invoked right after the DB connection is established.
  348. * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
  349. * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
  350. * It then triggers an [[EVENT_AFTER_OPEN]] event.
  351. */
  352. protected function initConnection()
  353. {
  354. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  355. if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
  356. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
  357. }
  358. if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'])) {
  359. $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
  360. }
  361. $this->trigger(self::EVENT_AFTER_OPEN);
  362. }
  363. /**
  364. * Creates a command for execution.
  365. * @param string $sql the SQL statement to be executed
  366. * @param array $params the parameters to be bound to the SQL statement
  367. * @return Command the DB command
  368. */
  369. public function createCommand($sql = null, $params = [])
  370. {
  371. $this->open();
  372. $command = new Command([
  373. 'db' => $this,
  374. 'sql' => $sql,
  375. ]);
  376. return $command->bindValues($params);
  377. }
  378. /**
  379. * Returns the currently active transaction.
  380. * @return Transaction the currently active transaction. Null if no active transaction.
  381. */
  382. public function getTransaction()
  383. {
  384. return $this->_transaction && $this->_transaction->isActive ? $this->_transaction : null;
  385. }
  386. /**
  387. * Starts a transaction.
  388. * @return Transaction the transaction initiated
  389. */
  390. public function beginTransaction()
  391. {
  392. $this->open();
  393. $this->_transaction = new Transaction(['db' => $this]);
  394. $this->_transaction->begin();
  395. return $this->_transaction;
  396. }
  397. /**
  398. * Returns the schema information for the database opened by this connection.
  399. * @return Schema the schema information for the database opened by this connection.
  400. * @throws NotSupportedException if there is no support for the current driver type
  401. */
  402. public function getSchema()
  403. {
  404. if ($this->_schema !== null) {
  405. return $this->_schema;
  406. } else {
  407. $driver = $this->getDriverName();
  408. if (isset($this->schemaMap[$driver])) {
  409. $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
  410. $config['db'] = $this;
  411. return $this->_schema = Yii::createObject($config);
  412. } else {
  413. throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
  414. }
  415. }
  416. }
  417. /**
  418. * Returns the query builder for the current DB connection.
  419. * @return QueryBuilder the query builder for the current DB connection.
  420. */
  421. public function getQueryBuilder()
  422. {
  423. return $this->getSchema()->getQueryBuilder();
  424. }
  425. /**
  426. * Obtains the schema information for the named table.
  427. * @param string $name table name.
  428. * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
  429. * @return TableSchema table schema information. Null if the named table does not exist.
  430. */
  431. public function getTableSchema($name, $refresh = false)
  432. {
  433. return $this->getSchema()->getTableSchema($name, $refresh);
  434. }
  435. /**
  436. * Returns the ID of the last inserted row or sequence value.
  437. * @param string $sequenceName name of the sequence object (required by some DBMS)
  438. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  439. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
  440. */
  441. public function getLastInsertID($sequenceName = '')
  442. {
  443. return $this->getSchema()->getLastInsertID($sequenceName);
  444. }
  445. /**
  446. * Quotes a string value for use in a query.
  447. * Note that if the parameter is not a string, it will be returned without change.
  448. * @param string $str string to be quoted
  449. * @return string the properly quoted string
  450. * @see http://www.php.net/manual/en/function.PDO-quote.php
  451. */
  452. public function quoteValue($str)
  453. {
  454. return $this->getSchema()->quoteValue($str);
  455. }
  456. /**
  457. * Quotes a table name for use in a query.
  458. * If the table name contains schema prefix, the prefix will also be properly quoted.
  459. * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
  460. * then this method will do nothing.
  461. * @param string $name table name
  462. * @return string the properly quoted table name
  463. */
  464. public function quoteTableName($name)
  465. {
  466. return $this->getSchema()->quoteTableName($name);
  467. }
  468. /**
  469. * Quotes a column name for use in a query.
  470. * If the column name contains prefix, the prefix will also be properly quoted.
  471. * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
  472. * then this method will do nothing.
  473. * @param string $name column name
  474. * @return string the properly quoted column name
  475. */
  476. public function quoteColumnName($name)
  477. {
  478. return $this->getSchema()->quoteColumnName($name);
  479. }
  480. /**
  481. * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
  482. * Tokens enclosed within double curly brackets are treated as table names, while
  483. * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
  484. * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
  485. * with [[tablePrefix]].
  486. * @param string $sql the SQL to be quoted
  487. * @return string the quoted SQL
  488. */
  489. public function quoteSql($sql)
  490. {
  491. return preg_replace_callback('/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
  492. function ($matches) {
  493. if (isset($matches[3])) {
  494. return $this->quoteColumnName($matches[3]);
  495. } else {
  496. return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
  497. }
  498. }, $sql);
  499. }
  500. /**
  501. * Returns the name of the DB driver for the current [[dsn]].
  502. * @return string name of the DB driver
  503. */
  504. public function getDriverName()
  505. {
  506. if (($pos = strpos($this->dsn, ':')) !== false) {
  507. return strtolower(substr($this->dsn, 0, $pos));
  508. } else {
  509. $this->open();
  510. return strtolower($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  511. }
  512. }
  513. }