Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

316 lines
12KB

  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\InvalidParamException;
  9. use yii\base\NotSupportedException;
  10. /**
  11. * QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above).
  12. *
  13. * @author Timur Ruziev <resurtm@gmail.com>
  14. * @since 2.0
  15. */
  16. class QueryBuilder extends \yii\db\QueryBuilder
  17. {
  18. /**
  19. * @var array mapping from abstract column types (keys) to physical column types (values).
  20. */
  21. public $typeMap = [
  22. Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY',
  23. Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY',
  24. Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY',
  25. Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY',
  26. Schema::TYPE_CHAR => 'nchar(1)',
  27. Schema::TYPE_STRING => 'nvarchar(255)',
  28. Schema::TYPE_TEXT => 'nvarchar(max)',
  29. Schema::TYPE_SMALLINT => 'smallint',
  30. Schema::TYPE_INTEGER => 'int',
  31. Schema::TYPE_BIGINT => 'bigint',
  32. Schema::TYPE_FLOAT => 'float',
  33. Schema::TYPE_DOUBLE => 'float',
  34. Schema::TYPE_DECIMAL => 'decimal',
  35. Schema::TYPE_DATETIME => 'datetime',
  36. Schema::TYPE_TIMESTAMP => 'timestamp',
  37. Schema::TYPE_TIME => 'time',
  38. Schema::TYPE_DATE => 'date',
  39. Schema::TYPE_BINARY => 'varbinary(max)',
  40. Schema::TYPE_BOOLEAN => 'bit',
  41. Schema::TYPE_MONEY => 'decimal(19,4)',
  42. ];
  43. /**
  44. * @inheritdoc
  45. */
  46. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  47. {
  48. if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) {
  49. $orderBy = $this->buildOrderBy($orderBy);
  50. return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy;
  51. }
  52. if ($this->isOldMssql()) {
  53. return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  54. } else {
  55. return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  56. }
  57. }
  58. /**
  59. * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer.
  60. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
  61. * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
  62. * @param integer $limit the limit number. See [[Query::limit]] for more details.
  63. * @param integer $offset the offset number. See [[Query::offset]] for more details.
  64. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
  65. */
  66. protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  67. {
  68. $orderBy = $this->buildOrderBy($orderBy);
  69. if ($orderBy === '') {
  70. // ORDER BY clause is required when FETCH and OFFSET are in the SQL
  71. $orderBy = 'ORDER BY (SELECT NULL)';
  72. }
  73. $sql .= $this->separator . $orderBy;
  74. // http://technet.microsoft.com/en-us/library/gg699618.aspx
  75. $offset = $this->hasOffset($offset) ? $offset : '0';
  76. $sql .= $this->separator . "OFFSET $offset ROWS";
  77. if ($this->hasLimit($limit)) {
  78. $sql .= $this->separator . "FETCH NEXT $limit ROWS ONLY";
  79. }
  80. return $sql;
  81. }
  82. /**
  83. * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008.
  84. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
  85. * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
  86. * @param integer $limit the limit number. See [[Query::limit]] for more details.
  87. * @param integer $offset the offset number. See [[Query::offset]] for more details.
  88. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
  89. */
  90. protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  91. {
  92. $orderBy = $this->buildOrderBy($orderBy);
  93. if ($orderBy === '') {
  94. // ROW_NUMBER() requires an ORDER BY clause
  95. $orderBy = 'ORDER BY (SELECT NULL)';
  96. }
  97. $sql = preg_replace('/^([\s(])*SELECT(\s+DISTINCT)?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 rowNum = ROW_NUMBER() over ($orderBy),", $sql);
  98. if ($this->hasLimit($limit)) {
  99. $sql = "SELECT TOP $limit * FROM ($sql) sub";
  100. } else {
  101. $sql = "SELECT * FROM ($sql) sub";
  102. }
  103. if ($this->hasOffset($offset)) {
  104. $sql .= $this->separator . "WHERE rowNum > $offset";
  105. }
  106. return $sql;
  107. }
  108. /**
  109. * Builds a SQL statement for renaming a DB table.
  110. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
  111. * @param string $newName the new table name. The name will be properly quoted by the method.
  112. * @return string the SQL statement for renaming a DB table.
  113. */
  114. public function renameTable($oldName, $newName)
  115. {
  116. return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName);
  117. }
  118. /**
  119. * Builds a SQL statement for renaming a column.
  120. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  121. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  122. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  123. * @return string the SQL statement for renaming a DB column.
  124. */
  125. public function renameColumn($table, $oldName, $newName)
  126. {
  127. $table = $this->db->quoteTableName($table);
  128. $oldName = $this->db->quoteColumnName($oldName);
  129. $newName = $this->db->quoteColumnName($newName);
  130. return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'";
  131. }
  132. /**
  133. * Builds a SQL statement for changing the definition of a column.
  134. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  135. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  136. * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
  137. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  138. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  139. * @return string the SQL statement for changing the definition of a column.
  140. */
  141. public function alterColumn($table, $column, $type)
  142. {
  143. $type = $this->getColumnType($type);
  144. $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
  145. . $this->db->quoteColumnName($column) . ' '
  146. . $this->getColumnType($type);
  147. return $sql;
  148. }
  149. /**
  150. * Builds a SQL statement for enabling or disabling integrity check.
  151. * @param boolean $check whether to turn on or off the integrity check.
  152. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  153. * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
  154. * @return string the SQL statement for checking integrity
  155. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  156. */
  157. public function checkIntegrity($check = true, $schema = '', $table = '')
  158. {
  159. if ($schema !== '') {
  160. $table = "{$schema}.{$table}";
  161. }
  162. $table = $this->db->quoteTableName($table);
  163. if ($this->db->getTableSchema($table) === null) {
  164. throw new InvalidParamException("Table not found: $table");
  165. }
  166. $enable = $check ? 'CHECK' : 'NOCHECK';
  167. return "ALTER TABLE {$table} {$enable} CONSTRAINT ALL";
  168. }
  169. /**
  170. * @inheritdoc
  171. * @since 2.0.8
  172. */
  173. public function addCommentOnColumn($table, $column, $comment)
  174. {
  175. return "sp_updateextendedproperty @name = N'MS_Description', @value = {$this->db->quoteValue($comment)}, @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}, @level2type = N'Column', @level2name = {$this->db->quoteColumnName($column)}";
  176. }
  177. /**
  178. * @inheritdoc
  179. * @since 2.0.8
  180. */
  181. public function addCommentOnTable($table, $comment)
  182. {
  183. return "sp_updateextendedproperty @name = N'MS_Description', @value = {$this->db->quoteValue($comment)}, @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}";
  184. }
  185. /**
  186. * @inheritdoc
  187. * @since 2.0.8
  188. */
  189. public function dropCommentFromColumn($table, $column)
  190. {
  191. return "sp_dropextendedproperty @name = N'MS_Description', @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}, @level2type = N'Column', @level2name = {$this->db->quoteColumnName($column)}";
  192. }
  193. /**
  194. * @inheritdoc
  195. * @since 2.0.8
  196. */
  197. public function dropCommentFromTable($table)
  198. {
  199. return "sp_dropextendedproperty @name = N'MS_Description', @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}";
  200. }
  201. /**
  202. * Returns an array of column names given model name
  203. *
  204. * @param string $modelClass name of the model class
  205. * @return array|null array of column names
  206. */
  207. protected function getAllColumnNames($modelClass = null)
  208. {
  209. if (!$modelClass) {
  210. return null;
  211. }
  212. /* @var $model \yii\db\ActiveRecord */
  213. $model = new $modelClass;
  214. $schema = $model->getTableSchema();
  215. return array_keys($schema->columns);
  216. }
  217. /**
  218. * @var boolean whether MSSQL used is old.
  219. */
  220. private $_oldMssql;
  221. /**
  222. * @return boolean whether the version of the MSSQL being used is older than 2012.
  223. * @throws \yii\base\InvalidConfigException
  224. * @throws \yii\db\Exception
  225. */
  226. protected function isOldMssql()
  227. {
  228. if ($this->_oldMssql === null) {
  229. $pdo = $this->db->getSlavePdo();
  230. $version = explode('.', $pdo->getAttribute(\PDO::ATTR_SERVER_VERSION));
  231. $this->_oldMssql = $version[0] < 11;
  232. }
  233. return $this->_oldMssql;
  234. }
  235. /**
  236. * @inheritdoc
  237. * @throws NotSupportedException if `$columns` is an array
  238. */
  239. protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
  240. {
  241. if (is_array($columns)) {
  242. throw new NotSupportedException(__METHOD__ . ' is not supported by MSSQL.');
  243. }
  244. return parent::buildSubqueryInCondition($operator, $columns, $values, $params);
  245. }
  246. /**
  247. * Builds SQL for IN condition
  248. *
  249. * @param string $operator
  250. * @param array $columns
  251. * @param array $values
  252. * @param array $params
  253. * @return string SQL
  254. */
  255. protected function buildCompositeInCondition($operator, $columns, $values, &$params)
  256. {
  257. $quotedColumns = [];
  258. foreach ($columns as $i => $column) {
  259. $quotedColumns[$i] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
  260. }
  261. $vss = [];
  262. foreach ($values as $value) {
  263. $vs = [];
  264. foreach ($columns as $i => $column) {
  265. if (isset($value[$column])) {
  266. $phName = self::PARAM_PREFIX . count($params);
  267. $params[$phName] = $value[$column];
  268. $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' = ' : ' != ') . $phName;
  269. } else {
  270. $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' IS' : ' IS NOT') . ' NULL';
  271. }
  272. }
  273. $vss[] = '(' . implode($operator === 'IN' ? ' AND ' : ' OR ', $vs) . ')';
  274. }
  275. return '(' . implode($operator === 'IN' ? ' OR ' : ' AND ', $vss) . ')';
  276. }
  277. /**
  278. * @inheritdoc
  279. * @since 2.0.8
  280. */
  281. public function selectExists($rawSql)
  282. {
  283. return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
  284. }
  285. }