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.

168 line
6.7KB

  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\db\Exception;
  9. use yii\base\InvalidParamException;
  10. /**
  11. * QueryBuilder is the query builder for MySQL databases.
  12. *
  13. * @author Qiang Xue <qiang.xue@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(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  23. Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  24. Schema::TYPE_STRING => 'varchar(255)',
  25. Schema::TYPE_TEXT => 'text',
  26. Schema::TYPE_SMALLINT => 'smallint(6)',
  27. Schema::TYPE_INTEGER => 'int(11)',
  28. Schema::TYPE_BIGINT => 'bigint(20)',
  29. Schema::TYPE_FLOAT => 'float',
  30. Schema::TYPE_DOUBLE => 'double',
  31. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  32. Schema::TYPE_DATETIME => 'datetime',
  33. Schema::TYPE_TIMESTAMP => 'timestamp',
  34. Schema::TYPE_TIME => 'time',
  35. Schema::TYPE_DATE => 'date',
  36. Schema::TYPE_BINARY => 'blob',
  37. Schema::TYPE_BOOLEAN => 'tinyint(1)',
  38. Schema::TYPE_MONEY => 'decimal(19,4)',
  39. ];
  40. /**
  41. * Builds a SQL statement for renaming a column.
  42. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  43. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  44. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  45. * @return string the SQL statement for renaming a DB column.
  46. * @throws Exception
  47. */
  48. public function renameColumn($table, $oldName, $newName)
  49. {
  50. $quotedTable = $this->db->quoteTableName($table);
  51. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  52. if ($row === false) {
  53. throw new Exception("Unable to find column '$oldName' in table '$table'.");
  54. }
  55. if (isset($row['Create Table'])) {
  56. $sql = $row['Create Table'];
  57. } else {
  58. $row = array_values($row);
  59. $sql = $row[1];
  60. }
  61. if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
  62. foreach ($matches[1] as $i => $c) {
  63. if ($c === $oldName) {
  64. return "ALTER TABLE $quotedTable CHANGE "
  65. . $this->db->quoteColumnName($oldName) . ' '
  66. . $this->db->quoteColumnName($newName) . ' '
  67. . $matches[2][$i];
  68. }
  69. }
  70. }
  71. // try to give back a SQL anyway
  72. return "ALTER TABLE $quotedTable CHANGE "
  73. . $this->db->quoteColumnName($oldName) . ' '
  74. . $this->db->quoteColumnName($newName);
  75. }
  76. /**
  77. * Builds a SQL statement for dropping a foreign key constraint.
  78. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  79. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  80. * @return string the SQL statement for dropping a foreign key constraint.
  81. */
  82. public function dropForeignKey($name, $table)
  83. {
  84. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  85. . ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
  86. }
  87. /**
  88. * Builds a SQL statement for removing a primary key constraint to an existing table.
  89. * @param string $name the name of the primary key constraint to be removed.
  90. * @param string $table the table that the primary key constraint will be removed from.
  91. * @return string the SQL statement for removing a primary key constraint from an existing table.
  92. */
  93. public function dropPrimaryKey($name, $table)
  94. {
  95. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
  96. }
  97. /**
  98. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  99. * The sequence will be reset such that the primary key of the next new row inserted
  100. * will have the specified value or 1.
  101. * @param string $tableName the name of the table whose primary key sequence will be reset
  102. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  103. * the next new row's primary key will have a value 1.
  104. * @return string the SQL statement for resetting sequence
  105. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  106. */
  107. public function resetSequence($tableName, $value = null)
  108. {
  109. $table = $this->db->getTableSchema($tableName);
  110. if ($table !== null && $table->sequenceName !== null) {
  111. $tableName = $this->db->quoteTableName($tableName);
  112. if ($value === null) {
  113. $key = reset($table->primaryKey);
  114. $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
  115. } else {
  116. $value = (int) $value;
  117. }
  118. return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
  119. } elseif ($table === null) {
  120. throw new InvalidParamException("Table not found: $tableName");
  121. } else {
  122. throw new InvalidParamException("There is no sequence associated with table '$tableName'.");
  123. }
  124. }
  125. /**
  126. * Builds a SQL statement for enabling or disabling integrity check.
  127. * @param boolean $check whether to turn on or off the integrity check.
  128. * @param string $table the table name. Meaningless for MySQL.
  129. * @param string $schema the schema of the tables. Meaningless for MySQL.
  130. * @return string the SQL statement for checking integrity
  131. */
  132. public function checkIntegrity($check = true, $schema = '', $table = '')
  133. {
  134. return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
  135. }
  136. /**
  137. * @inheritdoc
  138. */
  139. public function buildLimit($limit, $offset)
  140. {
  141. $sql = '';
  142. if ($this->hasLimit($limit)) {
  143. $sql = 'LIMIT ' . $limit;
  144. if ($this->hasOffset($offset)) {
  145. $sql .= ' OFFSET ' . $offset;
  146. }
  147. } elseif ($this->hasOffset($offset)) {
  148. // limit is not optional in MySQL
  149. // http://stackoverflow.com/a/271650/1106908
  150. // http://dev.mysql.com/doc/refman/5.0/en/select.html#idm47619502796240
  151. $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
  152. }
  153. return $sql;
  154. }
  155. }