MySqlGrammar.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Database\Query\Builder;
  5. use Illuminate\Database\Query\JsonExpression;
  6. class MySqlGrammar extends Grammar
  7. {
  8. /**
  9. * The grammar specific operators.
  10. *
  11. * @var array
  12. */
  13. protected $operators = ['sounds like'];
  14. /**
  15. * The components that make up a select clause.
  16. *
  17. * @var array
  18. */
  19. protected $selectComponents = [
  20. 'aggregate',
  21. 'columns',
  22. 'from',
  23. 'joins',
  24. 'wheres',
  25. 'groups',
  26. 'havings',
  27. 'orders',
  28. 'limit',
  29. 'offset',
  30. 'lock',
  31. ];
  32. /**
  33. * Compile a select query into SQL.
  34. *
  35. * @param \Illuminate\Database\Query\Builder $query
  36. * @return string
  37. */
  38. public function compileSelect(Builder $query)
  39. {
  40. if ($query->unions && $query->aggregate) {
  41. return $this->compileUnionAggregate($query);
  42. }
  43. $sql = parent::compileSelect($query);
  44. if ($query->unions) {
  45. $sql = '('.$sql.') '.$this->compileUnions($query);
  46. }
  47. return $sql;
  48. }
  49. /**
  50. * Compile an insert ignore statement into SQL.
  51. *
  52. * @param \Illuminate\Database\Query\Builder $query
  53. * @param array $values
  54. * @return string
  55. */
  56. public function compileInsertOrIgnore(Builder $query, array $values)
  57. {
  58. return Str::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values));
  59. }
  60. /**
  61. * Compile a "JSON contains" statement into SQL.
  62. *
  63. * @param string $column
  64. * @param string $value
  65. * @return string
  66. */
  67. protected function compileJsonContains($column, $value)
  68. {
  69. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  70. return 'json_contains('.$field.', '.$value.$path.')';
  71. }
  72. /**
  73. * Compile a "JSON length" statement into SQL.
  74. *
  75. * @param string $column
  76. * @param string $operator
  77. * @param string $value
  78. * @return string
  79. */
  80. protected function compileJsonLength($column, $operator, $value)
  81. {
  82. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  83. return 'json_length('.$field.$path.') '.$operator.' '.$value;
  84. }
  85. /**
  86. * Compile a single union statement.
  87. *
  88. * @param array $union
  89. * @return string
  90. */
  91. protected function compileUnion(array $union)
  92. {
  93. $conjunction = $union['all'] ? ' union all ' : ' union ';
  94. return $conjunction.'('.$union['query']->toSql().')';
  95. }
  96. /**
  97. * Compile the random statement into SQL.
  98. *
  99. * @param string $seed
  100. * @return string
  101. */
  102. public function compileRandom($seed)
  103. {
  104. return 'RAND('.$seed.')';
  105. }
  106. /**
  107. * Compile the lock into SQL.
  108. *
  109. * @param \Illuminate\Database\Query\Builder $query
  110. * @param bool|string $value
  111. * @return string
  112. */
  113. protected function compileLock(Builder $query, $value)
  114. {
  115. if (! is_string($value)) {
  116. return $value ? 'for update' : 'lock in share mode';
  117. }
  118. return $value;
  119. }
  120. /**
  121. * Compile an update statement into SQL.
  122. *
  123. * @param \Illuminate\Database\Query\Builder $query
  124. * @param array $values
  125. * @return string
  126. */
  127. public function compileUpdate(Builder $query, $values)
  128. {
  129. $table = $this->wrapTable($query->from);
  130. // Each one of the columns in the update statements needs to be wrapped in the
  131. // keyword identifiers, also a place-holder needs to be created for each of
  132. // the values in the list of bindings so we can make the sets statements.
  133. $columns = $this->compileUpdateColumns($values);
  134. // If the query has any "join" clauses, we will setup the joins on the builder
  135. // and compile them so we can attach them to this update, as update queries
  136. // can get join statements to attach to other tables when they're needed.
  137. $joins = '';
  138. if (isset($query->joins)) {
  139. $joins = ' '.$this->compileJoins($query, $query->joins);
  140. }
  141. // Of course, update queries may also be constrained by where clauses so we'll
  142. // need to compile the where clauses and attach it to the query so only the
  143. // intended records are updated by the SQL statements we generate to run.
  144. $where = $this->compileWheres($query);
  145. $sql = rtrim("update {$table}{$joins} set $columns $where");
  146. // If the query has an order by clause we will compile it since MySQL supports
  147. // order bys on update statements. We'll compile them using the typical way
  148. // of compiling order bys. Then they will be appended to the SQL queries.
  149. if (! empty($query->orders)) {
  150. $sql .= ' '.$this->compileOrders($query, $query->orders);
  151. }
  152. // Updates on MySQL also supports "limits", which allow you to easily update a
  153. // single record very easily. This is not supported by all database engines
  154. // so we have customized this update compiler here in order to add it in.
  155. if (isset($query->limit)) {
  156. $sql .= ' '.$this->compileLimit($query, $query->limit);
  157. }
  158. return rtrim($sql);
  159. }
  160. /**
  161. * Compile all of the columns for an update statement.
  162. *
  163. * @param array $values
  164. * @return string
  165. */
  166. protected function compileUpdateColumns($values)
  167. {
  168. return collect($values)->map(function ($value, $key) {
  169. if ($this->isJsonSelector($key)) {
  170. return $this->compileJsonUpdateColumn($key, new JsonExpression($value));
  171. }
  172. return $this->wrap($key).' = '.$this->parameter($value);
  173. })->implode(', ');
  174. }
  175. /**
  176. * Prepares a JSON column being updated using the JSON_SET function.
  177. *
  178. * @param string $key
  179. * @param \Illuminate\Database\Query\JsonExpression $value
  180. * @return string
  181. */
  182. protected function compileJsonUpdateColumn($key, JsonExpression $value)
  183. {
  184. [$field, $path] = $this->wrapJsonFieldAndPath($key);
  185. return "{$field} = json_set({$field}{$path}, {$value->getValue()})";
  186. }
  187. /**
  188. * Prepare the bindings for an update statement.
  189. *
  190. * Booleans, integers, and doubles are inserted into JSON updates as raw values.
  191. *
  192. * @param array $bindings
  193. * @param array $values
  194. * @return array
  195. */
  196. public function prepareBindingsForUpdate(array $bindings, array $values)
  197. {
  198. $values = collect($values)->reject(function ($value, $column) {
  199. return $this->isJsonSelector($column) && is_bool($value);
  200. })->all();
  201. return parent::prepareBindingsForUpdate($bindings, $values);
  202. }
  203. /**
  204. * Compile a delete statement into SQL.
  205. *
  206. * @param \Illuminate\Database\Query\Builder $query
  207. * @return string
  208. */
  209. public function compileDelete(Builder $query)
  210. {
  211. $table = $this->wrapTable($query->from);
  212. $where = is_array($query->wheres) ? $this->compileWheres($query) : '';
  213. return isset($query->joins)
  214. ? $this->compileDeleteWithJoins($query, $table, $where)
  215. : $this->compileDeleteWithoutJoins($query, $table, $where);
  216. }
  217. /**
  218. * Compile a delete query that does not use joins.
  219. *
  220. * @param \Illuminate\Database\Query\Builder $query
  221. * @param string $table
  222. * @param string $where
  223. * @return string
  224. */
  225. protected function compileDeleteWithoutJoins($query, $table, $where)
  226. {
  227. $sql = trim("delete from {$table} {$where}");
  228. // When using MySQL, delete statements may contain order by statements and limits
  229. // so we will compile both of those here. Once we have finished compiling this
  230. // we will return the completed SQL statement so it will be executed for us.
  231. if (! empty($query->orders)) {
  232. $sql .= ' '.$this->compileOrders($query, $query->orders);
  233. }
  234. if (isset($query->limit)) {
  235. $sql .= ' '.$this->compileLimit($query, $query->limit);
  236. }
  237. return $sql;
  238. }
  239. /**
  240. * Compile a delete query that uses joins.
  241. *
  242. * @param \Illuminate\Database\Query\Builder $query
  243. * @param string $table
  244. * @param string $where
  245. * @return string
  246. */
  247. protected function compileDeleteWithJoins($query, $table, $where)
  248. {
  249. $joins = ' '.$this->compileJoins($query, $query->joins);
  250. $alias = stripos($table, ' as ') !== false
  251. ? explode(' as ', $table)[1] : $table;
  252. return trim("delete {$alias} from {$table}{$joins} {$where}");
  253. }
  254. /**
  255. * Wrap a single string in keyword identifiers.
  256. *
  257. * @param string $value
  258. * @return string
  259. */
  260. protected function wrapValue($value)
  261. {
  262. return $value === '*' ? $value : '`'.str_replace('`', '``', $value).'`';
  263. }
  264. /**
  265. * Wrap the given JSON selector.
  266. *
  267. * @param string $value
  268. * @return string
  269. */
  270. protected function wrapJsonSelector($value)
  271. {
  272. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  273. return 'json_unquote(json_extract('.$field.$path.'))';
  274. }
  275. /**
  276. * Wrap the given JSON selector for boolean values.
  277. *
  278. * @param string $value
  279. * @return string
  280. */
  281. protected function wrapJsonBooleanSelector($value)
  282. {
  283. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  284. return 'json_extract('.$field.$path.')';
  285. }
  286. }