Grammar.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use RuntimeException;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Str;
  6. use Illuminate\Database\Query\Builder;
  7. use Illuminate\Database\Query\JoinClause;
  8. use Illuminate\Database\Grammar as BaseGrammar;
  9. class Grammar extends BaseGrammar
  10. {
  11. /**
  12. * The grammar specific operators.
  13. *
  14. * @var array
  15. */
  16. protected $operators = [];
  17. /**
  18. * The components that make up a select clause.
  19. *
  20. * @var array
  21. */
  22. protected $selectComponents = [
  23. 'aggregate',
  24. 'columns',
  25. 'from',
  26. 'joins',
  27. 'wheres',
  28. 'groups',
  29. 'havings',
  30. 'orders',
  31. 'limit',
  32. 'offset',
  33. 'unions',
  34. 'lock',
  35. ];
  36. /**
  37. * Compile a select query into SQL.
  38. *
  39. * @param \Illuminate\Database\Query\Builder $query
  40. * @return string
  41. */
  42. public function compileSelect(Builder $query)
  43. {
  44. if ($query->unions && $query->aggregate) {
  45. return $this->compileUnionAggregate($query);
  46. }
  47. // If the query does not have any columns set, we'll set the columns to the
  48. // * character to just get all of the columns from the database. Then we
  49. // can build the query and concatenate all the pieces together as one.
  50. $original = $query->columns;
  51. if (is_null($query->columns)) {
  52. $query->columns = ['*'];
  53. }
  54. // To compile the query, we'll spin through each component of the query and
  55. // see if that component exists. If it does we'll just call the compiler
  56. // function for the component which is responsible for making the SQL.
  57. $sql = trim($this->concatenate(
  58. $this->compileComponents($query))
  59. );
  60. $query->columns = $original;
  61. return $sql;
  62. }
  63. /**
  64. * Compile the components necessary for a select clause.
  65. *
  66. * @param \Illuminate\Database\Query\Builder $query
  67. * @return array
  68. */
  69. protected function compileComponents(Builder $query)
  70. {
  71. $sql = [];
  72. foreach ($this->selectComponents as $component) {
  73. // To compile the query, we'll spin through each component of the query and
  74. // see if that component exists. If it does we'll just call the compiler
  75. // function for the component which is responsible for making the SQL.
  76. if (isset($query->$component) && ! is_null($query->$component)) {
  77. $method = 'compile'.ucfirst($component);
  78. $sql[$component] = $this->$method($query, $query->$component);
  79. }
  80. }
  81. return $sql;
  82. }
  83. /**
  84. * Compile an aggregated select clause.
  85. *
  86. * @param \Illuminate\Database\Query\Builder $query
  87. * @param array $aggregate
  88. * @return string
  89. */
  90. protected function compileAggregate(Builder $query, $aggregate)
  91. {
  92. $column = $this->columnize($aggregate['columns']);
  93. // If the query has a "distinct" constraint and we're not asking for all columns
  94. // we need to prepend "distinct" onto the column name so that the query takes
  95. // it into account when it performs the aggregating operations on the data.
  96. if ($query->distinct && $column !== '*') {
  97. $column = 'distinct '.$column;
  98. }
  99. return 'select '.$aggregate['function'].'('.$column.') as aggregate';
  100. }
  101. /**
  102. * Compile the "select *" portion of the query.
  103. *
  104. * @param \Illuminate\Database\Query\Builder $query
  105. * @param array $columns
  106. * @return string|null
  107. */
  108. protected function compileColumns(Builder $query, $columns)
  109. {
  110. // If the query is actually performing an aggregating select, we will let that
  111. // compiler handle the building of the select clauses, as it will need some
  112. // more syntax that is best handled by that function to keep things neat.
  113. if (! is_null($query->aggregate)) {
  114. return;
  115. }
  116. $select = $query->distinct ? 'select distinct ' : 'select ';
  117. return $select.$this->columnize($columns);
  118. }
  119. /**
  120. * Compile the "from" portion of the query.
  121. *
  122. * @param \Illuminate\Database\Query\Builder $query
  123. * @param string $table
  124. * @return string
  125. */
  126. protected function compileFrom(Builder $query, $table)
  127. {
  128. return 'from '.$this->wrapTable($table);
  129. }
  130. /**
  131. * Compile the "join" portions of the query.
  132. *
  133. * @param \Illuminate\Database\Query\Builder $query
  134. * @param array $joins
  135. * @return string
  136. */
  137. protected function compileJoins(Builder $query, $joins)
  138. {
  139. return collect($joins)->map(function ($join) use ($query) {
  140. $table = $this->wrapTable($join->table);
  141. $nestedJoins = is_null($join->joins) ? '' : ' '.$this->compileJoins($query, $join->joins);
  142. $tableAndNestedJoins = is_null($join->joins) ? $table : '('.$table.$nestedJoins.')';
  143. return trim("{$join->type} join {$tableAndNestedJoins} {$this->compileWheres($join)}");
  144. })->implode(' ');
  145. }
  146. /**
  147. * Compile the "where" portions of the query.
  148. *
  149. * @param \Illuminate\Database\Query\Builder $query
  150. * @return string
  151. */
  152. protected function compileWheres(Builder $query)
  153. {
  154. // Each type of where clauses has its own compiler function which is responsible
  155. // for actually creating the where clauses SQL. This helps keep the code nice
  156. // and maintainable since each clause has a very small method that it uses.
  157. if (is_null($query->wheres)) {
  158. return '';
  159. }
  160. // If we actually have some where clauses, we will strip off the first boolean
  161. // operator, which is added by the query builders for convenience so we can
  162. // avoid checking for the first clauses in each of the compilers methods.
  163. if (count($sql = $this->compileWheresToArray($query)) > 0) {
  164. return $this->concatenateWhereClauses($query, $sql);
  165. }
  166. return '';
  167. }
  168. /**
  169. * Get an array of all the where clauses for the query.
  170. *
  171. * @param \Illuminate\Database\Query\Builder $query
  172. * @return array
  173. */
  174. protected function compileWheresToArray($query)
  175. {
  176. return collect($query->wheres)->map(function ($where) use ($query) {
  177. return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where);
  178. })->all();
  179. }
  180. /**
  181. * Format the where clause statements into one string.
  182. *
  183. * @param \Illuminate\Database\Query\Builder $query
  184. * @param array $sql
  185. * @return string
  186. */
  187. protected function concatenateWhereClauses($query, $sql)
  188. {
  189. $conjunction = $query instanceof JoinClause ? 'on' : 'where';
  190. return $conjunction.' '.$this->removeLeadingBoolean(implode(' ', $sql));
  191. }
  192. /**
  193. * Compile a raw where clause.
  194. *
  195. * @param \Illuminate\Database\Query\Builder $query
  196. * @param array $where
  197. * @return string
  198. */
  199. protected function whereRaw(Builder $query, $where)
  200. {
  201. return $where['sql'];
  202. }
  203. /**
  204. * Compile a basic where clause.
  205. *
  206. * @param \Illuminate\Database\Query\Builder $query
  207. * @param array $where
  208. * @return string
  209. */
  210. protected function whereBasic(Builder $query, $where)
  211. {
  212. $value = $this->parameter($where['value']);
  213. return $this->wrap($where['column']).' '.$where['operator'].' '.$value;
  214. }
  215. /**
  216. * Compile a "where in" clause.
  217. *
  218. * @param \Illuminate\Database\Query\Builder $query
  219. * @param array $where
  220. * @return string
  221. */
  222. protected function whereIn(Builder $query, $where)
  223. {
  224. if (! empty($where['values'])) {
  225. return $this->wrap($where['column']).' in ('.$this->parameterize($where['values']).')';
  226. }
  227. return '0 = 1';
  228. }
  229. /**
  230. * Compile a "where not in" clause.
  231. *
  232. * @param \Illuminate\Database\Query\Builder $query
  233. * @param array $where
  234. * @return string
  235. */
  236. protected function whereNotIn(Builder $query, $where)
  237. {
  238. if (! empty($where['values'])) {
  239. return $this->wrap($where['column']).' not in ('.$this->parameterize($where['values']).')';
  240. }
  241. return '1 = 1';
  242. }
  243. /**
  244. * Compile a "where not in raw" clause.
  245. *
  246. * For safety, whereIntegerInRaw ensures this method is only used with integer values.
  247. *
  248. * @param \Illuminate\Database\Query\Builder $query
  249. * @param array $where
  250. * @return string
  251. */
  252. protected function whereNotInRaw(Builder $query, $where)
  253. {
  254. if (! empty($where['values'])) {
  255. return $this->wrap($where['column']).' not in ('.implode(', ', $where['values']).')';
  256. }
  257. return '1 = 1';
  258. }
  259. /**
  260. * Compile a where in sub-select clause.
  261. *
  262. * @param \Illuminate\Database\Query\Builder $query
  263. * @param array $where
  264. * @return string
  265. */
  266. protected function whereInSub(Builder $query, $where)
  267. {
  268. return $this->wrap($where['column']).' in ('.$this->compileSelect($where['query']).')';
  269. }
  270. /**
  271. * Compile a where not in sub-select clause.
  272. *
  273. * @param \Illuminate\Database\Query\Builder $query
  274. * @param array $where
  275. * @return string
  276. */
  277. protected function whereNotInSub(Builder $query, $where)
  278. {
  279. return $this->wrap($where['column']).' not in ('.$this->compileSelect($where['query']).')';
  280. }
  281. /**
  282. * Compile a "where in raw" clause.
  283. *
  284. * For safety, whereIntegerInRaw ensures this method is only used with integer values.
  285. *
  286. * @param \Illuminate\Database\Query\Builder $query
  287. * @param array $where
  288. * @return string
  289. */
  290. protected function whereInRaw(Builder $query, $where)
  291. {
  292. if (! empty($where['values'])) {
  293. return $this->wrap($where['column']).' in ('.implode(', ', $where['values']).')';
  294. }
  295. return '0 = 1';
  296. }
  297. /**
  298. * Compile a "where null" clause.
  299. *
  300. * @param \Illuminate\Database\Query\Builder $query
  301. * @param array $where
  302. * @return string
  303. */
  304. protected function whereNull(Builder $query, $where)
  305. {
  306. return $this->wrap($where['column']).' is null';
  307. }
  308. /**
  309. * Compile a "where not null" clause.
  310. *
  311. * @param \Illuminate\Database\Query\Builder $query
  312. * @param array $where
  313. * @return string
  314. */
  315. protected function whereNotNull(Builder $query, $where)
  316. {
  317. return $this->wrap($where['column']).' is not null';
  318. }
  319. /**
  320. * Compile a "between" where clause.
  321. *
  322. * @param \Illuminate\Database\Query\Builder $query
  323. * @param array $where
  324. * @return string
  325. */
  326. protected function whereBetween(Builder $query, $where)
  327. {
  328. $between = $where['not'] ? 'not between' : 'between';
  329. $min = $this->parameter(reset($where['values']));
  330. $max = $this->parameter(end($where['values']));
  331. return $this->wrap($where['column']).' '.$between.' '.$min.' and '.$max;
  332. }
  333. /**
  334. * Compile a "where date" clause.
  335. *
  336. * @param \Illuminate\Database\Query\Builder $query
  337. * @param array $where
  338. * @return string
  339. */
  340. protected function whereDate(Builder $query, $where)
  341. {
  342. return $this->dateBasedWhere('date', $query, $where);
  343. }
  344. /**
  345. * Compile a "where time" clause.
  346. *
  347. * @param \Illuminate\Database\Query\Builder $query
  348. * @param array $where
  349. * @return string
  350. */
  351. protected function whereTime(Builder $query, $where)
  352. {
  353. return $this->dateBasedWhere('time', $query, $where);
  354. }
  355. /**
  356. * Compile a "where day" clause.
  357. *
  358. * @param \Illuminate\Database\Query\Builder $query
  359. * @param array $where
  360. * @return string
  361. */
  362. protected function whereDay(Builder $query, $where)
  363. {
  364. return $this->dateBasedWhere('day', $query, $where);
  365. }
  366. /**
  367. * Compile a "where month" clause.
  368. *
  369. * @param \Illuminate\Database\Query\Builder $query
  370. * @param array $where
  371. * @return string
  372. */
  373. protected function whereMonth(Builder $query, $where)
  374. {
  375. return $this->dateBasedWhere('month', $query, $where);
  376. }
  377. /**
  378. * Compile a "where year" clause.
  379. *
  380. * @param \Illuminate\Database\Query\Builder $query
  381. * @param array $where
  382. * @return string
  383. */
  384. protected function whereYear(Builder $query, $where)
  385. {
  386. return $this->dateBasedWhere('year', $query, $where);
  387. }
  388. /**
  389. * Compile a date based where clause.
  390. *
  391. * @param string $type
  392. * @param \Illuminate\Database\Query\Builder $query
  393. * @param array $where
  394. * @return string
  395. */
  396. protected function dateBasedWhere($type, Builder $query, $where)
  397. {
  398. $value = $this->parameter($where['value']);
  399. return $type.'('.$this->wrap($where['column']).') '.$where['operator'].' '.$value;
  400. }
  401. /**
  402. * Compile a where clause comparing two columns..
  403. *
  404. * @param \Illuminate\Database\Query\Builder $query
  405. * @param array $where
  406. * @return string
  407. */
  408. protected function whereColumn(Builder $query, $where)
  409. {
  410. return $this->wrap($where['first']).' '.$where['operator'].' '.$this->wrap($where['second']);
  411. }
  412. /**
  413. * Compile a nested where clause.
  414. *
  415. * @param \Illuminate\Database\Query\Builder $query
  416. * @param array $where
  417. * @return string
  418. */
  419. protected function whereNested(Builder $query, $where)
  420. {
  421. // Here we will calculate what portion of the string we need to remove. If this
  422. // is a join clause query, we need to remove the "on" portion of the SQL and
  423. // if it is a normal query we need to take the leading "where" of queries.
  424. $offset = $query instanceof JoinClause ? 3 : 6;
  425. return '('.substr($this->compileWheres($where['query']), $offset).')';
  426. }
  427. /**
  428. * Compile a where condition with a sub-select.
  429. *
  430. * @param \Illuminate\Database\Query\Builder $query
  431. * @param array $where
  432. * @return string
  433. */
  434. protected function whereSub(Builder $query, $where)
  435. {
  436. $select = $this->compileSelect($where['query']);
  437. return $this->wrap($where['column']).' '.$where['operator']." ($select)";
  438. }
  439. /**
  440. * Compile a where exists clause.
  441. *
  442. * @param \Illuminate\Database\Query\Builder $query
  443. * @param array $where
  444. * @return string
  445. */
  446. protected function whereExists(Builder $query, $where)
  447. {
  448. return 'exists ('.$this->compileSelect($where['query']).')';
  449. }
  450. /**
  451. * Compile a where exists clause.
  452. *
  453. * @param \Illuminate\Database\Query\Builder $query
  454. * @param array $where
  455. * @return string
  456. */
  457. protected function whereNotExists(Builder $query, $where)
  458. {
  459. return 'not exists ('.$this->compileSelect($where['query']).')';
  460. }
  461. /**
  462. * Compile a where row values condition.
  463. *
  464. * @param \Illuminate\Database\Query\Builder $query
  465. * @param array $where
  466. * @return string
  467. */
  468. protected function whereRowValues(Builder $query, $where)
  469. {
  470. $columns = $this->columnize($where['columns']);
  471. $values = $this->parameterize($where['values']);
  472. return '('.$columns.') '.$where['operator'].' ('.$values.')';
  473. }
  474. /**
  475. * Compile a "where JSON boolean" clause.
  476. *
  477. * @param \Illuminate\Database\Query\Builder $query
  478. * @param array $where
  479. * @return string
  480. */
  481. protected function whereJsonBoolean(Builder $query, $where)
  482. {
  483. $column = $this->wrapJsonBooleanSelector($where['column']);
  484. $value = $this->wrapJsonBooleanValue(
  485. $this->parameter($where['value'])
  486. );
  487. return $column.' '.$where['operator'].' '.$value;
  488. }
  489. /**
  490. * Compile a "where JSON contains" clause.
  491. *
  492. * @param \Illuminate\Database\Query\Builder $query
  493. * @param array $where
  494. * @return string
  495. */
  496. protected function whereJsonContains(Builder $query, $where)
  497. {
  498. $not = $where['not'] ? 'not ' : '';
  499. return $not.$this->compileJsonContains(
  500. $where['column'], $this->parameter($where['value'])
  501. );
  502. }
  503. /**
  504. * Compile a "JSON contains" statement into SQL.
  505. *
  506. * @param string $column
  507. * @param string $value
  508. * @return string
  509. *
  510. * @throws \RuntimeException
  511. */
  512. protected function compileJsonContains($column, $value)
  513. {
  514. throw new RuntimeException('This database engine does not support JSON contains operations.');
  515. }
  516. /**
  517. * Prepare the binding for a "JSON contains" statement.
  518. *
  519. * @param mixed $binding
  520. * @return string
  521. */
  522. public function prepareBindingForJsonContains($binding)
  523. {
  524. return json_encode($binding);
  525. }
  526. /**
  527. * Compile a "where JSON length" clause.
  528. *
  529. * @param \Illuminate\Database\Query\Builder $query
  530. * @param array $where
  531. * @return string
  532. */
  533. protected function whereJsonLength(Builder $query, $where)
  534. {
  535. return $this->compileJsonLength(
  536. $where['column'], $where['operator'], $this->parameter($where['value'])
  537. );
  538. }
  539. /**
  540. * Compile a "JSON length" statement into SQL.
  541. *
  542. * @param string $column
  543. * @param string $operator
  544. * @param string $value
  545. * @return string
  546. *
  547. * @throws \RuntimeException
  548. */
  549. protected function compileJsonLength($column, $operator, $value)
  550. {
  551. throw new RuntimeException('This database engine does not support JSON length operations.');
  552. }
  553. /**
  554. * Compile the "group by" portions of the query.
  555. *
  556. * @param \Illuminate\Database\Query\Builder $query
  557. * @param array $groups
  558. * @return string
  559. */
  560. protected function compileGroups(Builder $query, $groups)
  561. {
  562. return 'group by '.$this->columnize($groups);
  563. }
  564. /**
  565. * Compile the "having" portions of the query.
  566. *
  567. * @param \Illuminate\Database\Query\Builder $query
  568. * @param array $havings
  569. * @return string
  570. */
  571. protected function compileHavings(Builder $query, $havings)
  572. {
  573. $sql = implode(' ', array_map([$this, 'compileHaving'], $havings));
  574. return 'having '.$this->removeLeadingBoolean($sql);
  575. }
  576. /**
  577. * Compile a single having clause.
  578. *
  579. * @param array $having
  580. * @return string
  581. */
  582. protected function compileHaving(array $having)
  583. {
  584. // If the having clause is "raw", we can just return the clause straight away
  585. // without doing any more processing on it. Otherwise, we will compile the
  586. // clause into SQL based on the components that make it up from builder.
  587. if ($having['type'] === 'Raw') {
  588. return $having['boolean'].' '.$having['sql'];
  589. } elseif ($having['type'] === 'between') {
  590. return $this->compileHavingBetween($having);
  591. }
  592. return $this->compileBasicHaving($having);
  593. }
  594. /**
  595. * Compile a basic having clause.
  596. *
  597. * @param array $having
  598. * @return string
  599. */
  600. protected function compileBasicHaving($having)
  601. {
  602. $column = $this->wrap($having['column']);
  603. $parameter = $this->parameter($having['value']);
  604. return $having['boolean'].' '.$column.' '.$having['operator'].' '.$parameter;
  605. }
  606. /**
  607. * Compile a "between" having clause.
  608. *
  609. * @param array $having
  610. * @return string
  611. */
  612. protected function compileHavingBetween($having)
  613. {
  614. $between = $having['not'] ? 'not between' : 'between';
  615. $column = $this->wrap($having['column']);
  616. $min = $this->parameter(head($having['values']));
  617. $max = $this->parameter(last($having['values']));
  618. return $having['boolean'].' '.$column.' '.$between.' '.$min.' and '.$max;
  619. }
  620. /**
  621. * Compile the "order by" portions of the query.
  622. *
  623. * @param \Illuminate\Database\Query\Builder $query
  624. * @param array $orders
  625. * @return string
  626. */
  627. protected function compileOrders(Builder $query, $orders)
  628. {
  629. if (! empty($orders)) {
  630. return 'order by '.implode(', ', $this->compileOrdersToArray($query, $orders));
  631. }
  632. return '';
  633. }
  634. /**
  635. * Compile the query orders to an array.
  636. *
  637. * @param \Illuminate\Database\Query\Builder $query
  638. * @param array $orders
  639. * @return array
  640. */
  641. protected function compileOrdersToArray(Builder $query, $orders)
  642. {
  643. return array_map(function ($order) {
  644. return $order['sql'] ?? $this->wrap($order['column']).' '.$order['direction'];
  645. }, $orders);
  646. }
  647. /**
  648. * Compile the random statement into SQL.
  649. *
  650. * @param string $seed
  651. * @return string
  652. */
  653. public function compileRandom($seed)
  654. {
  655. return 'RANDOM()';
  656. }
  657. /**
  658. * Compile the "limit" portions of the query.
  659. *
  660. * @param \Illuminate\Database\Query\Builder $query
  661. * @param int $limit
  662. * @return string
  663. */
  664. protected function compileLimit(Builder $query, $limit)
  665. {
  666. return 'limit '.(int) $limit;
  667. }
  668. /**
  669. * Compile the "offset" portions of the query.
  670. *
  671. * @param \Illuminate\Database\Query\Builder $query
  672. * @param int $offset
  673. * @return string
  674. */
  675. protected function compileOffset(Builder $query, $offset)
  676. {
  677. return 'offset '.(int) $offset;
  678. }
  679. /**
  680. * Compile the "union" queries attached to the main query.
  681. *
  682. * @param \Illuminate\Database\Query\Builder $query
  683. * @return string
  684. */
  685. protected function compileUnions(Builder $query)
  686. {
  687. $sql = '';
  688. foreach ($query->unions as $union) {
  689. $sql .= $this->compileUnion($union);
  690. }
  691. if (! empty($query->unionOrders)) {
  692. $sql .= ' '.$this->compileOrders($query, $query->unionOrders);
  693. }
  694. if (isset($query->unionLimit)) {
  695. $sql .= ' '.$this->compileLimit($query, $query->unionLimit);
  696. }
  697. if (isset($query->unionOffset)) {
  698. $sql .= ' '.$this->compileOffset($query, $query->unionOffset);
  699. }
  700. return ltrim($sql);
  701. }
  702. /**
  703. * Compile a single union statement.
  704. *
  705. * @param array $union
  706. * @return string
  707. */
  708. protected function compileUnion(array $union)
  709. {
  710. $conjunction = $union['all'] ? ' union all ' : ' union ';
  711. return $conjunction.$union['query']->toSql();
  712. }
  713. /**
  714. * Compile a union aggregate query into SQL.
  715. *
  716. * @param \Illuminate\Database\Query\Builder $query
  717. * @return string
  718. */
  719. protected function compileUnionAggregate(Builder $query)
  720. {
  721. $sql = $this->compileAggregate($query, $query->aggregate);
  722. $query->aggregate = null;
  723. return $sql.' from ('.$this->compileSelect($query).') as '.$this->wrapTable('temp_table');
  724. }
  725. /**
  726. * Compile an exists statement into SQL.
  727. *
  728. * @param \Illuminate\Database\Query\Builder $query
  729. * @return string
  730. */
  731. public function compileExists(Builder $query)
  732. {
  733. $select = $this->compileSelect($query);
  734. return "select exists({$select}) as {$this->wrap('exists')}";
  735. }
  736. /**
  737. * Compile an insert statement into SQL.
  738. *
  739. * @param \Illuminate\Database\Query\Builder $query
  740. * @param array $values
  741. * @return string
  742. */
  743. public function compileInsert(Builder $query, array $values)
  744. {
  745. // Essentially we will force every insert to be treated as a batch insert which
  746. // simply makes creating the SQL easier for us since we can utilize the same
  747. // basic routine regardless of an amount of records given to us to insert.
  748. $table = $this->wrapTable($query->from);
  749. if (! is_array(reset($values))) {
  750. $values = [$values];
  751. }
  752. $columns = $this->columnize(array_keys(reset($values)));
  753. // We need to build a list of parameter place-holders of values that are bound
  754. // to the query. Each insert should have the exact same amount of parameter
  755. // bindings so we will loop through the record and parameterize them all.
  756. $parameters = collect($values)->map(function ($record) {
  757. return '('.$this->parameterize($record).')';
  758. })->implode(', ');
  759. return "insert into $table ($columns) values $parameters";
  760. }
  761. /**
  762. * Compile an insert ignore statement into SQL.
  763. *
  764. * @param \Illuminate\Database\Query\Builder $query
  765. * @param array $values
  766. * @return string
  767. */
  768. public function compileInsertOrIgnore(Builder $query, array $values)
  769. {
  770. throw new RuntimeException('This database engine does not support inserting while ignoring errors.');
  771. }
  772. /**
  773. * Compile an insert and get ID statement into SQL.
  774. *
  775. * @param \Illuminate\Database\Query\Builder $query
  776. * @param array $values
  777. * @param string $sequence
  778. * @return string
  779. */
  780. public function compileInsertGetId(Builder $query, $values, $sequence)
  781. {
  782. return $this->compileInsert($query, $values);
  783. }
  784. /**
  785. * Compile an insert statement using a subquery into SQL.
  786. *
  787. * @param \Illuminate\Database\Query\Builder $query
  788. * @param array $columns
  789. * @param string $sql
  790. * @return string
  791. */
  792. public function compileInsertUsing(Builder $query, array $columns, string $sql)
  793. {
  794. return "insert into {$this->wrapTable($query->from)} ({$this->columnize($columns)}) $sql";
  795. }
  796. /**
  797. * Compile an update statement into SQL.
  798. *
  799. * @param \Illuminate\Database\Query\Builder $query
  800. * @param array $values
  801. * @return string
  802. */
  803. public function compileUpdate(Builder $query, $values)
  804. {
  805. $table = $this->wrapTable($query->from);
  806. // Each one of the columns in the update statements needs to be wrapped in the
  807. // keyword identifiers, also a place-holder needs to be created for each of
  808. // the values in the list of bindings so we can make the sets statements.
  809. $columns = collect($values)->map(function ($value, $key) {
  810. return $this->wrap($key).' = '.$this->parameter($value);
  811. })->implode(', ');
  812. // If the query has any "join" clauses, we will setup the joins on the builder
  813. // and compile them so we can attach them to this update, as update queries
  814. // can get join statements to attach to other tables when they're needed.
  815. $joins = '';
  816. if (isset($query->joins)) {
  817. $joins = ' '.$this->compileJoins($query, $query->joins);
  818. }
  819. // Of course, update queries may also be constrained by where clauses so we'll
  820. // need to compile the where clauses and attach it to the query so only the
  821. // intended records are updated by the SQL statements we generate to run.
  822. $wheres = $this->compileWheres($query);
  823. return trim("update {$table}{$joins} set $columns $wheres");
  824. }
  825. /**
  826. * Prepare the bindings for an update statement.
  827. *
  828. * @param array $bindings
  829. * @param array $values
  830. * @return array
  831. */
  832. public function prepareBindingsForUpdate(array $bindings, array $values)
  833. {
  834. $cleanBindings = Arr::except($bindings, ['select', 'join']);
  835. return array_values(
  836. array_merge($bindings['join'], $values, Arr::flatten($cleanBindings))
  837. );
  838. }
  839. /**
  840. * Compile a delete statement into SQL.
  841. *
  842. * @param \Illuminate\Database\Query\Builder $query
  843. * @return string
  844. */
  845. public function compileDelete(Builder $query)
  846. {
  847. $wheres = is_array($query->wheres) ? $this->compileWheres($query) : '';
  848. return trim("delete from {$this->wrapTable($query->from)} $wheres");
  849. }
  850. /**
  851. * Prepare the bindings for a delete statement.
  852. *
  853. * @param array $bindings
  854. * @return array
  855. */
  856. public function prepareBindingsForDelete(array $bindings)
  857. {
  858. return Arr::flatten(
  859. Arr::except($bindings, 'select')
  860. );
  861. }
  862. /**
  863. * Compile a truncate table statement into SQL.
  864. *
  865. * @param \Illuminate\Database\Query\Builder $query
  866. * @return array
  867. */
  868. public function compileTruncate(Builder $query)
  869. {
  870. return ['truncate '.$this->wrapTable($query->from) => []];
  871. }
  872. /**
  873. * Compile the lock into SQL.
  874. *
  875. * @param \Illuminate\Database\Query\Builder $query
  876. * @param bool|string $value
  877. * @return string
  878. */
  879. protected function compileLock(Builder $query, $value)
  880. {
  881. return is_string($value) ? $value : '';
  882. }
  883. /**
  884. * Determine if the grammar supports savepoints.
  885. *
  886. * @return bool
  887. */
  888. public function supportsSavepoints()
  889. {
  890. return true;
  891. }
  892. /**
  893. * Compile the SQL statement to define a savepoint.
  894. *
  895. * @param string $name
  896. * @return string
  897. */
  898. public function compileSavepoint($name)
  899. {
  900. return 'SAVEPOINT '.$name;
  901. }
  902. /**
  903. * Compile the SQL statement to execute a savepoint rollback.
  904. *
  905. * @param string $name
  906. * @return string
  907. */
  908. public function compileSavepointRollBack($name)
  909. {
  910. return 'ROLLBACK TO SAVEPOINT '.$name;
  911. }
  912. /**
  913. * Wrap a value in keyword identifiers.
  914. *
  915. * @param \Illuminate\Database\Query\Expression|string $value
  916. * @param bool $prefixAlias
  917. * @return string
  918. */
  919. public function wrap($value, $prefixAlias = false)
  920. {
  921. if ($this->isExpression($value)) {
  922. return $this->getValue($value);
  923. }
  924. // If the value being wrapped has a column alias we will need to separate out
  925. // the pieces so we can wrap each of the segments of the expression on its
  926. // own, and then join these both back together using the "as" connector.
  927. if (stripos($value, ' as ') !== false) {
  928. return $this->wrapAliasedValue($value, $prefixAlias);
  929. }
  930. // If the given value is a JSON selector we will wrap it differently than a
  931. // traditional value. We will need to split this path and wrap each part
  932. // wrapped, etc. Otherwise, we will simply wrap the value as a string.
  933. if ($this->isJsonSelector($value)) {
  934. return $this->wrapJsonSelector($value);
  935. }
  936. return $this->wrapSegments(explode('.', $value));
  937. }
  938. /**
  939. * Wrap the given JSON selector.
  940. *
  941. * @param string $value
  942. * @return string
  943. */
  944. protected function wrapJsonSelector($value)
  945. {
  946. throw new RuntimeException('This database engine does not support JSON operations.');
  947. }
  948. /**
  949. * Wrap the given JSON selector for boolean values.
  950. *
  951. * @param string $value
  952. * @return string
  953. */
  954. protected function wrapJsonBooleanSelector($value)
  955. {
  956. return $this->wrapJsonSelector($value);
  957. }
  958. /**
  959. * Wrap the given JSON boolean value.
  960. *
  961. * @param string $value
  962. * @return string
  963. */
  964. protected function wrapJsonBooleanValue($value)
  965. {
  966. return $value;
  967. }
  968. /**
  969. * Split the given JSON selector into the field and the optional path and wrap them separately.
  970. *
  971. * @param string $column
  972. * @return array
  973. */
  974. protected function wrapJsonFieldAndPath($column)
  975. {
  976. $parts = explode('->', $column, 2);
  977. $field = $this->wrap($parts[0]);
  978. $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1], '->') : '';
  979. return [$field, $path];
  980. }
  981. /**
  982. * Wrap the given JSON path.
  983. *
  984. * @param string $value
  985. * @param string $delimiter
  986. * @return string
  987. */
  988. protected function wrapJsonPath($value, $delimiter = '->')
  989. {
  990. $value = preg_replace("/([\\\\]+)?\\'/", "\\'", $value);
  991. return '\'$."'.str_replace($delimiter, '"."', $value).'"\'';
  992. }
  993. /**
  994. * Determine if the given string is a JSON selector.
  995. *
  996. * @param string $value
  997. * @return bool
  998. */
  999. protected function isJsonSelector($value)
  1000. {
  1001. return Str::contains($value, '->');
  1002. }
  1003. /**
  1004. * Concatenate an array of segments, removing empties.
  1005. *
  1006. * @param array $segments
  1007. * @return string
  1008. */
  1009. protected function concatenate($segments)
  1010. {
  1011. return implode(' ', array_filter($segments, function ($value) {
  1012. return (string) $value !== '';
  1013. }));
  1014. }
  1015. /**
  1016. * Remove the leading boolean from a statement.
  1017. *
  1018. * @param string $value
  1019. * @return string
  1020. */
  1021. protected function removeLeadingBoolean($value)
  1022. {
  1023. return preg_replace('/and |or /i', '', $value, 1);
  1024. }
  1025. /**
  1026. * Get the grammar specific operators.
  1027. *
  1028. * @return array
  1029. */
  1030. public function getOperators()
  1031. {
  1032. return $this->operators;
  1033. }
  1034. }