PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/db/schema/CDbCommandBuilder.php

https://bitbucket.org/rezanachmad/php-selenium-training
PHP | 756 lines | 502 code | 47 blank | 207 comment | 72 complexity | 849453dfe164e73ac39783b61315a820 MD5 | raw file
  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. * @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. * @return CDbCommand update command.
  239. */
  240. public function createUpdateCommand($table,$data,$criteria)
  241. {
  242. $this->ensureTable($table);
  243. $fields=array();
  244. $values=array();
  245. $bindByPosition=isset($criteria->params[0]);
  246. $i=0;
  247. foreach($data as $name=>$value)
  248. {
  249. if(($column=$table->getColumn($name))!==null)
  250. {
  251. if($value instanceof CDbExpression)
  252. {
  253. $fields[]=$column->rawName.'='.$value->expression;
  254. foreach($value->params as $n=>$v)
  255. $values[$n]=$v;
  256. }
  257. elseif($bindByPosition)
  258. {
  259. $fields[]=$column->rawName.'=?';
  260. $values[]=$column->typecast($value);
  261. }
  262. else
  263. {
  264. $fields[]=$column->rawName.'='.self::PARAM_PREFIX.$i;
  265. $values[self::PARAM_PREFIX.$i]=$column->typecast($value);
  266. $i++;
  267. }
  268. }
  269. }
  270. if($fields===array())
  271. throw new CDbException(Yii::t('yii','No columns are being updated for table "{table}".',
  272. array('{table}'=>$table->name)));
  273. $sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
  274. $sql=$this->applyJoin($sql,$criteria->join);
  275. $sql=$this->applyCondition($sql,$criteria->condition);
  276. $sql=$this->applyOrder($sql,$criteria->order);
  277. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  278. $command=$this->_connection->createCommand($sql);
  279. $this->bindValues($command,array_merge($values,$criteria->params));
  280. return $command;
  281. }
  282. /**
  283. * Creates an UPDATE command that increments/decrements certain columns.
  284. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  285. * @param array $counters counters to be updated (counter increments/decrements indexed by column names.)
  286. * @param CDbCriteria $criteria the query criteria
  287. * @return CDbCommand the created command
  288. * @throws CException if no counter is specified
  289. */
  290. public function createUpdateCounterCommand($table,$counters,$criteria)
  291. {
  292. $this->ensureTable($table);
  293. $fields=array();
  294. foreach($counters as $name=>$value)
  295. {
  296. if(($column=$table->getColumn($name))!==null)
  297. {
  298. $value=(float)$value;
  299. if($value<0)
  300. $fields[]="{$column->rawName}={$column->rawName}-".(-$value);
  301. else
  302. $fields[]="{$column->rawName}={$column->rawName}+".$value;
  303. }
  304. }
  305. if($fields!==array())
  306. {
  307. $sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
  308. $sql=$this->applyJoin($sql,$criteria->join);
  309. $sql=$this->applyCondition($sql,$criteria->condition);
  310. $sql=$this->applyOrder($sql,$criteria->order);
  311. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  312. $command=$this->_connection->createCommand($sql);
  313. $this->bindValues($command,$criteria->params);
  314. return $command;
  315. }
  316. else
  317. throw new CDbException(Yii::t('yii','No counter columns are being updated for table "{table}".',
  318. array('{table}'=>$table->name)));
  319. }
  320. /**
  321. * Creates a command based on a given SQL statement.
  322. * @param string $sql the explicitly specified SQL statement
  323. * @param array $params parameters that will be bound to the SQL statement
  324. * @return CDbCommand the created command
  325. */
  326. public function createSqlCommand($sql,$params=array())
  327. {
  328. $command=$this->_connection->createCommand($sql);
  329. $this->bindValues($command,$params);
  330. return $command;
  331. }
  332. /**
  333. * Alters the SQL to apply JOIN clause.
  334. * @param string $sql the SQL statement to be altered
  335. * @param string $join the JOIN clause (starting with join type, such as INNER JOIN)
  336. * @return string the altered SQL statement
  337. */
  338. public function applyJoin($sql,$join)
  339. {
  340. if($join!='')
  341. return $sql.' '.$join;
  342. else
  343. return $sql;
  344. }
  345. /**
  346. * Alters the SQL to apply WHERE clause.
  347. * @param string $sql the SQL statement without WHERE clause
  348. * @param string $condition the WHERE clause (without WHERE keyword)
  349. * @return string the altered SQL statement
  350. */
  351. public function applyCondition($sql,$condition)
  352. {
  353. if($condition!='')
  354. return $sql.' WHERE '.$condition;
  355. else
  356. return $sql;
  357. }
  358. /**
  359. * Alters the SQL to apply ORDER BY.
  360. * @param string $sql SQL statement without ORDER BY.
  361. * @param string $orderBy column ordering
  362. * @return string modified SQL applied with ORDER BY.
  363. */
  364. public function applyOrder($sql,$orderBy)
  365. {
  366. if($orderBy!='')
  367. return $sql.' ORDER BY '.$orderBy;
  368. else
  369. return $sql;
  370. }
  371. /**
  372. * Alters the SQL to apply LIMIT and OFFSET.
  373. * Default implementation is applicable for PostgreSQL, MySQL and SQLite.
  374. * @param string $sql SQL query string without LIMIT and OFFSET.
  375. * @param integer $limit maximum number of rows, -1 to ignore limit.
  376. * @param integer $offset row offset, -1 to ignore offset.
  377. * @return string SQL with LIMIT and OFFSET
  378. */
  379. public function applyLimit($sql,$limit,$offset)
  380. {
  381. if($limit>=0)
  382. $sql.=' LIMIT '.(int)$limit;
  383. if($offset>0)
  384. $sql.=' OFFSET '.(int)$offset;
  385. return $sql;
  386. }
  387. /**
  388. * Alters the SQL to apply GROUP BY.
  389. * @param string $sql SQL query string without GROUP BY.
  390. * @param string $group GROUP BY
  391. * @return string SQL with GROUP BY.
  392. */
  393. public function applyGroup($sql,$group)
  394. {
  395. if($group!='')
  396. return $sql.' GROUP BY '.$group;
  397. else
  398. return $sql;
  399. }
  400. /**
  401. * Alters the SQL to apply HAVING.
  402. * @param string $sql SQL query string without HAVING
  403. * @param string $having HAVING
  404. * @return string SQL with HAVING
  405. */
  406. public function applyHaving($sql,$having)
  407. {
  408. if($having!='')
  409. return $sql.' HAVING '.$having;
  410. else
  411. return $sql;
  412. }
  413. /**
  414. * Binds parameter values for an SQL command.
  415. * @param CDbCommand $command database command
  416. * @param array $values values for binding (integer-indexed array for question mark placeholders, string-indexed array for named placeholders)
  417. */
  418. public function bindValues($command, $values)
  419. {
  420. if(($n=count($values))===0)
  421. return;
  422. if(isset($values[0])) // question mark placeholders
  423. {
  424. for($i=0;$i<$n;++$i)
  425. $command->bindValue($i+1,$values[$i]);
  426. }
  427. else // named placeholders
  428. {
  429. foreach($values as $name=>$value)
  430. {
  431. if($name[0]!==':')
  432. $name=':'.$name;
  433. $command->bindValue($name,$value);
  434. }
  435. }
  436. }
  437. /**
  438. * Creates a query criteria.
  439. * @param mixed $condition query condition or criteria.
  440. * If a string, it is treated as query condition (the WHERE clause);
  441. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria} object;
  442. * Otherwise, it should be an instance of {@link CDbCriteria}.
  443. * @param array $params parameters to be bound to an SQL statement.
  444. * This is only used when the first parameter is a string (query condition).
  445. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  446. * @return CDbCriteria the created query criteria
  447. * @throws CException if the condition is not string, array and CDbCriteria
  448. */
  449. public function createCriteria($condition='',$params=array())
  450. {
  451. if(is_array($condition))
  452. $criteria=new CDbCriteria($condition);
  453. elseif($condition instanceof CDbCriteria)
  454. $criteria=clone $condition;
  455. else
  456. {
  457. $criteria=new CDbCriteria;
  458. $criteria->condition=$condition;
  459. $criteria->params=$params;
  460. }
  461. return $criteria;
  462. }
  463. /**
  464. * Creates a query criteria with the specified primary key.
  465. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  466. * @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).
  467. * @param mixed $condition query condition or criteria.
  468. * If a string, it is treated as query condition;
  469. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria};
  470. * Otherwise, it should be an instance of {@link CDbCriteria}.
  471. * @param array $params parameters to be bound to an SQL statement.
  472. * This is only used when the second parameter is a string (query condition).
  473. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  474. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  475. * @return CDbCriteria the created query criteria
  476. */
  477. public function createPkCriteria($table,$pk,$condition='',$params=array(),$prefix=null)
  478. {
  479. $this->ensureTable($table);
  480. $criteria=$this->createCriteria($condition,$params);
  481. if($criteria->alias!='')
  482. $prefix=$this->_schema->quoteTableName($criteria->alias).'.';
  483. if(!is_array($pk)) // single key
  484. $pk=array($pk);
  485. if(is_array($table->primaryKey) && !isset($pk[0]) && $pk!==array()) // single composite key
  486. $pk=array($pk);
  487. $condition=$this->createInCondition($table,$table->primaryKey,$pk,$prefix);
  488. if($criteria->condition!='')
  489. $criteria->condition=$condition.' AND ('.$criteria->condition.')';
  490. else
  491. $criteria->condition=$condition;
  492. return $criteria;
  493. }
  494. /**
  495. * Generates the expression for selecting rows of specified primary key values.
  496. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  497. * @param array $values list of primary key values to be selected within
  498. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  499. * @return string the expression for selection
  500. */
  501. public function createPkCondition($table,$values,$prefix=null)
  502. {
  503. $this->ensureTable($table);
  504. return $this->createInCondition($table,$table->primaryKey,$values,$prefix);
  505. }
  506. /**
  507. * Creates a query criteria with the specified column values.
  508. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  509. * @param array $columns column values that should be matched in the query (name=>value)
  510. * @param mixed $condition query condition or criteria.
  511. * If a string, it is treated as query condition;
  512. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria};
  513. * Otherwise, it should be an instance of {@link CDbCriteria}.
  514. * @param array $params parameters to be bound to an SQL statement.
  515. * This is only used when the third parameter is a string (query condition).
  516. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  517. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  518. * @return CDbCriteria the created query criteria
  519. */
  520. public function createColumnCriteria($table,$columns,$condition='',$params=array(),$prefix=null)
  521. {
  522. $this->ensureTable($table);
  523. $criteria=$this->createCriteria($condition,$params);
  524. if($criteria->alias!='')
  525. $prefix=$this->_schema->quoteTableName($criteria->alias).'.';
  526. $bindByPosition=isset($criteria->params[0]);
  527. $conditions=array();
  528. $values=array();
  529. $i=0;
  530. if($prefix===null)
  531. $prefix=$table->rawName.'.';
  532. foreach($columns as $name=>$value)
  533. {
  534. if(($column=$table->getColumn($name))!==null)
  535. {
  536. if(is_array($value))
  537. $conditions[]=$this->createInCondition($table,$name,$value,$prefix);
  538. elseif($value!==null)
  539. {
  540. if($bindByPosition)
  541. {
  542. $conditions[]=$prefix.$column->rawName.'=?';
  543. $values[]=$value;
  544. }
  545. else
  546. {
  547. $conditions[]=$prefix.$column->rawName.'='.self::PARAM_PREFIX.$i;
  548. $values[self::PARAM_PREFIX.$i]=$value;
  549. $i++;
  550. }
  551. }
  552. else
  553. $conditions[]=$prefix.$column->rawName.' IS NULL';
  554. }
  555. else
  556. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  557. array('{table}'=>$table->name,'{column}'=>$name)));
  558. }
  559. $criteria->params=array_merge($values,$criteria->params);
  560. if(isset($conditions[0]))
  561. {
  562. if($criteria->condition!='')
  563. $criteria->condition=implode(' AND ',$conditions).' AND ('.$criteria->condition.')';
  564. else
  565. $criteria->condition=implode(' AND ',$conditions);
  566. }
  567. return $criteria;
  568. }
  569. /**
  570. * Generates the expression for searching the specified keywords within a list of columns.
  571. * The search expression is generated using the 'LIKE' SQL syntax.
  572. * Every word in the keywords must be present and appear in at least one of the columns.
  573. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  574. * @param array $columns list of column names for potential search condition.
  575. * @param mixed $keywords search keywords. This can be either a string with space-separated keywords or an array of keywords.
  576. * @param string $prefix optional column prefix (with dot at the end). If null, the table name will be used as the prefix.
  577. * @param boolean $caseSensitive whether the search is case-sensitive. Defaults to true.
  578. * @return string SQL search condition matching on a set of columns. An empty string is returned
  579. * if either the column array or the keywords are empty.
  580. */
  581. public function createSearchCondition($table,$columns,$keywords,$prefix=null,$caseSensitive=true)
  582. {
  583. $this->ensureTable($table);
  584. if(!is_array($keywords))
  585. $keywords=preg_split('/\s+/u',$keywords,-1,PREG_SPLIT_NO_EMPTY);
  586. if(empty($keywords))
  587. return '';
  588. if($prefix===null)
  589. $prefix=$table->rawName.'.';
  590. $conditions=array();
  591. foreach($columns as $name)
  592. {
  593. if(($column=$table->getColumn($name))===null)
  594. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  595. array('{table}'=>$table->name,'{column}'=>$name)));
  596. $condition=array();
  597. foreach($keywords as $keyword)
  598. {
  599. $keyword='%'.strtr($keyword,array('%'=>'\%', '_'=>'\_')).'%';
  600. if($caseSensitive)
  601. $condition[]=$prefix.$column->rawName.' LIKE '.$this->_connection->quoteValue('%'.$keyword.'%');
  602. else
  603. $condition[]='LOWER('.$prefix.$column->rawName.') LIKE LOWER('.$this->_connection->quoteValue('%'.$keyword.'%').')';
  604. }
  605. $conditions[]=implode(' AND ',$condition);
  606. }
  607. return '('.implode(' OR ',$conditions).')';
  608. }
  609. /**
  610. * Generates the expression for selecting rows of specified primary key values.
  611. * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
  612. * @param mixed $columnName the column name(s). It can be either a string indicating a single column
  613. * or an array of column names. If the latter, it stands for a composite key.
  614. * @param array $values list of key values to be selected within
  615. * @param string $prefix column prefix (ended with dot). If null, it will be the table name
  616. * @return string the expression for selection
  617. */
  618. public function createInCondition($table,$columnName,$values,$prefix=null)
  619. {
  620. if(($n=count($values))<1)
  621. return '0=1';
  622. $this->ensureTable($table);
  623. if($prefix===null)
  624. $prefix=$table->rawName.'.';
  625. $db=$this->_connection;
  626. if(is_array($columnName) && count($columnName)===1)
  627. $columnName=reset($columnName);
  628. if(is_string($columnName)) // simple key
  629. {
  630. if(!isset($table->columns[$columnName]))
  631. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  632. array('{table}'=>$table->name, '{column}'=>$columnName)));
  633. $column=$table->columns[$columnName];
  634. foreach($values as &$value)
  635. {
  636. $value=$column->typecast($value);
  637. if(is_string($value))
  638. $value=$db->quoteValue($value);
  639. }
  640. if($n===1)
  641. return $prefix.$column->rawName.($values[0]===null?' IS NULL':'='.$values[0]);
  642. else
  643. return $prefix.$column->rawName.' IN ('.implode(', ',$values).')';
  644. }
  645. elseif(is_array($columnName)) // composite key: $values=array(array('pk1'=>'v1','pk2'=>'v2'),array(...))
  646. {
  647. foreach($columnName as $name)
  648. {
  649. if(!isset($table->columns[$name]))
  650. throw new CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
  651. array('{table}'=>$table->name, '{column}'=>$name)));
  652. for($i=0;$i<$n;++$i)
  653. {
  654. if(isset($values[$i][$name]))
  655. {
  656. $value=$table->columns[$name]->typecast($values[$i][$name]);
  657. if(is_string($value))
  658. $values[$i][$name]=$db->quoteValue($value);
  659. else
  660. $values[$i][$name]=$value;
  661. }
  662. else
  663. throw new CDbException(Yii::t('yii','The value for the column "{column}" is not supplied when querying the table "{table}".',
  664. array('{table}'=>$table->name,'{column}'=>$name)));
  665. }
  666. }
  667. if(count($values)===1)
  668. {
  669. $entries=array();
  670. foreach($values[0] as $name=>$value)
  671. $entries[]=$prefix.$table->columns[$name]->rawName.($value===null?' IS NULL':'='.$value);
  672. return implode(' AND ',$entries);
  673. }
  674. return $this->createCompositeInCondition($table,$values,$prefix);
  675. }
  676. else
  677. throw new CDbException(Yii::t('yii','Column name must be either a string or an array.'));
  678. }
  679. /**
  680. * Generates the expression for selecting rows with specified composite key values.
  681. * @param CDbTableSchema $table the table schema
  682. * @param array $values list of primary key values to be selected within
  683. * @param string $prefix column prefix (ended with dot)
  684. * @return string the expression for selection
  685. */
  686. protected function createCompositeInCondition($table,$values,$prefix)
  687. {
  688. $keyNames=array();
  689. foreach(array_keys($values[0]) as $name)
  690. $keyNames[]=$prefix.$table->columns[$name]->rawName;
  691. $vs=array();
  692. foreach($values as $value)
  693. $vs[]='('.implode(', ',$value).')';
  694. return '('.implode(', ',$keyNames).') IN ('.implode(', ',$vs).')';
  695. }
  696. /**
  697. * Checks if the parameter is a valid table schema.
  698. * If it is a string, the corresponding table schema will be retrieved.
  699. * @param mixed $table table schema ({@link CDbTableSchema}) or table name (string).
  700. * If this refers to a valid table name, this parameter will be returned with the corresponding table schema.
  701. * @throws CDbException if the table name is not valid
  702. */
  703. protected function ensureTable(&$table)
  704. {
  705. if(is_string($table) && ($table=$this->_schema->getTable($tableName=$table))===null)
  706. throw new CDbException(Yii::t('yii','Table "{table}" does not exist.',
  707. array('{table}'=>$tableName)));
  708. }
  709. }