PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/db/schema/CDbCommandBuilder.php

https://bitbucket.org/dinhtrung/yiicorecms/
PHP | 737 lines | 484 code | 45 blank | 208 comment | 78 complexity | 0c8d46cd9704ae8a414e936b8b1f0712 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, CC0-1.0, BSD-2-Clause, GPL-2.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. /**
  3. * CDbCommandBuilder class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CDbCommandBuilder provides basic methods to create query commands for tables.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @version $Id: CDbCommandBuilder.php 3001 2011-02-24 16:42:44Z alexander.makarow $
  15. * @package system.db.schema
  16. * @since 1.0
  17. */
  18. class CDbCommandBuilder extends CComponent
  19. {
  20. const PARAM_PREFIX=':yp';
  21. private $_schema;
  22. private $_connection;
  23. /**
  24. * @param CDbSchema $schema the schema for this command builder
  25. */
  26. public function __construct($schema)
  27. {
  28. $this->_schema=$schema;
  29. $this->_connection=$schema->getDbConnection();
  30. }
  31. /**
  32. * @return CDbConnection database connection.
  33. */
  34. public function getDbConnection()
  35. {
  36. return $this->_connection;
  37. }
  38. /**
  39. * @return CDbSchema the schema for this command builder.
  40. */
  41. public function getSchema()
  42. {
  43. return $this->_schema;
  44. }
  45. /**
  46. * Returns the last insertion ID for the specified table.
  47. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  48. * @return mixed last insertion id. Null is returned if no sequence name.
  49. */
  50. public function getLastInsertID($table)
  51. {
  52. $this->ensureTable($table);
  53. if($table->sequenceName!==null)
  54. return $this->_connection->getLastInsertID($table->sequenceName);
  55. else
  56. return null;
  57. }
  58. /**
  59. * Creates a SELECT command for a single table.
  60. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  61. * @param CDbCriteria $criteria the query criteria
  62. * @param string $alias the alias name of the primary table. Defaults to 't'.
  63. * @return CDbCommand query command.
  64. */
  65. public function createFindCommand($table,$criteria,$alias='t')
  66. {
  67. $this->ensureTable($table);
  68. $select=is_array($criteria->select) ? implode(', ',$criteria->select) : $criteria->select;
  69. if($criteria->alias!='')
  70. $alias=$criteria->alias;
  71. $alias=$this->_schema->quoteTableName($alias);
  72. // issue 1432: need to expand * when SQL has JOIN
  73. if($select==='*' && !empty($criteria->join))
  74. {
  75. $prefix=$alias.'.';
  76. $select=array();
  77. foreach($table->getColumnNames() as $name)
  78. $select[]=$prefix.$this->_schema->quoteColumnName($name);
  79. $select=implode(', ',$select);
  80. }
  81. $sql=($criteria->distinct ? 'SELECT DISTINCT':'SELECT')." {$select} FROM {$table->rawName} $alias";
  82. $sql=$this->applyJoin($sql,$criteria->join);
  83. $sql=$this->applyCondition($sql,$criteria->condition);
  84. $sql=$this->applyGroup($sql,$criteria->group);
  85. $sql=$this->applyHaving($sql,$criteria->having);
  86. $sql=$this->applyOrder($sql,$criteria->order);
  87. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  88. $command=$this->_connection->createCommand($sql);
  89. $this->bindValues($command,$criteria->params);
  90. return $command;
  91. }
  92. /**
  93. * Creates a COUNT(*) command for a single table.
  94. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  95. * @param CDbCriteria $criteria the query criteria
  96. * @param string $alias the alias name of the primary table. Defaults to 't'.
  97. * @return CDbCommand query command.
  98. */
  99. public function createCountCommand($table,$criteria,$alias='t')
  100. {
  101. $this->ensureTable($table);
  102. if($criteria->alias!='')
  103. $alias=$criteria->alias;
  104. $alias=$this->_schema->quoteTableName($alias);
  105. if(!empty($criteria->group) || !empty($criteria->having))
  106. {
  107. $select=is_array($criteria->select) ? implode(', ',$criteria->select) : $criteria->select;
  108. if($criteria->alias!='')
  109. $alias=$criteria->alias;
  110. $sql=($criteria->distinct ? 'SELECT DISTINCT':'SELECT')." {$select} FROM {$table->rawName} $alias";
  111. $sql=$this->applyJoin($sql,$criteria->join);
  112. $sql=$this->applyCondition($sql,$criteria->condition);
  113. $sql=$this->applyGroup($sql,$criteria->group);
  114. $sql=$this->applyHaving($sql,$criteria->having);
  115. $sql="SELECT COUNT(*) FROM ($sql) sq";
  116. }
  117. else
  118. {
  119. if(is_string($criteria->select) && stripos($criteria->select,'count')===0)
  120. $sql="SELECT ".$criteria->select;
  121. else if($criteria->distinct)
  122. {
  123. if(is_array($table->primaryKey))
  124. {
  125. $pk=array();
  126. foreach($table->primaryKey as $key)
  127. $pk[]=$alias.'.'.$key;
  128. $pk=implode(', ',$pk);
  129. }
  130. else
  131. $pk=$alias.'.'.$table->primaryKey;
  132. $sql="SELECT COUNT(DISTINCT $pk)";
  133. }
  134. else
  135. $sql="SELECT COUNT(*)";
  136. $sql.=" FROM {$table->rawName} $alias";
  137. $sql=$this->applyJoin($sql,$criteria->join);
  138. $sql=$this->applyCondition($sql,$criteria->condition);
  139. }
  140. $command=$this->_connection->createCommand($sql);
  141. $this->bindValues($command,$criteria->params);
  142. return $command;
  143. }
  144. /**
  145. * Creates a DELETE command.
  146. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  147. * @param CDbCriteria $criteria the query criteria
  148. * @return CDbCommand delete command.
  149. */
  150. public function createDeleteCommand($table,$criteria)
  151. {
  152. $this->ensureTable($table);
  153. $sql="DELETE FROM {$table->rawName}";
  154. $sql=$this->applyJoin($sql,$criteria->join);
  155. $sql=$this->applyCondition($sql,$criteria->condition);
  156. $sql=$this->applyGroup($sql,$criteria->group);
  157. $sql=$this->applyHaving($sql,$criteria->having);
  158. $sql=$this->applyOrder($sql,$criteria->order);
  159. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  160. $command=$this->_connection->createCommand($sql);
  161. $this->bindValues($command,$criteria->params);
  162. return $command;
  163. }
  164. /**
  165. * Creates an INSERT command.
  166. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  167. * @param array $data data to be inserted (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
  168. * @return CDbCommand insert command
  169. */
  170. public function createInsertCommand($table,$data)
  171. {
  172. $this->ensureTable($table);
  173. $fields=array();
  174. $values=array();
  175. $placeholders=array();
  176. $i=0;
  177. foreach($data as $name=>$value)
  178. {
  179. if(($column=$table->getColumn($name))!==null && ($value!==null || $column->allowNull))
  180. {
  181. $fields[]=$column->rawName;
  182. if($value instanceof CDbExpression)
  183. {
  184. $placeholders[]=$value->expression;
  185. foreach($value->params as $n=>$v)
  186. $values[$n]=$v;
  187. }
  188. else
  189. {
  190. $placeholders[]=self::PARAM_PREFIX.$i;
  191. $values[self::PARAM_PREFIX.$i]=$column->typecast($value);
  192. $i++;
  193. }
  194. }
  195. }
  196. if($fields===array())
  197. {
  198. $pks=is_array($table->primaryKey) ? $table->primaryKey : array($table->primaryKey);
  199. foreach($pks as $pk)
  200. {
  201. $fields[]=$table->getColumn($pk)->rawName;
  202. $placeholders[]='NULL';
  203. }
  204. }
  205. $sql="INSERT INTO {$table->rawName} (".implode(', ',$fields).') VALUES ('.implode(', ',$placeholders).')';
  206. $command=$this->_connection->createCommand($sql);
  207. foreach($values as $name=>$value)
  208. $command->bindValue($name,$value);
  209. return $command;
  210. }
  211. /**
  212. * Creates an UPDATE command.
  213. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  214. * @param array $data list of columns to be updated (name=>value)
  215. * @param CDbCriteria $criteria the query criteria
  216. * @return CDbCommand update command.
  217. */
  218. public function createUpdateCommand($table,$data,$criteria)
  219. {
  220. $this->ensureTable($table);
  221. $fields=array();
  222. $values=array();
  223. $bindByPosition=isset($criteria->params[0]);
  224. $i=0;
  225. foreach($data as $name=>$value)
  226. {
  227. if(($column=$table->getColumn($name))!==null)
  228. {
  229. if($value instanceof CDbExpression)
  230. {
  231. $fields[]=$column->rawName.'='.$value->expression;
  232. foreach($value->params as $n=>$v)
  233. $values[$n]=$v;
  234. }
  235. else if($bindByPosition)
  236. {
  237. $fields[]=$column->rawName.'=?';
  238. $values[]=$column->typecast($value);
  239. }
  240. else
  241. {
  242. $fields[]=$column->rawName.'='.self::PARAM_PREFIX.$i;
  243. $values[self::PARAM_PREFIX.$i]=$column->typecast($value);
  244. $i++;
  245. }
  246. }
  247. }
  248. if($fields===array())
  249. throw new CDbException(Yii::t('yii','No columns are being updated for table "{table}".',
  250. array('{table}'=>$table->name)));
  251. $sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
  252. $sql=$this->applyJoin($sql,$criteria->join);
  253. $sql=$this->applyCondition($sql,$criteria->condition);
  254. $sql=$this->applyOrder($sql,$criteria->order);
  255. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  256. $command=$this->_connection->createCommand($sql);
  257. $this->bindValues($command,array_merge($values,$criteria->params));
  258. return $command;
  259. }
  260. /**
  261. * Creates an UPDATE command that increments/decrements certain columns.
  262. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  263. * @param array $counters counters to be updated (counter increments/decrements indexed by column names.)
  264. * @param CDbCriteria $criteria the query criteria
  265. * @return CDbCommand the created command
  266. * @throws CException if no counter is specified
  267. */
  268. public function createUpdateCounterCommand($table,$counters,$criteria)
  269. {
  270. $this->ensureTable($table);
  271. $fields=array();
  272. foreach($counters as $name=>$value)
  273. {
  274. if(($column=$table->getColumn($name))!==null)
  275. {
  276. $value=(int)$value;
  277. if($value<0)
  278. $fields[]="{$column->rawName}={$column->rawName}-".(-$value);
  279. else
  280. $fields[]="{$column->rawName}={$column->rawName}+".$value;
  281. }
  282. }
  283. if($fields!==array())
  284. {
  285. $sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
  286. $sql=$this->applyJoin($sql,$criteria->join);
  287. $sql=$this->applyCondition($sql,$criteria->condition);
  288. $sql=$this->applyOrder($sql,$criteria->order);
  289. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  290. $command=$this->_connection->createCommand($sql);
  291. $this->bindValues($command,$criteria->params);
  292. return $command;
  293. }
  294. else
  295. throw new CDbException(Yii::t('yii','No counter columns are being updated for table "{table}".',
  296. array('{table}'=>$table->name)));
  297. }
  298. /**
  299. * Creates a command based on a given SQL statement.
  300. * @param string $sql the explicitly specified SQL statement
  301. * @param array $params parameters that will be bound to the SQL statement
  302. * @return CDbCommand the created command
  303. */
  304. public function createSqlCommand($sql,$params=array())
  305. {
  306. $command=$this->_connection->createCommand($sql);
  307. $this->bindValues($command,$params);
  308. return $command;
  309. }
  310. /**
  311. * Alters the SQL to apply JOIN clause.
  312. * @param string $sql the SQL statement to be altered
  313. * @param string $join the JOIN clause (starting with join type, such as INNER JOIN)
  314. * @return string the altered SQL statement
  315. */
  316. public function applyJoin($sql,$join)
  317. {
  318. if($join!='')
  319. return $sql.' '.$join;
  320. else
  321. return $sql;
  322. }
  323. /**
  324. * Alters the SQL to apply WHERE clause.
  325. * @param string $sql the SQL statement without WHERE clause
  326. * @param string $condition the WHERE clause (without WHERE keyword)
  327. * @return string the altered SQL statement
  328. */
  329. public function applyCondition($sql,$condition)
  330. {
  331. if($condition!='')
  332. return $sql.' WHERE '.$condition;
  333. else
  334. return $sql;
  335. }
  336. /**
  337. * Alters the SQL to apply ORDER BY.
  338. * @param string $sql SQL statement without ORDER BY.
  339. * @param string $orderBy column ordering
  340. * @return string modified SQL applied with ORDER BY.
  341. */
  342. public function applyOrder($sql,$orderBy)
  343. {
  344. if($orderBy!='')
  345. return $sql.' ORDER BY '.$orderBy;
  346. else
  347. return $sql;
  348. }
  349. /**
  350. * Alters the SQL to apply LIMIT and OFFSET.
  351. * Default implementation is applicable for PostgreSQL, MySQL and SQLite.
  352. * @param string $sql SQL query string without LIMIT and OFFSET.
  353. * @param integer $limit maximum number of rows, -1 to ignore limit.
  354. * @param integer $offset row offset, -1 to ignore offset.
  355. * @return string SQL with LIMIT and OFFSET
  356. */
  357. public function applyLimit($sql,$limit,$offset)
  358. {
  359. if($limit>=0)
  360. $sql.=' LIMIT '.(int)$limit;
  361. if($offset>0)
  362. $sql.=' OFFSET '.(int)$offset;
  363. return $sql;
  364. }
  365. /**
  366. * Alters the SQL to apply GROUP BY.
  367. * @param string $sql SQL query string without GROUP BY.
  368. * @param string $group GROUP BY
  369. * @return string SQL with GROUP BY.
  370. */
  371. public function applyGroup($sql,$group)
  372. {
  373. if($group!='')
  374. return $sql.' GROUP BY '.$group;
  375. else
  376. return $sql;
  377. }
  378. /**
  379. * Alters the SQL to apply HAVING.
  380. * @param string $sql SQL query string without HAVING
  381. * @param string $having HAVING
  382. * @return string SQL with HAVING
  383. * @since 1.0.1
  384. */
  385. public function applyHaving($sql,$having)
  386. {
  387. if($having!='')
  388. return $sql.' HAVING '.$having;
  389. else
  390. return $sql;
  391. }
  392. /**
  393. * Binds parameter values for an SQL command.
  394. * @param CDbCommand $command database command
  395. * @param array $values values for binding (integer-indexed array for question mark placeholders, string-indexed array for named placeholders)
  396. */
  397. public function bindValues($command, $values)
  398. {
  399. if(($n=count($values))===0)
  400. return;
  401. if(isset($values[0])) // question mark placeholders
  402. {
  403. for($i=0;$i<$n;++$i)
  404. $command->bindValue($i+1,$values[$i]);
  405. }
  406. else // named placeholders
  407. {
  408. foreach($values as $name=>$value)
  409. {
  410. if($name[0]!==':')
  411. $name=':'.$name;
  412. $command->bindValue($name,$value);
  413. }
  414. }
  415. }
  416. /**
  417. * Creates a query criteria.
  418. * @param mixed $condition query condition or criteria.
  419. * If a string, it is treated as query condition (the WHERE clause);
  420. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria} object;
  421. * Otherwise, it should be an instance of {@link CDbCriteria}.
  422. * @param array $params parameters to be bound to an SQL statement.
  423. * This is only used when the first parameter is a string (query condition).
  424. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  425. * @return CDbCriteria the created query criteria
  426. * @throws CException if the condition is not string, array and CDbCriteria
  427. */
  428. public function createCriteria($condition='',$params=array())
  429. {
  430. if(is_array($condition))
  431. $criteria=new CDbCriteria($condition);
  432. else if($condition instanceof CDbCriteria)
  433. $criteria=clone $condition;
  434. else
  435. {
  436. $criteria=new CDbCriteria;
  437. $criteria->condition=$condition;
  438. $criteria->params=$params;
  439. }
  440. return $criteria;
  441. }
  442. /**
  443. * Creates a query criteria with the specified primary key.
  444. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  445. * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
  446. * @param mixed $condition query condition or criteria.
  447. * If a string, it is treated as query condition;
  448. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria};
  449. * Otherwise, it should be an instance of {@link CDbCriteria}.
  450. * @param array $params parameters to be bound to an SQL statement.
  451. * This is only used when the second parameter is a string (query condition).
  452. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  453. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  454. * @return CDbCriteria the created query criteria
  455. */
  456. public function createPkCriteria($table,$pk,$condition='',$params=array(),$prefix=null)
  457. {
  458. $this->ensureTable($table);
  459. $criteria=$this->createCriteria($condition,$params);
  460. if($criteria->alias!='')
  461. $prefix=$this->_schema->quoteTableName($criteria->alias).'.';
  462. if(!is_array($pk)) // single key
  463. $pk=array($pk);
  464. if(is_array($table->primaryKey) && !isset($pk[0]) && $pk!==array()) // single composite key
  465. $pk=array($pk);
  466. $condition=$this->createInCondition($table,$table->primaryKey,$pk,$prefix);
  467. if($criteria->condition!='')
  468. $criteria->condition=$condition.' AND ('.$criteria->condition.')';
  469. else
  470. $criteria->condition=$condition;
  471. return $criteria;
  472. }
  473. /**
  474. * Generates the expression for selecting rows of specified primary key values.
  475. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  476. * @param array $values list of primary key values to be selected within
  477. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  478. * @return string the expression for selection
  479. */
  480. public function createPkCondition($table,$values,$prefix=null)
  481. {
  482. $this->ensureTable($table);
  483. return $this->createInCondition($table,$table->primaryKey,$values,$prefix);
  484. }
  485. /**
  486. * Creates a query criteria with the specified column values.
  487. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  488. * @param array $columns column values that should be matched in the query (name=>value)
  489. * @param mixed $condition query condition or criteria.
  490. * If a string, it is treated as query condition;
  491. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria};
  492. * Otherwise, it should be an instance of {@link CDbCriteria}.
  493. * @param array $params parameters to be bound to an SQL statement.
  494. * This is only used when the third parameter is a string (query condition).
  495. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  496. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  497. * @return CDbCriteria the created query criteria
  498. */
  499. public function createColumnCriteria($table,$columns,$condition='',$params=array(),$prefix=null)
  500. {
  501. $this->ensureTable($table);
  502. $criteria=$this->createCriteria($condition,$params);
  503. if($criteria->alias!='')
  504. $prefix=$this->_schema->quoteTableName($criteria->alias).'.';
  505. $bindByPosition=isset($criteria->params[0]);
  506. $conditions=array();
  507. $values=array();
  508. $i=0;
  509. if($prefix===null)
  510. $prefix=$table->rawName.'.';
  511. foreach($columns as $name=>$value)
  512. {
  513. if(($column=$table->getColumn($name))!==null)
  514. {
  515. if(is_array($value))
  516. $conditions[]=$this->createInCondition($table,$name,$value,$prefix);
  517. else if($value!==null)
  518. {
  519. if($bindByPosition)
  520. {
  521. $conditions[]=$prefix.$column->rawName.'=?';
  522. $values[]=$value;
  523. }
  524. else
  525. {
  526. $conditions[]=$prefix.$column->rawName.'='.self::PARAM_PREFIX.$i;
  527. $values[self::PARAM_PREFIX.$i]=$value;
  528. $i++;
  529. }
  530. }
  531. else
  532. $conditions[]=$prefix.$column->rawName.' IS NULL';
  533. }
  534. else
  535. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  536. array('{table}'=>$table->name,'{column}'=>$name)));
  537. }
  538. $criteria->params=array_merge($values,$criteria->params);
  539. if(isset($conditions[0]))
  540. {
  541. if($criteria->condition!='')
  542. $criteria->condition=implode(' AND ',$conditions).' AND ('.$criteria->condition.')';
  543. else
  544. $criteria->condition=implode(' AND ',$conditions);
  545. }
  546. return $criteria;
  547. }
  548. /**
  549. * Generates the expression for searching the specified keywords within a list of columns.
  550. * The search expression is generated using the 'LIKE' SQL syntax.
  551. * Every word in the keywords must be present and appear in at least one of the columns.
  552. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  553. * @param array $columns list of column names for potential search condition.
  554. * @param mixed $keywords search keywords. This can be either a string with space-separated keywords or an array of keywords.
  555. * @param string $prefix optional column prefix (with dot at the end). If null, the table name will be used as the prefix.
  556. * @param boolean $caseSensitive whether the search is case-sensitive. Defaults to true. This parameter
  557. * has been available since version 1.0.4.
  558. * @return string SQL search condition matching on a set of columns. An empty string is returned
  559. * if either the column array or the keywords are empty.
  560. */
  561. public function createSearchCondition($table,$columns,$keywords,$prefix=null,$caseSensitive=true)
  562. {
  563. $this->ensureTable($table);
  564. if(!is_array($keywords))
  565. $keywords=preg_split('/\s+/u',$keywords,-1,PREG_SPLIT_NO_EMPTY);
  566. if(empty($keywords))
  567. return '';
  568. if($prefix===null)
  569. $prefix=$table->rawName.'.';
  570. $conditions=array();
  571. foreach($columns as $name)
  572. {
  573. if(($column=$table->getColumn($name))===null)
  574. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  575. array('{table}'=>$table->name,'{column}'=>$name)));
  576. $condition=array();
  577. foreach($keywords as $keyword)
  578. {
  579. $keyword='%'.strtr($keyword,array('%'=>'\%', '_'=>'\_')).'%';
  580. if($caseSensitive)
  581. $condition[]=$prefix.$column->rawName.' LIKE '.$this->_connection->quoteValue('%'.$keyword.'%');
  582. else
  583. $condition[]='LOWER('.$prefix.$column->rawName.') LIKE LOWER('.$this->_connection->quoteValue('%'.$keyword.'%').')';
  584. }
  585. $conditions[]=implode(' AND ',$condition);
  586. }
  587. return '('.implode(' OR ',$conditions).')';
  588. }
  589. /**
  590. * Generates the expression for selecting rows of specified primary key values.
  591. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  592. * @param mixed $columnName the column name(s). It can be either a string indicating a single column
  593. * or an array of column names. If the latter, it stands for a composite key.
  594. * @param array $values list of key values to be selected within
  595. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  596. * @return string the expression for selection
  597. * @since 1.0.4
  598. */
  599. public function createInCondition($table,$columnName,$values,$prefix=null)
  600. {
  601. if(($n=count($values))<1)
  602. return '0=1';
  603. $this->ensureTable($table);
  604. if($prefix===null)
  605. $prefix=$table->rawName.'.';
  606. $db=$this->_connection;
  607. if(is_array($columnName) && count($columnName)===1)
  608. $columnName=reset($columnName);
  609. if(is_string($columnName)) // simple key
  610. {
  611. if(!isset($table->columns[$columnName]))
  612. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  613. array('{table}'=>$table->name, '{column}'=>$columnName)));
  614. $column=$table->columns[$columnName];
  615. foreach($values as &$value)
  616. {
  617. $value=$column->typecast($value);
  618. if(is_string($value))
  619. $value=$db->quoteValue($value);
  620. }
  621. if($n===1)
  622. return $prefix.$column->rawName.($values[0]===null?' IS NULL':'='.$values[0]);
  623. else
  624. return $prefix.$column->rawName.' IN ('.implode(', ',$values).')';
  625. }
  626. else if(is_array($columnName)) // composite key: $values=array(array('pk1'=>'v1','pk2'=>'v2'),array(...))
  627. {
  628. foreach($columnName as $name)
  629. {
  630. if(!isset($table->columns[$name]))
  631. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  632. array('{table}'=>$table->name, '{column}'=>$name)));
  633. for($i=0;$i<$n;++$i)
  634. {
  635. if(isset($values[$i][$name]))
  636. {
  637. $value=$table->columns[$name]->typecast($values[$i][$name]);
  638. if(is_string($value))
  639. $values[$i][$name]=$db->quoteValue($value);
  640. else
  641. $values[$i][$name]=$value;
  642. }
  643. else
  644. throw new CDbException(Yii::t('yii','The value for the column "{column}" is not supplied when querying the table "{table}".',
  645. array('{table}'=>$table->name,'{column}'=>$name)));
  646. }
  647. }
  648. if(count($values)===1)
  649. {
  650. $entries=array();
  651. foreach($values[0] as $name=>$value)
  652. $entries[]=$prefix.$table->columns[$name]->rawName.($value===null?' IS NULL':'='.$value);
  653. return implode(' AND ',$entries);
  654. }
  655. return $this->createCompositeInCondition($table,$values,$prefix);
  656. }
  657. else
  658. throw new CDbException(Yii::t('yii','Column name must be either a string or an array.'));
  659. }
  660. /**
  661. * Generates the expression for selecting rows with specified composite key values.
  662. * @param CDbTableSchema $table the table schema
  663. * @param array $values list of primary key values to be selected within
  664. * @param string $prefix column prefix (ended with dot)
  665. * @return string the expression for selection
  666. * @since 1.0.4
  667. */
  668. protected function createCompositeInCondition($table,$values,$prefix)
  669. {
  670. $keyNames=array();
  671. foreach(array_keys($values[0]) as $name)
  672. $keyNames[]=$prefix.$table->columns[$name]->rawName;
  673. $vs=array();
  674. foreach($values as $value)
  675. $vs[]='('.implode(', ',$value).')';
  676. return '('.implode(', ',$keyNames).') IN ('.implode(', ',$vs).')';
  677. }
  678. /**
  679. * Checks if the parameter is a valid table schema.
  680. * If it is a string, the corresponding table schema will be retrieved.
  681. * @param mixed $table table schema ({@link CDbTableSchema}) or table name (string).
  682. * If this refers to a valid table name, this parameter will be returned with the corresponding table schema.
  683. * @throws CDbException if the table name is not valid
  684. * @since 1.0.4
  685. */
  686. protected function ensureTable(&$table)
  687. {
  688. if(is_string($table) && ($table=$this->_schema->getTable($tableName=$table))===null)
  689. throw new CDbException(Yii::t('yii','Table "{table}" does not exist.',
  690. array('{table}'=>$tableName)));
  691. }
  692. }