SQLiteGrammar.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Str;
  6. class SQLiteGrammar extends Grammar
  7. {
  8. /**
  9. * All of the available clause operators.
  10. *
  11. * @var string[]
  12. */
  13. protected $operators = [
  14. '=', '<', '>', '<=', '>=', '<>', '!=',
  15. 'like', 'not like', 'ilike',
  16. '&', '|', '<<', '>>',
  17. ];
  18. /**
  19. * Compile the lock into SQL.
  20. *
  21. * @param \Illuminate\Database\Query\Builder $query
  22. * @param bool|string $value
  23. * @return string
  24. */
  25. protected function compileLock(Builder $query, $value)
  26. {
  27. return '';
  28. }
  29. /**
  30. * Wrap a union subquery in parentheses.
  31. *
  32. * @param string $sql
  33. * @return string
  34. */
  35. protected function wrapUnion($sql)
  36. {
  37. return 'select * from ('.$sql.')';
  38. }
  39. /**
  40. * Compile a "where date" clause.
  41. *
  42. * @param \Illuminate\Database\Query\Builder $query
  43. * @param array $where
  44. * @return string
  45. */
  46. protected function whereDate(Builder $query, $where)
  47. {
  48. return $this->dateBasedWhere('%Y-%m-%d', $query, $where);
  49. }
  50. /**
  51. * Compile a "where day" clause.
  52. *
  53. * @param \Illuminate\Database\Query\Builder $query
  54. * @param array $where
  55. * @return string
  56. */
  57. protected function whereDay(Builder $query, $where)
  58. {
  59. return $this->dateBasedWhere('%d', $query, $where);
  60. }
  61. /**
  62. * Compile a "where month" clause.
  63. *
  64. * @param \Illuminate\Database\Query\Builder $query
  65. * @param array $where
  66. * @return string
  67. */
  68. protected function whereMonth(Builder $query, $where)
  69. {
  70. return $this->dateBasedWhere('%m', $query, $where);
  71. }
  72. /**
  73. * Compile a "where year" clause.
  74. *
  75. * @param \Illuminate\Database\Query\Builder $query
  76. * @param array $where
  77. * @return string
  78. */
  79. protected function whereYear(Builder $query, $where)
  80. {
  81. return $this->dateBasedWhere('%Y', $query, $where);
  82. }
  83. /**
  84. * Compile a "where time" clause.
  85. *
  86. * @param \Illuminate\Database\Query\Builder $query
  87. * @param array $where
  88. * @return string
  89. */
  90. protected function whereTime(Builder $query, $where)
  91. {
  92. return $this->dateBasedWhere('%H:%M:%S', $query, $where);
  93. }
  94. /**
  95. * Compile a date based where clause.
  96. *
  97. * @param string $type
  98. * @param \Illuminate\Database\Query\Builder $query
  99. * @param array $where
  100. * @return string
  101. */
  102. protected function dateBasedWhere($type, Builder $query, $where)
  103. {
  104. $value = $this->parameter($where['value']);
  105. return "strftime('{$type}', {$this->wrap($where['column'])}) {$where['operator']} cast({$value} as text)";
  106. }
  107. /**
  108. * Compile the index hints for the query.
  109. *
  110. * @param \Illuminate\Database\Query\Builder $query
  111. * @param \Illuminate\Database\Query\IndexHint $indexHint
  112. * @return string
  113. */
  114. protected function compileIndexHint(Builder $query, $indexHint)
  115. {
  116. return $indexHint->type === 'force'
  117. ? "indexed by {$indexHint->index}"
  118. : '';
  119. }
  120. /**
  121. * Compile a "JSON length" statement into SQL.
  122. *
  123. * @param string $column
  124. * @param string $operator
  125. * @param string $value
  126. * @return string
  127. */
  128. protected function compileJsonLength($column, $operator, $value)
  129. {
  130. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  131. return 'json_array_length('.$field.$path.') '.$operator.' '.$value;
  132. }
  133. /**
  134. * Compile a "JSON contains" statement into SQL.
  135. *
  136. * @param string $column
  137. * @param mixed $value
  138. * @return string
  139. */
  140. protected function compileJsonContains($column, $value)
  141. {
  142. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  143. return 'exists (select 1 from json_each('.$field.$path.') where '.$this->wrap('json_each.value').' is '.$value.')';
  144. }
  145. /**
  146. * Prepare the binding for a "JSON contains" statement.
  147. *
  148. * @param mixed $binding
  149. * @return mixed
  150. */
  151. public function prepareBindingForJsonContains($binding)
  152. {
  153. return $binding;
  154. }
  155. /**
  156. * Compile a "JSON contains key" statement into SQL.
  157. *
  158. * @param string $column
  159. * @return string
  160. */
  161. protected function compileJsonContainsKey($column)
  162. {
  163. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  164. return 'json_type('.$field.$path.') is not null';
  165. }
  166. /**
  167. * Compile a group limit clause.
  168. *
  169. * @param \Illuminate\Database\Query\Builder $query
  170. * @return string
  171. */
  172. protected function compileGroupLimit(Builder $query)
  173. {
  174. $version = $query->getConnection()->getServerVersion();
  175. if (version_compare($version, '3.25.0') >= 0) {
  176. return parent::compileGroupLimit($query);
  177. }
  178. $query->groupLimit = null;
  179. return $this->compileSelect($query);
  180. }
  181. /**
  182. * Compile an update statement into SQL.
  183. *
  184. * @param \Illuminate\Database\Query\Builder $query
  185. * @param array $values
  186. * @return string
  187. */
  188. public function compileUpdate(Builder $query, array $values)
  189. {
  190. if (isset($query->joins) || isset($query->limit)) {
  191. return $this->compileUpdateWithJoinsOrLimit($query, $values);
  192. }
  193. return parent::compileUpdate($query, $values);
  194. }
  195. /**
  196. * Compile an insert ignore statement into SQL.
  197. *
  198. * @param \Illuminate\Database\Query\Builder $query
  199. * @param array $values
  200. * @return string
  201. */
  202. public function compileInsertOrIgnore(Builder $query, array $values)
  203. {
  204. return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsert($query, $values));
  205. }
  206. /**
  207. * Compile an insert ignore statement using a subquery into SQL.
  208. *
  209. * @param \Illuminate\Database\Query\Builder $query
  210. * @param array $columns
  211. * @param string $sql
  212. * @return string
  213. */
  214. public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
  215. {
  216. return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsertUsing($query, $columns, $sql));
  217. }
  218. /**
  219. * Compile the columns for an update statement.
  220. *
  221. * @param \Illuminate\Database\Query\Builder $query
  222. * @param array $values
  223. * @return string
  224. */
  225. protected function compileUpdateColumns(Builder $query, array $values)
  226. {
  227. $jsonGroups = $this->groupJsonColumnsForUpdate($values);
  228. return collect($values)->reject(function ($value, $key) {
  229. return $this->isJsonSelector($key);
  230. })->merge($jsonGroups)->map(function ($value, $key) use ($jsonGroups) {
  231. $column = last(explode('.', $key));
  232. $value = isset($jsonGroups[$key]) ? $this->compileJsonPatch($column, $value) : $this->parameter($value);
  233. return $this->wrap($column).' = '.$value;
  234. })->implode(', ');
  235. }
  236. /**
  237. * Compile an "upsert" statement into SQL.
  238. *
  239. * @param \Illuminate\Database\Query\Builder $query
  240. * @param array $values
  241. * @param array $uniqueBy
  242. * @param array $update
  243. * @return string
  244. */
  245. public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
  246. {
  247. $sql = $this->compileInsert($query, $values);
  248. $sql .= ' on conflict ('.$this->columnize($uniqueBy).') do update set ';
  249. $columns = collect($update)->map(function ($value, $key) {
  250. return is_numeric($key)
  251. ? $this->wrap($value).' = '.$this->wrapValue('excluded').'.'.$this->wrap($value)
  252. : $this->wrap($key).' = '.$this->parameter($value);
  253. })->implode(', ');
  254. return $sql.$columns;
  255. }
  256. /**
  257. * Group the nested JSON columns.
  258. *
  259. * @param array $values
  260. * @return array
  261. */
  262. protected function groupJsonColumnsForUpdate(array $values)
  263. {
  264. $groups = [];
  265. foreach ($values as $key => $value) {
  266. if ($this->isJsonSelector($key)) {
  267. Arr::set($groups, str_replace('->', '.', Str::after($key, '.')), $value);
  268. }
  269. }
  270. return $groups;
  271. }
  272. /**
  273. * Compile a "JSON" patch statement into SQL.
  274. *
  275. * @param string $column
  276. * @param mixed $value
  277. * @return string
  278. */
  279. protected function compileJsonPatch($column, $value)
  280. {
  281. return "json_patch(ifnull({$this->wrap($column)}, json('{}')), json({$this->parameter($value)}))";
  282. }
  283. /**
  284. * Compile an update statement with joins or limit into SQL.
  285. *
  286. * @param \Illuminate\Database\Query\Builder $query
  287. * @param array $values
  288. * @return string
  289. */
  290. protected function compileUpdateWithJoinsOrLimit(Builder $query, array $values)
  291. {
  292. $table = $this->wrapTable($query->from);
  293. $columns = $this->compileUpdateColumns($query, $values);
  294. $alias = last(preg_split('/\s+as\s+/i', $query->from));
  295. $selectSql = $this->compileSelect($query->select($alias.'.rowid'));
  296. return "update {$table} set {$columns} where {$this->wrap('rowid')} in ({$selectSql})";
  297. }
  298. /**
  299. * Prepare the bindings for an update statement.
  300. *
  301. * @param array $bindings
  302. * @param array $values
  303. * @return array
  304. */
  305. public function prepareBindingsForUpdate(array $bindings, array $values)
  306. {
  307. $groups = $this->groupJsonColumnsForUpdate($values);
  308. $values = collect($values)->reject(function ($value, $key) {
  309. return $this->isJsonSelector($key);
  310. })->merge($groups)->map(function ($value) {
  311. return is_array($value) ? json_encode($value) : $value;
  312. })->all();
  313. $cleanBindings = Arr::except($bindings, 'select');
  314. return array_values(
  315. array_merge($values, Arr::flatten($cleanBindings))
  316. );
  317. }
  318. /**
  319. * Compile a delete statement into SQL.
  320. *
  321. * @param \Illuminate\Database\Query\Builder $query
  322. * @return string
  323. */
  324. public function compileDelete(Builder $query)
  325. {
  326. if (isset($query->joins) || isset($query->limit)) {
  327. return $this->compileDeleteWithJoinsOrLimit($query);
  328. }
  329. return parent::compileDelete($query);
  330. }
  331. /**
  332. * Compile a delete statement with joins or limit into SQL.
  333. *
  334. * @param \Illuminate\Database\Query\Builder $query
  335. * @return string
  336. */
  337. protected function compileDeleteWithJoinsOrLimit(Builder $query)
  338. {
  339. $table = $this->wrapTable($query->from);
  340. $alias = last(preg_split('/\s+as\s+/i', $query->from));
  341. $selectSql = $this->compileSelect($query->select($alias.'.rowid'));
  342. return "delete from {$table} where {$this->wrap('rowid')} in ({$selectSql})";
  343. }
  344. /**
  345. * Compile a truncate table statement into SQL.
  346. *
  347. * @param \Illuminate\Database\Query\Builder $query
  348. * @return array
  349. */
  350. public function compileTruncate(Builder $query)
  351. {
  352. return [
  353. 'delete from sqlite_sequence where name = ?' => [$this->getTablePrefix().$query->from],
  354. 'delete from '.$this->wrapTable($query->from) => [],
  355. ];
  356. }
  357. /**
  358. * Wrap the given JSON selector.
  359. *
  360. * @param string $value
  361. * @return string
  362. */
  363. protected function wrapJsonSelector($value)
  364. {
  365. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  366. return 'json_extract('.$field.$path.')';
  367. }
  368. }