QueryBuilder.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\mssql;
  8. use yii\base\InvalidArgumentException;
  9. use yii\db\Constraint;
  10. use yii\db\Expression;
  11. /**
  12. * QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above).
  13. *
  14. * @author Timur Ruziev <resurtm@gmail.com>
  15. * @since 2.0
  16. */
  17. class QueryBuilder extends \yii\db\QueryBuilder
  18. {
  19. /**
  20. * @var array mapping from abstract column types (keys) to physical column types (values).
  21. */
  22. public $typeMap = [
  23. Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY',
  24. Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY',
  25. Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY',
  26. Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY',
  27. Schema::TYPE_CHAR => 'nchar(1)',
  28. Schema::TYPE_STRING => 'nvarchar(255)',
  29. Schema::TYPE_TEXT => 'nvarchar(max)',
  30. Schema::TYPE_TINYINT => 'tinyint',
  31. Schema::TYPE_SMALLINT => 'smallint',
  32. Schema::TYPE_INTEGER => 'int',
  33. Schema::TYPE_BIGINT => 'bigint',
  34. Schema::TYPE_FLOAT => 'float',
  35. Schema::TYPE_DOUBLE => 'float',
  36. Schema::TYPE_DECIMAL => 'decimal(18,0)',
  37. Schema::TYPE_DATETIME => 'datetime',
  38. Schema::TYPE_TIMESTAMP => 'datetime',
  39. Schema::TYPE_TIME => 'time',
  40. Schema::TYPE_DATE => 'date',
  41. Schema::TYPE_BINARY => 'varbinary(max)',
  42. Schema::TYPE_BOOLEAN => 'bit',
  43. Schema::TYPE_MONEY => 'decimal(19,4)',
  44. ];
  45. /**
  46. * {@inheritdoc}
  47. */
  48. protected function defaultExpressionBuilders()
  49. {
  50. return array_merge(parent::defaultExpressionBuilders(), [
  51. 'yii\db\conditions\InCondition' => 'yii\db\mssql\conditions\InConditionBuilder',
  52. 'yii\db\conditions\LikeCondition' => 'yii\db\mssql\conditions\LikeConditionBuilder',
  53. ]);
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  59. {
  60. if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) {
  61. $orderBy = $this->buildOrderBy($orderBy);
  62. return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy;
  63. }
  64. if (version_compare($this->db->getSchema()->getServerVersion(), '11', '<')) {
  65. return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  66. }
  67. return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  68. }
  69. /**
  70. * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer.
  71. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
  72. * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter.
  73. * @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details.
  74. * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details.
  75. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
  76. */
  77. protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  78. {
  79. $orderBy = $this->buildOrderBy($orderBy);
  80. if ($orderBy === '') {
  81. // ORDER BY clause is required when FETCH and OFFSET are in the SQL
  82. $orderBy = 'ORDER BY (SELECT NULL)';
  83. }
  84. $sql .= $this->separator . $orderBy;
  85. // http://technet.microsoft.com/en-us/library/gg699618.aspx
  86. $offset = $this->hasOffset($offset) ? $offset : '0';
  87. $sql .= $this->separator . "OFFSET $offset ROWS";
  88. if ($this->hasLimit($limit)) {
  89. $sql .= $this->separator . "FETCH NEXT $limit ROWS ONLY";
  90. }
  91. return $sql;
  92. }
  93. /**
  94. * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008.
  95. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
  96. * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter.
  97. * @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details.
  98. * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details.
  99. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
  100. */
  101. protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  102. {
  103. $orderBy = $this->buildOrderBy($orderBy);
  104. if ($orderBy === '') {
  105. // ROW_NUMBER() requires an ORDER BY clause
  106. $orderBy = 'ORDER BY (SELECT NULL)';
  107. }
  108. $sql = preg_replace('/^([\s(])*SELECT(\s+DISTINCT)?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 rowNum = ROW_NUMBER() over ($orderBy),", $sql);
  109. if ($this->hasLimit($limit)) {
  110. $sql = "SELECT TOP $limit * FROM ($sql) sub";
  111. } else {
  112. $sql = "SELECT * FROM ($sql) sub";
  113. }
  114. if ($this->hasOffset($offset)) {
  115. $sql .= $this->separator . "WHERE rowNum > $offset";
  116. }
  117. return $sql;
  118. }
  119. /**
  120. * Builds a SQL statement for renaming a DB table.
  121. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
  122. * @param string $newName the new table name. The name will be properly quoted by the method.
  123. * @return string the SQL statement for renaming a DB table.
  124. */
  125. public function renameTable($oldName, $newName)
  126. {
  127. return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName);
  128. }
  129. /**
  130. * Builds a SQL statement for renaming a column.
  131. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  132. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  133. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  134. * @return string the SQL statement for renaming a DB column.
  135. */
  136. public function renameColumn($table, $oldName, $newName)
  137. {
  138. $table = $this->db->quoteTableName($table);
  139. $oldName = $this->db->quoteColumnName($oldName);
  140. $newName = $this->db->quoteColumnName($newName);
  141. return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'";
  142. }
  143. /**
  144. * Builds a SQL statement for changing the definition of a column.
  145. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  146. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  147. * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
  148. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  149. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  150. * @return string the SQL statement for changing the definition of a column.
  151. */
  152. public function alterColumn($table, $column, $type)
  153. {
  154. $type = $this->getColumnType($type);
  155. $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
  156. . $this->db->quoteColumnName($column) . ' '
  157. . $this->getColumnType($type);
  158. return $sql;
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. public function addDefaultValue($name, $table, $column, $value)
  164. {
  165. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
  166. . $this->db->quoteColumnName($name) . ' DEFAULT ' . $this->db->quoteValue($value) . ' FOR '
  167. . $this->db->quoteColumnName($column);
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function dropDefaultValue($name, $table)
  173. {
  174. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  175. . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
  176. }
  177. /**
  178. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  179. * The sequence will be reset such that the primary key of the next new row inserted
  180. * will have the specified value or 1.
  181. * @param string $tableName the name of the table whose primary key sequence will be reset
  182. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  183. * the next new row's primary key will have a value 1.
  184. * @return string the SQL statement for resetting sequence
  185. * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
  186. */
  187. public function resetSequence($tableName, $value = null)
  188. {
  189. $table = $this->db->getTableSchema($tableName);
  190. if ($table !== null && $table->sequenceName !== null) {
  191. $tableName = $this->db->quoteTableName($tableName);
  192. if ($value === null) {
  193. $key = $this->db->quoteColumnName(reset($table->primaryKey));
  194. $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
  195. } else {
  196. $value = (int) $value;
  197. }
  198. return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})";
  199. } elseif ($table === null) {
  200. throw new InvalidArgumentException("Table not found: $tableName");
  201. }
  202. throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
  203. }
  204. /**
  205. * Builds a SQL statement for enabling or disabling integrity check.
  206. * @param bool $check whether to turn on or off the integrity check.
  207. * @param string $schema the schema of the tables.
  208. * @param string $table the table name.
  209. * @return string the SQL statement for checking integrity
  210. */
  211. public function checkIntegrity($check = true, $schema = '', $table = '')
  212. {
  213. $enable = $check ? 'CHECK' : 'NOCHECK';
  214. $schema = $schema ?: $this->db->getSchema()->defaultSchema;
  215. $tableNames = $this->db->getTableSchema($table) ? [$table] : $this->db->getSchema()->getTableNames($schema);
  216. $viewNames = $this->db->getSchema()->getViewNames($schema);
  217. $tableNames = array_diff($tableNames, $viewNames);
  218. $command = '';
  219. foreach ($tableNames as $tableName) {
  220. $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
  221. $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; ";
  222. }
  223. return $command;
  224. }
  225. /**
  226. * Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a comment
  227. * already exists. If so, it will be updated, otherwise, it will be added.
  228. *
  229. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  230. * @param string $table the table to be commented or whose column is to be commented. The table name will be
  231. * properly quoted by the method.
  232. * @param string $column optional. The name of the column to be commented. If empty, the command will add the
  233. * comment to the table instead. The column name will be properly quoted by the method.
  234. * @return string the SQL statement for adding a comment.
  235. * @throws InvalidArgumentException if the table does not exist.
  236. * @since 2.0.24
  237. */
  238. protected function buildAddCommentSql($comment, $table, $column = null)
  239. {
  240. $tableSchema = $this->db->schema->getTableSchema($table);
  241. if ($tableSchema === null) {
  242. throw new InvalidArgumentException("Table not found: $table");
  243. }
  244. $schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'": 'SCHEMA_NAME()';
  245. $tableName = "N" . $this->db->quoteValue($tableSchema->name);
  246. $columnName = $column ? "N" . $this->db->quoteValue($column) : null;
  247. $comment = "N" . $this->db->quoteValue($comment);
  248. $functionParams = "
  249. @name = N'MS_description',
  250. @value = $comment,
  251. @level0type = N'SCHEMA', @level0name = $schemaName,
  252. @level1type = N'TABLE', @level1name = $tableName"
  253. . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
  254. return "
  255. IF NOT EXISTS (
  256. SELECT 1
  257. FROM fn_listextendedproperty (
  258. N'MS_description',
  259. 'SCHEMA', $schemaName,
  260. 'TABLE', $tableName,
  261. " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
  262. )
  263. )
  264. EXEC sys.sp_addextendedproperty $functionParams
  265. ELSE
  266. EXEC sys.sp_updateextendedproperty $functionParams
  267. ";
  268. }
  269. /**
  270. * {@inheritdoc}
  271. * @since 2.0.8
  272. */
  273. public function addCommentOnColumn($table, $column, $comment)
  274. {
  275. return $this->buildAddCommentSql($comment, $table, $column);
  276. }
  277. /**
  278. * {@inheritdoc}
  279. * @since 2.0.8
  280. */
  281. public function addCommentOnTable($table, $comment)
  282. {
  283. return $this->buildAddCommentSql($comment, $table);
  284. }
  285. /**
  286. * Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment
  287. * already exists before trying to perform the removal.
  288. *
  289. * @param string $table the table that will have the comment removed or whose column will have the comment removed.
  290. * The table name will be properly quoted by the method.
  291. * @param string $column optional. The name of the column whose comment will be removed. If empty, the command
  292. * will remove the comment from the table instead. The column name will be properly quoted by the method.
  293. * @return string the SQL statement for removing the comment.
  294. * @throws InvalidArgumentException if the table does not exist.
  295. * @since 2.0.24
  296. */
  297. protected function buildRemoveCommentSql($table, $column = null)
  298. {
  299. $tableSchema = $this->db->schema->getTableSchema($table);
  300. if ($tableSchema === null) {
  301. throw new InvalidArgumentException("Table not found: $table");
  302. }
  303. $schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'": 'SCHEMA_NAME()';
  304. $tableName = "N" . $this->db->quoteValue($tableSchema->name);
  305. $columnName = $column ? "N" . $this->db->quoteValue($column) : null;
  306. return "
  307. IF EXISTS (
  308. SELECT 1
  309. FROM fn_listextendedproperty (
  310. N'MS_description',
  311. 'SCHEMA', $schemaName,
  312. 'TABLE', $tableName,
  313. " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
  314. )
  315. )
  316. EXEC sys.sp_dropextendedproperty
  317. @name = N'MS_description',
  318. @level0type = N'SCHEMA', @level0name = $schemaName,
  319. @level1type = N'TABLE', @level1name = $tableName"
  320. . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
  321. }
  322. /**
  323. * {@inheritdoc}
  324. * @since 2.0.8
  325. */
  326. public function dropCommentFromColumn($table, $column)
  327. {
  328. return $this->buildRemoveCommentSql($table, $column);
  329. }
  330. /**
  331. * {@inheritdoc}
  332. * @since 2.0.8
  333. */
  334. public function dropCommentFromTable($table)
  335. {
  336. return $this->buildRemoveCommentSql($table);
  337. }
  338. /**
  339. * Returns an array of column names given model name.
  340. *
  341. * @param string $modelClass name of the model class
  342. * @return array|null array of column names
  343. */
  344. protected function getAllColumnNames($modelClass = null)
  345. {
  346. if (!$modelClass) {
  347. return null;
  348. }
  349. /* @var $modelClass \yii\db\ActiveRecord */
  350. $schema = $modelClass::getTableSchema();
  351. return array_keys($schema->columns);
  352. }
  353. /**
  354. * @return bool whether the version of the MSSQL being used is older than 2012.
  355. * @throws \yii\base\InvalidConfigException
  356. * @throws \yii\db\Exception
  357. * @deprecated 2.0.14 Use [[Schema::getServerVersion]] with [[\version_compare()]].
  358. */
  359. protected function isOldMssql()
  360. {
  361. return version_compare($this->db->getSchema()->getServerVersion(), '11', '<');
  362. }
  363. /**
  364. * {@inheritdoc}
  365. * @since 2.0.8
  366. */
  367. public function selectExists($rawSql)
  368. {
  369. return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
  370. }
  371. /**
  372. * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
  373. * @param string $table the table that data will be saved into.
  374. * @param array $columns the column data (name => value) to be saved into the table.
  375. * @return array normalized columns
  376. */
  377. private function normalizeTableRowData($table, $columns, &$params)
  378. {
  379. if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
  380. $columnSchemas = $tableSchema->columns;
  381. foreach ($columns as $name => $value) {
  382. // @see https://github.com/yiisoft/yii2/issues/12599
  383. if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && (is_string($value) || $value === null)) {
  384. $phName = $this->bindParam($value, $params);
  385. $columns[$name] = new Expression("CONVERT(VARBINARY, $phName)", $params);
  386. }
  387. }
  388. }
  389. return $columns;
  390. }
  391. /**
  392. * {@inheritdoc}
  393. */
  394. public function insert($table, $columns, &$params)
  395. {
  396. return parent::insert($table, $this->normalizeTableRowData($table, $columns, $params), $params);
  397. }
  398. /**
  399. * {@inheritdoc}
  400. * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql
  401. * @see http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  402. */
  403. public function upsert($table, $insertColumns, $updateColumns, &$params)
  404. {
  405. /** @var Constraint[] $constraints */
  406. list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
  407. if (empty($uniqueNames)) {
  408. return $this->insert($table, $insertColumns, $params);
  409. }
  410. $onCondition = ['or'];
  411. $quotedTableName = $this->db->quoteTableName($table);
  412. foreach ($constraints as $constraint) {
  413. $constraintCondition = ['and'];
  414. foreach ($constraint->columnNames as $name) {
  415. $quotedName = $this->db->quoteColumnName($name);
  416. $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
  417. }
  418. $onCondition[] = $constraintCondition;
  419. }
  420. $on = $this->buildCondition($onCondition, $params);
  421. list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
  422. $mergeSql = 'MERGE ' . $this->db->quoteTableName($table) . ' WITH (HOLDLOCK) '
  423. . 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') '
  424. . "ON ($on)";
  425. $insertValues = [];
  426. foreach ($insertNames as $name) {
  427. $quotedName = $this->db->quoteColumnName($name);
  428. if (strrpos($quotedName, '.') === false) {
  429. $quotedName = '[EXCLUDED].' . $quotedName;
  430. }
  431. $insertValues[] = $quotedName;
  432. }
  433. $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
  434. . ' VALUES (' . implode(', ', $insertValues) . ')';
  435. if ($updateColumns === false) {
  436. return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
  437. }
  438. if ($updateColumns === true) {
  439. $updateColumns = [];
  440. foreach ($updateNames as $name) {
  441. $quotedName = $this->db->quoteColumnName($name);
  442. if (strrpos($quotedName, '.') === false) {
  443. $quotedName = '[EXCLUDED].' . $quotedName;
  444. }
  445. $updateColumns[$name] = new Expression($quotedName);
  446. }
  447. }
  448. list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
  449. $updateSql = 'UPDATE SET ' . implode(', ', $updates);
  450. return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
  451. }
  452. /**
  453. * {@inheritdoc}
  454. */
  455. public function update($table, $columns, $condition, &$params)
  456. {
  457. return parent::update($table, $this->normalizeTableRowData($table, $columns, $params), $condition, $params);
  458. }
  459. /**
  460. * {@inheritdoc}
  461. */
  462. public function getColumnType($type)
  463. {
  464. $columnType = parent::getColumnType($type);
  465. // remove unsupported keywords
  466. $columnType = preg_replace("/\s*comment '.*'/i", '', $columnType);
  467. $columnType = preg_replace('/ first$/i', '', $columnType);
  468. return $columnType;
  469. }
  470. /**
  471. * {@inheritdoc}
  472. */
  473. protected function extractAlias($table)
  474. {
  475. if (preg_match('/^\[.*\]$/', $table)) {
  476. return false;
  477. }
  478. return parent::extractAlias($table);
  479. }
  480. }