PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/db/schema/CDbCommandBuilder.php

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