Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PostgresGrammar.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Str;
  5. use Illuminate\Database\Query\Builder;
  6. class PostgresGrammar extends Grammar
  7. {
  8. /**
  9. * The components that make up a select clause.
  10. *
  11. * @var array
  12. */
  13. protected $selectComponents = [
  14. 'aggregate',
  15. 'columns',
  16. 'from',
  17. 'joins',
  18. 'wheres',
  19. 'groups',
  20. 'havings',
  21. 'orders',
  22. 'limit',
  23. 'offset',
  24. 'lock',
  25. ];
  26. /**
  27. * All of the available clause operators.
  28. *
  29. * @var array
  30. */
  31. protected $operators = [
  32. '=', '<', '>', '<=', '>=', '<>', '!=',
  33. 'like', 'not like', 'between', 'ilike', 'not ilike',
  34. '~', '&', '|', '#', '<<', '>>', '<<=', '>>=',
  35. '&&', '@>', '<@', '?', '?|', '?&', '||', '-', '-', '#-',
  36. 'is distinct from', 'is not distinct from',
  37. ];
  38. /**
  39. * {@inheritdoc}
  40. *
  41. * @param \Illuminate\Database\Query\Builder $query
  42. * @param array $where
  43. * @return string
  44. */
  45. protected function whereBasic(Builder $query, $where)
  46. {
  47. if (Str::contains(strtolower($where['operator']), 'like')) {
  48. return sprintf(
  49. '%s::text %s %s',
  50. $this->wrap($where['column']),
  51. $where['operator'],
  52. $this->parameter($where['value'])
  53. );
  54. }
  55. return parent::whereBasic($query, $where);
  56. }
  57. /**
  58. * Compile a "where date" clause.
  59. *
  60. * @param \Illuminate\Database\Query\Builder $query
  61. * @param array $where
  62. * @return string
  63. */
  64. protected function whereDate(Builder $query, $where)
  65. {
  66. $value = $this->parameter($where['value']);
  67. return $this->wrap($where['column']).'::date '.$where['operator'].' '.$value;
  68. }
  69. /**
  70. * Compile a "where time" clause.
  71. *
  72. * @param \Illuminate\Database\Query\Builder $query
  73. * @param array $where
  74. * @return string
  75. */
  76. protected function whereTime(Builder $query, $where)
  77. {
  78. $value = $this->parameter($where['value']);
  79. return $this->wrap($where['column']).'::time '.$where['operator'].' '.$value;
  80. }
  81. /**
  82. * Compile a date based where clause.
  83. *
  84. * @param string $type
  85. * @param \Illuminate\Database\Query\Builder $query
  86. * @param array $where
  87. * @return string
  88. */
  89. protected function dateBasedWhere($type, Builder $query, $where)
  90. {
  91. $value = $this->parameter($where['value']);
  92. return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value;
  93. }
  94. /**
  95. * Compile a select query into SQL.
  96. *
  97. * @param \Illuminate\Database\Query\Builder $query
  98. * @return string
  99. */
  100. public function compileSelect(Builder $query)
  101. {
  102. if ($query->unions && $query->aggregate) {
  103. return $this->compileUnionAggregate($query);
  104. }
  105. $sql = parent::compileSelect($query);
  106. if ($query->unions) {
  107. $sql = '('.$sql.') '.$this->compileUnions($query);
  108. }
  109. return $sql;
  110. }
  111. /**
  112. * Compile a single union statement.
  113. *
  114. * @param array $union
  115. * @return string
  116. */
  117. protected function compileUnion(array $union)
  118. {
  119. $conjunction = $union['all'] ? ' union all ' : ' union ';
  120. return $conjunction.'('.$union['query']->toSql().')';
  121. }
  122. /**
  123. * Compile a "JSON contains" statement into SQL.
  124. *
  125. * @param string $column
  126. * @param string $value
  127. * @return string
  128. */
  129. protected function compileJsonContains($column, $value)
  130. {
  131. $column = str_replace('->>', '->', $this->wrap($column));
  132. return '('.$column.')::jsonb @> '.$value;
  133. }
  134. /**
  135. * Compile a "JSON length" statement into SQL.
  136. *
  137. * @param string $column
  138. * @param string $operator
  139. * @param string $value
  140. * @return string
  141. */
  142. protected function compileJsonLength($column, $operator, $value)
  143. {
  144. $column = str_replace('->>', '->', $this->wrap($column));
  145. return 'json_array_length(('.$column.')::json) '.$operator.' '.$value;
  146. }
  147. /**
  148. * Compile the lock into SQL.
  149. *
  150. * @param \Illuminate\Database\Query\Builder $query
  151. * @param bool|string $value
  152. * @return string
  153. */
  154. protected function compileLock(Builder $query, $value)
  155. {
  156. if (! is_string($value)) {
  157. return $value ? 'for update' : 'for share';
  158. }
  159. return $value;
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function compileInsert(Builder $query, array $values)
  165. {
  166. $table = $this->wrapTable($query->from);
  167. return empty($values)
  168. ? "insert into {$table} DEFAULT VALUES"
  169. : parent::compileInsert($query, $values);
  170. }
  171. /**
  172. * Compile an insert and get ID statement into SQL.
  173. *
  174. * @param \Illuminate\Database\Query\Builder $query
  175. * @param array $values
  176. * @param string $sequence
  177. * @return string
  178. */
  179. public function compileInsertGetId(Builder $query, $values, $sequence)
  180. {
  181. if (is_null($sequence)) {
  182. $sequence = 'id';
  183. }
  184. return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence);
  185. }
  186. /**
  187. * Compile an update statement into SQL.
  188. *
  189. * @param \Illuminate\Database\Query\Builder $query
  190. * @param array $values
  191. * @return string
  192. */
  193. public function compileUpdate(Builder $query, $values)
  194. {
  195. $table = $this->wrapTable($query->from);
  196. // Each one of the columns in the update statements needs to be wrapped in the
  197. // keyword identifiers, also a place-holder needs to be created for each of
  198. // the values in the list of bindings so we can make the sets statements.
  199. $columns = $this->compileUpdateColumns($query, $values);
  200. $from = $this->compileUpdateFrom($query);
  201. $where = $this->compileUpdateWheres($query);
  202. return trim("update {$table} set {$columns}{$from} {$where}");
  203. }
  204. /**
  205. * Compile the columns for the update statement.
  206. *
  207. * @param \Illuminate\Database\Query\Builder $query
  208. * @param array $values
  209. * @return string
  210. */
  211. protected function compileUpdateColumns($query, $values)
  212. {
  213. // When gathering the columns for an update statement, we'll wrap each of the
  214. // columns and convert it to a parameter value. Then we will concatenate a
  215. // list of the columns that can be added into this update query clauses.
  216. return collect($values)->map(function ($value, $key) use ($query) {
  217. $column = Str::after($key, $query->from.'.');
  218. if ($this->isJsonSelector($key)) {
  219. return $this->compileJsonUpdateColumn($column, $value);
  220. }
  221. return $this->wrap($column).' = '.$this->parameter($value);
  222. })->implode(', ');
  223. }
  224. /**
  225. * Prepares a JSON column being updated using the JSONB_SET function.
  226. *
  227. * @param string $key
  228. * @param mixed $value
  229. * @return string
  230. */
  231. protected function compileJsonUpdateColumn($key, $value)
  232. {
  233. $parts = explode('->', $key);
  234. $field = $this->wrap(array_shift($parts));
  235. $path = '\'{"'.implode('","', $parts).'"}\'';
  236. return "{$field} = jsonb_set({$field}::jsonb, {$path}, {$this->parameter($value)})";
  237. }
  238. /**
  239. * Compile the "from" clause for an update with a join.
  240. *
  241. * @param \Illuminate\Database\Query\Builder $query
  242. * @return string|null
  243. */
  244. protected function compileUpdateFrom(Builder $query)
  245. {
  246. if (! isset($query->joins)) {
  247. return '';
  248. }
  249. // When using Postgres, updates with joins list the joined tables in the from
  250. // clause, which is different than other systems like MySQL. Here, we will
  251. // compile out the tables that are joined and add them to a from clause.
  252. $froms = collect($query->joins)->map(function ($join) {
  253. return $this->wrapTable($join->table);
  254. })->all();
  255. if (count($froms) > 0) {
  256. return ' from '.implode(', ', $froms);
  257. }
  258. }
  259. /**
  260. * Compile the additional where clauses for updates with joins.
  261. *
  262. * @param \Illuminate\Database\Query\Builder $query
  263. * @return string
  264. */
  265. protected function compileUpdateWheres(Builder $query)
  266. {
  267. $baseWheres = $this->compileWheres($query);
  268. if (! isset($query->joins)) {
  269. return $baseWheres;
  270. }
  271. // Once we compile the join constraints, we will either use them as the where
  272. // clause or append them to the existing base where clauses. If we need to
  273. // strip the leading boolean we will do so when using as the only where.
  274. $joinWheres = $this->compileUpdateJoinWheres($query);
  275. if (trim($baseWheres) == '') {
  276. return 'where '.$this->removeLeadingBoolean($joinWheres);
  277. }
  278. return $baseWheres.' '.$joinWheres;
  279. }
  280. /**
  281. * Compile the "join" clause where clauses for an update.
  282. *
  283. * @param \Illuminate\Database\Query\Builder $query
  284. * @return string
  285. */
  286. protected function compileUpdateJoinWheres(Builder $query)
  287. {
  288. $joinWheres = [];
  289. // Here we will just loop through all of the join constraints and compile them
  290. // all out then implode them. This should give us "where" like syntax after
  291. // everything has been built and then we will join it to the real wheres.
  292. foreach ($query->joins as $join) {
  293. foreach ($join->wheres as $where) {
  294. $method = "where{$where['type']}";
  295. $joinWheres[] = $where['boolean'].' '.$this->$method($query, $where);
  296. }
  297. }
  298. return implode(' ', $joinWheres);
  299. }
  300. /**
  301. * Prepare the bindings for an update statement.
  302. *
  303. * @param array $bindings
  304. * @param array $values
  305. * @return array
  306. */
  307. public function prepareBindingsForUpdate(array $bindings, array $values)
  308. {
  309. $values = collect($values)->map(function ($value, $column) {
  310. return $this->isJsonSelector($column) && ! $this->isExpression($value)
  311. ? json_encode($value)
  312. : $value;
  313. })->all();
  314. // Update statements with "joins" in Postgres use an interesting syntax. We need to
  315. // take all of the bindings and put them on the end of this array since they are
  316. // added to the end of the "where" clause statements as typical where clauses.
  317. $bindingsWithoutJoin = Arr::except($bindings, 'join');
  318. return array_values(
  319. array_merge($values, $bindings['join'], Arr::flatten($bindingsWithoutJoin))
  320. );
  321. }
  322. /**
  323. * Compile a delete statement into SQL.
  324. *
  325. * @param \Illuminate\Database\Query\Builder $query
  326. * @return string
  327. */
  328. public function compileDelete(Builder $query)
  329. {
  330. $table = $this->wrapTable($query->from);
  331. return isset($query->joins)
  332. ? $this->compileDeleteWithJoins($query, $table)
  333. : parent::compileDelete($query);
  334. }
  335. /**
  336. * Compile a delete query that uses joins.
  337. *
  338. * @param \Illuminate\Database\Query\Builder $query
  339. * @param string $table
  340. * @return string
  341. */
  342. protected function compileDeleteWithJoins($query, $table)
  343. {
  344. $using = ' USING '.collect($query->joins)->map(function ($join) {
  345. return $this->wrapTable($join->table);
  346. })->implode(', ');
  347. $where = count($query->wheres) > 0 ? ' '.$this->compileUpdateWheres($query) : '';
  348. return trim("delete from {$table}{$using}{$where}");
  349. }
  350. /**
  351. * Compile a truncate table statement into SQL.
  352. *
  353. * @param \Illuminate\Database\Query\Builder $query
  354. * @return array
  355. */
  356. public function compileTruncate(Builder $query)
  357. {
  358. return ['truncate '.$this->wrapTable($query->from).' restart identity cascade' => []];
  359. }
  360. /**
  361. * Wrap the given JSON selector.
  362. *
  363. * @param string $value
  364. * @return string
  365. */
  366. protected function wrapJsonSelector($value)
  367. {
  368. $path = explode('->', $value);
  369. $field = $this->wrapSegments(explode('.', array_shift($path)));
  370. $wrappedPath = $this->wrapJsonPathAttributes($path);
  371. $attribute = array_pop($wrappedPath);
  372. if (! empty($wrappedPath)) {
  373. return $field.'->'.implode('->', $wrappedPath).'->>'.$attribute;
  374. }
  375. return $field.'->>'.$attribute;
  376. }
  377. /**
  378. *Wrap the given JSON selector for boolean values.
  379. *
  380. * @param string $value
  381. * @return string
  382. */
  383. protected function wrapJsonBooleanSelector($value)
  384. {
  385. $selector = str_replace(
  386. '->>', '->',
  387. $this->wrapJsonSelector($value)
  388. );
  389. return '('.$selector.')::jsonb';
  390. }
  391. /**
  392. * Wrap the given JSON boolean value.
  393. *
  394. * @param string $value
  395. * @return string
  396. */
  397. protected function wrapJsonBooleanValue($value)
  398. {
  399. return "'".$value."'::jsonb";
  400. }
  401. /**
  402. * Wrap the attributes of the give JSON path.
  403. *
  404. * @param array $path
  405. * @return array
  406. */
  407. protected function wrapJsonPathAttributes($path)
  408. {
  409. return array_map(function ($attribute) {
  410. return "'$attribute'";
  411. }, $path);
  412. }
  413. }