MySqlGrammar.php 9.1 KB

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