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 (isset($select[$orderBy]) &&
  106. $select[$orderBy] instanceof ExpressionInterface
  107. ) {
  108. $key = $select[$orderBy]->sql(new ValueBinder());
  109. }
  110. $order->add([$key => $direction]);
  111. // Leave original order clause unchanged.
  112. return $orderBy;
  113. });
  114. } else {
  115. $order = new OrderByExpression('(SELECT NULL)');
  116. }
  117. $query = clone $original;
  118. $query->select([
  119. '_cake_page_rownum_' => new UnaryExpression('ROW_NUMBER() OVER', $order)
  120. ])->limit(null)
  121. ->offset(null)
  122. ->order([], true);
  123. $outer = new Query($query->getConnection());
  124. $outer->select('*')
  125. ->from(['_cake_paging_' => $query]);
  126. if ($offset) {
  127. $outer->where(["$field > " . (int)$offset]);
  128. }
  129. if ($limit) {
  130. $value = (int)$offset + (int)$limit;
  131. $outer->where(["$field <= $value"]);
  132. }
  133. // Decorate the original query as that is what the
  134. // end developer will be calling execute() on originally.
  135. $original->decorateResults(function ($row) {
  136. if (isset($row['_cake_page_rownum_'])) {
  137. unset($row['_cake_page_rownum_']);
  138. }
  139. return $row;
  140. });
  141. return $outer;
  142. }
  143. /**
  144. * Returns the passed query after rewriting the DISTINCT clause, so that drivers
  145. * that do not support the "ON" part can provide the actual way it should be done
  146. *
  147. * @param \Cake\Database\Query $original The query to be transformed
  148. * @return \Cake\Database\Query
  149. */
  150. protected function _transformDistinct($original)
  151. {
  152. if (!is_array($original->clause('distinct'))) {
  153. return $original;
  154. }
  155. $query = clone $original;
  156. $distinct = $query->clause('distinct');
  157. $query->distinct(false);
  158. $order = new OrderByExpression($distinct);
  159. $query
  160. ->select(function ($q) use ($distinct, $order) {
  161. $over = $q->newExpr('ROW_NUMBER() OVER')
  162. ->add('(PARTITION BY')
  163. ->add($q->newExpr()->add($distinct)->setConjunction(','))
  164. ->add($order)
  165. ->add(')')
  166. ->setConjunction(' ');
  167. return [
  168. '_cake_distinct_pivot_' => $over
  169. ];
  170. })
  171. ->limit(null)
  172. ->offset(null)
  173. ->order([], true);
  174. $outer = new Query($query->getConnection());
  175. $outer->select('*')
  176. ->from(['_cake_distinct_' => $query])
  177. ->where(['_cake_distinct_pivot_' => 1]);
  178. // Decorate the original query as that is what the
  179. // end developer will be calling execute() on originally.
  180. $original->decorateResults(function ($row) {
  181. if (isset($row['_cake_distinct_pivot_'])) {
  182. unset($row['_cake_distinct_pivot_']);
  183. }
  184. return $row;
  185. });
  186. return $outer;
  187. }
  188. /**
  189. * Returns a dictionary of expressions to be transformed when compiling a Query
  190. * to SQL. Array keys are method names to be called in this class
  191. *
  192. * @return array
  193. */
  194. protected function _expressionTranslators()
  195. {
  196. $namespace = 'Cake\Database\Expression';
  197. return [
  198. $namespace . '\FunctionExpression' => '_transformFunctionExpression',
  199. $namespace . '\TupleComparison' => '_transformTupleComparison'
  200. ];
  201. }
  202. /**
  203. * Receives a FunctionExpression and changes it so that it conforms to this
  204. * SQL dialect.
  205. *
  206. * @param \Cake\Database\Expression\FunctionExpression $expression The function expression to convert to TSQL.
  207. * @return void
  208. */
  209. protected function _transformFunctionExpression(FunctionExpression $expression)
  210. {
  211. switch ($expression->getName()) {
  212. case 'CONCAT':
  213. // CONCAT function is expressed as exp1 + exp2
  214. $expression->setName('')->setConjunction(' +');
  215. break;
  216. case 'DATEDIFF':
  217. $hasDay = false;
  218. $visitor = function ($value) use (&$hasDay) {
  219. if ($value === 'day') {
  220. $hasDay = true;
  221. }
  222. return $value;
  223. };
  224. $expression->iterateParts($visitor);
  225. if (!$hasDay) {
  226. $expression->add(['day' => 'literal'], [], true);
  227. }
  228. break;
  229. case 'CURRENT_DATE':
  230. $time = new FunctionExpression('GETUTCDATE');
  231. $expression->setName('CONVERT')->add(['date' => 'literal', $time]);
  232. break;
  233. case 'CURRENT_TIME':
  234. $time = new FunctionExpression('GETUTCDATE');
  235. $expression->setName('CONVERT')->add(['time' => 'literal', $time]);
  236. break;
  237. case 'NOW':
  238. $expression->setName('GETUTCDATE');
  239. break;
  240. case 'EXTRACT':
  241. $expression->setName('DATEPART')->setConjunction(' ,');
  242. break;
  243. case 'DATE_ADD':
  244. $params = [];
  245. $visitor = function ($p, $key) use (&$params) {
  246. if ($key === 0) {
  247. $params[2] = $p;
  248. } else {
  249. $valueUnit = explode(' ', $p);
  250. $params[0] = rtrim($valueUnit[1], 's');
  251. $params[1] = $valueUnit[0];
  252. }
  253. return $p;
  254. };
  255. $manipulator = function ($p, $key) use (&$params) {
  256. return $params[$key];
  257. };
  258. $expression
  259. ->setName('DATEADD')
  260. ->setConjunction(',')
  261. ->iterateParts($visitor)
  262. ->iterateParts($manipulator)
  263. ->add([$params[2] => 'literal']);
  264. break;
  265. case 'DAYOFWEEK':
  266. $expression
  267. ->setName('DATEPART')
  268. ->setConjunction(' ')
  269. ->add(['weekday, ' => 'literal'], [], true);
  270. break;
  271. case 'SUBSTR':
  272. $expression->setName('SUBSTRING');
  273. if (count($expression) < 4) {
  274. $params = [];
  275. $expression
  276. ->iterateParts(function ($p) use (&$params) {
  277. return $params[] = $p;
  278. })
  279. ->add([new FunctionExpression('LEN', [$params[0]]), ['string']]);
  280. }
  281. break;
  282. }
  283. }
  284. /**
  285. * Get the schema dialect.
  286. *
  287. * Used by Cake\Schema package to reflect schema and
  288. * generate schema.
  289. *
  290. * @return \Cake\Database\Schema\SqlserverSchema
  291. */
  292. public function schemaDialect()
  293. {
  294. return new SqlserverSchema($this);
  295. }
  296. /**
  297. * Returns a SQL snippet for creating a new transaction savepoint
  298. *
  299. * @param string $name save point name
  300. * @return string
  301. */
  302. public function savePointSQL($name)
  303. {
  304. return 'SAVE TRANSACTION t' . $name;
  305. }
  306. /**
  307. * Returns a SQL snippet for releasing a previously created save point
  308. *
  309. * @param string $name save point name
  310. * @return string
  311. */
  312. public function releaseSavePointSQL($name)
  313. {
  314. return 'COMMIT TRANSACTION t' . $name;
  315. }
  316. /**
  317. * Returns a SQL snippet for rollbacking a previously created save point
  318. *
  319. * @param string $name save point name
  320. * @return string
  321. */
  322. public function rollbackSavePointSQL($name)
  323. {
  324. return 'ROLLBACK TRANSACTION t' . $name;
  325. }
  326. /**
  327. * {@inheritDoc}
  328. *
  329. * @return \Cake\Database\SqlserverCompiler
  330. */
  331. public function newCompiler()
  332. {
  333. return new SqlserverCompiler();
  334. }
  335. /**
  336. * {@inheritDoc}
  337. */
  338. public function disableForeignKeySQL()
  339. {
  340. return 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"';
  341. }
  342. /**
  343. * {@inheritDoc}
  344. */
  345. public function enableForeignKeySQL()
  346. {
  347. return 'EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"';
  348. }
  349. }