xpdoquery.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. /*
  3. * Copyright 2010-2015 by MODX, LLC.
  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(__DIR__) . '/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, true);
  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]) && is_scalar($conditions[0]) && !$this->isConditionalClause($conditions[0]) && is_array($pk) && count($conditions) == count($pk)) {
  49. $iteration= 0;
  50. foreach ($pk as $k) {
  51. if (!isset ($conditions[$iteration])) {
  52. $conditions[$iteration]= null;
  53. }
  54. $isString= in_array($fieldMeta[$k]['phptype'], $this->_quotable);
  55. $field= array();
  56. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($k) . " = ?";
  57. $field['binding']= array (
  58. 'value' => $conditions[$iteration],
  59. 'type' => $isString ? \PDO::PARAM_STR : \PDO::PARAM_INT,
  60. 'length' => 0
  61. );
  62. $field['conjunction']= $conjunction;
  63. $result[$iteration]= new xPDOQueryCondition($field);
  64. $iteration++;
  65. }
  66. } else {
  67. foreach ($conditions as $key => $val) {
  68. if (is_int($key)) {
  69. if (is_array($val)) {
  70. $result[]= $this->parseConditions($val, $conjunction);
  71. continue;
  72. } elseif ($this->isConditionalClause($val)) {
  73. $result[]= new xPDOQueryCondition(array('sql' => $val, 'binding' => null, 'conjunction' => $conjunction));
  74. continue;
  75. } else {
  76. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing condition with key {$key}: " . print_r($val, true));
  77. continue;
  78. }
  79. } elseif (is_scalar($val) || is_array($val) || $val === null) {
  80. $alias= $command == 'SELECT' ? $this->_class : trim($this->xpdo->getTableName($this->_class, false), $this->xpdo->_escapeCharOpen . $this->xpdo->_escapeCharClose);
  81. $operator= '=';
  82. $conj = $conjunction;
  83. $key_operator= explode(':', $key);
  84. if ($key_operator && count($key_operator) === 2) {
  85. $key= $key_operator[0];
  86. $operator= $key_operator[1];
  87. }
  88. elseif ($key_operator && count($key_operator) === 3) {
  89. $conj= $key_operator[0];
  90. $key= $key_operator[1];
  91. $operator= $key_operator[2];
  92. }
  93. if (strpos($key, '.') !== false) {
  94. $key_parts= explode('.', $key);
  95. $alias= trim($key_parts[0], " {$this->xpdo->_escapeCharOpen}{$this->xpdo->_escapeCharClose}");
  96. $key= $key_parts[1];
  97. }
  98. if ($val === null) {
  99. $type= \PDO::PARAM_NULL;
  100. if (!in_array($operator, array('IS', 'IS NOT'))) {
  101. $operator= $operator === '!=' ? 'IS NOT' : 'IS';
  102. }
  103. }
  104. elseif (isset($fieldMeta[$key]) && !in_array($fieldMeta[$key]['phptype'], $this->_quotable)) {
  105. $type= \PDO::PARAM_INT;
  106. }
  107. else {
  108. $type= \PDO::PARAM_STR;
  109. }
  110. if (in_array(strtoupper($operator), array('IN', 'NOT IN')) && is_array($val)) {
  111. $vals = array();
  112. foreach ($val as $v) {
  113. switch ($type) {
  114. case \PDO::PARAM_INT:
  115. $vals[] = (integer) $v;
  116. break;
  117. case \PDO::PARAM_STR:
  118. $vals[] = $this->xpdo->quote($v);
  119. break;
  120. default:
  121. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing {$operator} condition with key {$key}: " . print_r($v, true));
  122. break;
  123. }
  124. }
  125. if (!empty($vals)) {
  126. $val = "(" . implode(',', $vals) . ")";
  127. $sql = "{$this->xpdo->escape($alias)}.{$this->xpdo->escape($key)} {$operator} {$val}";
  128. $result[]= new xPDOQueryCondition(array('sql' => $sql, 'binding' => null, 'conjunction' => $conj));
  129. continue;
  130. } else {
  131. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error parsing {$operator} condition with key {$key}: " . print_r($val, true));
  132. continue;
  133. }
  134. }
  135. $field= array ();
  136. if ($type === \PDO::PARAM_NULL) {
  137. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($key) . ' ' . $operator . ' NULL';
  138. $field['binding']= null;
  139. $field['conjunction']= $conj;
  140. } else {
  141. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($key) . ' ' . $operator . ' ?';
  142. $field['binding']= array (
  143. 'value' => $val,
  144. 'type' => $type,
  145. 'length' => 0
  146. );
  147. $field['conjunction']= $conj;
  148. }
  149. $result[]= new xPDOQueryCondition($field);
  150. }
  151. }
  152. }
  153. }
  154. elseif ($this->isConditionalClause($conditions)) {
  155. $result= new xPDOQueryCondition(array(
  156. 'sql' => $conditions
  157. ,'binding' => null
  158. ,'conjunction' => $conjunction
  159. ));
  160. }
  161. elseif (($pktype == 'integer' && is_numeric($conditions)) || ($pktype == 'string' && is_string($conditions))) {
  162. if ($pktype == 'integer') {
  163. $param_type= \PDO::PARAM_INT;
  164. } else {
  165. $param_type= \PDO::PARAM_STR;
  166. }
  167. $field['sql']= $this->xpdo->escape($alias) . '.' . $this->xpdo->escape($pk) . ' = ?';
  168. $field['binding']= array ('value' => $conditions, 'type' => $param_type, 'length' => 0);
  169. $field['conjunction']= $conjunction;
  170. $result = new xPDOQueryCondition($field);
  171. }
  172. return $result;
  173. }
  174. public function construct() {
  175. $constructed= false;
  176. $this->bindings= array ();
  177. $command= strtoupper($this->query['command']);
  178. $sql= $this->query['command'] . ' ';
  179. $limit= !empty($this->query['limit']) ? intval($this->query['limit']) : 0;
  180. $offset= !empty($this->query['offset']) ? intval($this->query['offset']) : 0;
  181. $orderBySql = '';
  182. if ($command == 'SELECT' && !empty ($this->query['sortby'])) {
  183. $sortby= reset($this->query['sortby']);
  184. $orderBySql= 'ORDER BY ';
  185. $orderBySql.= $sortby['column'];
  186. if ($sortby['direction']) $orderBySql.= ' ' . $sortby['direction'];
  187. while ($sortby= next($this->query['sortby'])) {
  188. $orderBySql.= ', ';
  189. $orderBySql.= $sortby['column'];
  190. if ($sortby['direction']) $orderBySql.= ' ' . $sortby['direction'];
  191. }
  192. }
  193. if ($command == 'SELECT' && $orderBySql == '' && !empty($limit) && !empty($offset)) {
  194. $pk = $this->xpdo->getPK($this->getClass());
  195. if ($pk) {
  196. if (!is_array($pk)) $pk = array($pk);
  197. $orderBy = array();
  198. foreach ($pk as $k) {
  199. $orderBy[] = $this->xpdo->escape($this->getAlias()) . '.' . $this->xpdo->escape($k);
  200. }
  201. $orderBySql = "ORDER BY " . implode(', ', $orderBy);
  202. }
  203. }
  204. if ($command == 'SELECT') {
  205. $sql.= !empty($this->query['distinct']) ? $this->query['distinct'] . ' ' : '';
  206. if (!empty($limit) && empty($offset)) {
  207. $this->query['top'] = $limit;
  208. }
  209. $sql.= $this->query['top'] > 0 ? 'TOP ' . $this->query['top'] . ' ' : '';
  210. $columns= array ();
  211. if (empty ($this->query['columns'])) {
  212. $this->select('*');
  213. }
  214. foreach ($this->query['columns'] as $alias => $column) {
  215. $ignorealias = is_int($alias);
  216. $escape = !preg_match('/\bAS\b/i', $column) && !preg_match('/\./', $column) && !preg_match('/\(/', $column);
  217. if ($escape) {
  218. $column= $this->xpdo->escape(trim($column));
  219. } else {
  220. $column= trim($column);
  221. }
  222. if (!$ignorealias) {
  223. $alias = $escape ? $this->xpdo->escape($alias) : $alias;
  224. $columns[]= "{$column} AS {$alias}";
  225. } else {
  226. $columns[]= "{$column}";
  227. }
  228. }
  229. $sql.= implode(', ', $columns);
  230. if(!empty($limit) && !empty($offset)) {
  231. $sql.= ', ROW_NUMBER() OVER (' . $orderBySql . ') AS [xpdoRowNr]';
  232. }
  233. $sql.= ' ';
  234. }
  235. if ($command != 'UPDATE') {
  236. $sql.= 'FROM ';
  237. }
  238. $tables= array ();
  239. foreach ($this->query['from']['tables'] as $table) {
  240. if ($command != 'SELECT') {
  241. $tables[]= $this->xpdo->escape($table['table']);
  242. } else {
  243. $tables[]= $this->xpdo->escape($table['table']) . ' AS ' . $this->xpdo->escape($table['alias']);
  244. }
  245. }
  246. $sql.= $this->query['from']['tables'] ? implode(', ', $tables) . ' ' : '';
  247. if (!empty ($this->query['from']['joins'])) {
  248. foreach ($this->query['from']['joins'] as $join) {
  249. $sql.= $join['type'] . ' ' . $this->xpdo->escape($join['table']) . ' AS ' . $this->xpdo->escape($join['alias']) . ' ';
  250. if (!empty ($join['conditions'])) {
  251. $sql.= 'ON ';
  252. $sql.= $this->buildConditionalClause($join['conditions']);
  253. $sql.= ' ';
  254. }
  255. }
  256. }
  257. if ($command == 'UPDATE') {
  258. if (!empty($this->query['set'])) {
  259. $clauses = array();
  260. foreach ($this->query['set'] as $setKey => $setVal) {
  261. $value = $setVal['value'];
  262. $type = $setVal['type'];
  263. if ($value !== null && in_array($type, array(\PDO::PARAM_INT, \PDO::PARAM_STR))) {
  264. $value = $this->xpdo->quote($value, $type);
  265. } elseif ($value === null) {
  266. $value = 'NULL';
  267. }
  268. $clauses[] = $this->xpdo->escape($setKey) . ' = ' . $value;
  269. }
  270. if (!empty($clauses)) {
  271. $sql.= 'SET ' . implode(', ', $clauses) . ' ';
  272. }
  273. unset($clauses);
  274. }
  275. }
  276. if (!empty ($this->query['where'])) {
  277. if ($where= $this->buildConditionalClause($this->query['where'])) {
  278. $sql.= 'WHERE ' . $where . ' ';
  279. }
  280. }
  281. if ($command == 'SELECT' && !empty ($this->query['groupby'])) {
  282. $groupby= reset($this->query['groupby']);
  283. $sql.= 'GROUP BY ';
  284. $sql.= $groupby['column'];
  285. if ($groupby['direction']) $sql.= ' ' . $groupby['direction'];
  286. while ($groupby= next($this->query['groupby'])) {
  287. $sql.= ', ';
  288. $sql.= $groupby['column'];
  289. if ($groupby['direction']) $sql.= ' ' . $groupby['direction'];
  290. }
  291. $sql.= ' ';
  292. }
  293. if (!empty ($this->query['having'])) {
  294. $sql.= 'HAVING ';
  295. $sql.= $this->buildConditionalClause($this->query['having']);
  296. $sql.= ' ';
  297. }
  298. if ($command == 'SELECT' && !empty($limit) && !empty($offset)) {
  299. if (!empty($orderBySql)) {
  300. $sql = "WITH OrderedSettings AS ($sql) SELECT * FROM OrderedSettings WHERE [xpdoRowNr] BETWEEN " . ($offset + 1) . " AND " . ($offset + $limit);
  301. } else {
  302. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "limit() in sqlsrv requires either an explicit sortby or a defined primary key; limit ignored");
  303. }
  304. } else {
  305. $sql.= $orderBySql;
  306. }
  307. $this->sql= $sql;
  308. return (!empty ($this->sql));
  309. }
  310. }