CDbConnection.php 28 KB

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