SqlDialectTrait.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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;
  16. use Cake\Database\Expression\Comparison;
  17. /**
  18. * Sql dialect trait
  19. */
  20. trait SqlDialectTrait
  21. {
  22. /**
  23. * Quotes a database identifier (a column name, table name, etc..) to
  24. * be used safely in queries without the risk of using reserved words
  25. *
  26. * @param string $identifier The identifier to quote.
  27. * @return string
  28. */
  29. public function quoteIdentifier($identifier)
  30. {
  31. $identifier = trim($identifier);
  32. if ($identifier === '*' || $identifier === '') {
  33. return $identifier;
  34. }
  35. // string
  36. if (preg_match('/^[\w-]+$/u', $identifier)) {
  37. return $this->_startQuote . $identifier . $this->_endQuote;
  38. }
  39. // string.string
  40. if (preg_match('/^[\w-]+\.[^ \*]*$/u', $identifier)) {
  41. $items = explode('.', $identifier);
  42. return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
  43. }
  44. // string.*
  45. if (preg_match('/^[\w-]+\.\*$/u', $identifier)) {
  46. return $this->_startQuote . str_replace('.*', $this->_endQuote . '.*', $identifier);
  47. }
  48. // Functions
  49. if (preg_match('/^([\w-]+)\((.*)\)$/', $identifier, $matches)) {
  50. return $matches[1] . '(' . $this->quoteIdentifier($matches[2]) . ')';
  51. }
  52. // Alias.field AS thing
  53. if (preg_match('/^([\w-]+(\.[\w\s-]+|\(.*\))*)\s+AS\s*([\w-]+)$/ui', $identifier, $matches)) {
  54. return $this->quoteIdentifier($matches[1]) . ' AS ' . $this->quoteIdentifier($matches[3]);
  55. }
  56. // string.string with spaces
  57. if (preg_match('/^([\w-]+\.[\w][\w\s\-]*[\w])(.*)/u', $identifier, $matches)) {
  58. $items = explode('.', $matches[1]);
  59. $field = implode($this->_endQuote . '.' . $this->_startQuote, $items);
  60. return $this->_startQuote . $field . $this->_endQuote . $matches[2];
  61. }
  62. if (preg_match('/^[\w_\s-]*[\w_-]+/u', $identifier)) {
  63. return $this->_startQuote . $identifier . $this->_endQuote;
  64. }
  65. return $identifier;
  66. }
  67. /**
  68. * Returns a callable function that will be used to transform a passed Query object.
  69. * This function, in turn, will return an instance of a Query object that has been
  70. * transformed to accommodate any specificities of the SQL dialect in use.
  71. *
  72. * @param string $type the type of query to be transformed
  73. * (select, insert, update, delete)
  74. * @return callable
  75. */
  76. public function queryTranslator($type)
  77. {
  78. return function ($query) use ($type) {
  79. if ($this->isAutoQuotingEnabled()) {
  80. $query = (new IdentifierQuoter($this))->quote($query);
  81. }
  82. /** @var \Cake\ORM\Query $query */
  83. $query = $this->{'_' . $type . 'QueryTranslator'}($query);
  84. $translators = $this->_expressionTranslators();
  85. if (!$translators) {
  86. return $query;
  87. }
  88. $query->traverseExpressions(function ($expression) use ($translators, $query) {
  89. foreach ($translators as $class => $method) {
  90. if ($expression instanceof $class) {
  91. $this->{$method}($expression, $query);
  92. }
  93. }
  94. });
  95. return $query;
  96. };
  97. }
  98. /**
  99. * Returns an associative array of methods that will transform Expression
  100. * objects to conform with the specific SQL dialect. Keys are class names
  101. * and values a method in this class.
  102. *
  103. * @return array
  104. */
  105. protected function _expressionTranslators()
  106. {
  107. return [];
  108. }
  109. /**
  110. * Apply translation steps to select queries.
  111. *
  112. * @param \Cake\Database\Query $query The query to translate
  113. * @return \Cake\Database\Query The modified query
  114. */
  115. protected function _selectQueryTranslator($query)
  116. {
  117. return $this->_transformDistinct($query);
  118. }
  119. /**
  120. * Returns the passed query after rewriting the DISTINCT clause, so that drivers
  121. * that do not support the "ON" part can provide the actual way it should be done
  122. *
  123. * @param \Cake\Database\Query $query The query to be transformed
  124. * @return \Cake\Database\Query
  125. */
  126. protected function _transformDistinct($query)
  127. {
  128. if (is_array($query->clause('distinct'))) {
  129. $query->group($query->clause('distinct'), true);
  130. $query->distinct(false);
  131. }
  132. return $query;
  133. }
  134. /**
  135. * Apply translation steps to delete queries.
  136. *
  137. * Chops out aliases on delete query conditions as most database dialects do not
  138. * support aliases in delete queries. This also removes aliases
  139. * in table names as they frequently don't work either.
  140. *
  141. * We are intentionally not supporting deletes with joins as they have even poorer support.
  142. *
  143. * @param \Cake\Database\Query $query The query to translate
  144. * @return \Cake\Database\Query The modified query
  145. */
  146. protected function _deleteQueryTranslator($query)
  147. {
  148. $hadAlias = false;
  149. $tables = [];
  150. foreach ($query->clause('from') as $alias => $table) {
  151. if (is_string($alias)) {
  152. $hadAlias = true;
  153. }
  154. $tables[] = $table;
  155. }
  156. if ($hadAlias) {
  157. $query->from($tables, true);
  158. }
  159. if (!$hadAlias) {
  160. return $query;
  161. }
  162. return $this->_removeAliasesFromConditions($query);
  163. }
  164. /**
  165. * Apply translation steps to update queries.
  166. *
  167. * Chops out aliases on update query conditions as not all database dialects do support
  168. * aliases in update queries.
  169. *
  170. * Just like for delete queries, joins are currently not supported for update queries.
  171. *
  172. * @param \Cake\Database\Query $query The query to translate
  173. * @return \Cake\Database\Query The modified query
  174. */
  175. protected function _updateQueryTranslator($query)
  176. {
  177. return $this->_removeAliasesFromConditions($query);
  178. }
  179. /**
  180. * Removes aliases from the `WHERE` clause of a query.
  181. *
  182. * @param \Cake\Database\Query $query The query to process.
  183. * @return \Cake\Database\Query The modified query.
  184. * @throws \RuntimeException In case the processed query contains any joins, as removing
  185. * aliases from the conditions can break references to the joined tables.
  186. */
  187. protected function _removeAliasesFromConditions($query)
  188. {
  189. if ($query->clause('join')) {
  190. throw new \RuntimeException(
  191. 'Aliases are being removed from conditions for UPDATE/DELETE queries, ' .
  192. 'this can break references to joined tables.'
  193. );
  194. }
  195. $conditions = $query->clause('where');
  196. if ($conditions) {
  197. $conditions->traverse(function ($condition) {
  198. if (!($condition instanceof Comparison)) {
  199. return $condition;
  200. }
  201. $field = $condition->getField();
  202. if ($field instanceof ExpressionInterface || strpos($field, '.') === false) {
  203. return $condition;
  204. }
  205. list(, $field) = explode('.', $field);
  206. $condition->setField($field);
  207. return $condition;
  208. });
  209. }
  210. return $query;
  211. }
  212. /**
  213. * Apply translation steps to insert queries.
  214. *
  215. * @param \Cake\Database\Query $query The query to translate
  216. * @return \Cake\Database\Query The modified query
  217. */
  218. protected function _insertQueryTranslator($query)
  219. {
  220. return $query;
  221. }
  222. /**
  223. * Returns a SQL snippet for creating a new transaction savepoint
  224. *
  225. * @param string $name save point name
  226. * @return string
  227. */
  228. public function savePointSQL($name)
  229. {
  230. return 'SAVEPOINT LEVEL' . $name;
  231. }
  232. /**
  233. * Returns a SQL snippet for releasing a previously created save point
  234. *
  235. * @param string $name save point name
  236. * @return string
  237. */
  238. public function releaseSavePointSQL($name)
  239. {
  240. return 'RELEASE SAVEPOINT LEVEL' . $name;
  241. }
  242. /**
  243. * Returns a SQL snippet for rollbacking a previously created save point
  244. *
  245. * @param string $name save point name
  246. * @return string
  247. */
  248. public function rollbackSavePointSQL($name)
  249. {
  250. return 'ROLLBACK TO SAVEPOINT LEVEL' . $name;
  251. }
  252. }