PageRenderTime 104ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/yii/framework/db/CDbConnection.php

https://github.com/joshuaswarren/weatherhub
PHP | 794 lines | 457 code | 24 blank | 313 comment | 23 complexity | 7ea8c2716a24abc425287067f1e2186a MD5 | raw file
  1. <?php
  2. /**
  3. * CDbConnection class file
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CDbConnection represents a connection to a database.
  12. *
  13. * CDbConnection works together with {@link CDbCommand}, {@link CDbDataReader}
  14. * and {@link CDbTransaction} to provide data access to various DBMS
  15. * in a common set of APIs. They are a thin wrapper of the {@link http://www.php.net/manual/en/ref.pdo.php PDO}
  16. * PHP extension.
  17. *
  18. * To establish a connection, set {@link setActive active} to true after
  19. * specifying {@link connectionString}, {@link username} and {@link password}.
  20. *
  21. * The following example shows how to create a CDbConnection instance and establish
  22. * the actual connection:
  23. * <pre>
  24. * $connection=new CDbConnection($dsn,$username,$password);
  25. * $connection->active=true;
  26. * </pre>
  27. *
  28. * After the DB connection is established, one can execute an SQL statement like the following:
  29. * <pre>
  30. * $command=$connection->createCommand($sqlStatement);
  31. * $command->execute(); // a non-query SQL statement execution
  32. * // or execute an SQL query and fetch the result set
  33. * $reader=$command->query();
  34. *
  35. * // each $row is an array representing a row of data
  36. * foreach($reader as $row) ...
  37. * </pre>
  38. *
  39. * One can do prepared SQL execution and bind parameters to the prepared SQL:
  40. * <pre>
  41. * $command=$connection->createCommand($sqlStatement);
  42. * $command->bindParam($name1,$value1);
  43. * $command->bindParam($name2,$value2);
  44. * $command->execute();
  45. * </pre>
  46. *
  47. * To use transaction, do like the following:
  48. * <pre>
  49. * $transaction=$connection->beginTransaction();
  50. * try
  51. * {
  52. * $connection->createCommand($sql1)->execute();
  53. * $connection->createCommand($sql2)->execute();
  54. * //.... other SQL executions
  55. * $transaction->commit();
  56. * }
  57. * catch(Exception $e)
  58. * {
  59. * $transaction->rollBack();
  60. * }
  61. * </pre>
  62. *
  63. * CDbConnection also provides a set of methods to support setting and querying
  64. * of certain DBMS attributes, such as {@link getNullConversion nullConversion}.
  65. *
  66. * Since CDbConnection implements the interface IApplicationComponent, it can
  67. * be used as an application component and be configured in application configuration,
  68. * like the following,
  69. * <pre>
  70. * array(
  71. * 'components'=>array(
  72. * 'db'=>array(
  73. * 'class'=>'CDbConnection',
  74. * 'connectionString'=>'sqlite:path/to/dbfile',
  75. * ),
  76. * ),
  77. * )
  78. * </pre>
  79. *
  80. * @author Qiang Xue <qiang.xue@gmail.com>
  81. * @version $Id: CDbConnection.php 3255 2011-06-13 12:39:41Z alexander.makarow $
  82. * @package system.db
  83. * @since 1.0
  84. */
  85. class CDbConnection extends CApplicationComponent
  86. {
  87. /**
  88. * @var string The Data Source Name, or DSN, contains the information required to connect to the database.
  89. * @see http://www.php.net/manual/en/function.PDO-construct.php
  90. *
  91. * Note that if you're using GBK or BIG5 then it's highly recommended to
  92. * update to PHP 5.3.6+ and to specify charset via DSN like
  93. * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
  94. */
  95. public $connectionString;
  96. /**
  97. * @var string the username for establishing DB connection. Defaults to empty string.
  98. */
  99. public $username='';
  100. /**
  101. * @var string the password for establishing DB connection. Defaults to empty string.
  102. */
  103. public $password='';
  104. /**
  105. * @var integer number of seconds that table metadata can remain valid in cache.
  106. * Use 0 or negative value to indicate not caching schema.
  107. * If greater than 0 and the primary cache is enabled, the table metadata will be cached.
  108. * @see schemaCachingExclude
  109. */
  110. public $schemaCachingDuration=0;
  111. /**
  112. * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
  113. * @see schemaCachingDuration
  114. */
  115. public $schemaCachingExclude=array();
  116. /**
  117. * @var string the ID of the cache application component that is used to cache the table metadata.
  118. * Defaults to 'cache' which refers to the primary cache application component.
  119. * Set this property to false if you want to disable caching table metadata.
  120. * @since 1.0.10
  121. */
  122. public $schemaCacheID='cache';
  123. /**
  124. * @var integer number of seconds that query results can remain valid in cache.
  125. * Use 0 or negative value to indicate not caching query results (the default behavior).
  126. *
  127. * In order to enable query caching, this property must be a positive
  128. * integer and {@link queryCacheID} must point to a valid cache component ID.
  129. *
  130. * The method {@link cache()} is provided as a convenient way of setting this property
  131. * and {@link queryCachingDependency} on the fly.
  132. *
  133. * @see cache
  134. * @see queryCachingDependency
  135. * @see queryCacheID
  136. * @since 1.1.7
  137. */
  138. public $queryCachingDuration=0;
  139. /**
  140. * @var CCacheDependency the dependency that will be used when saving query results into cache.
  141. * @see queryCachingDuration
  142. * @since 1.1.7
  143. */
  144. public $queryCachingDependency;
  145. /**
  146. * @var integer the number of SQL statements that need to be cached next.
  147. * If this is 0, then even if query caching is enabled, no query will be cached.
  148. * Note that each time after executing a SQL statement (whether executed on DB server or fetched from
  149. * query cache), this property will be reduced by 1 until 0.
  150. * @since 1.1.7
  151. */
  152. public $queryCachingCount=0;
  153. /**
  154. * @var string the ID of the cache application component that is used for query caching.
  155. * Defaults to 'cache' which refers to the primary cache application component.
  156. * Set this property to false if you want to disable query caching.
  157. * @since 1.1.7
  158. */
  159. public $queryCacheID='cache';
  160. /**
  161. * @var boolean whether the database connection should be automatically established
  162. * the component is being initialized. Defaults to true. Note, this property is only
  163. * effective when the CDbConnection object is used as an application component.
  164. */
  165. public $autoConnect=true;
  166. /**
  167. * @var string the charset used for database connection. The property is only used
  168. * for MySQL and PostgreSQL databases. Defaults to null, meaning using default charset
  169. * as specified by the database.
  170. *
  171. * Note that if you're using GBK or BIG5 then it's highly recommended to
  172. * update to PHP 5.3.6+ and to specify charset via DSN like
  173. * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
  174. */
  175. public $charset;
  176. /**
  177. * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
  178. * will use the native prepare support if available. For some databases (such as MySQL),
  179. * this may need to be set true so that PDO can emulate the prepare support to bypass
  180. * the buggy native prepare support. Note, this property is only effective for PHP 5.1.3 or above.
  181. * The default value is null, which will not change the ATTR_EMULATE_PREPARES value of PDO.
  182. */
  183. public $emulatePrepare;
  184. /**
  185. * @var boolean whether to log the values that are bound to a prepare SQL statement.
  186. * Defaults to false. During development, you may consider setting this property to true
  187. * so that parameter values bound to SQL statements are logged for debugging purpose.
  188. * You should be aware that logging parameter values could be expensive and have significant
  189. * impact on the performance of your application.
  190. * @since 1.0.5
  191. */
  192. public $enableParamLogging=false;
  193. /**
  194. * @var boolean whether to enable profiling the SQL statements being executed.
  195. * Defaults to false. This should be mainly enabled and used during development
  196. * to find out the bottleneck of SQL executions.
  197. * @since 1.0.6
  198. */
  199. public $enableProfiling=false;
  200. /**
  201. * @var string the default prefix for table names. Defaults to null, meaning no table prefix.
  202. * By setting this property, any token like '{{tableName}}' in {@link CDbCommand::text} will
  203. * be replaced by 'prefixTableName', where 'prefix' refers to this property value.
  204. * @since 1.1.0
  205. */
  206. public $tablePrefix;
  207. /**
  208. * @var array list of SQL statements that should be executed right after the DB connection is established.
  209. * @since 1.1.1
  210. */
  211. public $initSQLs;
  212. /**
  213. * @var array mapping between PDO driver and schema class name.
  214. * A schema class can be specified using path alias.
  215. * @since 1.1.6
  216. */
  217. public $driverMap=array(
  218. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  219. 'mysqli'=>'CMysqlSchema', // MySQL
  220. 'mysql'=>'CMysqlSchema', // MySQL
  221. 'sqlite'=>'CSqliteSchema', // sqlite 3
  222. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  223. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  224. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  225. 'sqlsrv'=>'CMssqlSchema', // Mssql
  226. 'oci'=>'COciSchema', // Oracle driver
  227. );
  228. /**
  229. * @var string Custom PDO wrapper class.
  230. * @since 1.1.8
  231. */
  232. public $pdoClass = 'PDO';
  233. private $_attributes=array();
  234. private $_active=false;
  235. private $_pdo;
  236. private $_transaction;
  237. private $_schema;
  238. /**
  239. * Constructor.
  240. * Note, the DB connection is not established when this connection
  241. * instance is created. Set {@link setActive active} property to true
  242. * to establish the connection.
  243. * @param string $dsn The Data Source Name, or DSN, contains the information required to connect to the database.
  244. * @param string $username The user name for the DSN string.
  245. * @param string $password The password for the DSN string.
  246. * @see http://www.php.net/manual/en/function.PDO-construct.php
  247. */
  248. public function __construct($dsn='',$username='',$password='')
  249. {
  250. $this->connectionString=$dsn;
  251. $this->username=$username;
  252. $this->password=$password;
  253. }
  254. /**
  255. * Close the connection when serializing.
  256. * @return array
  257. */
  258. public function __sleep()
  259. {
  260. $this->close();
  261. return array_keys(get_object_vars($this));
  262. }
  263. /**
  264. * Returns a list of available PDO drivers.
  265. * @return array list of available PDO drivers
  266. * @see http://www.php.net/manual/en/function.PDO-getAvailableDrivers.php
  267. */
  268. public static function getAvailableDrivers()
  269. {
  270. return PDO::getAvailableDrivers();
  271. }
  272. /**
  273. * Initializes the component.
  274. * This method is required by {@link IApplicationComponent} and is invoked by application
  275. * when the CDbConnection is used as an application component.
  276. * If you override this method, make sure to call the parent implementation
  277. * so that the component can be marked as initialized.
  278. */
  279. public function init()
  280. {
  281. parent::init();
  282. if($this->autoConnect)
  283. $this->setActive(true);
  284. }
  285. /**
  286. * Returns whether the DB connection is established.
  287. * @return boolean whether the DB connection is established
  288. */
  289. public function getActive()
  290. {
  291. return $this->_active;
  292. }
  293. /**
  294. * Open or close the DB connection.
  295. * @param boolean $value whether to open or close DB connection
  296. * @throws CException if connection fails
  297. */
  298. public function setActive($value)
  299. {
  300. if($value!=$this->_active)
  301. {
  302. if($value)
  303. $this->open();
  304. else
  305. $this->close();
  306. }
  307. }
  308. /**
  309. * Sets the parameters about query caching.
  310. * This method can be used to enable or disable query caching.
  311. * By setting the $duration parameter to be 0, the query caching will be disabled.
  312. * Otherwise, query results of the new SQL statements executed next will be saved in cache
  313. * and remain valid for the specified duration.
  314. * If the same query is executed again, the result may be fetched from cache directly
  315. * without actually executing the SQL statement.
  316. * @param integer $duration the number of seconds that query results may remain valid in cache.
  317. * If this is 0, the caching will be disabled.
  318. * @param CCacheDependency $dependency the dependency that will be used when saving the query results into cache.
  319. * @param integer $queryCount number of SQL queries that need to be cached after calling this method. Defaults to 1,
  320. * meaning that the next SQL query will be cached.
  321. * @return CDbConnection the connection instance itself.
  322. * @since 1.1.7
  323. */
  324. public function cache($duration, $dependency=null, $queryCount=1)
  325. {
  326. $this->queryCachingDuration=$duration;
  327. $this->queryCachingDependency=$dependency;
  328. $this->queryCachingCount=$queryCount;
  329. return $this;
  330. }
  331. /**
  332. * Opens DB connection if it is currently not
  333. * @throws CException if connection fails
  334. */
  335. protected function open()
  336. {
  337. if($this->_pdo===null)
  338. {
  339. if(empty($this->connectionString))
  340. throw new CDbException(Yii::t('yii','CDbConnection.connectionString cannot be empty.'));
  341. try
  342. {
  343. Yii::trace('Opening DB connection','system.db.CDbConnection');
  344. $this->_pdo=$this->createPdoInstance();
  345. $this->initConnection($this->_pdo);
  346. $this->_active=true;
  347. }
  348. catch(PDOException $e)
  349. {
  350. if(YII_DEBUG)
  351. {
  352. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection: {error}',
  353. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$e->errorInfo);
  354. }
  355. else
  356. {
  357. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  358. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'),(int)$e->getCode(),$e->errorInfo);
  359. }
  360. }
  361. }
  362. }
  363. /**
  364. * Closes the currently active DB connection.
  365. * It does nothing if the connection is already closed.
  366. */
  367. protected function close()
  368. {
  369. Yii::trace('Closing DB connection','system.db.CDbConnection');
  370. $this->_pdo=null;
  371. $this->_active=false;
  372. $this->_schema=null;
  373. }
  374. /**
  375. * Creates the PDO instance.
  376. * When some functionalities are missing in the pdo driver, we may use
  377. * an adapter class to provides them.
  378. * @return PDO the pdo instance
  379. * @since 1.0.4
  380. */
  381. protected function createPdoInstance()
  382. {
  383. $pdoClass=$this->pdoClass;
  384. if(($pos=strpos($this->connectionString,':'))!==false)
  385. {
  386. $driver=strtolower(substr($this->connectionString,0,$pos));
  387. if($driver==='mssql' || $driver==='dblib' || $driver==='sqlsrv')
  388. $pdoClass='CMssqlPdoAdapter';
  389. }
  390. return new $pdoClass($this->connectionString,$this->username,
  391. $this->password,$this->_attributes);
  392. }
  393. /**
  394. * Initializes the open db connection.
  395. * This method is invoked right after the db connection is established.
  396. * The default implementation is to set the charset for MySQL and PostgreSQL database connections.
  397. * @param PDO $pdo the PDO instance
  398. */
  399. protected function initConnection($pdo)
  400. {
  401. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  402. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  403. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  404. if($this->charset!==null)
  405. {
  406. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  407. if(in_array($driver,array('pgsql','mysql','mysqli')))
  408. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  409. }
  410. if($this->initSQLs!==null)
  411. {
  412. foreach($this->initSQLs as $sql)
  413. $pdo->exec($sql);
  414. }
  415. }
  416. /**
  417. * Returns the PDO instance.
  418. * @return PDO the PDO instance, null if the connection is not established yet
  419. */
  420. public function getPdoInstance()
  421. {
  422. return $this->_pdo;
  423. }
  424. /**
  425. * Creates a command for execution.
  426. * @param mixed $query the DB query to be executed. This can be either a string representing a SQL statement,
  427. * or an array representing different fragments of a SQL statement. Please refer to {@link CDbCommand::__construct}
  428. * for more details about how to pass an array as the query. If this parameter is not given,
  429. * you will have to call query builder methods of {@link CDbCommand} to build the DB query.
  430. * @return CDbCommand the DB command
  431. */
  432. public function createCommand($query=null)
  433. {
  434. $this->setActive(true);
  435. return new CDbCommand($this,$query);
  436. }
  437. /**
  438. * Returns the currently active transaction.
  439. * @return CDbTransaction the currently active transaction. Null if no active transaction.
  440. */
  441. public function getCurrentTransaction()
  442. {
  443. if($this->_transaction!==null)
  444. {
  445. if($this->_transaction->getActive())
  446. return $this->_transaction;
  447. }
  448. return null;
  449. }
  450. /**
  451. * Starts a transaction.
  452. * @return CDbTransaction the transaction initiated
  453. */
  454. public function beginTransaction()
  455. {
  456. Yii::trace('Starting transaction','system.db.CDbConnection');
  457. $this->setActive(true);
  458. $this->_pdo->beginTransaction();
  459. return $this->_transaction=new CDbTransaction($this);
  460. }
  461. /**
  462. * Returns the database schema for the current connection
  463. * @return CDbSchema the database schema for the current connection
  464. */
  465. public function getSchema()
  466. {
  467. if($this->_schema!==null)
  468. return $this->_schema;
  469. else
  470. {
  471. $driver=$this->getDriverName();
  472. if(isset($this->driverMap[$driver]))
  473. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  474. else
  475. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  476. array('{driver}'=>$driver)));
  477. }
  478. }
  479. /**
  480. * Returns the SQL command builder for the current DB connection.
  481. * @return CDbCommandBuilder the command builder
  482. * @since 1.0.4
  483. */
  484. public function getCommandBuilder()
  485. {
  486. return $this->getSchema()->getCommandBuilder();
  487. }
  488. /**
  489. * Returns the ID of the last inserted row or sequence value.
  490. * @param string $sequenceName name of the sequence object (required by some DBMS)
  491. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  492. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
  493. */
  494. public function getLastInsertID($sequenceName='')
  495. {
  496. $this->setActive(true);
  497. return $this->_pdo->lastInsertId($sequenceName);
  498. }
  499. /**
  500. * Quotes a string value for use in a query.
  501. * @param string $str string to be quoted
  502. * @return string the properly quoted string
  503. * @see http://www.php.net/manual/en/function.PDO-quote.php
  504. */
  505. public function quoteValue($str)
  506. {
  507. if(is_int($str) || is_float($str))
  508. return $str;
  509. $this->setActive(true);
  510. if(($value=$this->_pdo->quote($str))!==false)
  511. return $value;
  512. else // the driver doesn't support quote (e.g. oci)
  513. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  514. }
  515. /**
  516. * Quotes a table name for use in a query.
  517. * If the table name contains schema prefix, the prefix will also be properly quoted.
  518. * @param string $name table name
  519. * @return string the properly quoted table name
  520. */
  521. public function quoteTableName($name)
  522. {
  523. return $this->getSchema()->quoteTableName($name);
  524. }
  525. /**
  526. * Quotes a column name for use in a query.
  527. * If the column name contains prefix, the prefix will also be properly quoted.
  528. * @param string $name column name
  529. * @return string the properly quoted column name
  530. */
  531. public function quoteColumnName($name)
  532. {
  533. return $this->getSchema()->quoteColumnName($name);
  534. }
  535. /**
  536. * Determines the PDO type for the specified PHP type.
  537. * @param string $type The PHP type (obtained by gettype() call).
  538. * @return integer the corresponding PDO type
  539. */
  540. public function getPdoType($type)
  541. {
  542. static $map=array
  543. (
  544. 'boolean'=>PDO::PARAM_BOOL,
  545. 'integer'=>PDO::PARAM_INT,
  546. 'string'=>PDO::PARAM_STR,
  547. 'NULL'=>PDO::PARAM_NULL,
  548. );
  549. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  550. }
  551. /**
  552. * Returns the case of the column names
  553. * @return mixed the case of the column names
  554. * @see http://www.php.net/manual/en/pdo.setattribute.php
  555. */
  556. public function getColumnCase()
  557. {
  558. return $this->getAttribute(PDO::ATTR_CASE);
  559. }
  560. /**
  561. * Sets the case of the column names.
  562. * @param mixed $value the case of the column names
  563. * @see http://www.php.net/manual/en/pdo.setattribute.php
  564. */
  565. public function setColumnCase($value)
  566. {
  567. $this->setAttribute(PDO::ATTR_CASE,$value);
  568. }
  569. /**
  570. * Returns how the null and empty strings are converted.
  571. * @return mixed how the null and empty strings are converted
  572. * @see http://www.php.net/manual/en/pdo.setattribute.php
  573. */
  574. public function getNullConversion()
  575. {
  576. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  577. }
  578. /**
  579. * Sets how the null and empty strings are converted.
  580. * @param mixed $value how the null and empty strings are converted
  581. * @see http://www.php.net/manual/en/pdo.setattribute.php
  582. */
  583. public function setNullConversion($value)
  584. {
  585. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  586. }
  587. /**
  588. * Returns whether creating or updating a DB record will be automatically committed.
  589. * Some DBMS (such as sqlite) may not support this feature.
  590. * @return boolean whether creating or updating a DB record will be automatically committed.
  591. */
  592. public function getAutoCommit()
  593. {
  594. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  595. }
  596. /**
  597. * Sets whether creating or updating a DB record will be automatically committed.
  598. * Some DBMS (such as sqlite) may not support this feature.
  599. * @param boolean $value whether creating or updating a DB record will be automatically committed.
  600. */
  601. public function setAutoCommit($value)
  602. {
  603. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  604. }
  605. /**
  606. * Returns whether the connection is persistent or not.
  607. * Some DBMS (such as sqlite) may not support this feature.
  608. * @return boolean whether the connection is persistent or not
  609. */
  610. public function getPersistent()
  611. {
  612. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  613. }
  614. /**
  615. * Sets whether the connection is persistent or not.
  616. * Some DBMS (such as sqlite) may not support this feature.
  617. * @param boolean $value whether the connection is persistent or not
  618. */
  619. public function setPersistent($value)
  620. {
  621. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  622. }
  623. /**
  624. * Returns the name of the DB driver
  625. * @return string name of the DB driver
  626. */
  627. public function getDriverName()
  628. {
  629. if(($pos=strpos($this->connectionString, ':'))!==false)
  630. return strtolower(substr($this->connectionString, 0, $pos));
  631. // return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  632. }
  633. /**
  634. * Returns the version information of the DB driver.
  635. * @return string the version information of the DB driver
  636. */
  637. public function getClientVersion()
  638. {
  639. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  640. }
  641. /**
  642. * Returns the status of the connection.
  643. * Some DBMS (such as sqlite) may not support this feature.
  644. * @return string the status of the connection
  645. */
  646. public function getConnectionStatus()
  647. {
  648. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  649. }
  650. /**
  651. * Returns whether the connection performs data prefetching.
  652. * @return boolean whether the connection performs data prefetching
  653. */
  654. public function getPrefetch()
  655. {
  656. return $this->getAttribute(PDO::ATTR_PREFETCH);
  657. }
  658. /**
  659. * Returns the information of DBMS server.
  660. * @return string the information of DBMS server
  661. */
  662. public function getServerInfo()
  663. {
  664. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  665. }
  666. /**
  667. * Returns the version information of DBMS server.
  668. * @return string the version information of DBMS server
  669. */
  670. public function getServerVersion()
  671. {
  672. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  673. }
  674. /**
  675. * Returns the timeout settings for the connection.
  676. * @return integer timeout settings for the connection
  677. */
  678. public function getTimeout()
  679. {
  680. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  681. }
  682. /**
  683. * Obtains a specific DB connection attribute information.
  684. * @param integer $name the attribute to be queried
  685. * @return mixed the corresponding attribute information
  686. * @see http://www.php.net/manual/en/function.PDO-getAttribute.php
  687. */
  688. public function getAttribute($name)
  689. {
  690. $this->setActive(true);
  691. return $this->_pdo->getAttribute($name);
  692. }
  693. /**
  694. * Sets an attribute on the database connection.
  695. * @param integer $name the attribute to be set
  696. * @param mixed $value the attribute value
  697. * @see http://www.php.net/manual/en/function.PDO-setAttribute.php
  698. */
  699. public function setAttribute($name,$value)
  700. {
  701. if($this->_pdo instanceof PDO)
  702. $this->_pdo->setAttribute($name,$value);
  703. else
  704. $this->_attributes[$name]=$value;
  705. }
  706. /**
  707. * Returns the attributes that are previously explicitly set for the DB connection.
  708. * @return array attributes (name=>value) that are previously explicitly set for the DB connection.
  709. * @see setAttributes
  710. * @since 1.1.7
  711. */
  712. public function getAttributes()
  713. {
  714. return $this->_attributes;
  715. }
  716. /**
  717. * Sets a set of attributes on the database connection.
  718. * @param array $values attributes (name=>value) to be set.
  719. * @see setAttribute
  720. * @since 1.1.7
  721. */
  722. public function setAttributes($values)
  723. {
  724. foreach($values as $name=>$value)
  725. $this->_attributes[$name]=$value;
  726. }
  727. /**
  728. * Returns the statistical results of SQL executions.
  729. * The results returned include the number of SQL statements executed and
  730. * the total time spent.
  731. * In order to use this method, {@link enableProfiling} has to be set true.
  732. * @return array the first element indicates the number of SQL statements executed,
  733. * and the second element the total time spent in SQL execution.
  734. * @since 1.0.6
  735. */
  736. public function getStats()
  737. {
  738. $logger=Yii::getLogger();
  739. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  740. $count=count($timings);
  741. $time=array_sum($timings);
  742. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  743. $count+=count($timings);
  744. $time+=array_sum($timings);
  745. return array($count,$time);
  746. }
  747. }