PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/a10/lib/yii-1.1.10/db/schema/CDbCommandBuilder.php

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