Grammar.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Contracts\Database\Query\Expression;
  4. use Illuminate\Database\Concerns\CompilesJsonPaths;
  5. use Illuminate\Database\Grammar as BaseGrammar;
  6. use Illuminate\Database\Query\Builder;
  7. use Illuminate\Database\Query\JoinClause;
  8. use Illuminate\Database\Query\JoinLateralClause;
  9. use Illuminate\Support\Arr;
  10. use RuntimeException;
  11. class Grammar extends BaseGrammar
  12. {
  13. use CompilesJsonPaths;
  14. /**
  15. * The grammar specific operators.
  16. *
  17. * @var array
  18. */
  19. protected $operators = [];
  20. /**
  21. * The grammar specific bitwise operators.
  22. *
  23. * @var array
  24. */
  25. protected $bitwiseOperators = [];
  26. /**
  27. * The components that make up a select clause.
  28. *
  29. * @var string[]
  30. */
  31. protected $selectComponents = [
  32. 'aggregate',
  33. 'columns',
  34. 'from',
  35. 'indexHint',
  36. 'joins',
  37. 'wheres',
  38. 'groups',
  39. 'havings',
  40. 'orders',
  41. 'limit',
  42. 'offset',
  43. 'lock',
  44. ];
  45. /**
  46. * Compile a select query into SQL.
  47. *
  48. * @param \Illuminate\Database\Query\Builder $query
  49. * @return string
  50. */
  51. public function compileSelect(Builder $query)
  52. {
  53. if (($query->unions || $query->havings) && $query->aggregate) {
  54. return $this->compileUnionAggregate($query);
  55. }
  56. // If a "group limit" is in place, we will need to compile the SQL to use a
  57. // different syntax. This primarily supports limits on eager loads using
  58. // Eloquent. We'll also set the columns if they have not been defined.
  59. if (isset($query->groupLimit)) {
  60. if (is_null($query->columns)) {
  61. $query->columns = ['*'];
  62. }
  63. return $this->compileGroupLimit($query);
  64. }
  65. // If the query does not have any columns set, we'll set the columns to the
  66. // * character to just get all of the columns from the database. Then we
  67. // can build the query and concatenate all the pieces together as one.
  68. $original = $query->columns;
  69. if (is_null($query->columns)) {
  70. $query->columns = ['*'];
  71. }
  72. // To compile the query, we'll spin through each component of the query and
  73. // see if that component exists. If it does we'll just call the compiler
  74. // function for the component which is responsible for making the SQL.
  75. $sql = trim($this->concatenate(
  76. $this->compileComponents($query))
  77. );
  78. if ($query->unions) {
  79. $sql = $this->wrapUnion($sql).' '.$this->compileUnions($query);
  80. }
  81. $query->columns = $original;
  82. return $sql;
  83. }
  84. /**
  85. * Compile the components necessary for a select clause.
  86. *
  87. * @param \Illuminate\Database\Query\Builder $query
  88. * @return array
  89. */
  90. protected function compileComponents(Builder $query)
  91. {
  92. $sql = [];
  93. foreach ($this->selectComponents as $component) {
  94. if (isset($query->$component)) {
  95. $method = 'compile'.ucfirst($component);
  96. $sql[$component] = $this->$method($query, $query->$component);
  97. }
  98. }
  99. return $sql;
  100. }
  101. /**
  102. * Compile an aggregated select clause.
  103. *
  104. * @param \Illuminate\Database\Query\Builder $query
  105. * @param array $aggregate
  106. * @return string
  107. */
  108. protected function compileAggregate(Builder $query, $aggregate)
  109. {
  110. $column = $this->columnize($aggregate['columns']);
  111. // If the query has a "distinct" constraint and we're not asking for all columns
  112. // we need to prepend "distinct" onto the column name so that the query takes
  113. // it into account when it performs the aggregating operations on the data.
  114. if (is_array($query->distinct)) {
  115. $column = 'distinct '.$this->columnize($query->distinct);
  116. } elseif ($query->distinct && $column !== '*') {
  117. $column = 'distinct '.$column;
  118. }
  119. return 'select '.$aggregate['function'].'('.$column.') as aggregate';
  120. }
  121. /**
  122. * Compile the "select *" portion of the query.
  123. *
  124. * @param \Illuminate\Database\Query\Builder $query
  125. * @param array $columns
  126. * @return string|null
  127. */
  128. protected function compileColumns(Builder $query, $columns)
  129. {
  130. // If the query is actually performing an aggregating select, we will let that
  131. // compiler handle the building of the select clauses, as it will need some
  132. // more syntax that is best handled by that function to keep things neat.
  133. if (! is_null($query->aggregate)) {
  134. return;
  135. }
  136. if ($query->distinct) {
  137. $select = 'select distinct ';
  138. } else {
  139. $select = 'select ';
  140. }
  141. return $select.$this->columnize($columns);
  142. }
  143. /**
  144. * Compile the "from" portion of the query.
  145. *
  146. * @param \Illuminate\Database\Query\Builder $query
  147. * @param string $table
  148. * @return string
  149. */
  150. protected function compileFrom(Builder $query, $table)
  151. {
  152. return 'from '.$this->wrapTable($table);
  153. }
  154. /**
  155. * Compile the "join" portions of the query.
  156. *
  157. * @param \Illuminate\Database\Query\Builder $query
  158. * @param array $joins
  159. * @return string
  160. */
  161. protected function compileJoins(Builder $query, $joins)
  162. {
  163. return collect($joins)->map(function ($join) use ($query) {
  164. $table = $this->wrapTable($join->table);
  165. $nestedJoins = is_null($join->joins) ? '' : ' '.$this->compileJoins($query, $join->joins);
  166. $tableAndNestedJoins = is_null($join->joins) ? $table : '('.$table.$nestedJoins.')';
  167. if ($join instanceof JoinLateralClause) {
  168. return $this->compileJoinLateral($join, $tableAndNestedJoins);
  169. }
  170. return trim("{$join->type} join {$tableAndNestedJoins} {$this->compileWheres($join)}");
  171. })->implode(' ');
  172. }
  173. /**
  174. * Compile a "lateral join" clause.
  175. *
  176. * @param \Illuminate\Database\Query\JoinLateralClause $join
  177. * @param string $expression
  178. * @return string
  179. *
  180. * @throws \RuntimeException
  181. */
  182. public function compileJoinLateral(JoinLateralClause $join, string $expression): string
  183. {
  184. throw new RuntimeException('This database engine does not support lateral joins.');
  185. }
  186. /**
  187. * Compile the "where" portions of the query.
  188. *
  189. * @param \Illuminate\Database\Query\Builder $query
  190. * @return string
  191. */
  192. public function compileWheres(Builder $query)
  193. {
  194. // Each type of where clause has its own compiler function, which is responsible
  195. // for actually creating the where clauses SQL. This helps keep the code nice
  196. // and maintainable since each clause has a very small method that it uses.
  197. if (is_null($query->wheres)) {
  198. return '';
  199. }
  200. // If we actually have some where clauses, we will strip off the first boolean
  201. // operator, which is added by the query builders for convenience so we can
  202. // avoid checking for the first clauses in each of the compilers methods.
  203. if (count($sql = $this->compileWheresToArray($query)) > 0) {
  204. return $this->concatenateWhereClauses($query, $sql);
  205. }
  206. return '';
  207. }
  208. /**
  209. * Get an array of all the where clauses for the query.
  210. *
  211. * @param \Illuminate\Database\Query\Builder $query
  212. * @return array
  213. */
  214. protected function compileWheresToArray($query)
  215. {
  216. return collect($query->wheres)->map(function ($where) use ($query) {
  217. return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where);
  218. })->all();
  219. }
  220. /**
  221. * Format the where clause statements into one string.
  222. *
  223. * @param \Illuminate\Database\Query\Builder $query
  224. * @param array $sql
  225. * @return string
  226. */
  227. protected function concatenateWhereClauses($query, $sql)
  228. {
  229. $conjunction = $query instanceof JoinClause ? 'on' : 'where';
  230. return $conjunction.' '.$this->removeLeadingBoolean(implode(' ', $sql));
  231. }
  232. /**
  233. * Compile a raw where clause.
  234. *
  235. * @param \Illuminate\Database\Query\Builder $query
  236. * @param array $where
  237. * @return string
  238. */
  239. protected function whereRaw(Builder $query, $where)
  240. {
  241. return $where['sql'] instanceof Expression ? $where['sql']->getValue($this) : $where['sql'];
  242. }
  243. /**
  244. * Compile a basic where clause.
  245. *
  246. * @param \Illuminate\Database\Query\Builder $query
  247. * @param array $where
  248. * @return string
  249. */
  250. protected function whereBasic(Builder $query, $where)
  251. {
  252. $value = $this->parameter($where['value']);
  253. $operator = str_replace('?', '??', $where['operator']);
  254. return $this->wrap($where['column']).' '.$operator.' '.$value;
  255. }
  256. /**
  257. * Compile a bitwise operator where clause.
  258. *
  259. * @param \Illuminate\Database\Query\Builder $query
  260. * @param array $where
  261. * @return string
  262. */
  263. protected function whereBitwise(Builder $query, $where)
  264. {
  265. return $this->whereBasic($query, $where);
  266. }
  267. /**
  268. * Compile a "where in" clause.
  269. *
  270. * @param \Illuminate\Database\Query\Builder $query
  271. * @param array $where
  272. * @return string
  273. */
  274. protected function whereIn(Builder $query, $where)
  275. {
  276. if (! empty($where['values'])) {
  277. return $this->wrap($where['column']).' in ('.$this->parameterize($where['values']).')';
  278. }
  279. return '0 = 1';
  280. }
  281. /**
  282. * Compile a "where not in" clause.
  283. *
  284. * @param \Illuminate\Database\Query\Builder $query
  285. * @param array $where
  286. * @return string
  287. */
  288. protected function whereNotIn(Builder $query, $where)
  289. {
  290. if (! empty($where['values'])) {
  291. return $this->wrap($where['column']).' not in ('.$this->parameterize($where['values']).')';
  292. }
  293. return '1 = 1';
  294. }
  295. /**
  296. * Compile a "where not in raw" clause.
  297. *
  298. * For safety, whereIntegerInRaw ensures this method is only used with integer values.
  299. *
  300. * @param \Illuminate\Database\Query\Builder $query
  301. * @param array $where
  302. * @return string
  303. */
  304. protected function whereNotInRaw(Builder $query, $where)
  305. {
  306. if (! empty($where['values'])) {
  307. return $this->wrap($where['column']).' not in ('.implode(', ', $where['values']).')';
  308. }
  309. return '1 = 1';
  310. }
  311. /**
  312. * Compile a "where in raw" clause.
  313. *
  314. * For safety, whereIntegerInRaw ensures this method is only used with integer values.
  315. *
  316. * @param \Illuminate\Database\Query\Builder $query
  317. * @param array $where
  318. * @return string
  319. */
  320. protected function whereInRaw(Builder $query, $where)
  321. {
  322. if (! empty($where['values'])) {
  323. return $this->wrap($where['column']).' in ('.implode(', ', $where['values']).')';
  324. }
  325. return '0 = 1';
  326. }
  327. /**
  328. * Compile a "where null" clause.
  329. *
  330. * @param \Illuminate\Database\Query\Builder $query
  331. * @param array $where
  332. * @return string
  333. */
  334. protected function whereNull(Builder $query, $where)
  335. {
  336. return $this->wrap($where['column']).' is null';
  337. }
  338. /**
  339. * Compile a "where not null" clause.
  340. *
  341. * @param \Illuminate\Database\Query\Builder $query
  342. * @param array $where
  343. * @return string
  344. */
  345. protected function whereNotNull(Builder $query, $where)
  346. {
  347. return $this->wrap($where['column']).' is not null';
  348. }
  349. /**
  350. * Compile a "between" where clause.
  351. *
  352. * @param \Illuminate\Database\Query\Builder $query
  353. * @param array $where
  354. * @return string
  355. */
  356. protected function whereBetween(Builder $query, $where)
  357. {
  358. $between = $where['not'] ? 'not between' : 'between';
  359. $min = $this->parameter(is_array($where['values']) ? reset($where['values']) : $where['values'][0]);
  360. $max = $this->parameter(is_array($where['values']) ? end($where['values']) : $where['values'][1]);
  361. return $this->wrap($where['column']).' '.$between.' '.$min.' and '.$max;
  362. }
  363. /**
  364. * Compile a "between" where clause.
  365. *
  366. * @param \Illuminate\Database\Query\Builder $query
  367. * @param array $where
  368. * @return string
  369. */
  370. protected function whereBetweenColumns(Builder $query, $where)
  371. {
  372. $between = $where['not'] ? 'not between' : 'between';
  373. $min = $this->wrap(is_array($where['values']) ? reset($where['values']) : $where['values'][0]);
  374. $max = $this->wrap(is_array($where['values']) ? end($where['values']) : $where['values'][1]);
  375. return $this->wrap($where['column']).' '.$between.' '.$min.' and '.$max;
  376. }
  377. /**
  378. * Compile a "where date" clause.
  379. *
  380. * @param \Illuminate\Database\Query\Builder $query
  381. * @param array $where
  382. * @return string
  383. */
  384. protected function whereDate(Builder $query, $where)
  385. {
  386. return $this->dateBasedWhere('date', $query, $where);
  387. }
  388. /**
  389. * Compile a "where time" clause.
  390. *
  391. * @param \Illuminate\Database\Query\Builder $query
  392. * @param array $where
  393. * @return string
  394. */
  395. protected function whereTime(Builder $query, $where)
  396. {
  397. return $this->dateBasedWhere('time', $query, $where);
  398. }
  399. /**
  400. * Compile a "where day" clause.
  401. *
  402. * @param \Illuminate\Database\Query\Builder $query
  403. * @param array $where
  404. * @return string
  405. */
  406. protected function whereDay(Builder $query, $where)
  407. {
  408. return $this->dateBasedWhere('day', $query, $where);
  409. }
  410. /**
  411. * Compile a "where month" clause.
  412. *
  413. * @param \Illuminate\Database\Query\Builder $query
  414. * @param array $where
  415. * @return string
  416. */
  417. protected function whereMonth(Builder $query, $where)
  418. {
  419. return $this->dateBasedWhere('month', $query, $where);
  420. }
  421. /**
  422. * Compile a "where year" clause.
  423. *
  424. * @param \Illuminate\Database\Query\Builder $query
  425. * @param array $where
  426. * @return string
  427. */
  428. protected function whereYear(Builder $query, $where)
  429. {
  430. return $this->dateBasedWhere('year', $query, $where);
  431. }
  432. /**
  433. * Compile a date based where clause.
  434. *
  435. * @param string $type
  436. * @param \Illuminate\Database\Query\Builder $query
  437. * @param array $where
  438. * @return string
  439. */
  440. protected function dateBasedWhere($type, Builder $query, $where)
  441. {
  442. $value = $this->parameter($where['value']);
  443. return $type.'('.$this->wrap($where['column']).') '.$where['operator'].' '.$value;
  444. }
  445. /**
  446. * Compile a where clause comparing two columns.
  447. *
  448. * @param \Illuminate\Database\Query\Builder $query
  449. * @param array $where
  450. * @return string
  451. */
  452. protected function whereColumn(Builder $query, $where)
  453. {
  454. return $this->wrap($where['first']).' '.$where['operator'].' '.$this->wrap($where['second']);
  455. }
  456. /**
  457. * Compile a nested where clause.
  458. *
  459. * @param \Illuminate\Database\Query\Builder $query
  460. * @param array $where
  461. * @return string
  462. */
  463. protected function whereNested(Builder $query, $where)
  464. {
  465. // Here we will calculate what portion of the string we need to remove. If this
  466. // is a join clause query, we need to remove the "on" portion of the SQL and
  467. // if it is a normal query we need to take the leading "where" of queries.
  468. $offset = $where['query'] instanceof JoinClause ? 3 : 6;
  469. return '('.substr($this->compileWheres($where['query']), $offset).')';
  470. }
  471. /**
  472. * Compile a where condition with a sub-select.
  473. *
  474. * @param \Illuminate\Database\Query\Builder $query
  475. * @param array $where
  476. * @return string
  477. */
  478. protected function whereSub(Builder $query, $where)
  479. {
  480. $select = $this->compileSelect($where['query']);
  481. return $this->wrap($where['column']).' '.$where['operator']." ($select)";
  482. }
  483. /**
  484. * Compile a where exists clause.
  485. *
  486. * @param \Illuminate\Database\Query\Builder $query
  487. * @param array $where
  488. * @return string
  489. */
  490. protected function whereExists(Builder $query, $where)
  491. {
  492. return 'exists ('.$this->compileSelect($where['query']).')';
  493. }
  494. /**
  495. * Compile a where exists clause.
  496. *
  497. * @param \Illuminate\Database\Query\Builder $query
  498. * @param array $where
  499. * @return string
  500. */
  501. protected function whereNotExists(Builder $query, $where)
  502. {
  503. return 'not exists ('.$this->compileSelect($where['query']).')';
  504. }
  505. /**
  506. * Compile a where row values condition.
  507. *
  508. * @param \Illuminate\Database\Query\Builder $query
  509. * @param array $where
  510. * @return string
  511. */
  512. protected function whereRowValues(Builder $query, $where)
  513. {
  514. $columns = $this->columnize($where['columns']);
  515. $values = $this->parameterize($where['values']);
  516. return '('.$columns.') '.$where['operator'].' ('.$values.')';
  517. }
  518. /**
  519. * Compile a "where JSON boolean" clause.
  520. *
  521. * @param \Illuminate\Database\Query\Builder $query
  522. * @param array $where
  523. * @return string
  524. */
  525. protected function whereJsonBoolean(Builder $query, $where)
  526. {
  527. $column = $this->wrapJsonBooleanSelector($where['column']);
  528. $value = $this->wrapJsonBooleanValue(
  529. $this->parameter($where['value'])
  530. );
  531. return $column.' '.$where['operator'].' '.$value;
  532. }
  533. /**
  534. * Compile a "where JSON contains" clause.
  535. *
  536. * @param \Illuminate\Database\Query\Builder $query
  537. * @param array $where
  538. * @return string
  539. */
  540. protected function whereJsonContains(Builder $query, $where)
  541. {
  542. $not = $where['not'] ? 'not ' : '';
  543. return $not.$this->compileJsonContains(
  544. $where['column'],
  545. $this->parameter($where['value'])
  546. );
  547. }
  548. /**
  549. * Compile a "JSON contains" statement into SQL.
  550. *
  551. * @param string $column
  552. * @param string $value
  553. * @return string
  554. *
  555. * @throws \RuntimeException
  556. */
  557. protected function compileJsonContains($column, $value)
  558. {
  559. throw new RuntimeException('This database engine does not support JSON contains operations.');
  560. }
  561. /**
  562. * Compile a "where JSON overlaps" clause.
  563. *
  564. * @param \Illuminate\Database\Query\Builder $query
  565. * @param array $where
  566. * @return string
  567. */
  568. protected function whereJsonOverlaps(Builder $query, $where)
  569. {
  570. $not = $where['not'] ? 'not ' : '';
  571. return $not.$this->compileJsonOverlaps(
  572. $where['column'],
  573. $this->parameter($where['value'])
  574. );
  575. }
  576. /**
  577. * Compile a "JSON overlaps" statement into SQL.
  578. *
  579. * @param string $column
  580. * @param string $value
  581. * @return string
  582. *
  583. * @throws \RuntimeException
  584. */
  585. protected function compileJsonOverlaps($column, $value)
  586. {
  587. throw new RuntimeException('This database engine does not support JSON overlaps operations.');
  588. }
  589. /**
  590. * Prepare the binding for a "JSON contains" statement.
  591. *
  592. * @param mixed $binding
  593. * @return string
  594. */
  595. public function prepareBindingForJsonContains($binding)
  596. {
  597. return json_encode($binding, JSON_UNESCAPED_UNICODE);
  598. }
  599. /**
  600. * Compile a "where JSON contains key" clause.
  601. *
  602. * @param \Illuminate\Database\Query\Builder $query
  603. * @param array $where
  604. * @return string
  605. */
  606. protected function whereJsonContainsKey(Builder $query, $where)
  607. {
  608. $not = $where['not'] ? 'not ' : '';
  609. return $not.$this->compileJsonContainsKey(
  610. $where['column']
  611. );
  612. }
  613. /**
  614. * Compile a "JSON contains key" statement into SQL.
  615. *
  616. * @param string $column
  617. * @return string
  618. *
  619. * @throws \RuntimeException
  620. */
  621. protected function compileJsonContainsKey($column)
  622. {
  623. throw new RuntimeException('This database engine does not support JSON contains key operations.');
  624. }
  625. /**
  626. * Compile a "where JSON length" clause.
  627. *
  628. * @param \Illuminate\Database\Query\Builder $query
  629. * @param array $where
  630. * @return string
  631. */
  632. protected function whereJsonLength(Builder $query, $where)
  633. {
  634. return $this->compileJsonLength(
  635. $where['column'],
  636. $where['operator'],
  637. $this->parameter($where['value'])
  638. );
  639. }
  640. /**
  641. * Compile a "JSON length" statement into SQL.
  642. *
  643. * @param string $column
  644. * @param string $operator
  645. * @param string $value
  646. * @return string
  647. *
  648. * @throws \RuntimeException
  649. */
  650. protected function compileJsonLength($column, $operator, $value)
  651. {
  652. throw new RuntimeException('This database engine does not support JSON length operations.');
  653. }
  654. /**
  655. * Compile a "JSON value cast" statement into SQL.
  656. *
  657. * @param string $value
  658. * @return string
  659. */
  660. public function compileJsonValueCast($value)
  661. {
  662. return $value;
  663. }
  664. /**
  665. * Compile a "where fulltext" clause.
  666. *
  667. * @param \Illuminate\Database\Query\Builder $query
  668. * @param array $where
  669. * @return string
  670. */
  671. public function whereFullText(Builder $query, $where)
  672. {
  673. throw new RuntimeException('This database engine does not support fulltext search operations.');
  674. }
  675. /**
  676. * Compile a clause based on an expression.
  677. *
  678. * @param \Illuminate\Database\Query\Builder $query
  679. * @param array $where
  680. * @return string
  681. */
  682. public function whereExpression(Builder $query, $where)
  683. {
  684. return $where['column']->getValue($this);
  685. }
  686. /**
  687. * Compile the "group by" portions of the query.
  688. *
  689. * @param \Illuminate\Database\Query\Builder $query
  690. * @param array $groups
  691. * @return string
  692. */
  693. protected function compileGroups(Builder $query, $groups)
  694. {
  695. return 'group by '.$this->columnize($groups);
  696. }
  697. /**
  698. * Compile the "having" portions of the query.
  699. *
  700. * @param \Illuminate\Database\Query\Builder $query
  701. * @return string
  702. */
  703. protected function compileHavings(Builder $query)
  704. {
  705. return 'having '.$this->removeLeadingBoolean(collect($query->havings)->map(function ($having) {
  706. return $having['boolean'].' '.$this->compileHaving($having);
  707. })->implode(' '));
  708. }
  709. /**
  710. * Compile a single having clause.
  711. *
  712. * @param array $having
  713. * @return string
  714. */
  715. protected function compileHaving(array $having)
  716. {
  717. // If the having clause is "raw", we can just return the clause straight away
  718. // without doing any more processing on it. Otherwise, we will compile the
  719. // clause into SQL based on the components that make it up from builder.
  720. return match ($having['type']) {
  721. 'Raw' => $having['sql'],
  722. 'between' => $this->compileHavingBetween($having),
  723. 'Null' => $this->compileHavingNull($having),
  724. 'NotNull' => $this->compileHavingNotNull($having),
  725. 'bit' => $this->compileHavingBit($having),
  726. 'Expression' => $this->compileHavingExpression($having),
  727. 'Nested' => $this->compileNestedHavings($having),
  728. default => $this->compileBasicHaving($having),
  729. };
  730. }
  731. /**
  732. * Compile a basic having clause.
  733. *
  734. * @param array $having
  735. * @return string
  736. */
  737. protected function compileBasicHaving($having)
  738. {
  739. $column = $this->wrap($having['column']);
  740. $parameter = $this->parameter($having['value']);
  741. return $column.' '.$having['operator'].' '.$parameter;
  742. }
  743. /**
  744. * Compile a "between" having clause.
  745. *
  746. * @param array $having
  747. * @return string
  748. */
  749. protected function compileHavingBetween($having)
  750. {
  751. $between = $having['not'] ? 'not between' : 'between';
  752. $column = $this->wrap($having['column']);
  753. $min = $this->parameter(head($having['values']));
  754. $max = $this->parameter(last($having['values']));
  755. return $column.' '.$between.' '.$min.' and '.$max;
  756. }
  757. /**
  758. * Compile a having null clause.
  759. *
  760. * @param array $having
  761. * @return string
  762. */
  763. protected function compileHavingNull($having)
  764. {
  765. $column = $this->wrap($having['column']);
  766. return $column.' is null';
  767. }
  768. /**
  769. * Compile a having not null clause.
  770. *
  771. * @param array $having
  772. * @return string
  773. */
  774. protected function compileHavingNotNull($having)
  775. {
  776. $column = $this->wrap($having['column']);
  777. return $column.' is not null';
  778. }
  779. /**
  780. * Compile a having clause involving a bit operator.
  781. *
  782. * @param array $having
  783. * @return string
  784. */
  785. protected function compileHavingBit($having)
  786. {
  787. $column = $this->wrap($having['column']);
  788. $parameter = $this->parameter($having['value']);
  789. return '('.$column.' '.$having['operator'].' '.$parameter.') != 0';
  790. }
  791. /**
  792. * Compile a having clause involving an expression.
  793. *
  794. * @param array $having
  795. * @return string
  796. */
  797. protected function compileHavingExpression($having)
  798. {
  799. return $having['column']->getValue($this);
  800. }
  801. /**
  802. * Compile a nested having clause.
  803. *
  804. * @param array $having
  805. * @return string
  806. */
  807. protected function compileNestedHavings($having)
  808. {
  809. return '('.substr($this->compileHavings($having['query']), 7).')';
  810. }
  811. /**
  812. * Compile the "order by" portions of the query.
  813. *
  814. * @param \Illuminate\Database\Query\Builder $query
  815. * @param array $orders
  816. * @return string
  817. */
  818. protected function compileOrders(Builder $query, $orders)
  819. {
  820. if (! empty($orders)) {
  821. return 'order by '.implode(', ', $this->compileOrdersToArray($query, $orders));
  822. }
  823. return '';
  824. }
  825. /**
  826. * Compile the query orders to an array.
  827. *
  828. * @param \Illuminate\Database\Query\Builder $query
  829. * @param array $orders
  830. * @return array
  831. */
  832. protected function compileOrdersToArray(Builder $query, $orders)
  833. {
  834. return array_map(function ($order) {
  835. return $order['sql'] ?? $this->wrap($order['column']).' '.$order['direction'];
  836. }, $orders);
  837. }
  838. /**
  839. * Compile the random statement into SQL.
  840. *
  841. * @param string|int $seed
  842. * @return string
  843. */
  844. public function compileRandom($seed)
  845. {
  846. return 'RANDOM()';
  847. }
  848. /**
  849. * Compile the "limit" portions of the query.
  850. *
  851. * @param \Illuminate\Database\Query\Builder $query
  852. * @param int $limit
  853. * @return string
  854. */
  855. protected function compileLimit(Builder $query, $limit)
  856. {
  857. return 'limit '.(int) $limit;
  858. }
  859. /**
  860. * Compile a group limit clause.
  861. *
  862. * @param \Illuminate\Database\Query\Builder $query
  863. * @return string
  864. */
  865. protected function compileGroupLimit(Builder $query)
  866. {
  867. $selectBindings = array_merge($query->getRawBindings()['select'], $query->getRawBindings()['order']);
  868. $query->setBindings($selectBindings, 'select');
  869. $query->setBindings([], 'order');
  870. $limit = (int) $query->groupLimit['value'];
  871. $offset = $query->offset;
  872. if (isset($offset)) {
  873. $offset = (int) $offset;
  874. $limit += $offset;
  875. $query->offset = null;
  876. }
  877. $components = $this->compileComponents($query);
  878. $components['columns'] .= $this->compileRowNumber(
  879. $query->groupLimit['column'],
  880. $components['orders'] ?? ''
  881. );
  882. unset($components['orders']);
  883. $table = $this->wrap('laravel_table');
  884. $row = $this->wrap('laravel_row');
  885. $sql = $this->concatenate($components);
  886. $sql = 'select * from ('.$sql.') as '.$table.' where '.$row.' <= '.$limit;
  887. if (isset($offset)) {
  888. $sql .= ' and '.$row.' > '.$offset;
  889. }
  890. return $sql.' order by '.$row;
  891. }
  892. /**
  893. * Compile a row number clause.
  894. *
  895. * @param string $partition
  896. * @param string $orders
  897. * @return string
  898. */
  899. protected function compileRowNumber($partition, $orders)
  900. {
  901. $over = trim('partition by '.$this->wrap($partition).' '.$orders);
  902. return ', row_number() over ('.$over.') as '.$this->wrap('laravel_row');
  903. }
  904. /**
  905. * Compile the "offset" portions of the query.
  906. *
  907. * @param \Illuminate\Database\Query\Builder $query
  908. * @param int $offset
  909. * @return string
  910. */
  911. protected function compileOffset(Builder $query, $offset)
  912. {
  913. return 'offset '.(int) $offset;
  914. }
  915. /**
  916. * Compile the "union" queries attached to the main query.
  917. *
  918. * @param \Illuminate\Database\Query\Builder $query
  919. * @return string
  920. */
  921. protected function compileUnions(Builder $query)
  922. {
  923. $sql = '';
  924. foreach ($query->unions as $union) {
  925. $sql .= $this->compileUnion($union);
  926. }
  927. if (! empty($query->unionOrders)) {
  928. $sql .= ' '.$this->compileOrders($query, $query->unionOrders);
  929. }
  930. if (isset($query->unionLimit)) {
  931. $sql .= ' '.$this->compileLimit($query, $query->unionLimit);
  932. }
  933. if (isset($query->unionOffset)) {
  934. $sql .= ' '.$this->compileOffset($query, $query->unionOffset);
  935. }
  936. return ltrim($sql);
  937. }
  938. /**
  939. * Compile a single union statement.
  940. *
  941. * @param array $union
  942. * @return string
  943. */
  944. protected function compileUnion(array $union)
  945. {
  946. $conjunction = $union['all'] ? ' union all ' : ' union ';
  947. return $conjunction.$this->wrapUnion($union['query']->toSql());
  948. }
  949. /**
  950. * Wrap a union subquery in parentheses.
  951. *
  952. * @param string $sql
  953. * @return string
  954. */
  955. protected function wrapUnion($sql)
  956. {
  957. return '('.$sql.')';
  958. }
  959. /**
  960. * Compile a union aggregate query into SQL.
  961. *
  962. * @param \Illuminate\Database\Query\Builder $query
  963. * @return string
  964. */
  965. protected function compileUnionAggregate(Builder $query)
  966. {
  967. $sql = $this->compileAggregate($query, $query->aggregate);
  968. $query->aggregate = null;
  969. return $sql.' from ('.$this->compileSelect($query).') as '.$this->wrapTable('temp_table');
  970. }
  971. /**
  972. * Compile an exists statement into SQL.
  973. *
  974. * @param \Illuminate\Database\Query\Builder $query
  975. * @return string
  976. */
  977. public function compileExists(Builder $query)
  978. {
  979. $select = $this->compileSelect($query);
  980. return "select exists({$select}) as {$this->wrap('exists')}";
  981. }
  982. /**
  983. * Compile an insert statement into SQL.
  984. *
  985. * @param \Illuminate\Database\Query\Builder $query
  986. * @param array $values
  987. * @return string
  988. */
  989. public function compileInsert(Builder $query, array $values)
  990. {
  991. // Essentially we will force every insert to be treated as a batch insert which
  992. // simply makes creating the SQL easier for us since we can utilize the same
  993. // basic routine regardless of an amount of records given to us to insert.
  994. $table = $this->wrapTable($query->from);
  995. if (empty($values)) {
  996. return "insert into {$table} default values";
  997. }
  998. if (! is_array(reset($values))) {
  999. $values = [$values];
  1000. }
  1001. $columns = $this->columnize(array_keys(reset($values)));
  1002. // We need to build a list of parameter place-holders of values that are bound
  1003. // to the query. Each insert should have the exact same number of parameter
  1004. // bindings so we will loop through the record and parameterize them all.
  1005. $parameters = collect($values)->map(function ($record) {
  1006. return '('.$this->parameterize($record).')';
  1007. })->implode(', ');
  1008. return "insert into $table ($columns) values $parameters";
  1009. }
  1010. /**
  1011. * Compile an insert ignore statement into SQL.
  1012. *
  1013. * @param \Illuminate\Database\Query\Builder $query
  1014. * @param array $values
  1015. * @return string
  1016. *
  1017. * @throws \RuntimeException
  1018. */
  1019. public function compileInsertOrIgnore(Builder $query, array $values)
  1020. {
  1021. throw new RuntimeException('This database engine does not support inserting while ignoring errors.');
  1022. }
  1023. /**
  1024. * Compile an insert and get ID statement into SQL.
  1025. *
  1026. * @param \Illuminate\Database\Query\Builder $query
  1027. * @param array $values
  1028. * @param string $sequence
  1029. * @return string
  1030. */
  1031. public function compileInsertGetId(Builder $query, $values, $sequence)
  1032. {
  1033. return $this->compileInsert($query, $values);
  1034. }
  1035. /**
  1036. * Compile an insert statement using a subquery into SQL.
  1037. *
  1038. * @param \Illuminate\Database\Query\Builder $query
  1039. * @param array $columns
  1040. * @param string $sql
  1041. * @return string
  1042. */
  1043. public function compileInsertUsing(Builder $query, array $columns, string $sql)
  1044. {
  1045. $table = $this->wrapTable($query->from);
  1046. if (empty($columns) || $columns === ['*']) {
  1047. return "insert into {$table} $sql";
  1048. }
  1049. return "insert into {$table} ({$this->columnize($columns)}) $sql";
  1050. }
  1051. /**
  1052. * Compile an insert ignore statement using a subquery into SQL.
  1053. *
  1054. * @param \Illuminate\Database\Query\Builder $query
  1055. * @param array $columns
  1056. * @param string $sql
  1057. * @return string
  1058. *
  1059. * @throws \RuntimeException
  1060. */
  1061. public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
  1062. {
  1063. throw new RuntimeException('This database engine does not support inserting while ignoring errors.');
  1064. }
  1065. /**
  1066. * Compile an update statement into SQL.
  1067. *
  1068. * @param \Illuminate\Database\Query\Builder $query
  1069. * @param array $values
  1070. * @return string
  1071. */
  1072. public function compileUpdate(Builder $query, array $values)
  1073. {
  1074. $table = $this->wrapTable($query->from);
  1075. $columns = $this->compileUpdateColumns($query, $values);
  1076. $where = $this->compileWheres($query);
  1077. return trim(
  1078. isset($query->joins)
  1079. ? $this->compileUpdateWithJoins($query, $table, $columns, $where)
  1080. : $this->compileUpdateWithoutJoins($query, $table, $columns, $where)
  1081. );
  1082. }
  1083. /**
  1084. * Compile the columns for an update statement.
  1085. *
  1086. * @param \Illuminate\Database\Query\Builder $query
  1087. * @param array $values
  1088. * @return string
  1089. */
  1090. protected function compileUpdateColumns(Builder $query, array $values)
  1091. {
  1092. return collect($values)->map(function ($value, $key) {
  1093. return $this->wrap($key).' = '.$this->parameter($value);
  1094. })->implode(', ');
  1095. }
  1096. /**
  1097. * Compile an update statement without joins into SQL.
  1098. *
  1099. * @param \Illuminate\Database\Query\Builder $query
  1100. * @param string $table
  1101. * @param string $columns
  1102. * @param string $where
  1103. * @return string
  1104. */
  1105. protected function compileUpdateWithoutJoins(Builder $query, $table, $columns, $where)
  1106. {
  1107. return "update {$table} set {$columns} {$where}";
  1108. }
  1109. /**
  1110. * Compile an update statement with joins into SQL.
  1111. *
  1112. * @param \Illuminate\Database\Query\Builder $query
  1113. * @param string $table
  1114. * @param string $columns
  1115. * @param string $where
  1116. * @return string
  1117. */
  1118. protected function compileUpdateWithJoins(Builder $query, $table, $columns, $where)
  1119. {
  1120. $joins = $this->compileJoins($query, $query->joins);
  1121. return "update {$table} {$joins} set {$columns} {$where}";
  1122. }
  1123. /**
  1124. * Compile an "upsert" statement into SQL.
  1125. *
  1126. * @param \Illuminate\Database\Query\Builder $query
  1127. * @param array $values
  1128. * @param array $uniqueBy
  1129. * @param array $update
  1130. * @return string
  1131. *
  1132. * @throws \RuntimeException
  1133. */
  1134. public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
  1135. {
  1136. throw new RuntimeException('This database engine does not support upserts.');
  1137. }
  1138. /**
  1139. * Prepare the bindings for an update statement.
  1140. *
  1141. * @param array $bindings
  1142. * @param array $values
  1143. * @return array
  1144. */
  1145. public function prepareBindingsForUpdate(array $bindings, array $values)
  1146. {
  1147. $cleanBindings = Arr::except($bindings, ['select', 'join']);
  1148. $values = Arr::flatten(array_map(fn ($value) => value($value), $values));
  1149. return array_values(
  1150. array_merge($bindings['join'], $values, Arr::flatten($cleanBindings))
  1151. );
  1152. }
  1153. /**
  1154. * Compile a delete statement into SQL.
  1155. *
  1156. * @param \Illuminate\Database\Query\Builder $query
  1157. * @return string
  1158. */
  1159. public function compileDelete(Builder $query)
  1160. {
  1161. $table = $this->wrapTable($query->from);
  1162. $where = $this->compileWheres($query);
  1163. return trim(
  1164. isset($query->joins)
  1165. ? $this->compileDeleteWithJoins($query, $table, $where)
  1166. : $this->compileDeleteWithoutJoins($query, $table, $where)
  1167. );
  1168. }
  1169. /**
  1170. * Compile a delete statement without joins into SQL.
  1171. *
  1172. * @param \Illuminate\Database\Query\Builder $query
  1173. * @param string $table
  1174. * @param string $where
  1175. * @return string
  1176. */
  1177. protected function compileDeleteWithoutJoins(Builder $query, $table, $where)
  1178. {
  1179. return "delete from {$table} {$where}";
  1180. }
  1181. /**
  1182. * Compile a delete statement with joins into SQL.
  1183. *
  1184. * @param \Illuminate\Database\Query\Builder $query
  1185. * @param string $table
  1186. * @param string $where
  1187. * @return string
  1188. */
  1189. protected function compileDeleteWithJoins(Builder $query, $table, $where)
  1190. {
  1191. $alias = last(explode(' as ', $table));
  1192. $joins = $this->compileJoins($query, $query->joins);
  1193. return "delete {$alias} from {$table} {$joins} {$where}";
  1194. }
  1195. /**
  1196. * Prepare the bindings for a delete statement.
  1197. *
  1198. * @param array $bindings
  1199. * @return array
  1200. */
  1201. public function prepareBindingsForDelete(array $bindings)
  1202. {
  1203. return Arr::flatten(
  1204. Arr::except($bindings, 'select')
  1205. );
  1206. }
  1207. /**
  1208. * Compile a truncate table statement into SQL.
  1209. *
  1210. * @param \Illuminate\Database\Query\Builder $query
  1211. * @return array
  1212. */
  1213. public function compileTruncate(Builder $query)
  1214. {
  1215. return ['truncate table '.$this->wrapTable($query->from) => []];
  1216. }
  1217. /**
  1218. * Compile the lock into SQL.
  1219. *
  1220. * @param \Illuminate\Database\Query\Builder $query
  1221. * @param bool|string $value
  1222. * @return string
  1223. */
  1224. protected function compileLock(Builder $query, $value)
  1225. {
  1226. return is_string($value) ? $value : '';
  1227. }
  1228. /**
  1229. * Determine if the grammar supports savepoints.
  1230. *
  1231. * @return bool
  1232. */
  1233. public function supportsSavepoints()
  1234. {
  1235. return true;
  1236. }
  1237. /**
  1238. * Compile the SQL statement to define a savepoint.
  1239. *
  1240. * @param string $name
  1241. * @return string
  1242. */
  1243. public function compileSavepoint($name)
  1244. {
  1245. return 'SAVEPOINT '.$name;
  1246. }
  1247. /**
  1248. * Compile the SQL statement to execute a savepoint rollback.
  1249. *
  1250. * @param string $name
  1251. * @return string
  1252. */
  1253. public function compileSavepointRollBack($name)
  1254. {
  1255. return 'ROLLBACK TO SAVEPOINT '.$name;
  1256. }
  1257. /**
  1258. * Wrap the given JSON selector for boolean values.
  1259. *
  1260. * @param string $value
  1261. * @return string
  1262. */
  1263. protected function wrapJsonBooleanSelector($value)
  1264. {
  1265. return $this->wrapJsonSelector($value);
  1266. }
  1267. /**
  1268. * Wrap the given JSON boolean value.
  1269. *
  1270. * @param string $value
  1271. * @return string
  1272. */
  1273. protected function wrapJsonBooleanValue($value)
  1274. {
  1275. return $value;
  1276. }
  1277. /**
  1278. * Concatenate an array of segments, removing empties.
  1279. *
  1280. * @param array $segments
  1281. * @return string
  1282. */
  1283. protected function concatenate($segments)
  1284. {
  1285. return implode(' ', array_filter($segments, function ($value) {
  1286. return (string) $value !== '';
  1287. }));
  1288. }
  1289. /**
  1290. * Remove the leading boolean from a statement.
  1291. *
  1292. * @param string $value
  1293. * @return string
  1294. */
  1295. protected function removeLeadingBoolean($value)
  1296. {
  1297. return preg_replace('/and |or /i', '', $value, 1);
  1298. }
  1299. /**
  1300. * Substitute the given bindings into the given raw SQL query.
  1301. *
  1302. * @param string $sql
  1303. * @param array $bindings
  1304. * @return string
  1305. */
  1306. public function substituteBindingsIntoRawSql($sql, $bindings)
  1307. {
  1308. $bindings = array_map(fn ($value) => $this->escape($value), $bindings);
  1309. $query = '';
  1310. $isStringLiteral = false;
  1311. for ($i = 0; $i < strlen($sql); $i++) {
  1312. $char = $sql[$i];
  1313. $nextChar = $sql[$i + 1] ?? null;
  1314. // Single quotes can be escaped as '' according to the SQL standard while
  1315. // MySQL uses \'. Postgres has operators like ?| that must get encoded
  1316. // in PHP like ??|. We should skip over the escaped characters here.
  1317. if (in_array($char.$nextChar, ["\'", "''", '??'])) {
  1318. $query .= $char.$nextChar;
  1319. $i += 1;
  1320. } elseif ($char === "'") { // Starting / leaving string literal...
  1321. $query .= $char;
  1322. $isStringLiteral = ! $isStringLiteral;
  1323. } elseif ($char === '?' && ! $isStringLiteral) { // Substitutable binding...
  1324. $query .= array_shift($bindings) ?? '?';
  1325. } else { // Normal character...
  1326. $query .= $char;
  1327. }
  1328. }
  1329. return $query;
  1330. }
  1331. /**
  1332. * Get the grammar specific operators.
  1333. *
  1334. * @return array
  1335. */
  1336. public function getOperators()
  1337. {
  1338. return $this->operators;
  1339. }
  1340. /**
  1341. * Get the grammar specific bitwise operators.
  1342. *
  1343. * @return array
  1344. */
  1345. public function getBitwiseOperators()
  1346. {
  1347. return $this->bitwiseOperators;
  1348. }
  1349. }