SqlserverDialectTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Dialect;
  16. use Cake\Database\ExpressionInterface;
  17. use Cake\Database\Expression\FunctionExpression;
  18. use Cake\Database\Expression\OrderByExpression;
  19. use Cake\Database\Expression\UnaryExpression;
  20. use Cake\Database\Query;
  21. use Cake\Database\Schema\SqlserverSchema;
  22. use Cake\Database\SqlDialectTrait;
  23. use Cake\Database\SqlserverCompiler;
  24. use Cake\Database\ValueBinder;
  25. use PDO;
  26. /**
  27. * Contains functions that encapsulates the SQL dialect used by SQLServer,
  28. * including query translators and schema introspection.
  29. *
  30. * @internal
  31. */
  32. trait SqlserverDialectTrait
  33. {
  34. use SqlDialectTrait;
  35. use TupleComparisonTranslatorTrait;
  36. /**
  37. * String used to start a database identifier quoting to make it safe
  38. *
  39. * @var string
  40. */
  41. protected $_startQuote = '[';
  42. /**
  43. * String used to end a database identifier quoting to make it safe
  44. *
  45. * @var string
  46. */
  47. protected $_endQuote = ']';
  48. /**
  49. * Modify the limit/offset to TSQL
  50. *
  51. * @param \Cake\Database\Query $query The query to translate
  52. * @return \Cake\Database\Query The modified query
  53. */
  54. protected function _selectQueryTranslator($query)
  55. {
  56. $limit = $query->clause('limit');
  57. $offset = $query->clause('offset');
  58. if ($limit && $offset === null) {
  59. $query->modifier(['_auto_top_' => sprintf('TOP %d', $limit)]);
  60. }
  61. if ($offset !== null && !$query->clause('order')) {
  62. $query->order($query->newExpr()->add('(SELECT NULL)'));
  63. }
  64. if ($this->_version() < 11 && $offset !== null) {
  65. return $this->_pagingSubquery($query, $limit, $offset);
  66. }
  67. return $this->_transformDistinct($query);
  68. }
  69. /**
  70. * Get the version of SQLserver we are connected to.
  71. *
  72. * @return int
  73. */
  74. // @codingStandardsIgnoreLine
  75. public function _version()
  76. {
  77. $this->connect();
  78. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  79. }
  80. /**
  81. * Generate a paging subquery for older versions of SQLserver.
  82. *
  83. * Prior to SQLServer 2012 there was no equivalent to LIMIT OFFSET, so a subquery must
  84. * be used.
  85. *
  86. * @param \Cake\Database\Query $original The query to wrap in a subquery.
  87. * @param int $limit The number of rows to fetch.
  88. * @param int $offset The number of rows to offset.
  89. * @return \Cake\Database\Query Modified query object.
  90. */
  91. protected function _pagingSubquery($original, $limit, $offset)
  92. {
  93. $field = '_cake_paging_._cake_page_rownum_';
  94. if ($original->clause('order')) {
  95. // SQL server does not support column aliases in OVER clauses. But
  96. // the only practical way to specify the use of calculated columns
  97. // is with their alias. So substitute the select SQL in place of
  98. // any column aliases for those entries in the order clause.
  99. $select = $original->clause('select');
  100. $order = new OrderByExpression();
  101. $original
  102. ->clause('order')
  103. ->iterateParts(function ($direction, $orderBy) use ($select, $order) {
  104. $key = $orderBy;
  105. if (
  106. isset($select[$orderBy]) &&
  107. $select[$orderBy] instanceof ExpressionInterface
  108. ) {
  109. $key = $select[$orderBy]->sql(new ValueBinder());
  110. }
  111. $order->add([$key => $direction]);
  112. // Leave original order clause unchanged.
  113. return $orderBy;
  114. });
  115. } else {
  116. $order = new OrderByExpression('(SELECT NULL)');
  117. }
  118. $query = clone $original;
  119. $query->select([
  120. '_cake_page_rownum_' => new UnaryExpression('ROW_NUMBER() OVER', $order),
  121. ])->limit(null)
  122. ->offset(null)
  123. ->order([], true);
  124. $outer = new Query($query->getConnection());
  125. $outer->select('*')
  126. ->from(['_cake_paging_' => $query]);
  127. if ($offset) {
  128. $outer->where(["$field > " . (int)$offset]);
  129. }
  130. if ($limit) {
  131. $value = (int)$offset + (int)$limit;
  132. $outer->where(["$field <= $value"]);
  133. }
  134. // Decorate the original query as that is what the
  135. // end developer will be calling execute() on originally.
  136. $original->decorateResults(function ($row) {
  137. if (isset($row['_cake_page_rownum_'])) {
  138. unset($row['_cake_page_rownum_']);
  139. }
  140. return $row;
  141. });
  142. return $outer;
  143. }
  144. /**
  145. * Returns the passed query after rewriting the DISTINCT clause, so that drivers
  146. * that do not support the "ON" part can provide the actual way it should be done
  147. *
  148. * @param \Cake\Database\Query $original The query to be transformed
  149. * @return \Cake\Database\Query
  150. */
  151. protected function _transformDistinct($original)
  152. {
  153. if (!is_array($original->clause('distinct'))) {
  154. return $original;
  155. }
  156. $query = clone $original;
  157. $distinct = $query->clause('distinct');
  158. $query->distinct(false);
  159. $order = new OrderByExpression($distinct);
  160. $query
  161. ->select(function ($q) use ($distinct, $order) {
  162. $over = $q->newExpr('ROW_NUMBER() OVER')
  163. ->add('(PARTITION BY')
  164. ->add($q->newExpr()->add($distinct)->setConjunction(','))
  165. ->add($order)
  166. ->add(')')
  167. ->setConjunction(' ');
  168. return [
  169. '_cake_distinct_pivot_' => $over,
  170. ];
  171. })
  172. ->limit(null)
  173. ->offset(null)
  174. ->order([], true);
  175. $outer = new Query($query->getConnection());
  176. $outer->select('*')
  177. ->from(['_cake_distinct_' => $query])
  178. ->where(['_cake_distinct_pivot_' => 1]);
  179. // Decorate the original query as that is what the
  180. // end developer will be calling execute() on originally.
  181. $original->decorateResults(function ($row) {
  182. if (isset($row['_cake_distinct_pivot_'])) {
  183. unset($row['_cake_distinct_pivot_']);
  184. }
  185. return $row;
  186. });
  187. return $outer;
  188. }
  189. /**
  190. * Returns a dictionary of expressions to be transformed when compiling a Query
  191. * to SQL. Array keys are method names to be called in this class
  192. *
  193. * @return array
  194. */
  195. protected function _expressionTranslators()
  196. {
  197. $namespace = 'Cake\Database\Expression';
  198. return [
  199. $namespace . '\FunctionExpression' => '_transformFunctionExpression',
  200. $namespace . '\TupleComparison' => '_transformTupleComparison',
  201. ];
  202. }
  203. /**
  204. * Receives a FunctionExpression and changes it so that it conforms to this
  205. * SQL dialect.
  206. *
  207. * @param \Cake\Database\Expression\FunctionExpression $expression The function expression to convert to TSQL.
  208. * @return void
  209. */
  210. protected function _transformFunctionExpression(FunctionExpression $expression)
  211. {
  212. switch ($expression->getName()) {
  213. case 'CONCAT':
  214. // CONCAT function is expressed as exp1 + exp2
  215. $expression->setName('')->setConjunction(' +');
  216. break;
  217. case 'DATEDIFF':
  218. $hasDay = false;
  219. $visitor = function ($value) use (&$hasDay) {
  220. if ($value === 'day') {
  221. $hasDay = true;
  222. }
  223. return $value;
  224. };
  225. $expression->iterateParts($visitor);
  226. if (!$hasDay) {
  227. $expression->add(['day' => 'literal'], [], true);
  228. }
  229. break;
  230. case 'CURRENT_DATE':
  231. $time = new FunctionExpression('GETUTCDATE');
  232. $expression->setName('CONVERT')->add(['date' => 'literal', $time]);
  233. break;
  234. case 'CURRENT_TIME':
  235. $time = new FunctionExpression('GETUTCDATE');
  236. $expression->setName('CONVERT')->add(['time' => 'literal', $time]);
  237. break;
  238. case 'NOW':
  239. $expression->setName('GETUTCDATE');
  240. break;
  241. case 'EXTRACT':
  242. $expression->setName('DATEPART')->setConjunction(' ,');
  243. break;
  244. case 'DATE_ADD':
  245. $params = [];
  246. $visitor = function ($p, $key) use (&$params) {
  247. if ($key === 0) {
  248. $params[2] = $p;
  249. } else {
  250. $valueUnit = explode(' ', $p);
  251. $params[0] = rtrim($valueUnit[1], 's');
  252. $params[1] = $valueUnit[0];
  253. }
  254. return $p;
  255. };
  256. $manipulator = function ($p, $key) use (&$params) {
  257. return $params[$key];
  258. };
  259. $expression
  260. ->setName('DATEADD')
  261. ->setConjunction(',')
  262. ->iterateParts($visitor)
  263. ->iterateParts($manipulator)
  264. ->add([$params[2] => 'literal']);
  265. break;
  266. case 'DAYOFWEEK':
  267. $expression
  268. ->setName('DATEPART')
  269. ->setConjunction(' ')
  270. ->add(['weekday, ' => 'literal'], [], true);
  271. break;
  272. case 'SUBSTR':
  273. $expression->setName('SUBSTRING');
  274. if (count($expression) < 4) {
  275. $params = [];
  276. $expression
  277. ->iterateParts(function ($p) use (&$params) {
  278. return $params[] = $p;
  279. })
  280. ->add([new FunctionExpression('LEN', [$params[0]]), ['string']]);
  281. }
  282. break;
  283. }
  284. }
  285. /**
  286. * Get the schema dialect.
  287. *
  288. * Used by Cake\Schema package to reflect schema and
  289. * generate schema.
  290. *
  291. * @return \Cake\Database\Schema\SqlserverSchema
  292. */
  293. public function schemaDialect()
  294. {
  295. return new SqlserverSchema($this);
  296. }
  297. /**
  298. * Returns a SQL snippet for creating a new transaction savepoint
  299. *
  300. * @param string $name save point name
  301. * @return string
  302. */
  303. public function savePointSQL($name)
  304. {
  305. return 'SAVE TRANSACTION t' . $name;
  306. }
  307. /**
  308. * Returns a SQL snippet for releasing a previously created save point
  309. *
  310. * @param string $name save point name
  311. * @return string
  312. */
  313. public function releaseSavePointSQL($name)
  314. {
  315. return 'COMMIT TRANSACTION t' . $name;
  316. }
  317. /**
  318. * Returns a SQL snippet for rollbacking a previously created save point
  319. *
  320. * @param string $name save point name
  321. * @return string
  322. */
  323. public function rollbackSavePointSQL($name)
  324. {
  325. return 'ROLLBACK TRANSACTION t' . $name;
  326. }
  327. /**
  328. * {@inheritDoc}
  329. *
  330. * @return \Cake\Database\SqlserverCompiler
  331. */
  332. public function newCompiler()
  333. {
  334. return new SqlserverCompiler();
  335. }
  336. /**
  337. * {@inheritDoc}
  338. */
  339. public function disableForeignKeySQL()
  340. {
  341. return 'EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"';
  342. }
  343. /**
  344. * {@inheritDoc}
  345. */
  346. public function enableForeignKeySQL()
  347. {
  348. return 'EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"';
  349. }
  350. }