SqlServerGrammar.php 12 KB

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