PageRenderTime 27ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/core/xpdo/om/sqlsrv/xpdoquery.class.php

https://github.com/rostislav/revolution
PHP | 294 lines | 258 code | 5 blank | 31 comment | 80 complexity | 59e505e8a399cdae2ab467ef7da266a0 MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2006-2010 by Jason Coward <xpdo@opengeek.com>
  4. *
  5. * This file is part of xPDO.
  6. *
  7. * xPDO is free software; you can redistribute it and/or modify it under the
  8. * terms of the GNU General Public License as published by the Free Software
  9. * Foundation; either version 2 of the License, or (at your option) any later
  10. * version.
  11. *
  12. * xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
  13. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  14. * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along with
  17. * xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  18. * Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /**
  21. * The sqlsrv implementation of xPDOQuery.
  22. *
  23. * @package xpdo
  24. * @subpackage om.sqlsrv
  25. */
  26. /** Include the base {@see xPDOQuery} class */
  27. include_once (dirname(dirname(__FILE__)) . '/xpdoquery.class.php');
  28. /**
  29. * An implementation of xPDOQuery for the sqlsrv database driver.
  30. *
  31. * @package xpdo
  32. * @subpackage om.sqlsrv
  33. */
  34. class xPDOQuery_sqlsrv extends xPDOQuery {
  35. public function __construct(& $xpdo, $class, $criteria= null) {
  36. parent :: __construct($xpdo, $class, $criteria);
  37. $this->query['top']= 0;
  38. }
  39. public function parseConditions($conditions, $conjunction = xPDOQuery::SQL_AND) {
  40. $result= array ();
  41. $pk= $this->xpdo->getPK($this->_class);
  42. $pktype= $this->xpdo->getPKType($this->_class);
  43. $fieldMeta= $this->xpdo->getFieldMeta($this->_class);
  44. $command= strtoupper($this->query['command']);
  45. $alias= $command == 'SELECT' ? $this->_class : $this->xpdo->getTableName($this->_class, false);
  46. $alias= trim($alias, $this->xpdo->_escapeCharOpen . $this->xpdo->_escapeCharClose);
  47. if (is_array($conditions)) {
  48. if (isset ($conditions[0]) && !$this->isConditionalClause($conditions[0]) && is_array($pk) && count($conditions) == count($pk)) {
  49. $iteration= 0;
  50. $sql= '';
  51. foreach ($pk as $k) {
  52. if (!isset ($conditions[$iteration])) {
  53. $conditions[$iteration]= null;
  54. }
  55. $isString= in_array($fieldMeta[$k]['phptype'], $this->_quotable);
  56. $field= array();
  57. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($k) . " = ?";
  58. $field['binding']= array (
  59. 'value' => $conditions[$iteration],
  60. 'type' => $isString ? PDO::PARAM_STR : PDO::PARAM_INT,
  61. 'length' => 0
  62. );
  63. $field['conjunction']= $conjunction;
  64. $result[$iteration]= new xPDOQueryCondition($field);
  65. $iteration++;
  66. }
  67. } else {
  68. $bindings= array ();
  69. reset($conditions);
  70. while (list ($key, $val)= each($conditions)) {
  71. if (is_int($key)) {
  72. if (is_array($val)) {
  73. $result[]= $this->parseConditions($val, $conjunction);
  74. continue;
  75. } elseif ($this->isConditionalClause($val)) {
  76. $result[]= new xPDOQueryCondition(array('sql' => $val, 'binding' => null, 'conjunction' => $conjunction));
  77. continue;
  78. } else {
  79. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing condition with key {$key}: " . print_r($val, true));
  80. continue;
  81. }
  82. } elseif (is_scalar($val) || is_array($val) || $val === null) {
  83. $alias= $command == 'SELECT' ? $this->_class : trim($this->xpdo->getTableName($this->_class, false), $this->xpdo->_escapeCharOpen . $this->xpdo->_escapeCharClose);
  84. $operator= '=';
  85. $conj = $conjunction;
  86. $key_operator= explode(':', $key);
  87. if ($key_operator && count($key_operator) === 2) {
  88. $key= $key_operator[0];
  89. $operator= $key_operator[1];
  90. }
  91. elseif ($key_operator && count($key_operator) === 3) {
  92. $conj= $key_operator[0];
  93. $key= $key_operator[1];
  94. $operator= $key_operator[2];
  95. }
  96. if (strpos($key, '.') !== false) {
  97. $key_parts= explode('.', $key);
  98. $alias= trim($key_parts[0], " {$this->xpdo->_escapeCharOpen}{$this->xpdo->_escapeCharClose}");
  99. $key= $key_parts[1];
  100. }
  101. if ($val === null) {
  102. $type= PDO::PARAM_NULL;
  103. if (!in_array($operator, array('IS', 'IS NOT'))) {
  104. $operator= $operator === '!=' ? 'IS NOT' : 'IS';
  105. }
  106. }
  107. elseif (isset($fieldMeta[$key]) && !in_array($fieldMeta[$key]['phptype'], $this->_quotable)) {
  108. $type= PDO::PARAM_INT;
  109. }
  110. else {
  111. $type= PDO::PARAM_STR;
  112. }
  113. if (in_array(strtoupper($operator), array('IN', 'NOT IN')) && is_array($val)) {
  114. $vals = array();
  115. foreach ($val as $v) {
  116. switch ($type) {
  117. case PDO::PARAM_INT:
  118. $vals[] = (integer) $v;
  119. break;
  120. case PDO::PARAM_STR:
  121. $vals[] = $this->xpdo->quote($v);
  122. break;
  123. default:
  124. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing {$operator} condition with key {$key}: " . print_r($v, true));
  125. break;
  126. }
  127. }
  128. if (!empty($vals)) {
  129. $val = "(" . implode(',', $vals) . ")";
  130. $sql = "{$this->xpdo->escape($alias)}.{$this->xpdo->escape($key)} {$operator} {$val}";
  131. $result[]= new xPDOQueryCondition(array('sql' => $sql, 'binding' => null, 'conjunction' => $conj));
  132. continue;
  133. } else {
  134. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing {$operator} condition with key {$key}: " . print_r($val, true));
  135. continue;
  136. }
  137. }
  138. $field= array ();
  139. if ($type === PDO::PARAM_NULL) {
  140. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($key) . ' ' . $operator . ' NULL';
  141. $field['binding']= null;
  142. $field['conjunction']= $conj;
  143. } else {
  144. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($key) . ' ' . $operator . ' ?';
  145. $field['binding']= array (
  146. 'value' => $val,
  147. 'type' => $type,
  148. 'length' => 0
  149. );
  150. $field['conjunction']= $conj;
  151. }
  152. $result[]= new xPDOQueryCondition($field);
  153. }
  154. }
  155. }
  156. }
  157. elseif ($this->isConditionalClause($conditions)) {
  158. $result= new xPDOQueryCondition(array(
  159. 'sql' => $conditions
  160. ,'binding' => null
  161. ,'conjunction' => $conjunction
  162. ));
  163. }
  164. elseif (($pktype == 'integer' && is_numeric($conditions)) || ($pktype == 'string' && is_string($conditions))) {
  165. if ($pktype == 'integer') {
  166. $param_type= PDO::PARAM_INT;
  167. } else {
  168. $param_type= PDO::PARAM_STR;
  169. }
  170. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($pk) . ' = ?';
  171. $field['binding']= array ('value' => $conditions, 'type' => $param_type, 'length' => 0);
  172. $field['conjunction']= $conjunction;
  173. $result = new xPDOQueryCondition($field);
  174. }
  175. return $result;
  176. }
  177. public function construct() {
  178. $constructed= false;
  179. $this->bindings= array ();
  180. $command= strtoupper($this->query['command']);
  181. $sql= $this->query['command'] . ' ';
  182. $limit= !empty($this->query['limit']) ? intval($this->query['limit']) : 0;
  183. $offset= !empty($this->query['offset']) ? intval($this->query['offset']) : 0;
  184. if ($command == 'SELECT') {
  185. $sql.= !empty($this->query['distinct']) ? $this->query['distinct'] . ' ' : '';
  186. if (!empty($limit) && empty($offset)) {
  187. $this->query['top'] = $limit;
  188. }
  189. $sql.= $this->query['top'] > 0 ? 'TOP ' . $this->query['top'] . ' ' : '';
  190. $columns= array ();
  191. if (empty ($this->query['columns'])) {
  192. $this->select('*');
  193. }
  194. foreach ($this->query['columns'] as $alias => $column) {
  195. $ignorealias = is_int($alias);
  196. $escape = !preg_match('/\bAS\b/i', $column) && !preg_match('/\./', $column) && !preg_match('/\(/', $column);
  197. if ($escape) {
  198. $column= $this->xpdo->escape(trim($column));
  199. } else {
  200. $column= trim($column);
  201. }
  202. if (!$ignorealias) {
  203. $alias = $escape ? $this->xpdo->escape($alias) : $alias;
  204. $columns[]= "{$column} AS {$alias}";
  205. } else {
  206. $columns[]= "{$column}";
  207. }
  208. }
  209. $sql.= implode(', ', $columns);
  210. $sql.= ' ';
  211. }
  212. $sql.= 'FROM ';
  213. $tables= array ();
  214. foreach ($this->query['from']['tables'] as $table) {
  215. if ($command != 'SELECT') {
  216. $tables[]= $this->xpdo->escape($table['table']);
  217. } else {
  218. $tables[]= $this->xpdo->escape($table['table']) . ' AS ' . $this->xpdo->escape($table['alias']);
  219. }
  220. }
  221. $sql.= $this->query['from']['tables'] ? implode(', ', $tables) . ' ' : '';
  222. if (!empty ($this->query['from']['joins'])) {
  223. foreach ($this->query['from']['joins'] as $join) {
  224. $sql.= $join['type'] . ' ' . $this->xpdo->escape($join['table']) . ' AS ' . $this->xpdo->escape($join['alias']) . ' ';
  225. if (!empty ($join['conditions'])) {
  226. $sql.= 'ON ';
  227. $sql.= $this->buildConditionalClause($join['conditions']);
  228. $sql.= ' ';
  229. }
  230. }
  231. }
  232. if (!empty ($this->query['where'])) {
  233. if ($where= $this->buildConditionalClause($this->query['where'])) {
  234. $sql.= 'WHERE ' . $where . ' ';
  235. }
  236. }
  237. if ($command == 'SELECT' && !empty ($this->query['groupby'])) {
  238. $groupby= reset($this->query['groupby']);
  239. $sql.= 'GROUP BY ';
  240. $sql.= $groupby['column'];
  241. if ($groupby['direction']) $sql.= ' ' . $groupby['direction'];
  242. while ($groupby= next($this->query['groupby'])) {
  243. $sql.= ', ';
  244. $sql.= $groupby['column'];
  245. if ($groupby['direction']) $sql.= ' ' . $groupby['direction'];
  246. }
  247. $sql.= ' ';
  248. }
  249. if (!empty ($this->query['having'])) {
  250. $sql.= 'HAVING ';
  251. $sql.= $this->buildConditionalClause($this->query['having']);
  252. $sql.= ' ';
  253. }
  254. $orderBySql = '';
  255. if ($command == 'SELECT' && !empty ($this->query['sortby'])) {
  256. $sortby= reset($this->query['sortby']);
  257. $orderBySql= 'ORDER BY ';
  258. $orderBySql.= $sortby['column'];
  259. if ($sortby['direction']) $orderBySql.= ' ' . $sortby['direction'];
  260. while ($sortby= next($this->query['sortby'])) {
  261. $orderBySql.= ', ';
  262. $orderBySql.= $sortby['column'];
  263. if ($sortby['direction']) $orderBySql.= ' ' . $sortby['direction'];
  264. }
  265. }
  266. if ($command == 'SELECT' && !empty($limit) && !empty($offset)) {
  267. if (empty($orderBySql)) {
  268. $pk = $this->xpdo->getPK($this->getClass());
  269. if ($pk) {
  270. if (!is_array($pk)) $pk = array($pk);
  271. $orderBy = array();
  272. foreach ($pk as $k) {
  273. $orderBy[] = $this->xpdo->escape('xpdoLimit1') . '.' . $this->xpdo->escape($this->getAlias() . '_' . $k);
  274. }
  275. $orderBySql = "ORDER BY " . implode(', ', $orderBy);
  276. }
  277. }
  278. if (!empty($orderBySql)) {
  279. $sql = "SELECT [xpdoLimit2].* FROM (SELECT [xpdoLimit1].*, ROW_NUMBER() OVER({$orderBySql}) AS [xpdoRowNr] FROM ({$sql}) [xpdoLimit1]) [xpdoLimit2] WHERE [xpdoLimit2].[xpdoRowNr] BETWEEN " . ($offset + 1) . " AND " . ($offset + $limit);
  280. } else {
  281. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "limit() in sqlsrv requires either an explicit sortby or a defined primary key; limit ignored");
  282. }
  283. } else {
  284. $sql.= $orderBySql;
  285. }
  286. $this->sql= $sql;
  287. return (!empty ($this->sql));
  288. }
  289. }