PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/yii/framework/db/CDbCommand.php

https://github.com/joshuaswarren/weatherhub
PHP | 1317 lines | 596 code | 94 blank | 627 comment | 80 complexity | 0a12669bbf6ef6bba43046d45a79f087 MD5 | raw file
  1. <?php
  2. /**
  3. * This file contains the CDbCommand class.
  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. * CDbCommand represents an SQL statement to execute against a database.
  12. *
  13. * It is usually created by calling {@link CDbConnection::createCommand}.
  14. * The SQL statement to be executed may be set via {@link setText Text}.
  15. *
  16. * To execute a non-query SQL (such as insert, delete, update), call
  17. * {@link execute}. To execute an SQL statement that returns result data set
  18. * (such as SELECT), use {@link query} or its convenient versions {@link queryRow},
  19. * {@link queryColumn}, or {@link queryScalar}.
  20. *
  21. * If an SQL statement returns results (such as a SELECT SQL), the results
  22. * can be accessed via the returned {@link CDbDataReader}.
  23. *
  24. * CDbCommand supports SQL statment preparation and parameter binding.
  25. * Call {@link bindParam} to bind a PHP variable to a parameter in SQL.
  26. * Call {@link bindValue} to bind a value to an SQL parameter.
  27. * When binding a parameter, the SQL statement is automatically prepared.
  28. * You may also call {@link prepare} to explicitly prepare an SQL statement.
  29. *
  30. * Starting from version 1.1.6, CDbCommand can also be used as a query builder
  31. * that builds a SQL statement from code fragments. For example,
  32. * <pre>
  33. * $user = Yii::app()->db->createCommand()
  34. * ->select('username, password')
  35. * ->from('tbl_user')
  36. * ->where('id=:id', array(':id'=>1))
  37. * ->queryRow();
  38. * </pre>
  39. *
  40. * @author Qiang Xue <qiang.xue@gmail.com>
  41. * @version $Id: CDbCommand.php 3240 2011-05-25 19:22:47Z qiang.xue $
  42. * @package system.db
  43. * @since 1.0
  44. */
  45. class CDbCommand extends CComponent
  46. {
  47. /**
  48. * @var array the parameters (name=>value) to be bound to the current query.
  49. * @since 1.1.6
  50. */
  51. public $params=array();
  52. private $_connection;
  53. private $_text;
  54. private $_statement;
  55. private $_paramLog=array();
  56. private $_query;
  57. private $_fetchMode = array(PDO::FETCH_ASSOC);
  58. /**
  59. * Constructor.
  60. * @param CDbConnection $connection the database connection
  61. * @param mixed $query the DB query to be executed. This can be either
  62. * a string representing a SQL statement, or an array whose name-value pairs
  63. * will be used to set the corresponding properties of the created command object.
  64. *
  65. * For example, you can pass in either <code>'SELECT * FROM tbl_user'</code>
  66. * or <code>array('select'=>'*', 'from'=>'tbl_user')</code>. They are equivalent
  67. * in terms of the final query result.
  68. *
  69. * When passing the query as an array, the following properties are commonly set:
  70. * {@link select}, {@link distinct}, {@link from}, {@link where}, {@link join},
  71. * {@link group}, {@link having}, {@link order}, {@link limit}, {@link offset} and
  72. * {@link union}. Please refer to the setter of each of these properties for details
  73. * about valid property values. This feature has been available since version 1.1.6.
  74. *
  75. * Since 1.1.7 it is possible to use a specific mode of data fetching by setting
  76. * {@link setFetchMode FetchMode}. See {@link http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php}
  77. * for more details.
  78. */
  79. public function __construct(CDbConnection $connection,$query=null)
  80. {
  81. $this->_connection=$connection;
  82. if(is_array($query))
  83. {
  84. foreach($query as $name=>$value)
  85. $this->$name=$value;
  86. }
  87. else
  88. $this->setText($query);
  89. }
  90. /**
  91. * Set the statement to null when serializing.
  92. * @return array
  93. */
  94. public function __sleep()
  95. {
  96. $this->_statement=null;
  97. return array_keys(get_object_vars($this));
  98. }
  99. /**
  100. * Set the default fetch mode for this statement
  101. * @param mixed $mode fetch mode
  102. * @return CDbCommand
  103. * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
  104. * @since 1.1.7
  105. */
  106. public function setFetchMode($mode)
  107. {
  108. $params=func_get_args();
  109. $this->_fetchMode = $params;
  110. return $this;
  111. }
  112. /**
  113. * Cleans up the command and prepares for building a new query.
  114. * This method is mainly used when a command object is being reused
  115. * multiple times for building different queries.
  116. * Calling this method will clean up all internal states of the command object.
  117. * @return CDbCommand this command instance
  118. * @since 1.1.6
  119. */
  120. public function reset()
  121. {
  122. $this->_text=null;
  123. $this->_query=null;
  124. $this->_statement=null;
  125. $this->_paramLog=array();
  126. $this->params=array();
  127. return $this;
  128. }
  129. /**
  130. * @return string the SQL statement to be executed
  131. */
  132. public function getText()
  133. {
  134. if($this->_text=='' && !empty($this->_query))
  135. $this->setText($this->buildQuery($this->_query));
  136. return $this->_text;
  137. }
  138. /**
  139. * Specifies the SQL statement to be executed.
  140. * Any previous execution will be terminated or cancel.
  141. * @param string $value the SQL statement to be executed
  142. * @return CDbCommand this command instance
  143. */
  144. public function setText($value)
  145. {
  146. if($this->_connection->tablePrefix!==null && $value!='')
  147. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  148. else
  149. $this->_text=$value;
  150. $this->cancel();
  151. return $this;
  152. }
  153. /**
  154. * @return CDbConnection the connection associated with this command
  155. */
  156. public function getConnection()
  157. {
  158. return $this->_connection;
  159. }
  160. /**
  161. * @return PDOStatement the underlying PDOStatement for this command
  162. * It could be null if the statement is not prepared yet.
  163. */
  164. public function getPdoStatement()
  165. {
  166. return $this->_statement;
  167. }
  168. /**
  169. * Prepares the SQL statement to be executed.
  170. * For complex SQL statement that is to be executed multiple times,
  171. * this may improve performance.
  172. * For SQL statement with binding parameters, this method is invoked
  173. * automatically.
  174. */
  175. public function prepare()
  176. {
  177. if($this->_statement==null)
  178. {
  179. try
  180. {
  181. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  182. $this->_paramLog=array();
  183. }
  184. catch(Exception $e)
  185. {
  186. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  187. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  188. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  189. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  190. }
  191. }
  192. }
  193. /**
  194. * Cancels the execution of the SQL statement.
  195. */
  196. public function cancel()
  197. {
  198. $this->_statement=null;
  199. }
  200. /**
  201. * Binds a parameter to the SQL statement to be executed.
  202. * @param mixed $name Parameter identifier. For a prepared statement
  203. * using named placeholders, this will be a parameter name of
  204. * the form :name. For a prepared statement using question mark
  205. * placeholders, this will be the 1-indexed position of the parameter.
  206. * @param mixed $value Name of the PHP variable to bind to the SQL statement parameter
  207. * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
  208. * @param integer $length length of the data type
  209. * @param mixed $driverOptions the driver-specific options (this is available since version 1.1.6)
  210. * @return CDbCommand the current command being executed (this is available since version 1.0.8)
  211. * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
  212. */
  213. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  214. {
  215. $this->prepare();
  216. if($dataType===null)
  217. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  218. else if($length===null)
  219. $this->_statement->bindParam($name,$value,$dataType);
  220. else if($driverOptions===null)
  221. $this->_statement->bindParam($name,$value,$dataType,$length);
  222. else
  223. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  224. $this->_paramLog[$name]=&$value;
  225. return $this;
  226. }
  227. /**
  228. * Binds a value to a parameter.
  229. * @param mixed $name Parameter identifier. For a prepared statement
  230. * using named placeholders, this will be a parameter name of
  231. * the form :name. For a prepared statement using question mark
  232. * placeholders, this will be the 1-indexed position of the parameter.
  233. * @param mixed $value The value to bind to the parameter
  234. * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
  235. * @return CDbCommand the current command being executed (this is available since version 1.0.8)
  236. * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
  237. */
  238. public function bindValue($name, $value, $dataType=null)
  239. {
  240. $this->prepare();
  241. if($dataType===null)
  242. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  243. else
  244. $this->_statement->bindValue($name,$value,$dataType);
  245. $this->_paramLog[$name]=$value;
  246. return $this;
  247. }
  248. /**
  249. * Binds a list of values to the corresponding parameters.
  250. * This is similar to {@link bindValue} except that it binds multiple values.
  251. * Note that the SQL data type of each value is determined by its PHP type.
  252. * @param array $values the values to be bound. This must be given in terms of an associative
  253. * array with array keys being the parameter names, and array values the corresponding parameter values.
  254. * For example, <code>array(':name'=>'John', ':age'=>25)</code>.
  255. * @return CDbCommand the current command being executed
  256. * @since 1.1.5
  257. */
  258. public function bindValues($values)
  259. {
  260. $this->prepare();
  261. foreach($values as $name=>$value)
  262. {
  263. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  264. $this->_paramLog[$name]=$value;
  265. }
  266. return $this;
  267. }
  268. /**
  269. * Executes the SQL statement.
  270. * This method is meant only for executing non-query SQL statement.
  271. * No result set will be returned.
  272. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  273. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  274. * them in this way can improve the performance. Note that if you pass parameters in this way,
  275. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  276. * binding methods and the input parameters this way can improve the performance.
  277. * This parameter has been available since version 1.0.10.
  278. * @return integer number of rows affected by the execution.
  279. * @throws CException execution failed
  280. */
  281. public function execute($params=array())
  282. {
  283. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  284. {
  285. $p=array();
  286. foreach($pars as $name=>$value)
  287. $p[$name]=$name.'='.var_export($value,true);
  288. $par='. Bound with ' .implode(', ',$p);
  289. }
  290. else
  291. $par='';
  292. Yii::trace('Executing SQL: '.$this->getText().$par,'system.db.CDbCommand');
  293. try
  294. {
  295. if($this->_connection->enableProfiling)
  296. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  297. $this->prepare();
  298. if($params===array())
  299. $this->_statement->execute();
  300. else
  301. $this->_statement->execute($params);
  302. $n=$this->_statement->rowCount();
  303. if($this->_connection->enableProfiling)
  304. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  305. return $n;
  306. }
  307. catch(Exception $e)
  308. {
  309. if($this->_connection->enableProfiling)
  310. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().')','system.db.CDbCommand.execute');
  311. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  312. $message = $e->getMessage();
  313. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  314. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  315. if(YII_DEBUG)
  316. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  317. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  318. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  319. }
  320. }
  321. /**
  322. * Executes the SQL statement and returns query result.
  323. * This method is for executing an SQL query that returns result set.
  324. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  325. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  326. * them in this way can improve the performance. Note that if you pass parameters in this way,
  327. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  328. * binding methods and the input parameters this way can improve the performance.
  329. * This parameter has been available since version 1.0.10.
  330. * @return CDbDataReader the reader object for fetching the query result
  331. * @throws CException execution failed
  332. */
  333. public function query($params=array())
  334. {
  335. return $this->queryInternal('',0,$params);
  336. }
  337. /**
  338. * Executes the SQL statement and returns all rows.
  339. * @param boolean $fetchAssociative whether each row should be returned as an associated array with
  340. * column names as the keys or the array keys are column indexes (0-based).
  341. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  342. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  343. * them in this way can improve the performance. Note that if you pass parameters in this way,
  344. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  345. * binding methods and the input parameters this way can improve the performance.
  346. * This parameter has been available since version 1.0.10.
  347. * @return array all rows of the query result. Each array element is an array representing a row.
  348. * An empty array is returned if the query results in nothing.
  349. * @throws CException execution failed
  350. */
  351. public function queryAll($fetchAssociative=true,$params=array())
  352. {
  353. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  354. }
  355. /**
  356. * Executes the SQL statement and returns the first row of the result.
  357. * This is a convenient method of {@link query} when only the first row of data is needed.
  358. * @param boolean $fetchAssociative whether the row should be returned as an associated array with
  359. * column names as the keys or the array keys are column indexes (0-based).
  360. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  361. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  362. * them in this way can improve the performance. Note that if you pass parameters in this way,
  363. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  364. * binding methods and the input parameters this way can improve the performance.
  365. * This parameter has been available since version 1.0.10.
  366. * @return mixed the first row (in terms of an array) of the query result, false if no result.
  367. * @throws CException execution failed
  368. */
  369. public function queryRow($fetchAssociative=true,$params=array())
  370. {
  371. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  372. }
  373. /**
  374. * Executes the SQL statement and returns the value of the first column in the first row of data.
  375. * This is a convenient method of {@link query} when only a single scalar
  376. * value is needed (e.g. obtaining the count of the records).
  377. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  378. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  379. * them in this way can improve the performance. Note that if you pass parameters in this way,
  380. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  381. * binding methods and the input parameters this way can improve the performance.
  382. * This parameter has been available since version 1.0.10.
  383. * @return mixed the value of the first column in the first row of the query result. False is returned if there is no value.
  384. * @throws CException execution failed
  385. */
  386. public function queryScalar($params=array())
  387. {
  388. $result=$this->queryInternal('fetchColumn',0,$params);
  389. if(is_resource($result) && get_resource_type($result)==='stream')
  390. return stream_get_contents($result);
  391. else
  392. return $result;
  393. }
  394. /**
  395. * Executes the SQL statement and returns the first column of the result.
  396. * This is a convenient method of {@link query} when only the first column of data is needed.
  397. * Note, the column returned will contain the first element in each row of result.
  398. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  399. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  400. * them in this way can improve the performance. Note that if you pass parameters in this way,
  401. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  402. * binding methods and the input parameters this way can improve the performance.
  403. * This parameter has been available since version 1.0.10.
  404. * @return array the first column of the query result. Empty array if no result.
  405. * @throws CException execution failed
  406. */
  407. public function queryColumn($params=array())
  408. {
  409. return $this->queryInternal('fetchAll',PDO::FETCH_COLUMN,$params);
  410. }
  411. /**
  412. * @param string $method method of PDOStatement to be called
  413. * @param mixed $mode parameters to be passed to the method
  414. * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
  415. * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  416. * them in this way can improve the performance. Note that you pass parameters in this way,
  417. * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  418. * binding methods and the input parameters this way can improve the performance.
  419. * This parameter has been available since version 1.0.10.
  420. * @return mixed the method execution result
  421. */
  422. private function queryInternal($method,$mode,$params=array())
  423. {
  424. $params=array_merge($this->params,$params);
  425. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  426. {
  427. $p=array();
  428. foreach($pars as $name=>$value)
  429. $p[$name]=$name.'='.var_export($value,true);
  430. $par='. Bound with '.implode(', ',$p);
  431. }
  432. else
  433. $par='';
  434. Yii::trace('Querying SQL: '.$this->getText().$par,'system.db.CDbCommand');
  435. if($this->_connection->queryCachingCount>0 && $method!==''
  436. && $this->_connection->queryCachingDuration>0
  437. && $this->_connection->queryCacheID!==false
  438. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  439. {
  440. $this->_connection->queryCachingCount--;
  441. $cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
  442. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  443. if(($result=$cache->get($cacheKey))!==false)
  444. {
  445. Yii::trace('Query result found in cache','system.db.CDbCommand');
  446. return $result;
  447. }
  448. }
  449. try
  450. {
  451. if($this->_connection->enableProfiling)
  452. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  453. $this->prepare();
  454. if($params===array())
  455. $this->_statement->execute();
  456. else
  457. $this->_statement->execute($params);
  458. if($method==='')
  459. $result=new CDbDataReader($this);
  460. else
  461. {
  462. $mode=(array)$mode;
  463. $result=call_user_func_array(array($this->_statement, $method), $mode);
  464. $this->_statement->closeCursor();
  465. }
  466. if($this->_connection->enableProfiling)
  467. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  468. if(isset($cache,$cacheKey))
  469. $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  470. return $result;
  471. }
  472. catch(Exception $e)
  473. {
  474. if($this->_connection->enableProfiling)
  475. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  476. $errorInfo = $e instanceof PDOException ? $e->errorInfo : null;
  477. $message = $e->getMessage();
  478. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  479. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  480. if(YII_DEBUG)
  481. $message .= '. The SQL statement executed was: '.$this->getText().$par;
  482. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  483. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  484. }
  485. }
  486. /**
  487. * Builds a SQL SELECT statement from the given query specification.
  488. * @param array $query the query specification in name-value pairs. The following
  489. * query options are supported: {@link select}, {@link distinct}, {@link from},
  490. * {@link where}, {@link join}, {@link group}, {@link having}, {@link order},
  491. * {@link limit}, {@link offset} and {@link union}.
  492. * @return string the SQL statement
  493. * @since 1.1.6
  494. */
  495. public function buildQuery($query)
  496. {
  497. $sql=isset($query['distinct']) && $query['distinct'] ? 'SELECT DISTINCT' : 'SELECT';
  498. $sql.=' '.(isset($query['select']) ? $query['select'] : '*');
  499. if(isset($query['from']))
  500. $sql.="\nFROM ".$query['from'];
  501. else
  502. throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));
  503. if(isset($query['join']))
  504. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  505. if(isset($query['where']))
  506. $sql.="\nWHERE ".$query['where'];
  507. if(isset($query['group']))
  508. $sql.="\nGROUP BY ".$query['group'];
  509. if(isset($query['having']))
  510. $sql.="\nHAVING ".$query['having'];
  511. if(isset($query['order']))
  512. $sql.="\nORDER BY ".$query['order'];
  513. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  514. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  515. if($limit>=0 || $offset>0)
  516. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  517. if(isset($query['union']))
  518. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  519. return $sql;
  520. }
  521. /**
  522. * Sets the SELECT part of the query.
  523. * @param mixed $columns the columns to be selected. Defaults to '*', meaning all columns.
  524. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')).
  525. * Columns can contain table prefixes (e.g. "tbl_user.id") and/or column aliases (e.g. "tbl_user.id AS user_id").
  526. * The method will automatically quote the column names unless a column contains some parenthesis
  527. * (which means the column contains a DB expression).
  528. * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
  529. * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. This parameter is supported since version 1.1.8.
  530. * @return CDbCommand the command object itself
  531. * @since 1.1.6
  532. */
  533. public function select($columns='*', $option='')
  534. {
  535. if(is_string($columns) && strpos($columns,'(')!==false)
  536. $this->_query['select']=$columns;
  537. else
  538. {
  539. if(!is_array($columns))
  540. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  541. foreach($columns as $i=>$column)
  542. {
  543. if(is_object($column))
  544. $columns[$i]=(string)$column;
  545. else if(strpos($column,'(')===false)
  546. {
  547. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  548. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  549. else
  550. $columns[$i]=$this->_connection->quoteColumnName($column);
  551. }
  552. }
  553. $this->_query['select']=implode(', ',$columns);
  554. }
  555. if($option!='')
  556. $this->_query['select']=$option.' '.$this->_query['select'];
  557. return $this;
  558. }
  559. /**
  560. * Returns the SELECT part in the query.
  561. * @return string the SELECT part (without 'SELECT') in the query.
  562. * @since 1.1.6
  563. */
  564. public function getSelect()
  565. {
  566. return isset($this->_query['select']) ? $this->_query['select'] : '';
  567. }
  568. /**
  569. * Sets the SELECT part in the query.
  570. * @param mixed $value the data to be selected. Please refer to {@link select()} for details
  571. * on how to specify this parameter.
  572. * @since 1.1.6
  573. */
  574. public function setSelect($value)
  575. {
  576. $this->select($value);
  577. }
  578. /**
  579. * Sets the SELECT part of the query with the DISTINCT flag turned on.
  580. * This is the same as {@link select} except that the DISTINCT flag is turned on.
  581. * @param mixed $columns the columns to be selected. See {@link select} for more details.
  582. * @return CDbCommand the command object itself
  583. * @since 1.1.6
  584. */
  585. public function selectDistinct($columns='*')
  586. {
  587. $this->_query['distinct']=true;
  588. return $this->select($columns);
  589. }
  590. /**
  591. * Returns a value indicating whether SELECT DISTINCT should be used.
  592. * @return boolean a value indicating whether SELECT DISTINCT should be used.
  593. * @since 1.1.6
  594. */
  595. public function getDistinct()
  596. {
  597. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  598. }
  599. /**
  600. * Sets a value indicating whether SELECT DISTINCT should be used.
  601. * @param boolean $value a value indicating whether SELECT DISTINCT should be used.
  602. * @since 1.1.6
  603. */
  604. public function setDistinct($value)
  605. {
  606. $this->_query['distinct']=$value;
  607. }
  608. /**
  609. * Sets the FROM part of the query.
  610. * @param mixed $tables the table(s) to be selected from. This can be either a string (e.g. 'tbl_user')
  611. * or an array (e.g. array('tbl_user', 'tbl_profile')) specifying one or several table names.
  612. * Table names can contain schema prefixes (e.g. 'public.tbl_user') and/or table aliases (e.g. 'tbl_user u').
  613. * The method will automatically quote the table names unless it contains some parenthesis
  614. * (which means the table is given as a sub-query or DB expression).
  615. * @return CDbCommand the command object itself
  616. * @since 1.1.6
  617. */
  618. public function from($tables)
  619. {
  620. if(is_string($tables) && strpos($tables,'(')!==false)
  621. $this->_query['from']=$tables;
  622. else
  623. {
  624. if(!is_array($tables))
  625. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  626. foreach($tables as $i=>$table)
  627. {
  628. if(strpos($table,'(')===false)
  629. {
  630. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  631. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  632. else
  633. $tables[$i]=$this->_connection->quoteTableName($table);
  634. }
  635. }
  636. $this->_query['from']=implode(', ',$tables);
  637. }
  638. return $this;
  639. }
  640. /**
  641. * Returns the FROM part in the query.
  642. * @return string the FROM part (without 'FROM' ) in the query.
  643. * @since 1.1.6
  644. */
  645. public function getFrom()
  646. {
  647. return isset($this->_query['from']) ? $this->_query['from'] : '';
  648. }
  649. /**
  650. * Sets the FROM part in the query.
  651. * @param mixed $value the tables to be selected from. Please refer to {@link from()} for details
  652. * on how to specify this parameter.
  653. * @since 1.1.6
  654. */
  655. public function setFrom($value)
  656. {
  657. $this->from($value);
  658. }
  659. /**
  660. * Sets the WHERE part of the query.
  661. *
  662. * The method requires a $conditions parameter, and optionally a $params parameter
  663. * specifying the values to be bound to the query.
  664. *
  665. * The $conditions parameter should be either a string (e.g. 'id=1') or an array.
  666. * If the latter, it must be of the format <code>array(operator, operand1, operand2, ...)</code>,
  667. * where the operator can be one of the followings, and the possible operands depend on the corresponding
  668. * operator:
  669. * <ul>
  670. * <li><code>and</code>: the operands should be concatenated together using AND. For example,
  671. * array('and', 'id=1', 'id=2') will generate 'id=1 AND id=2'. If an operand is an array,
  672. * it will be converted into a string using the same rules described here. For example,
  673. * array('and', 'type=1', array('or', 'id=1', 'id=2')) will generate 'type=1 AND (id=1 OR id=2)'.
  674. * The method will NOT do any quoting or escaping.</li>
  675. * <li><code>or</code>: similar as the <code>and</code> operator except that the operands are concatenated using OR.</li>
  676. * <li><code>in</code>: operand 1 should be a column or DB expression, and operand 2 be an array representing
  677. * the range of the values that the column or DB expression should be in. For example,
  678. * array('in', 'id', array(1,2,3)) will generate 'id IN (1,2,3)'.
  679. * The method will properly quote the column name and escape values in the range.</li>
  680. * <li><code>not in</code>: similar as the <code>in</code> operator except that IN is replaced with NOT IN in the generated condition.</li>
  681. * <li><code>like</code>: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing
  682. * the values that the column or DB expression should be like.
  683. * For example, array('like', 'name', '%tester%') will generate "name LIKE '%tester%'".
  684. * When the value range is given as an array, multiple LIKE predicates will be generated and concatenated using AND.
  685. * For example, array('like', 'name', array('%test%', '%sample%')) will generate
  686. * "name LIKE '%test%' AND name LIKE '%sample%'".
  687. * The method will properly quote the column name and escape values in the range.</li>
  688. * <li><code>not like</code>: similar as the <code>like</code> operator except that LIKE is replaced with NOT LIKE in the generated condition.</li>
  689. * <li><code>or like</code>: similar as the <code>like</code> operator except that OR is used to concatenated the LIKE predicates.</li>
  690. * <li><code>or not like</code>: similar as the <code>not like</code> operator except that OR is used to concatenated the NOT LIKE predicates.</li>
  691. * </ul>
  692. * @param mixed $conditions the conditions that should be put in the WHERE part.
  693. * @param array $params the parameters (name=>value) to be bound to the query
  694. * @return CDbCommand the command object itself
  695. * @since 1.1.6
  696. */
  697. public function where($conditions, $params=array())
  698. {
  699. $this->_query['where']=$this->processConditions($conditions);
  700. foreach($params as $name=>$value)
  701. $this->params[$name]=$value;
  702. return $this;
  703. }
  704. /**
  705. * Returns the WHERE part in the query.
  706. * @return string the WHERE part (without 'WHERE' ) in the query.
  707. * @since 1.1.6
  708. */
  709. public function getWhere()
  710. {
  711. return isset($this->_query['where']) ? $this->_query['where'] : '';
  712. }
  713. /**
  714. * Sets the WHERE part in the query.
  715. * @param mixed $value the where part. Please refer to {@link where()} for details
  716. * on how to specify this parameter.
  717. * @since 1.1.6
  718. */
  719. public function setWhere($value)
  720. {
  721. $this->where($value);
  722. }
  723. /**
  724. * Appends an INNER JOIN part to the query.
  725. * @param string $table the table to be joined.
  726. * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
  727. * The method will automatically quote the table name unless it contains some parenthesis
  728. * (which means the table is given as a sub-query or DB expression).
  729. * @param mixed $conditions the join condition that should appear in the ON part.
  730. * Please refer to {@link where} on how to specify conditions.
  731. * @param array $params the parameters (name=>value) to be bound to the query
  732. * @return CDbCommand the command object itself
  733. * @since 1.1.6
  734. */
  735. public function join($table, $conditions, $params=array())
  736. {
  737. return $this->joinInternal('join', $table, $conditions, $params);
  738. }
  739. /**
  740. * Returns the join part in the query.
  741. * @return mixed the join part in the query. This can be an array representing
  742. * multiple join fragments, or a string representing a single jojin fragment.
  743. * Each join fragment will contain the proper join operator (e.g. LEFT JOIN).
  744. * @since 1.1.6
  745. */
  746. public function getJoin()
  747. {
  748. return isset($this->_query['join']) ? $this->_query['join'] : '';
  749. }
  750. /**
  751. * Sets the join part in the query.
  752. * @param mixed $value the join part in the query. This can be either a string or
  753. * an array representing multiple join parts in the query. Each part must contain
  754. * the proper join operator (e.g. 'LEFT JOIN tbl_profile ON tbl_user.id=tbl_profile.id')
  755. * @since 1.1.6
  756. */
  757. public function setJoin($value)
  758. {
  759. $this->_query['join']=$value;
  760. }
  761. /**
  762. * Appends a LEFT OUTER JOIN part to the query.
  763. * @param string $table the table to be joined.
  764. * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
  765. * The method will automatically quote the table name unless it contains some parenthesis
  766. * (which means the table is given as a sub-query or DB expression).
  767. * @param mixed $conditions the join condition that should appear in the ON part.
  768. * Please refer to {@link where} on how to specify conditions.
  769. * @param array $params the parameters (name=>value) to be bound to the query
  770. * @return CDbCommand the command object itself
  771. * @since 1.1.6
  772. */
  773. public function leftJoin($table, $conditions, $params=array())
  774. {
  775. return $this->joinInternal('left join', $table, $conditions, $params);
  776. }
  777. /**
  778. * Appends a RIGHT OUTER JOIN part to the query.
  779. * @param string $table the table to be joined.
  780. * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
  781. * The method will automatically quote the table name unless it contains some parenthesis
  782. * (which means the table is given as a sub-query or DB expression).
  783. * @param mixed $conditions the join condition that should appear in the ON part.
  784. * Please refer to {@link where} on how to specify conditions.
  785. * @param array $params the parameters (name=>value) to be bound to the query
  786. * @return CDbCommand the command object itself
  787. * @since 1.1.6
  788. */
  789. public function rightJoin($table, $conditions, $params=array())
  790. {
  791. return $this->joinInternal('right join', $table, $conditions, $params);
  792. }
  793. /**
  794. * Appends a CROSS JOIN part to the query.
  795. * Note that not all DBMS support CROSS JOIN.
  796. * @param string $table the table to be joined.
  797. * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
  798. * The method will automatically quote the table name unless it contains some parenthesis
  799. * (which means the table is given as a sub-query or DB expression).
  800. * @return CDbCommand the command object itself
  801. * @since 1.1.6
  802. */
  803. public function crossJoin($table)
  804. {
  805. return $this->joinInternal('cross join', $table);
  806. }
  807. /**
  808. * Appends a NATURAL JOIN part to the query.
  809. * Note that not all DBMS support NATURAL JOIN.
  810. * @param string $table the table to be joined.
  811. * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
  812. * The method will automatically quote the table name unless it contains some parenthesis
  813. * (which means the table is given as a sub-query or DB expression).
  814. * @return CDbCommand the command object itself
  815. * @since 1.1.6
  816. */
  817. public function naturalJoin($table)
  818. {
  819. return $this->joinInternal('natural join', $table);
  820. }
  821. /**
  822. * Sets the GROUP BY part of the query.
  823. * @param mixed $columns the columns to be grouped by.
  824. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')).
  825. * The method will automatically quote the column names unless a column contains some parenthesis
  826. * (which means the column contains a DB expression).
  827. * @return CDbCommand the command object itself
  828. * @since 1.1.6
  829. */
  830. public function group($columns)
  831. {
  832. if(is_string($columns) && strpos($columns,'(')!==false)
  833. $this->_query['group']=$columns;
  834. else
  835. {
  836. if(!is_array($columns))
  837. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  838. foreach($columns as $i=>$column)
  839. {
  840. if(is_object($column))
  841. $columns[$i]=(string)$column;
  842. else if(strpos($column,'(')===false)
  843. $columns[$i]=$this->_connection->quoteColumnName($column);
  844. }
  845. $this->_query['group']=implode(', ',$columns);
  846. }
  847. return $this;
  848. }
  849. /**
  850. * Returns the GROUP BY part in the query.
  851. * @return string the GROUP BY part (without 'GROUP BY' ) in the query.
  852. * @since 1.1.6
  853. */
  854. public function getGroup()
  855. {
  856. return isset($this->_query['group']) ? $this->_query['group'] : '';
  857. }
  858. /**
  859. * Sets the GROUP BY part in the query.
  860. * @param mixed $value the GROUP BY part. Please refer to {@link group()} for details
  861. * on how to specify this parameter.
  862. * @since 1.1.6
  863. */
  864. public function setGroup($value)
  865. {
  866. $this->group($value);
  867. }
  868. /**
  869. * Sets the HAVING part of the query.
  870. * @param mixed $conditions the conditions to be put after HAVING.
  871. * Please refer to {@link where} on how to specify conditions.
  872. * @param array $params the parameters (name=>value) to be bound to the query
  873. * @return CDbCommand the command object itself
  874. * @since 1.1.6
  875. */
  876. public function having($conditions, $params=array())
  877. {
  878. $this->_query['having']=$this->processConditions($conditions);
  879. foreach($params as $name=>$value)
  880. $this->params[$name]=$value;
  881. return $this;
  882. }
  883. /**
  884. * Returns the HAVING part in the query.
  885. * @return string the HAVING part (without 'HAVING' ) in the query.
  886. * @since 1.1.6
  887. */
  888. public function getHaving()
  889. {
  890. return isset($this->_query['having']) ? $this->_query['having'] : '';
  891. }
  892. /**
  893. * Sets the HAVING part in the query.
  894. * @param mixed $value the HAVING part. Please refer to {@link having()} for details
  895. * on how to specify this parameter.
  896. * @since 1.1.6
  897. */
  898. public function setHaving($value)
  899. {
  900. $this->having($value);
  901. }
  902. /**
  903. * Sets the ORDER BY part of the query.
  904. * @param mixed $columns the columns (and the directions) to be ordered by.
  905. * Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. array('id ASC', 'name DESC')).
  906. * The method will automatically quote the column names unless a column contains some parenthesis
  907. * (which means the column contains a DB expression).
  908. * @return CDbCommand the command object itself
  909. * @since 1.1.6
  910. */
  911. public function order($columns)
  912. {
  913. if(is_string($columns) && strpos($columns,'(')!==false)
  914. $this->_query['order']=$columns;
  915. else
  916. {
  917. if(!is_array($columns))
  918. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  919. foreach($columns as $i=>$column)
  920. {
  921. if(is_object($column))
  922. $columns[$i]=(string)$column;
  923. else if(strpos($column,'(')===false)
  924. {
  925. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  926. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  927. else
  928. $columns[$i]=$this->_connection->quoteColumnName($column);
  929. }
  930. }
  931. $this->_query['order']=implode(', ',$columns);
  932. }
  933. return $this;
  934. }
  935. /**
  936. * Returns the ORDER BY part in the query.
  937. * @return string the ORDER BY part (without 'ORDER BY' ) in the query.
  938. * @since 1.1.6
  939. */
  940. public function getOrder()
  941. {
  942. return isset($this->_query['order']) ? $this->_query['order'] : '';
  943. }
  944. /**
  945. * Sets the ORDER BY part in the query.
  946. * @param mixed $value the ORDER BY part. Please refer to {@link order()} for details
  947. * on how to specify this parameter.
  948. * @since 1.1.6
  949. */
  950. public function setOrder($value)
  951. {
  952. $this->order($value);
  953. }
  954. /**
  955. * Sets the LIMIT part of the query.
  956. * @param integer $limit the limit
  957. * @param integer $offset the offset
  958. * @return CDbCommand the command object itself
  959. * @since 1.1.6
  960. */
  961. public function limit($limit, $offset=null)
  962. {
  963. $this->_query['limit']=(int)$limit;
  964. if($offset!==null)
  965. $this->offset($offset);
  966. return $this;
  967. }
  968. /**
  969. * Returns the LIMIT part in the query.
  970. * @return string the LIMIT part (without 'LIMIT' ) in the query.
  971. * @since 1.1.6
  972. */
  973. public function getLimit()
  974. {
  975. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  976. }
  977. /**
  978. * Sets the LIMIT part in the query.
  979. * @param integer $value the LIMIT part. Please refer to {@link limit()} for details
  980. * on how to specify this parameter.
  981. * @since 1.1.6
  982. */
  983. public function setLimit($value)
  984. {
  985. $this->limit($value);
  986. }
  987. /**
  988. * Sets the OFFSET part of the query.
  989. * @param integer $offset the offset
  990. * @return CDbCommand the command object itself
  991. * @since 1.1.6
  992. */
  993. public function offset($offset)
  994. {
  995. $this->_query['offset']=(int)$offset;
  996. return $this;
  997. }
  998. /**
  999. * Returns the OFFSET part in the query.
  1000. * @return string the OFFSET part (without 'OFFSET' ) in the query.
  1001. * @since 1.1.6
  1002. */
  1003. public function getOffset()
  1004. {
  1005. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  1006. }
  1007. /**
  1008. * Sets the OFFSET part in the query.
  1009. * @param integer $value the OFFSET part. Please refer to {@link offset()} for details
  1010. * on how to specify this parameter.
  1011. * @since 1.1.6
  1012. */
  1013. public function setOffset($value)
  1014. {
  1015. $this->offset($value);
  1016. }
  1017. /**
  1018. * Appends a SQL statement using UNION operator.
  1019. * @param string $sql the SQL statement to be appended using UNION
  1020. * @return CDbCommand the command object itself
  1021. * @since 1.1.6
  1022. */
  1023. public function union($sql)
  1024. {
  1025. if(isset($this->_query['union']) && is_string($this->_query['union']))
  1026. $this->_query['union']=array($this->_query['union']);
  1027. $this->_query['union'][]=$sql;
  1028. return $this;
  1029. }
  1030. /**
  1031. * Returns the UNION part in the query.
  1032. * @return mixed the UNION part (without 'UNION' ) in the query.
  1033. * This can be either a string or an array representing multiple union parts.
  1034. * @since 1.1.6
  1035. */
  1036. public function getUnion()
  1037. {
  1038. return isset($this->_query['union']) ? $this->_query['union'] : '';
  1039. }
  1040. /**
  1041. * Sets the UNION part in the query.
  1042. * @param mixed $value the UNION part. This can be either a string or an array
  1043. * representing multiple SQL statements to be unioned together.
  1044. * @since 1.1.6
  1045. */
  1046. public function setUnion($value)
  1047. {
  1048. $this->_query['union']=$value;
  1049. }
  1050. /**
  1051. * Creates and executes an INSERT SQL statement.
  1052. * The method will properly escape the column names, and bind the values to be inserted.
  1053. * @param string $table the table that new rows will be inserted into.
  1054. * @param array $columns the column data (name=>value) to be inserted into the table.
  1055. * @return integer number of rows affected by the execution.
  1056. * @since 1.1.6
  1057. */
  1058. public function insert($table, $columns)
  1059. {
  1060. $params=array();
  1061. $names=array();
  1062. $placeholders=array();
  1063. foreach($columns as $name=>$value)
  1064. {
  1065. $names[]=$this->_connection->quoteColumnName($name);
  1066. if($value instanceof CDbExpression)
  1067. {
  1068. $placeholders[] = $value->expression;
  1069. foreach($value->params as $n => $v)
  1070. $params[$n] = $v;
  1071. }
  1072. else
  1073. {
  1074. $placeholders[] = ':' . $name;
  1075. $params[':' . $name] = $value;
  1076. }
  1077. }
  1078. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  1079. . ' (' . implode(', ',$names) . ') VALUES ('
  1080. . implode(', ', $placeholders) . ')';
  1081. return $this->setText($sql)->execute($params);
  1082. }
  1083. /**
  1084. * Creates and executes an UPDATE SQL statement.
  1085. * The method will properly escape the column names and bind the values to be updated.
  1086. * @param string $table the table to be updated.
  1087. * @param array $columns the column data (name=>value) to be updated.
  1088. * @param mixed $conditions the conditions that will be put in the WHERE part. Please
  1089. * refer to {@link where} on how to specify conditions.
  1090. * @param array $params the parameters to be bound to the query.
  1091. * @return integer number of rows affected by the execution.
  1092. * @since 1.1.6
  1093. */
  1094. public function update($table, $columns, $conditions='', $params=array())
  1095. {
  1096. $lines=array();
  1097. foreach($columns as $name=>$value)
  1098. {
  1099. if($value instanceof CDbExpression)
  1100. {
  1101. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  1102. foreach($value->params as $n => $v)
  1103. $params[$n] = $v;
  1104. }
  1105. else
  1106. {
  1107. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  1108. $params[':' . $name]=$value;
  1109. }
  1110. }
  1111. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  1112. if(($where=$this->processConditions($conditions))!='')
  1113. $sql.=' WHERE '.$where;
  1114. return $this->setText($sql)->execute($params);
  1115. }
  1116. /**
  1117. * Creates and executes a DELETE SQL statement.
  1118. * @param string $table the table where the data will be deleted from.
  1119. * @param mixed $conditions the conditions that will be put in the WHERE part. Please
  1120. * refer to {@link where} on how to specify conditions.
  1121. * @param array $params the parameters to be bound to the query.
  1122. * @return integer number of rows affected by the execution.
  1123. * @since 1.1.6
  1124. */
  1125. public function delete($table, $conditions='', $params=array())
  1126. {
  1127. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  1128. if(($where=$this->processConditions($conditions))!='')
  1129. $sql.=' WHERE '.$where;
  1130. return $this->setText($sql)->execute($params);
  1131. }
  1132. /**
  1133. * Builds and executes a SQL statement for creating a new DB table.
  1134. *
  1135. * The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
  1136. * where name stands for a column name which will be properly quoted by the method, and definition
  1137. * stands for the column type which can contain an abstract DB type.
  1138. * The {@link getColumnType} method will be invoked to convert any abstract type into a physical one.
  1139. *
  1140. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  1141. * inserted into the generated SQL.
  1142. *
  1143. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  1144. * @param array $columns the columns (name=>definition) in the new table.
  1145. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  1146. * @return integer number of rows affected by the execution.
  1147. * @since 1.1.6
  1148. */
  1149. public function createTable($table, $columns, $options=null)
  1150. {
  1151. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  1152. }
  1153. /**
  1154. * Builds and executes a SQL statement for renaming a DB table.
  1155. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  1156. * @param string $newName the new table name. The name will be properly quoted by the method.
  1157. * @return integer number of rows affected by the execution.
  1158. * @since 1.1.6
  1159. */
  1160. public function renameTable($table, $newName)
  1161. {
  1162. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  1163. }
  1164. /**
  1165. * Builds and executes a SQL statement for dropping a DB table.
  1166. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  1167. * @return integer number of rows affected by the execution.
  1168. * @since 1.1.6
  1169. */
  1170. public function dropTable($table)
  1171. {
  1172. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  1173. }
  1174. /**
  1175. * Builds and executes a SQL statement for truncating a DB table.
  1176. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  1177. * @return integer number of rows affected by the execution.
  1178. * @since 1.1.6
  1179. */
  1180. public function truncateTable($table)
  1181. {
  1182. $schema=$this->getConnection()->getSchema();
  1183. $n=$this->setText($schema->truncateTable($table))->execute();
  1184. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  1185. $schema->resetSequence($schema->getTable($table));
  1186. return $n;
  1187. }
  1188. /**
  1189. * Builds and executes a SQL statement for adding a new DB column.
  1190. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  1191. * @param string $column the name of the new column. The name will be properly quoted by the method.
  1192. * @param string $type the column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
  1193. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  1194. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  1195. * @return integer number of rows affected by the execution.
  1196. * @since 1.1.6
  1197. */
  1198. public function addColumn($table, $column, $type)
  1199. {
  1200. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  1201. }
  1202. /**
  1203. * Builds and executes a SQL statement for dropping a DB column.
  1204. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  1205. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  1206. * @return integer number of rows affected by the execution.
  1207. * @since 1.1.6
  1208. */
  1209. public function dropColumn($table, $column)
  1210. {
  1211. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  1212. }
  1213. /**
  1214. * Builds and executes a SQL statement for renaming a column.
  1215. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  1216. * @param string $name the old name of the column. The name will be properly quoted by the method.
  1217. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  1218. * @return integer number of rows affected by the execution.
  1219. * @since 1.1.6
  1220. */
  1221. public function renameColumn($table, $name, $newName)
  1222. {
  1223. return $this->setT