SqlServerGrammar.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 "JSON contains" statement into SQL.
  91. *
  92. * @param string $column
  93. * @param string $value
  94. * @return string
  95. */
  96. protected function compileJsonContains($column, $value)
  97. {
  98. $parts = explode('->', $column, 2);
  99. $field = $this->wrap($parts[0]);
  100. $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1]) : '';
  101. return $value.' in (select [value] from openjson('.$field.$path.'))';
  102. }
  103. /**
  104. * Prepare the binding for a "JSON contains" statement.
  105. *
  106. * @param mixed $binding
  107. * @return string
  108. */
  109. public function prepareBindingForJsonContains($binding)
  110. {
  111. return is_bool($binding) ? json_encode($binding) : $binding;
  112. }
  113. /**
  114. * Create a full ANSI offset clause for the query.
  115. *
  116. * @param \Illuminate\Database\Query\Builder $query
  117. * @param array $components
  118. * @return string
  119. */
  120. protected function compileAnsiOffset(Builder $query, $components)
  121. {
  122. // An ORDER BY clause is required to make this offset query work, so if one does
  123. // not exist we'll just create a dummy clause to trick the database and so it
  124. // does not complain about the queries for not having an "order by" clause.
  125. if (empty($components['orders'])) {
  126. $components['orders'] = 'order by (select 0)';
  127. }
  128. // We need to add the row number to the query so we can compare it to the offset
  129. // and limit values given for the statements. So we will add an expression to
  130. // the "select" that will give back the row numbers on each of the records.
  131. $components['columns'] .= $this->compileOver($components['orders']);
  132. unset($components['orders']);
  133. // Next we need to calculate the constraints that should be placed on the query
  134. // to get the right offset and limit from our query but if there is no limit
  135. // set we will just handle the offset only since that is all that matters.
  136. $sql = $this->concatenate($components);
  137. return $this->compileTableExpression($sql, $query);
  138. }
  139. /**
  140. * Compile the over statement for a table expression.
  141. *
  142. * @param string $orderings
  143. * @return string
  144. */
  145. protected function compileOver($orderings)
  146. {
  147. return ", row_number() over ({$orderings}) as row_num";
  148. }
  149. /**
  150. * Compile a common table expression for a query.
  151. *
  152. * @param string $sql
  153. * @param \Illuminate\Database\Query\Builder $query
  154. * @return string
  155. */
  156. protected function compileTableExpression($sql, $query)
  157. {
  158. $constraint = $this->compileRowConstraint($query);
  159. return "select * from ({$sql}) as temp_table where row_num {$constraint}";
  160. }
  161. /**
  162. * Compile the limit / offset row constraint for a query.
  163. *
  164. * @param \Illuminate\Database\Query\Builder $query
  165. * @return string
  166. */
  167. protected function compileRowConstraint($query)
  168. {
  169. $start = $query->offset + 1;
  170. if ($query->limit > 0) {
  171. $finish = $query->offset + $query->limit;
  172. return "between {$start} and {$finish}";
  173. }
  174. return ">= {$start}";
  175. }
  176. /**
  177. * Compile the random statement into SQL.
  178. *
  179. * @param string $seed
  180. * @return string
  181. */
  182. public function compileRandom($seed)
  183. {
  184. return 'NEWID()';
  185. }
  186. /**
  187. * Compile the "limit" portions of the query.
  188. *
  189. * @param \Illuminate\Database\Query\Builder $query
  190. * @param int $limit
  191. * @return string
  192. */
  193. protected function compileLimit(Builder $query, $limit)
  194. {
  195. return '';
  196. }
  197. /**
  198. * Compile the "offset" portions of the query.
  199. *
  200. * @param \Illuminate\Database\Query\Builder $query
  201. * @param int $offset
  202. * @return string
  203. */
  204. protected function compileOffset(Builder $query, $offset)
  205. {
  206. return '';
  207. }
  208. /**
  209. * Compile the lock into SQL.
  210. *
  211. * @param \Illuminate\Database\Query\Builder $query
  212. * @param bool|string $value
  213. * @return string
  214. */
  215. protected function compileLock(Builder $query, $value)
  216. {
  217. return '';
  218. }
  219. /**
  220. * Compile an exists statement into SQL.
  221. *
  222. * @param \Illuminate\Database\Query\Builder $query
  223. * @return string
  224. */
  225. public function compileExists(Builder $query)
  226. {
  227. $existsQuery = clone $query;
  228. $existsQuery->columns = [];
  229. return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));
  230. }
  231. /**
  232. * Compile a delete statement into SQL.
  233. *
  234. * @param \Illuminate\Database\Query\Builder $query
  235. * @return string
  236. */
  237. public function compileDelete(Builder $query)
  238. {
  239. $table = $this->wrapTable($query->from);
  240. $where = is_array($query->wheres) ? $this->compileWheres($query) : '';
  241. return isset($query->joins)
  242. ? $this->compileDeleteWithJoins($query, $table, $where)
  243. : trim("delete from {$table} {$where}");
  244. }
  245. /**
  246. * Compile a delete statement with joins into SQL.
  247. *
  248. * @param \Illuminate\Database\Query\Builder $query
  249. * @param string $table
  250. * @param string $where
  251. * @return string
  252. */
  253. protected function compileDeleteWithJoins(Builder $query, $table, $where)
  254. {
  255. $joins = ' '.$this->compileJoins($query, $query->joins);
  256. $alias = strpos(strtolower($table), ' as ') !== false
  257. ? explode(' as ', $table)[1] : $table;
  258. return trim("delete {$alias} from {$table}{$joins} {$where}");
  259. }
  260. /**
  261. * Compile a truncate table statement into SQL.
  262. *
  263. * @param \Illuminate\Database\Query\Builder $query
  264. * @return array
  265. */
  266. public function compileTruncate(Builder $query)
  267. {
  268. return ['truncate table '.$this->wrapTable($query->from) => []];
  269. }
  270. /**
  271. * Compile an update statement into SQL.
  272. *
  273. * @param \Illuminate\Database\Query\Builder $query
  274. * @param array $values
  275. * @return string
  276. */
  277. public function compileUpdate(Builder $query, $values)
  278. {
  279. list($table, $alias) = $this->parseUpdateTable($query->from);
  280. // Each one of the columns in the update statements needs to be wrapped in the
  281. // keyword identifiers, also a place-holder needs to be created for each of
  282. // the values in the list of bindings so we can make the sets statements.
  283. $columns = collect($values)->map(function ($value, $key) {
  284. return $this->wrap($key).' = '.$this->parameter($value);
  285. })->implode(', ');
  286. // If the query has any "join" clauses, we will setup the joins on the builder
  287. // and compile them so we can attach them to this update, as update queries
  288. // can get join statements to attach to other tables when they're needed.
  289. $joins = '';
  290. if (isset($query->joins)) {
  291. $joins = ' '.$this->compileJoins($query, $query->joins);
  292. }
  293. // Of course, update queries may also be constrained by where clauses so we'll
  294. // need to compile the where clauses and attach it to the query so only the
  295. // intended records are updated by the SQL statements we generate to run.
  296. $where = $this->compileWheres($query);
  297. if (! empty($joins)) {
  298. return trim("update {$alias} set {$columns} from {$table}{$joins} {$where}");
  299. }
  300. return trim("update {$table}{$joins} set $columns $where");
  301. }
  302. /**
  303. * Get the table and alias for the given table.
  304. *
  305. * @param string $table
  306. * @return array
  307. */
  308. protected function parseUpdateTable($table)
  309. {
  310. $table = $alias = $this->wrapTable($table);
  311. if (strpos(strtolower($table), '] as [') !== false) {
  312. $alias = '['.explode('] as [', $table)[1];
  313. }
  314. return [$table, $alias];
  315. }
  316. /**
  317. * Prepare the bindings for an update statement.
  318. *
  319. * @param array $bindings
  320. * @param array $values
  321. * @return array
  322. */
  323. public function prepareBindingsForUpdate(array $bindings, array $values)
  324. {
  325. // Update statements with joins in SQL Servers utilize an unique syntax. We need to
  326. // take all of the bindings and put them on the end of this array since they are
  327. // added to the end of the "where" clause statements as typical where clauses.
  328. $bindingsWithoutJoin = Arr::except($bindings, 'join');
  329. return array_values(
  330. array_merge($values, $bindings['join'], Arr::flatten($bindingsWithoutJoin))
  331. );
  332. }
  333. /**
  334. * Determine if the grammar supports savepoints.
  335. *
  336. * @return bool
  337. */
  338. public function supportsSavepoints()
  339. {
  340. return true;
  341. }
  342. /**
  343. * Compile the SQL statement to define a savepoint.
  344. *
  345. * @param string $name
  346. * @return string
  347. */
  348. public function compileSavepoint($name)
  349. {
  350. return 'SAVE TRANSACTION '.$name;
  351. }
  352. /**
  353. * Compile the SQL statement to execute a savepoint rollback.
  354. *
  355. * @param string $name
  356. * @return string
  357. */
  358. public function compileSavepointRollBack($name)
  359. {
  360. return 'ROLLBACK TRANSACTION '.$name;
  361. }
  362. /**
  363. * Get the format for database stored dates.
  364. *
  365. * @return string
  366. */
  367. public function getDateFormat()
  368. {
  369. return 'Y-m-d H:i:s.v';
  370. }
  371. /**
  372. * Wrap a single string in keyword identifiers.
  373. *
  374. * @param string $value
  375. * @return string
  376. */
  377. protected function wrapValue($value)
  378. {
  379. return $value === '*' ? $value : '['.str_replace(']', ']]', $value).']';
  380. }
  381. /**
  382. * Wrap the given JSON selector.
  383. *
  384. * @param string $value
  385. * @return string
  386. */
  387. protected function wrapJsonSelector($value)
  388. {
  389. $parts = explode('->', $value, 2);
  390. $field = $this->wrapSegments(explode('.', array_shift($parts)));
  391. return 'json_value('.$field.', '.$this->wrapJsonPath($parts[0]).')';
  392. }
  393. /**
  394. * Wrap the given JSON path.
  395. *
  396. * @param string $value
  397. * @return string
  398. */
  399. protected function wrapJsonPath($value)
  400. {
  401. return '\'$."'.str_replace('->', '"."', $value).'"\'';
  402. }
  403. /**
  404. * Wrap a table in keyword identifiers.
  405. *
  406. * @param \Illuminate\Database\Query\Expression|string $table
  407. * @return string
  408. */
  409. public function wrapTable($table)
  410. {
  411. return $this->wrapTableValuedFunction(parent::wrapTable($table));
  412. }
  413. /**
  414. * Wrap a table in keyword identifiers.
  415. *
  416. * @param string $table
  417. * @return string
  418. */
  419. protected function wrapTableValuedFunction($table)
  420. {
  421. if (preg_match('/^(.+?)(\(.*?\))]$/', $table, $matches) === 1) {
  422. $table = $matches[1].']'.$matches[2];
  423. }
  424. return $table;
  425. }
  426. }