MySqlGrammar.php 8.9KB

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