QueryBuilder.php 5.9 KB

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