PageRenderTime 56ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/db/schema/CDbCommandBuilder.php

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