SqlServerGrammar.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. namespace Illuminate\Database\Query\Grammars;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Database\Query\Builder;
  5. class SqlServerGrammar extends Grammar
  6. {
  7. /**
  8. * All of the available clause operators.
  9. *
  10. * @var array
  11. */
  12. protected $operators = [
  13. '=', '<', '>', '<=', '>=', '!<', '!>', '<>', '!=',
  14. 'like', 'not like', 'ilike',
  15. '&', '&=', '|', '|=', '^', '^=',
  16. ];
  17. /**
  18. * Compile a select query into SQL.
  19. *
  20. * @param \Illuminate\Database\Query\Builder $query
  21. * @return string
  22. */
  23. public function compileSelect(Builder $query)
  24. {
  25. if (! $query->offset) {
  26. return parent::compileSelect($query);
  27. }
  28. // If an offset is present on the query, we will need to wrap the query in
  29. // a big "ANSI" offset syntax block. This is very nasty compared to the
  30. // other database systems but is necessary for implementing features.
  31. if (is_null($query->columns)) {
  32. $query->columns = ['*'];
  33. }
  34. return $this->compileAnsiOffset(
  35. $query, $this->compileComponents($query)
  36. );
  37. }
  38. /**
  39. * Compile the "select *" portion of the query.
  40. *
  41. * @param \Illuminate\Database\Query\Builder $query
  42. * @param array $columns
  43. * @return string|null
  44. */
  45. protected function compileColumns(Builder $query, $columns)
  46. {
  47. if (! is_null($query->aggregate)) {
  48. return;
  49. }
  50. $select = $query->distinct ? 'select distinct ' : 'select ';
  51. // If there is a limit on the query, but not an offset, we will add the top
  52. // clause to the query, which serves as a "limit" type clause within the
  53. // SQL Server system similar to the limit keywords available in MySQL.
  54. if ($query->limit > 0 && $query->offset <= 0) {
  55. $select .= 'top '.$query->limit.' ';
  56. }
  57. return $select.$this->columnize($columns);
  58. }
  59. /**
  60. * Compile the "from" portion of the query.
  61. *
  62. * @param \Illuminate\Database\Query\Builder $query
  63. * @param string $table
  64. * @return string
  65. */
  66. protected function compileFrom(Builder $query, $table)
  67. {
  68. $from = parent::compileFrom($query, $table);
  69. if (is_string($query->lock)) {
  70. return $from.' '.$query->lock;
  71. }
  72. if (! is_null($query->lock)) {
  73. return $from.' with(rowlock,'.($query->lock ? 'updlock,' : '').'holdlock)';
  74. }
  75. return $from;
  76. }
  77. /**
  78. * Compile a "where date" clause.
  79. *
  80. * @param \Illuminate\Database\Query\Builder $query
  81. * @param array $where
  82. * @return string
  83. */
  84. protected function whereDate(Builder $query, $where)
  85. {
  86. $value = $this->parameter($where['value']);
  87. return 'cast('.$this->wrap($where['column']).' as date) '.$where['operator'].' '.$value;
  88. }
  89. /**
  90. * Compile a "where time" clause.
  91. *
  92. * @param \Illuminate\Database\Query\Builder $query
  93. * @param array $where
  94. * @return string
  95. */
  96. protected function whereTime(Builder $query, $where)
  97. {
  98. $value = $this->parameter($where['value']);
  99. return 'cast('.$this->wrap($where['column']).' as time) '.$where['operator'].' '.$value;
  100. }
  101. /**
  102. * Compile a "JSON contains" statement into SQL.
  103. *
  104. * @param string $column
  105. * @param string $value
  106. * @return string
  107. */
  108. protected function compileJsonContains($column, $value)
  109. {
  110. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  111. return $value.' in (select [value] from openjson('.$field.$path.'))';
  112. }
  113. /**
  114. * Prepare the binding for a "JSON contains" statement.
  115. *
  116. * @param mixed $binding
  117. * @return string
  118. */
  119. public function prepareBindingForJsonContains($binding)
  120. {
  121. return is_bool($binding) ? json_encode($binding) : $binding;
  122. }
  123. /**
  124. * Compile a "JSON length" statement into SQL.
  125. *
  126. * @param string $column
  127. * @param string $operator
  128. * @param string $value
  129. * @return string
  130. */
  131. protected function compileJsonLength($column, $operator, $value)
  132. {
  133. [$field, $path] = $this->wrapJsonFieldAndPath($column);
  134. return '(select count(*) from openjson('.$field.$path.')) '.$operator.' '.$value;
  135. }
  136. /**
  137. * Create a full ANSI offset clause for the query.
  138. *
  139. * @param \Illuminate\Database\Query\Builder $query
  140. * @param array $components
  141. * @return string
  142. */
  143. protected function compileAnsiOffset(Builder $query, $components)
  144. {
  145. // An ORDER BY clause is required to make this offset query work, so if one does
  146. // not exist we'll just create a dummy clause to trick the database and so it
  147. // does not complain about the queries for not having an "order by" clause.
  148. if (empty($components['orders'])) {
  149. $components['orders'] = 'order by (select 0)';
  150. }
  151. // We need to add the row number to the query so we can compare it to the offset
  152. // and limit values given for the statements. So we will add an expression to
  153. // the "select" that will give back the row numbers on each of the records.
  154. $components['columns'] .= $this->compileOver($components['orders']);
  155. unset($components['orders']);
  156. // Next we need to calculate the constraints that should be placed on the query
  157. // to get the right offset and limit from our query but if there is no limit
  158. // set we will just handle the offset only since that is all that matters.
  159. $sql = $this->concatenate($components);
  160. return $this->compileTableExpression($sql, $query);
  161. }
  162. /**
  163. * Compile the over statement for a table expression.
  164. *
  165. * @param string $orderings
  166. * @return string
  167. */
  168. protected function compileOver($orderings)
  169. {
  170. return ", row_number() over ({$orderings}) as row_num";
  171. }
  172. /**
  173. * Compile a common table expression for a query.
  174. *
  175. * @param string $sql
  176. * @param \Illuminate\Database\Query\Builder $query
  177. * @return string
  178. */
  179. protected function compileTableExpression($sql, $query)
  180. {
  181. $constraint = $this->compileRowConstraint($query);
  182. return "select * from ({$sql}) as temp_table where row_num {$constraint} order by row_num";
  183. }
  184. /**
  185. * Compile the limit / offset row constraint for a query.
  186. *
  187. * @param \Illuminate\Database\Query\Builder $query
  188. * @return string
  189. */
  190. protected function compileRowConstraint($query)
  191. {
  192. $start = $query->offset + 1;
  193. if ($query->limit > 0) {
  194. $finish = $query->offset + $query->limit;
  195. return "between {$start} and {$finish}";
  196. }
  197. return ">= {$start}";
  198. }
  199. /**
  200. * Compile the random statement into SQL.
  201. *
  202. * @param string $seed
  203. * @return string
  204. */
  205. public function compileRandom($seed)
  206. {
  207. return 'NEWID()';
  208. }
  209. /**
  210. * Compile the "limit" portions of the query.
  211. *
  212. * @param \Illuminate\Database\Query\Builder $query
  213. * @param int $limit
  214. * @return string
  215. */
  216. protected function compileLimit(Builder $query, $limit)
  217. {
  218. return '';
  219. }
  220. /**
  221. * Compile the "offset" portions of the query.
  222. *
  223. * @param \Illuminate\Database\Query\Builder $query
  224. * @param int $offset
  225. * @return string
  226. */
  227. protected function compileOffset(Builder $query, $offset)
  228. {
  229. return '';
  230. }
  231. /**
  232. * Compile the lock into SQL.
  233. *
  234. * @param \Illuminate\Database\Query\Builder $query
  235. * @param bool|string $value
  236. * @return string
  237. */
  238. protected function compileLock(Builder $query, $value)
  239. {
  240. return '';
  241. }
  242. /**
  243. * Compile an exists statement into SQL.
  244. *
  245. * @param \Illuminate\Database\Query\Builder $query
  246. * @return string
  247. */
  248. public function compileExists(Builder $query)
  249. {
  250. $existsQuery = clone $query;
  251. $existsQuery->columns = [];
  252. return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));
  253. }
  254. /**
  255. * Compile a delete statement into SQL.
  256. *
  257. * @param \Illuminate\Database\Query\Builder $query
  258. * @return string
  259. */
  260. public function compileDelete(Builder $query)
  261. {
  262. $table = $this->wrapTable($query->from);
  263. $where = is_array($query->wheres) ? $this->compileWheres($query) : '';
  264. return isset($query->joins)
  265. ? $this->compileDeleteWithJoins($query, $table, $where)
  266. : trim("delete from {$table} {$where}");
  267. }
  268. /**
  269. * Compile a delete statement with joins into SQL.
  270. *
  271. * @param \Illuminate\Database\Query\Builder $query
  272. * @param string $table
  273. * @param string $where
  274. * @return string
  275. */
  276. protected function compileDeleteWithJoins(Builder $query, $table, $where)
  277. {
  278. $joins = ' '.$this->compileJoins($query, $query->joins);
  279. $alias = stripos($table, ' as ') !== false
  280. ? explode(' as ', $table)[1] : $table;
  281. return trim("delete {$alias} from {$table}{$joins} {$where}");
  282. }
  283. /**
  284. * Compile a truncate table statement into SQL.
  285. *
  286. * @param \Illuminate\Database\Query\Builder $query
  287. * @return array
  288. */
  289. public function compileTruncate(Builder $query)
  290. {
  291. return ['truncate table '.$this->wrapTable($query->from) => []];
  292. }
  293. /**
  294. * Compile an update statement into SQL.
  295. *
  296. * @param \Illuminate\Database\Query\Builder $query
  297. * @param array $values
  298. * @return string
  299. */
  300. public function compileUpdate(Builder $query, $values)
  301. {
  302. [$table, $alias] = $this->parseUpdateTable($query->from);
  303. // Each one of the columns in the update statements needs to be wrapped in the
  304. // keyword identifiers, also a place-holder needs to be created for each of
  305. // the values in the list of bindings so we can make the sets statements.
  306. $columns = collect($values)->map(function ($value, $key) {
  307. return $this->wrap($key).' = '.$this->parameter($value);
  308. })->implode(', ');
  309. // If the query has any "join" clauses, we will setup the joins on the builder
  310. // and compile them so we can attach them to this update, as update queries
  311. // can get join statements to attach to other tables when they're needed.
  312. $joins = '';
  313. if (isset($query->joins)) {
  314. $joins = ' '.$this->compileJoins($query, $query->joins);
  315. }
  316. // Of course, update queries may also be constrained by where clauses so we'll
  317. // need to compile the where clauses and attach it to the query so only the
  318. // intended records are updated by the SQL statements we generate to run.
  319. $where = $this->compileWheres($query);
  320. if (! empty($joins)) {
  321. return trim("update {$alias} set {$columns} from {$table}{$joins} {$where}");
  322. }
  323. return trim("update {$table}{$joins} set $columns $where");
  324. }
  325. /**
  326. * Get the table and alias for the given table.
  327. *
  328. * @param string $table
  329. * @return array
  330. */
  331. protected function parseUpdateTable($table)
  332. {
  333. $table = $alias = $this->wrapTable($table);
  334. if (stripos($table, '] as [') !== false) {
  335. $alias = '['.explode('] as [', $table)[1];
  336. }
  337. return [$table, $alias];
  338. }
  339. /**
  340. * Prepare the bindings for an update statement.
  341. *
  342. * @param array $bindings
  343. * @param array $values
  344. * @return array
  345. */
  346. public function prepareBindingsForUpdate(array $bindings, array $values)
  347. {
  348. $cleanBindings = Arr::except($bindings, 'select');
  349. return array_values(
  350. array_merge($values, Arr::flatten($cleanBindings))
  351. );
  352. }
  353. /**
  354. * Compile the SQL statement to define a savepoint.
  355. *
  356. * @param string $name
  357. * @return string
  358. */
  359. public function compileSavepoint($name)
  360. {
  361. return 'SAVE TRANSACTION '.$name;
  362. }
  363. /**
  364. * Compile the SQL statement to execute a savepoint rollback.
  365. *
  366. * @param string $name
  367. * @return string
  368. */
  369. public function compileSavepointRollBack($name)
  370. {
  371. return 'ROLLBACK TRANSACTION '.$name;
  372. }
  373. /**
  374. * Get the format for database stored dates.
  375. *
  376. * @return string
  377. */
  378. public function getDateFormat()
  379. {
  380. return 'Y-m-d H:i:s.v';
  381. }
  382. /**
  383. * Wrap a single string in keyword identifiers.
  384. *
  385. * @param string $value
  386. * @return string
  387. */
  388. protected function wrapValue($value)
  389. {
  390. return $value === '*' ? $value : '['.str_replace(']', ']]', $value).']';
  391. }
  392. /**
  393. * Wrap the given JSON selector.
  394. *
  395. * @param string $value
  396. * @return string
  397. */
  398. protected function wrapJsonSelector($value)
  399. {
  400. [$field, $path] = $this->wrapJsonFieldAndPath($value);
  401. return 'json_value('.$field.$path.')';
  402. }
  403. /**
  404. * Wrap the given JSON boolean value.
  405. *
  406. * @param string $value
  407. * @return string
  408. */
  409. protected function wrapJsonBooleanValue($value)
  410. {
  411. return "'".$value."'";
  412. }
  413. /**
  414. * Wrap a table in keyword identifiers.
  415. *
  416. * @param \Illuminate\Database\Query\Expression|string $table
  417. * @return string
  418. */
  419. public function wrapTable($table)
  420. {
  421. if (! $this->isExpression($table)) {
  422. return $this->wrapTableValuedFunction(parent::wrapTable($table));
  423. }
  424. return $this->getValue($table);
  425. }
  426. /**
  427. * Wrap a table in keyword identifiers.
  428. *
  429. * @param string $table
  430. * @return string
  431. */
  432. protected function wrapTableValuedFunction($table)
  433. {
  434. if (preg_match('/^(.+?)(\(.*?\))]$/', $table, $matches) === 1) {
  435. $table = $matches[1].']'.$matches[2];
  436. }
  437. return $table;
  438. }
  439. }