CDbConnection.php 27 KB

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