QueryBuilder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. 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_SMALLINT => 'smallint',
  31. Schema::TYPE_INTEGER => 'int',
  32. Schema::TYPE_BIGINT => 'bigint',
  33. Schema::TYPE_FLOAT => 'float',
  34. Schema::TYPE_DOUBLE => 'float',
  35. Schema::TYPE_DECIMAL => 'decimal(18,0)',
  36. Schema::TYPE_DATETIME => 'datetime',
  37. Schema::TYPE_TIMESTAMP => 'datetime',
  38. Schema::TYPE_TIME => 'time',
  39. Schema::TYPE_DATE => 'date',
  40. Schema::TYPE_BINARY => 'varbinary(max)',
  41. Schema::TYPE_BOOLEAN => 'bit',
  42. Schema::TYPE_MONEY => 'decimal(19,4)',
  43. ];
  44. /**
  45. * @inheritdoc
  46. */
  47. protected $likeEscapingReplacements = [
  48. '%' => '[%]',
  49. '_' => '[_]',
  50. '[' => '[[]',
  51. ']' => '[]]',
  52. '\\' => '[\\]',
  53. ];
  54. /**
  55. * @inheritdoc
  56. */
  57. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  58. {
  59. if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) {
  60. $orderBy = $this->buildOrderBy($orderBy);
  61. return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy;
  62. }
  63. if ($this->isOldMssql()) {
  64. return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  65. } else {
  66. return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
  67. }
  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. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  162. * The sequence will be reset such that the primary key of the next new row inserted
  163. * will have the specified value or 1.
  164. * @param string $tableName the name of the table whose primary key sequence will be reset
  165. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  166. * the next new row's primary key will have a value 1.
  167. * @return string the SQL statement for resetting sequence
  168. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  169. */
  170. public function resetSequence($tableName, $value = null)
  171. {
  172. $table = $this->db->getTableSchema($tableName);
  173. if ($table !== null && $table->sequenceName !== null) {
  174. $tableName = $this->db->quoteTableName($tableName);
  175. if ($value === null) {
  176. $key = $this->db->quoteColumnName(reset($table->primaryKey));
  177. $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
  178. } else {
  179. $value = (int) $value;
  180. }
  181. return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})";
  182. } elseif ($table === null) {
  183. throw new InvalidParamException("Table not found: $tableName");
  184. } else {
  185. throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
  186. }
  187. }
  188. /**
  189. * Builds a SQL statement for enabling or disabling integrity check.
  190. * @param bool $check whether to turn on or off the integrity check.
  191. * @param string $schema the schema of the tables.
  192. * @param string $table the table name.
  193. * @return string the SQL statement for checking integrity
  194. */
  195. public function checkIntegrity($check = true, $schema = '', $table = '')
  196. {
  197. $enable = $check ? 'CHECK' : 'NOCHECK';
  198. $schema = $schema ?: $this->db->getSchema()->defaultSchema;
  199. $tableNames = $this->db->getTableSchema($table) ? [$table] : $this->db->getSchema()->getTableNames($schema);
  200. $viewNames = $this->db->getSchema()->getViewNames($schema);
  201. $tableNames = array_diff($tableNames, $viewNames);
  202. $command = '';
  203. foreach ($tableNames as $tableName) {
  204. $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
  205. $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; ";
  206. }
  207. return $command;
  208. }
  209. /**
  210. * @inheritdoc
  211. * @since 2.0.8
  212. */
  213. public function addCommentOnColumn($table, $column, $comment)
  214. {
  215. 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)}";
  216. }
  217. /**
  218. * @inheritdoc
  219. * @since 2.0.8
  220. */
  221. public function addCommentOnTable($table, $comment)
  222. {
  223. return "sp_updateextendedproperty @name = N'MS_Description', @value = {$this->db->quoteValue($comment)}, @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}";
  224. }
  225. /**
  226. * @inheritdoc
  227. * @since 2.0.8
  228. */
  229. public function dropCommentFromColumn($table, $column)
  230. {
  231. return "sp_dropextendedproperty @name = N'MS_Description', @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}, @level2type = N'Column', @level2name = {$this->db->quoteColumnName($column)}";
  232. }
  233. /**
  234. * @inheritdoc
  235. * @since 2.0.8
  236. */
  237. public function dropCommentFromTable($table)
  238. {
  239. return "sp_dropextendedproperty @name = N'MS_Description', @level1type = N'Table', @level1name = {$this->db->quoteTableName($table)}";
  240. }
  241. /**
  242. * Returns an array of column names given model name
  243. *
  244. * @param string $modelClass name of the model class
  245. * @return array|null array of column names
  246. */
  247. protected function getAllColumnNames($modelClass = null)
  248. {
  249. if (!$modelClass) {
  250. return null;
  251. }
  252. /* @var $modelClass \yii\db\ActiveRecord */
  253. $schema = $modelClass::getTableSchema();
  254. return array_keys($schema->columns);
  255. }
  256. /**
  257. * @var bool whether MSSQL used is old.
  258. */
  259. private $_oldMssql;
  260. /**
  261. * @return bool whether the version of the MSSQL being used is older than 2012.
  262. * @throws \yii\base\InvalidConfigException
  263. * @throws \yii\db\Exception
  264. */
  265. protected function isOldMssql()
  266. {
  267. if ($this->_oldMssql === null) {
  268. $pdo = $this->db->getSlavePdo();
  269. $version = explode('.', $pdo->getAttribute(\PDO::ATTR_SERVER_VERSION));
  270. $this->_oldMssql = $version[0] < 11;
  271. }
  272. return $this->_oldMssql;
  273. }
  274. /**
  275. * @inheritdoc
  276. * @throws NotSupportedException if `$columns` is an array
  277. */
  278. protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
  279. {
  280. if (is_array($columns)) {
  281. throw new NotSupportedException(__METHOD__ . ' is not supported by MSSQL.');
  282. }
  283. return parent::buildSubqueryInCondition($operator, $columns, $values, $params);
  284. }
  285. /**
  286. * Builds SQL for IN condition
  287. *
  288. * @param string $operator
  289. * @param array $columns
  290. * @param array $values
  291. * @param array $params
  292. * @return string SQL
  293. */
  294. protected function buildCompositeInCondition($operator, $columns, $values, &$params)
  295. {
  296. $quotedColumns = [];
  297. foreach ($columns as $i => $column) {
  298. $quotedColumns[$i] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
  299. }
  300. $vss = [];
  301. foreach ($values as $value) {
  302. $vs = [];
  303. foreach ($columns as $i => $column) {
  304. if (isset($value[$column])) {
  305. $phName = self::PARAM_PREFIX . count($params);
  306. $params[$phName] = $value[$column];
  307. $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' = ' : ' != ') . $phName;
  308. } else {
  309. $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' IS' : ' IS NOT') . ' NULL';
  310. }
  311. }
  312. $vss[] = '(' . implode($operator === 'IN' ? ' AND ' : ' OR ', $vs) . ')';
  313. }
  314. return '(' . implode($operator === 'IN' ? ' OR ' : ' AND ', $vss) . ')';
  315. }
  316. /**
  317. * @inheritdoc
  318. * @since 2.0.8
  319. */
  320. public function selectExists($rawSql)
  321. {
  322. return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
  323. }
  324. /**
  325. * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
  326. * @param string $table the table that data will be saved into.
  327. * @param array $columns the column data (name => value) to be saved into the table.
  328. * @return array normalized columns
  329. */
  330. private function normalizeTableRowData($table, $columns, &$params)
  331. {
  332. if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
  333. $columnSchemas = $tableSchema->columns;
  334. foreach ($columns as $name => $value) {
  335. // @see https://github.com/yiisoft/yii2/issues/12599
  336. if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && is_string($value)) {
  337. $phName = self::PARAM_PREFIX . count($params);
  338. $columns[$name] = new Expression("CONVERT(VARBINARY, $phName)", [$phName => $value]);
  339. }
  340. }
  341. }
  342. return $columns;
  343. }
  344. /**
  345. * @inheritdoc
  346. */
  347. public function insert($table, $columns, &$params)
  348. {
  349. return parent::insert($table, $this->normalizeTableRowData($table, $columns, $params), $params);
  350. }
  351. /**
  352. * @inheritdoc
  353. */
  354. public function update($table, $columns, $condition, &$params)
  355. {
  356. return parent::update($table, $this->normalizeTableRowData($table, $columns, $params), $condition, $params);
  357. }
  358. }