CDbCommandBuilder.php 30 KB

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