PageRenderTime 185ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 1ms

/yii/framework/db/schema/mssql/CMssqlCommandBuilder.php

https://github.com/joshuaswarren/weatherhub
PHP | 339 lines | 169 code | 18 blank | 152 comment | 24 complexity | 4f1b0a80d9b70888b58ea5f3564f2020 MD5 | raw file
  1. <?php
  2. /**
  3. * CMsCommandBuilder class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @author Christophe Boulain <Christophe.Boulain@gmail.com>
  7. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  8. * @link http://www.yiiframework.com/
  9. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  10. * @license http://www.yiiframework.com/license/
  11. */
  12. /**
  13. * CMssqlCommandBuilder provides basic methods to create query commands for tables for Mssql Servers.
  14. *
  15. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @author Christophe Boulain <Christophe.Boulain@gmail.com>
  17. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  18. * @version $Id: CMssqlCommandBuilder.php 3239 2011-05-25 19:05:47Z qiang.xue $
  19. * @package system.db.schema.mssql
  20. * @since 1.0.4
  21. */
  22. class CMssqlCommandBuilder extends CDbCommandBuilder
  23. {
  24. /**
  25. * Creates a COUNT(*) command for a single table.
  26. * Override parent implementation to remove the order clause of criteria if it exists
  27. * @param CDbTableSchema $table the table metadata
  28. * @param CDbCriteria $criteria the query criteria
  29. * @param string $alias the alias name of the primary table. Defaults to 't'.
  30. * @return CDbCommand query command.
  31. */
  32. public function createCountCommand($table,$criteria,$alias='t')
  33. {
  34. $criteria->order='';
  35. return parent::createCountCommand($table, $criteria,$alias);
  36. }
  37. /**
  38. * Creates a SELECT command for a single table.
  39. * Override parent implementation to check if an orderby clause if specified when querying with an offset
  40. * @param CDbTableSchema $table the table metadata
  41. * @param CDbCriteria $criteria the query criteria
  42. * @param string $alias the alias name of the primary table. Defaults to 't'.
  43. * @return CDbCommand query command.
  44. */
  45. public function createFindCommand($table,$criteria,$alias='t')
  46. {
  47. $criteria=$this->checkCriteria($table,$criteria);
  48. return parent::createFindCommand($table,$criteria,$alias);
  49. }
  50. /**
  51. * Creates an UPDATE command.
  52. * Override parent implementation because mssql don't want to update an identity column
  53. * @param CDbTableSchema $table the table metadata
  54. * @param array $data list of columns to be updated (name=>value)
  55. * @param CDbCriteria $criteria the query criteria
  56. * @return CDbCommand update command.
  57. */
  58. public function createUpdateCommand($table,$data,$criteria)
  59. {
  60. $criteria=$this->checkCriteria($table,$criteria);
  61. $fields=array();
  62. $values=array();
  63. $bindByPosition=isset($criteria->params[0]);
  64. $i=0;
  65. foreach($data as $name=>$value)
  66. {
  67. if(($column=$table->getColumn($name))!==null)
  68. {
  69. if ($table->sequenceName !== null && $column->isPrimaryKey === true) continue;
  70. if ($column->dbType === 'timestamp') continue;
  71. if($value instanceof CDbExpression)
  72. {
  73. $fields[]=$column->rawName.'='.$value->expression;
  74. foreach($value->params as $n=>$v)
  75. $values[$n]=$v;
  76. }
  77. else if($bindByPosition)
  78. {
  79. $fields[]=$column->rawName.'=?';
  80. $values[]=$column->typecast($value);
  81. }
  82. else
  83. {
  84. $fields[]=$column->rawName.'='.self::PARAM_PREFIX.$i;
  85. $values[self::PARAM_PREFIX.$i]=$column->typecast($value);
  86. $i++;
  87. }
  88. }
  89. }
  90. if($fields===array())
  91. throw new CDbException(Yii::t('yii','No columns are being updated for table "{table}".',
  92. array('{table}'=>$table->name)));
  93. $sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
  94. $sql=$this->applyJoin($sql,$criteria->join);
  95. $sql=$this->applyCondition($sql,$criteria->condition);
  96. $sql=$this->applyOrder($sql,$criteria->order);
  97. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  98. $command=$this->getDbConnection()->createCommand($sql);
  99. $this->bindValues($command,array_merge($values,$criteria->params));
  100. return $command;
  101. }
  102. /**
  103. * Creates a DELETE command.
  104. * Override parent implementation to check if an orderby clause if specified when querying with an offset
  105. * @param CDbTableSchema $table the table metadata
  106. * @param CDbCriteria $criteria the query criteria
  107. * @return CDbCommand delete command.
  108. */
  109. public function createDeleteCommand($table,$criteria)
  110. {
  111. $criteria=$this->checkCriteria($table, $criteria);
  112. return parent::createDeleteCommand($table, $criteria);
  113. }
  114. /**
  115. * Creates an UPDATE command that increments/decrements certain columns.
  116. * Override parent implementation to check if an orderby clause if specified when querying with an offset
  117. * @param CDbTableSchema $table the table metadata
  118. * @param CDbCriteria $counters the query criteria
  119. * @param array $criteria counters to be updated (counter increments/decrements indexed by column names.)
  120. * @return CDbCommand the created command
  121. * @throws CException if no counter is specified
  122. */
  123. public function createUpdateCounterCommand($table,$counters,$criteria)
  124. {
  125. $criteria=$this->checkCriteria($table, $criteria);
  126. return parent::createUpdateCounterCommand($table, $counters, $criteria);
  127. }
  128. /**
  129. * This is a port from Prado Framework.
  130. *
  131. * Overrides parent implementation. Alters the sql to apply $limit and $offset.
  132. * The idea for limit with offset is done by modifying the sql on the fly
  133. * with numerous assumptions on the structure of the sql string.
  134. * The modification is done with reference to the notes from
  135. * http://troels.arvin.dk/db/rdbms/#select-limit-offset
  136. *
  137. * <code>
  138. * SELECT * FROM (
  139. * SELECT TOP n * FROM (
  140. * SELECT TOP z columns -- (z=n+skip)
  141. * FROM tablename
  142. * ORDER BY key ASC
  143. * ) AS FOO ORDER BY key DESC -- ('FOO' may be anything)
  144. * ) AS BAR ORDER BY key ASC -- ('BAR' may be anything)
  145. * </code>
  146. *
  147. * <b>Regular expressions are used to alter the SQL query. The resulting SQL query
  148. * may be malformed for complex queries.</b> The following restrictions apply
  149. *
  150. * <ul>
  151. * <li>
  152. * In particular, <b>commas</b> should <b>NOT</b>
  153. * be used as part of the ordering expression or identifier. Commas must only be
  154. * used for separating the ordering clauses.
  155. * </li>
  156. * <li>
  157. * In the ORDER BY clause, the column name should NOT be be qualified
  158. * with a table name or view name. Alias the column names or use column index.
  159. * </li>
  160. * <li>
  161. * No clauses should follow the ORDER BY clause, e.g. no COMPUTE or FOR clauses.
  162. * </li>
  163. *
  164. * @param string $sql SQL query string.
  165. * @param integer $limit maximum number of rows, -1 to ignore limit.
  166. * @param integer $offset row offset, -1 to ignore offset.
  167. * @return string SQL with limit and offset.
  168. *
  169. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  170. */
  171. public function applyLimit($sql, $limit, $offset)
  172. {
  173. $limit = $limit!==null ? intval($limit) : -1;
  174. $offset = $offset!==null ? intval($offset) : -1;
  175. if ($limit > 0 && $offset <= 0) //just limit
  176. $sql = preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',"\\1SELECT\\2 TOP $limit", $sql);
  177. else if($limit > 0 && $offset > 0)
  178. $sql = $this->rewriteLimitOffsetSql($sql, $limit,$offset);
  179. return $sql;
  180. }
  181. /**
  182. * Rewrite sql to apply $limit > and $offset > 0 for MSSQL database.
  183. * See http://troels.arvin.dk/db/rdbms/#select-limit-offset
  184. * @param string $sql sql query
  185. * @param integer $limit $limit > 0
  186. * @param integer $offset $offset > 0
  187. * @return sql modified sql query applied with limit and offset.
  188. *
  189. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  190. */
  191. protected function rewriteLimitOffsetSql($sql, $limit, $offset)
  192. {
  193. $fetch = $limit+$offset;
  194. $sql = preg_replace('/^([\s(])*SELECT( DISTINCT)?(?!\s*TOP\s*\()/i',"\\1SELECT\\2 TOP $fetch", $sql);
  195. $ordering = $this->findOrdering($sql);
  196. $orginalOrdering = $this->joinOrdering($ordering, '[__outer__]');
  197. $reverseOrdering = $this->joinOrdering($this->reverseDirection($ordering), '[__inner__]');
  198. $sql = "SELECT * FROM (SELECT TOP {$limit} * FROM ($sql) as [__inner__] {$reverseOrdering}) as [__outer__] {$orginalOrdering}";
  199. return $sql;
  200. }
  201. /**
  202. * Base on simplified syntax http://msdn2.microsoft.com/en-us/library/aa259187(SQL.80).aspx
  203. *
  204. * @param string $sql $sql
  205. * @return array ordering expression as key and ordering direction as value
  206. *
  207. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  208. */
  209. protected function findOrdering($sql)
  210. {
  211. if(!preg_match('/ORDER BY/i', $sql))
  212. return array();
  213. $matches=array();
  214. $ordering=array();
  215. preg_match_all('/(ORDER BY)[\s"\[](.*)(ASC|DESC)?(?:[\s"\[]|$|COMPUTE|FOR)/i', $sql, $matches);
  216. if(count($matches)>1 && count($matches[2]) > 0)
  217. {
  218. $parts = explode(',', $matches[2][0]);
  219. foreach($parts as $part)
  220. {
  221. $subs=array();
  222. if(preg_match_all('/(.*)[\s"\]](ASC|DESC)$/i', trim($part), $subs))
  223. {
  224. if(count($subs) > 1 && count($subs[2]) > 0)
  225. {
  226. $name='';
  227. foreach(explode('.', $subs[1][0]) as $p)
  228. {
  229. if($name!=='')
  230. $name.='.';
  231. $name.='[' . trim($p, '[]') . ']';
  232. }
  233. $ordering[$name] = $subs[2][0];
  234. }
  235. //else what?
  236. }
  237. else
  238. $ordering[trim($part)] = 'ASC';
  239. }
  240. }
  241. // replacing column names with their alias names
  242. foreach($ordering as $name => $direction)
  243. {
  244. $matches = array();
  245. $pattern = '/\s+'.str_replace(array('[',']'), array('\[','\]'), $name).'\s+AS\s+(\[[^\]]+\])/i';
  246. preg_match($pattern, $sql, $matches);
  247. if(isset($matches[1]))
  248. {
  249. $ordering[$matches[1]] = $ordering[$name];
  250. unset($ordering[$name]);
  251. }
  252. }
  253. return $ordering;
  254. }
  255. /**
  256. * @param array $orders ordering obtained from findOrdering()
  257. * @param string $newPrefix new table prefix to the ordering columns
  258. * @return string concat the orderings
  259. *
  260. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  261. */
  262. protected function joinOrdering($orders, $newPrefix)
  263. {
  264. if(count($orders)>0)
  265. {
  266. $str=array();
  267. foreach($orders as $column => $direction)
  268. $str[] = $column.' '.$direction;
  269. $orderBy = 'ORDER BY '.implode(', ', $str);
  270. return preg_replace('/\s+\[[^\]]+\]\.(\[[^\]]+\])/i', ' '.$newPrefix.'.\1', $orderBy);
  271. }
  272. }
  273. /**
  274. * @param array $orders original ordering
  275. * @return array ordering with reversed direction.
  276. *
  277. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  278. */
  279. protected function reverseDirection($orders)
  280. {
  281. foreach($orders as $column => $direction)
  282. $orders[$column] = strtolower(trim($direction))==='desc' ? 'ASC' : 'DESC';
  283. return $orders;
  284. }
  285. /**
  286. * Checks if the criteria has an order by clause when using offset/limit.
  287. * Override parent implementation to check if an orderby clause if specified when querying with an offset
  288. * If not, order it by pk.
  289. * @param CMssqlTableSchema $table table schema
  290. * @param CDbCriteria $criteria criteria
  291. * @return CDbCrireria the modified criteria
  292. */
  293. protected function checkCriteria($table, $criteria)
  294. {
  295. if ($criteria->offset > 0 && $criteria->order==='')
  296. {
  297. $criteria->order=is_array($table->primaryKey)?implode(',',$table->primaryKey):$table->primaryKey;
  298. }
  299. return $criteria;
  300. }
  301. /**
  302. * Generates the expression for selecting rows with specified composite key values.
  303. * @param CDbTableSchema $table the table schema
  304. * @param array $values list of primary key values to be selected within
  305. * @param string $prefix column prefix (ended with dot)
  306. * @return string the expression for selection
  307. * @since 1.0.4
  308. */
  309. protected function createCompositeInCondition($table,$values,$prefix)
  310. {
  311. $vs=array();
  312. foreach($values as $value)
  313. {
  314. $c=array();
  315. foreach($value as $k=>$v)
  316. $c[]=$prefix.$table->columns[$k]->rawName.'='.$v;
  317. $vs[]='('.implode(' AND ',$c).')';
  318. }
  319. return '('.implode(' OR ',$vs).')';
  320. }
  321. }