QueryBuilder.php 27 KB

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