You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

299 lines
11KB

  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\mysql;
  8. use yii\base\InvalidParamException;
  9. use yii\db\Exception;
  10. use yii\db\Expression;
  11. /**
  12. * QueryBuilder is the query builder for MySQL databases.
  13. *
  14. * @author Qiang Xue <qiang.xue@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(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  24. Schema::TYPE_UPK => 'int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  25. Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  26. Schema::TYPE_UBIGPK => 'bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  27. Schema::TYPE_CHAR => 'char(1)',
  28. Schema::TYPE_STRING => 'varchar(255)',
  29. Schema::TYPE_TEXT => 'text',
  30. Schema::TYPE_SMALLINT => 'smallint(6)',
  31. Schema::TYPE_INTEGER => 'int(11)',
  32. Schema::TYPE_BIGINT => 'bigint(20)',
  33. Schema::TYPE_FLOAT => 'float',
  34. Schema::TYPE_DOUBLE => 'double',
  35. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  36. Schema::TYPE_DATETIME => 'datetime',
  37. Schema::TYPE_TIMESTAMP => 'timestamp',
  38. Schema::TYPE_TIME => 'time',
  39. Schema::TYPE_DATE => 'date',
  40. Schema::TYPE_BINARY => 'blob',
  41. Schema::TYPE_BOOLEAN => 'tinyint(1)',
  42. Schema::TYPE_MONEY => 'decimal(19,4)',
  43. ];
  44. /**
  45. * Builds a SQL statement for renaming a column.
  46. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  47. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  48. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  49. * @return string the SQL statement for renaming a DB column.
  50. * @throws Exception
  51. */
  52. public function renameColumn($table, $oldName, $newName)
  53. {
  54. $quotedTable = $this->db->quoteTableName($table);
  55. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  56. if ($row === false) {
  57. throw new Exception("Unable to find column '$oldName' in table '$table'.");
  58. }
  59. if (isset($row['Create Table'])) {
  60. $sql = $row['Create Table'];
  61. } else {
  62. $row = array_values($row);
  63. $sql = $row[1];
  64. }
  65. if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
  66. foreach ($matches[1] as $i => $c) {
  67. if ($c === $oldName) {
  68. return "ALTER TABLE $quotedTable CHANGE "
  69. . $this->db->quoteColumnName($oldName) . ' '
  70. . $this->db->quoteColumnName($newName) . ' '
  71. . $matches[2][$i];
  72. }
  73. }
  74. }
  75. // try to give back a SQL anyway
  76. return "ALTER TABLE $quotedTable CHANGE "
  77. . $this->db->quoteColumnName($oldName) . ' '
  78. . $this->db->quoteColumnName($newName);
  79. }
  80. /**
  81. * @inheritdoc
  82. * @see https://bugs.mysql.com/bug.php?id=48875
  83. */
  84. public function createIndex($name, $table, $columns, $unique = false)
  85. {
  86. return 'ALTER TABLE '
  87. . $this->db->quoteTableName($table)
  88. . ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
  89. . $this->db->quoteTableName($name)
  90. . ' (' . $this->buildColumns($columns) . ')';
  91. }
  92. /**
  93. * Builds a SQL statement for dropping a foreign key constraint.
  94. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  95. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  96. * @return string the SQL statement for dropping a foreign key constraint.
  97. */
  98. public function dropForeignKey($name, $table)
  99. {
  100. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  101. . ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
  102. }
  103. /**
  104. * Builds a SQL statement for removing a primary key constraint to an existing table.
  105. * @param string $name the name of the primary key constraint to be removed.
  106. * @param string $table the table that the primary key constraint will be removed from.
  107. * @return string the SQL statement for removing a primary key constraint from an existing table.
  108. */
  109. public function dropPrimaryKey($name, $table)
  110. {
  111. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
  112. }
  113. /**
  114. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  115. * The sequence will be reset such that the primary key of the next new row inserted
  116. * will have the specified value or 1.
  117. * @param string $tableName the name of the table whose primary key sequence will be reset
  118. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  119. * the next new row's primary key will have a value 1.
  120. * @return string the SQL statement for resetting sequence
  121. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  122. */
  123. public function resetSequence($tableName, $value = null)
  124. {
  125. $table = $this->db->getTableSchema($tableName);
  126. if ($table !== null && $table->sequenceName !== null) {
  127. $tableName = $this->db->quoteTableName($tableName);
  128. if ($value === null) {
  129. $key = reset($table->primaryKey);
  130. $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
  131. } else {
  132. $value = (int) $value;
  133. }
  134. return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
  135. } elseif ($table === null) {
  136. throw new InvalidParamException("Table not found: $tableName");
  137. } else {
  138. throw new InvalidParamException("There is no sequence associated with table '$tableName'.");
  139. }
  140. }
  141. /**
  142. * Builds a SQL statement for enabling or disabling integrity check.
  143. * @param boolean $check whether to turn on or off the integrity check.
  144. * @param string $schema the schema of the tables. Meaningless for MySQL.
  145. * @param string $table the table name. Meaningless for MySQL.
  146. * @return string the SQL statement for checking integrity
  147. */
  148. public function checkIntegrity($check = true, $schema = '', $table = '')
  149. {
  150. return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
  151. }
  152. /**
  153. * @inheritdoc
  154. */
  155. public function buildLimit($limit, $offset)
  156. {
  157. $sql = '';
  158. if ($this->hasLimit($limit)) {
  159. $sql = 'LIMIT ' . $limit;
  160. if ($this->hasOffset($offset)) {
  161. $sql .= ' OFFSET ' . $offset;
  162. }
  163. } elseif ($this->hasOffset($offset)) {
  164. // limit is not optional in MySQL
  165. // http://stackoverflow.com/a/271650/1106908
  166. // http://dev.mysql.com/doc/refman/5.0/en/select.html#idm47619502796240
  167. $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
  168. }
  169. return $sql;
  170. }
  171. /**
  172. * @inheritdoc
  173. */
  174. public function insert($table, $columns, &$params)
  175. {
  176. $schema = $this->db->getSchema();
  177. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  178. $columnSchemas = $tableSchema->columns;
  179. } else {
  180. $columnSchemas = [];
  181. }
  182. $names = [];
  183. $placeholders = [];
  184. foreach ($columns as $name => $value) {
  185. $names[] = $schema->quoteColumnName($name);
  186. if ($value instanceof Expression) {
  187. $placeholders[] = $value->expression;
  188. foreach ($value->params as $n => $v) {
  189. $params[$n] = $v;
  190. }
  191. } else {
  192. $phName = self::PARAM_PREFIX . count($params);
  193. $placeholders[] = $phName;
  194. $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
  195. }
  196. }
  197. if (empty($names) && $tableSchema !== null) {
  198. $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : reset($tableSchema->columns)->name;
  199. foreach ($columns as $name) {
  200. $names[] = $schema->quoteColumnName($name);
  201. $placeholders[] = 'DEFAULT';
  202. }
  203. }
  204. return 'INSERT INTO ' . $schema->quoteTableName($table)
  205. . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
  206. . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : ' DEFAULT VALUES');
  207. }
  208. /**
  209. * @inheritdoc
  210. * @since 2.0.8
  211. */
  212. public function addCommentOnColumn($table, $column, $comment)
  213. {
  214. $definition = $this->getColumnDefinition($table, $column);
  215. $definition = trim(preg_replace("/COMMENT '(.*?)'/i", '', $definition));
  216. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  217. . ' CHANGE ' . $this->db->quoteColumnName($column)
  218. . ' ' . $this->db->quoteColumnName($column)
  219. . (empty($definition) ? '' : ' ' . $definition)
  220. . ' COMMENT ' . $this->db->quoteValue($comment);
  221. }
  222. /**
  223. * @inheritdoc
  224. * @since 2.0.8
  225. */
  226. public function addCommentOnTable($table, $comment)
  227. {
  228. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
  229. }
  230. /**
  231. * @inheritdoc
  232. * @since 2.0.8
  233. */
  234. public function dropCommentFromColumn($table, $column)
  235. {
  236. return $this->addCommentOnColumn($table, $column, '');
  237. }
  238. /**
  239. * @inheritdoc
  240. * @since 2.0.8
  241. */
  242. public function dropCommentFromTable($table)
  243. {
  244. return $this->addCommentOnTable($table, '');
  245. }
  246. /**
  247. * Gets column definition.
  248. *
  249. * @param string $table table name
  250. * @param string $column column name
  251. * @return null|string the column definition
  252. * @throws Exception in case when table does not contain column
  253. */
  254. private function getColumnDefinition($table, $column)
  255. {
  256. $quotedTable = $this->db->quoteTableName($table);
  257. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  258. if ($row === false) {
  259. throw new Exception("Unable to find column '$column' in table '$table'.");
  260. }
  261. if (isset($row['Create Table'])) {
  262. $sql = $row['Create Table'];
  263. } else {
  264. $row = array_values($row);
  265. $sql = $row[1];
  266. }
  267. if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
  268. foreach ($matches[1] as $i => $c) {
  269. if ($c === $column) {
  270. return $matches[2][$i];
  271. }
  272. }
  273. }
  274. return null;
  275. }
  276. }