PageRenderTime 40ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/db/schema/CDbCommandBuilder.php

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