MySqlGrammar.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Database\Query\JoinLateralClause;
  5. use Illuminate\Support\Str;
  6. class MySqlGrammar extends Grammar
  7. {
  8. /**
  9. * The grammar specific operators.
  10. *
  11. * @var string[]
  12. */
  13. protected $operators = ['sounds like'];
  14. /**
  15. * Add a "where null" clause to the query.
  16. *
  17. * @param \Illuminate\Database\Query\Builder $query
  18. * @param array $where
  19. * @return string
  20. */
  21. protected function whereNull(Builder $query, $where)
  22. {
  23. $columnValue = (string) $this->getValue($where['column']);
  24. if ($this->isJsonSelector($columnValue)) {
  25. [$field, $path] = $this->wrapJsonFieldAndPath($columnValue);
  26. return '(json_extract('.$field.$path.') is null OR json_type(json_extract('.$field.$path.')) = \'NULL\')';
  27. }
  28. return parent::whereNull($query, $where);
  29. }
  30. /**
  31. * Add a "where not null" clause to the query.
  32. *
  33. * @param \Illuminate\Database\Query\Builder $query
  34. * @param array $where
  35. * @return string
  36. */
  37. protected function whereNotNull(Builder $query, $where)
  38. {
  39. $columnValue = (string) $this->getValue($where['column']);
  40. if ($this->isJsonSelector($columnValue)) {
  41. [$field, $path] = $this->wrapJsonFieldAndPath($columnValue);
  42. return '(json_extract('.$field.$path.') is not null AND json_type(json_extract('.$field.$path.')) != \'NULL\')';
  43. }
  44. return parent::whereNotNull($query, $where);
  45. }
  46. /**
  47. * Compile a "where fulltext" clause.
  48. *
  49. * @param \Illuminate\Database\Query\Builder $query
  50. * @param array $where
  51. * @return string
  52. */
  53. public function whereFullText(Builder $query, $where)
  54. {
  55. $columns = $this->columnize($where['columns']);
  56. $value = $this->parameter($where['value']);
  57. $mode = ($where['options']['mode'] ?? []) === 'boolean'
  58. ? ' in boolean mode'
  59. : ' in natural language mode';
  60. $expanded = ($where['options']['expanded'] ?? []) && ($where['options']['mode'] ?? []) !== 'boolean'
  61. ? ' with query expansion'
  62. : '';
  63. return "match ({$columns}) against (".$value."{$mode}{$expanded})";
  64. }
  65. /**
  66. * Compile the index hints for the query.
  67. *
  68. * @param \Illuminate\Database\Query\Builder $query
  69. * @param \Illuminate\Database\Query\IndexHint $indexHint
  70. * @return string
  71. */
  72. protected function compileIndexHint(Builder $query, $indexHint)
  73. {
  74. return match ($indexHint->type) {
  75. 'hint' => "use index ({$indexHint->index})",
  76. 'force' => "force index ({$indexHint->index})",
  77. default => "ignore index ({$indexHint->index})",
  78. };
  79. }
  80. /**
  81. * Compile a group limit clause.
  82. *
  83. * @param \Illuminate\Database\Query\Builder $query
  84. * @return string
  85. */
  86. protected function compileGroupLimit(Builder $query)
  87. {
  88. return $this->useLegacyGroupLimit($query)
  89. ? $this->compileLegacyGroupLimit($query)
  90. : parent::compileGroupLimit($query);
  91. }
  92. /**
  93. * Determine whether to use a legacy group limit clause for MySQL < 8.0.
  94. *
  95. * @param \Illuminate\Database\Query\Builder $query
  96. * @return bool
  97. */
  98. public function useLegacyGroupLimit(Builder $query)
  99. {
  100. $version = $query->getConnection()->getServerVersion();
  101. return ! $query->getConnection()->isMaria() && version_compare($version, '8.0.11') < 0;
  102. }
  103. /**
  104. * Compile a group limit clause for MySQL < 8.0.
  105. *
  106. * Derived from https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/.
  107. *
  108. * @param \Illuminate\Database\Query\Builder $query
  109. * @return string
  110. */
  111. protected function compileLegacyGroupLimit(Builder $query)
  112. {
  113. $limit = (int) $query->groupLimit['value'];
  114. $offset = $query->offset;
  115. if (isset($offset)) {
  116. $offset = (int) $offset;
  117. $limit += $offset;
  118. $query->offset = null;
  119. }
  120. $column = last(explode('.', $query->groupLimit['column']));
  121. $column = $this->wrap($column);
  122. $partition = ', @laravel_row := if(@laravel_group = '.$column.', @laravel_row + 1, 1) as `laravel_row`';
  123. $partition .= ', @laravel_group := '.$column;
  124. $orders = (array) $query->orders;
  125. array_unshift($orders, [
  126. 'column' => $query->groupLimit['column'],
  127. 'direction' => 'asc',
  128. ]);
  129. $query->orders = $orders;
  130. $components = $this->compileComponents($query);
  131. $sql = $this->concatenate($components);
  132. $from = '(select @laravel_row := 0, @laravel_group := 0) as `laravel_vars`, ('.$sql.') as `laravel_table`';
  133. $sql = 'select `laravel_table`.*'.$partition.' from '.$from.' having `laravel_row` <= '.$limit;
  134. if (isset($offset)) {
  135. $sql .= ' and `laravel_row` > '.$offset;
  136. }
  137. return $sql.' order by `laravel_row`';
  138. }
  139. /**
  140. * Compile an insert ignore statement into SQL.
  141. *
  142. * @param \Illuminate\Database\Query\Builder $query
  143. * @param array $values
  144. * @return string
  145. */
  146. public function compileInsertOrIgnore(Builder $query, array $values)
  147. {
  148. return Str::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values));
  149. }
  150. /**
  151. * Compile an insert ignore statement using a subquery into SQL.
  152. *
  153. * @param \Illuminate\Database\Query\Builder $query
  154. * @param array $columns
  155. * @param string $sql
  156. * @return string
  157. */
  158. public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
  159. {
  160. return Str::replaceFirst('insert', 'insert ignore', $this->compileInsertUsing($query, $columns, $sql));
  161. }
  162. /**
  163. * Compile a "JSON contains" statement into SQL.
  164. *
  165. * @param string $column
  166. * @param string $value
  167. * @return string
  168. */
  169. protected function compileJsonContains($column, $value)
  170. {
  171. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  172. return 'json_contains('.$field.', '.$value.$path.')';
  173. }
  174. /**
  175. * Compile a "JSON overlaps" statement into SQL.
  176. *
  177. * @param string $column
  178. * @param string $value
  179. * @return string
  180. */
  181. protected function compileJsonOverlaps($column, $value)
  182. {
  183. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  184. return 'json_overlaps('.$field.', '.$value.$path.')';
  185. }
  186. /**
  187. * Compile a "JSON contains key" statement into SQL.
  188. *
  189. * @param string $column
  190. * @return string
  191. */
  192. protected function compileJsonContainsKey($column)
  193. {
  194. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  195. return 'ifnull(json_contains_path('.$field.', \'one\''.$path.'), 0)';
  196. }
  197. /**
  198. * Compile a "JSON length" statement into SQL.
  199. *
  200. * @param string $column
  201. * @param string $operator
  202. * @param string $value
  203. * @return string
  204. */
  205. protected function compileJsonLength($column, $operator, $value)
  206. {
  207. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  208. return 'json_length('.$field.$path.') '.$operator.' '.$value;
  209. }
  210. /**
  211. * Compile a "JSON value cast" statement into SQL.
  212. *
  213. * @param string $value
  214. * @return string
  215. */
  216. public function compileJsonValueCast($value)
  217. {
  218. return 'cast('.$value.' as json)';
  219. }
  220. /**
  221. * Compile the random statement into SQL.
  222. *
  223. * @param string|int $seed
  224. * @return string
  225. */
  226. public function compileRandom($seed)
  227. {
  228. return 'RAND('.$seed.')';
  229. }
  230. /**
  231. * Compile the lock into SQL.
  232. *
  233. * @param \Illuminate\Database\Query\Builder $query
  234. * @param bool|string $value
  235. * @return string
  236. */
  237. protected function compileLock(Builder $query, $value)
  238. {
  239. if (! is_string($value)) {
  240. return $value ? 'for update' : 'lock in share mode';
  241. }
  242. return $value;
  243. }
  244. /**
  245. * Compile an insert statement into SQL.
  246. *
  247. * @param \Illuminate\Database\Query\Builder $query
  248. * @param array $values
  249. * @return string
  250. */
  251. public function compileInsert(Builder $query, array $values)
  252. {
  253. if (empty($values)) {
  254. $values = [[]];
  255. }
  256. return parent::compileInsert($query, $values);
  257. }
  258. /**
  259. * Compile the columns for an update statement.
  260. *
  261. * @param \Illuminate\Database\Query\Builder $query
  262. * @param array $values
  263. * @return string
  264. */
  265. protected function compileUpdateColumns(Builder $query, array $values)
  266. {
  267. return collect($values)->map(function ($value, $key) {
  268. if ($this->isJsonSelector($key)) {
  269. return $this->compileJsonUpdateColumn($key, $value);
  270. }
  271. return $this->wrap($key).' = '.$this->parameter($value);
  272. })->implode(', ');
  273. }
  274. /**
  275. * Compile an "upsert" statement into SQL.
  276. *
  277. * @param \Illuminate\Database\Query\Builder $query
  278. * @param array $values
  279. * @param array $uniqueBy
  280. * @param array $update
  281. * @return string
  282. */
  283. public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
  284. {
  285. $useUpsertAlias = $query->connection->getConfig('use_upsert_alias');
  286. $sql = $this->compileInsert($query, $values);
  287. if ($useUpsertAlias) {
  288. $sql .= ' as laravel_upsert_alias';
  289. }
  290. $sql .= ' on duplicate key update ';
  291. $columns = collect($update)->map(function ($value, $key) use ($useUpsertAlias) {
  292. if (! is_numeric($key)) {
  293. return $this->wrap($key).' = '.$this->parameter($value);
  294. }
  295. return $useUpsertAlias
  296. ? $this->wrap($value).' = '.$this->wrap('laravel_upsert_alias').'.'.$this->wrap($value)
  297. : $this->wrap($value).' = values('.$this->wrap($value).')';
  298. })->implode(', ');
  299. return $sql.$columns;
  300. }
  301. /**
  302. * Compile a "lateral join" clause.
  303. *
  304. * @param \Illuminate\Database\Query\JoinLateralClause $join
  305. * @param string $expression
  306. * @return string
  307. */
  308. public function compileJoinLateral(JoinLateralClause $join, string $expression): string
  309. {
  310. return trim("{$join->type} join lateral {$expression} on true");
  311. }
  312. /**
  313. * Prepare a JSON column being updated using the JSON_SET function.
  314. *
  315. * @param string $key
  316. * @param mixed $value
  317. * @return string
  318. */
  319. protected function compileJsonUpdateColumn($key, $value)
  320. {
  321. if (is_bool($value)) {
  322. $value = $value ? 'true' : 'false';
  323. } elseif (is_array($value)) {
  324. $value = 'cast(? as json)';
  325. } else {
  326. $value = $this->parameter($value);
  327. }
  328. [$field, $path] = $this->wrapJsonFieldAndPath($key);
  329. return "{$field} = json_set({$field}{$path}, {$value})";
  330. }
  331. /**
  332. * Compile an update statement without joins into SQL.
  333. *
  334. * @param \Illuminate\Database\Query\Builder $query
  335. * @param string $table
  336. * @param string $columns
  337. * @param string $where
  338. * @return string
  339. */
  340. protected function compileUpdateWithoutJoins(Builder $query, $table, $columns, $where)
  341. {
  342. $sql = parent::compileUpdateWithoutJoins($query, $table, $columns, $where);
  343. if (! empty($query->orders)) {
  344. $sql .= ' '.$this->compileOrders($query, $query->orders);
  345. }
  346. if (isset($query->limit)) {
  347. $sql .= ' '.$this->compileLimit($query, $query->limit);
  348. }
  349. return $sql;
  350. }
  351. /**
  352. * Prepare the bindings for an update statement.
  353. *
  354. * Booleans, integers, and doubles are inserted into JSON updates as raw values.
  355. *
  356. * @param array $bindings
  357. * @param array $values
  358. * @return array
  359. */
  360. public function prepareBindingsForUpdate(array $bindings, array $values)
  361. {
  362. $values = collect($values)->reject(function ($value, $column) {
  363. return $this->isJsonSelector($column) && is_bool($value);
  364. })->map(function ($value) {
  365. return is_array($value) ? json_encode($value) : $value;
  366. })->all();
  367. return parent::prepareBindingsForUpdate($bindings, $values);
  368. }
  369. /**
  370. * Compile a delete query that does not use joins.
  371. *
  372. * @param \Illuminate\Database\Query\Builder $query
  373. * @param string $table
  374. * @param string $where
  375. * @return string
  376. */
  377. protected function compileDeleteWithoutJoins(Builder $query, $table, $where)
  378. {
  379. $sql = parent::compileDeleteWithoutJoins($query, $table, $where);
  380. // When using MySQL, delete statements may contain order by statements and limits
  381. // so we will compile both of those here. Once we have finished compiling this
  382. // we will return the completed SQL statement so it will be executed for us.
  383. if (! empty($query->orders)) {
  384. $sql .= ' '.$this->compileOrders($query, $query->orders);
  385. }
  386. if (isset($query->limit)) {
  387. $sql .= ' '.$this->compileLimit($query, $query->limit);
  388. }
  389. return $sql;
  390. }
  391. /**
  392. * Wrap a single string in keyword identifiers.
  393. *
  394. * @param string $value
  395. * @return string
  396. */
  397. protected function wrapValue($value)
  398. {
  399. return $value === '*' ? $value : '`'.str_replace('`', '``', $value).'`';
  400. }
  401. /**
  402. * Wrap the given JSON selector.
  403. *
  404. * @param string $value
  405. * @return string
  406. */
  407. protected function wrapJsonSelector($value)
  408. {
  409. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  410. return 'json_unquote(json_extract('.$field.$path.'))';
  411. }
  412. /**
  413. * Wrap the given JSON selector for boolean values.
  414. *
  415. * @param string $value
  416. * @return string
  417. */
  418. protected function wrapJsonBooleanSelector($value)
  419. {
  420. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  421. return 'json_extract('.$field.$path.')';
  422. }
  423. }