QueryBuilder.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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\InvalidArgumentException;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Exception;
  11. use yii\db\Expression;
  12. use yii\db\Query;
  13. /**
  14. * QueryBuilder is the query builder for MySQL databases.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. class QueryBuilder extends \yii\db\QueryBuilder
  20. {
  21. /**
  22. * @var array mapping from abstract column types (keys) to physical column types (values).
  23. */
  24. public $typeMap = [
  25. Schema::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  26. Schema::TYPE_UPK => 'int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  27. Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  28. Schema::TYPE_UBIGPK => 'bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  29. Schema::TYPE_CHAR => 'char(1)',
  30. Schema::TYPE_STRING => 'varchar(255)',
  31. Schema::TYPE_TEXT => 'text',
  32. Schema::TYPE_TINYINT => 'tinyint(3)',
  33. Schema::TYPE_SMALLINT => 'smallint(6)',
  34. Schema::TYPE_INTEGER => 'int(11)',
  35. Schema::TYPE_BIGINT => 'bigint(20)',
  36. Schema::TYPE_FLOAT => 'float',
  37. Schema::TYPE_DOUBLE => 'double',
  38. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  39. Schema::TYPE_DATETIME => 'datetime',
  40. Schema::TYPE_TIMESTAMP => 'timestamp',
  41. Schema::TYPE_TIME => 'time',
  42. Schema::TYPE_DATE => 'date',
  43. Schema::TYPE_BINARY => 'blob',
  44. Schema::TYPE_BOOLEAN => 'tinyint(1)',
  45. Schema::TYPE_MONEY => 'decimal(19,4)',
  46. Schema::TYPE_JSON => 'json'
  47. ];
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function defaultExpressionBuilders()
  52. {
  53. return array_merge(parent::defaultExpressionBuilders(), [
  54. 'yii\db\JsonExpression' => 'yii\db\mysql\JsonExpressionBuilder',
  55. ]);
  56. }
  57. /**
  58. * Builds a SQL statement for renaming a column.
  59. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  60. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  61. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  62. * @return string the SQL statement for renaming a DB column.
  63. * @throws Exception
  64. */
  65. public function renameColumn($table, $oldName, $newName)
  66. {
  67. $quotedTable = $this->db->quoteTableName($table);
  68. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  69. if ($row === false) {
  70. throw new Exception("Unable to find column '$oldName' in table '$table'.");
  71. }
  72. if (isset($row['Create Table'])) {
  73. $sql = $row['Create Table'];
  74. } else {
  75. $row = array_values($row);
  76. $sql = $row[1];
  77. }
  78. if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
  79. foreach ($matches[1] as $i => $c) {
  80. if ($c === $oldName) {
  81. return "ALTER TABLE $quotedTable CHANGE "
  82. . $this->db->quoteColumnName($oldName) . ' '
  83. . $this->db->quoteColumnName($newName) . ' '
  84. . $matches[2][$i];
  85. }
  86. }
  87. }
  88. // try to give back a SQL anyway
  89. return "ALTER TABLE $quotedTable CHANGE "
  90. . $this->db->quoteColumnName($oldName) . ' '
  91. . $this->db->quoteColumnName($newName);
  92. }
  93. /**
  94. * {@inheritdoc}
  95. * @see https://bugs.mysql.com/bug.php?id=48875
  96. */
  97. public function createIndex($name, $table, $columns, $unique = false)
  98. {
  99. return 'ALTER TABLE '
  100. . $this->db->quoteTableName($table)
  101. . ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
  102. . $this->db->quoteTableName($name)
  103. . ' (' . $this->buildColumns($columns) . ')';
  104. }
  105. /**
  106. * Builds a SQL statement for dropping a foreign key constraint.
  107. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  108. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  109. * @return string the SQL statement for dropping a foreign key constraint.
  110. */
  111. public function dropForeignKey($name, $table)
  112. {
  113. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  114. . ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
  115. }
  116. /**
  117. * Builds a SQL statement for removing a primary key constraint to an existing table.
  118. * @param string $name the name of the primary key constraint to be removed.
  119. * @param string $table the table that the primary key constraint will be removed from.
  120. * @return string the SQL statement for removing a primary key constraint from an existing table.
  121. */
  122. public function dropPrimaryKey($name, $table)
  123. {
  124. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. public function dropUnique($name, $table)
  130. {
  131. return $this->dropIndex($name, $table);
  132. }
  133. /**
  134. * {@inheritdoc}
  135. * @throws NotSupportedException this is not supported by MySQL.
  136. */
  137. public function addCheck($name, $table, $expression)
  138. {
  139. throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
  140. }
  141. /**
  142. * {@inheritdoc}
  143. * @throws NotSupportedException this is not supported by MySQL.
  144. */
  145. public function dropCheck($name, $table)
  146. {
  147. throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
  148. }
  149. /**
  150. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  151. * The sequence will be reset such that the primary key of the next new row inserted
  152. * will have the specified value or 1.
  153. * @param string $tableName the name of the table whose primary key sequence will be reset
  154. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  155. * the next new row's primary key will have a value 1.
  156. * @return string the SQL statement for resetting sequence
  157. * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
  158. */
  159. public function resetSequence($tableName, $value = null)
  160. {
  161. $table = $this->db->getTableSchema($tableName);
  162. if ($table !== null && $table->sequenceName !== null) {
  163. $tableName = $this->db->quoteTableName($tableName);
  164. if ($value === null) {
  165. $key = reset($table->primaryKey);
  166. $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
  167. } else {
  168. $value = (int) $value;
  169. }
  170. return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
  171. } elseif ($table === null) {
  172. throw new InvalidArgumentException("Table not found: $tableName");
  173. }
  174. throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
  175. }
  176. /**
  177. * Builds a SQL statement for enabling or disabling integrity check.
  178. * @param bool $check whether to turn on or off the integrity check.
  179. * @param string $schema the schema of the tables. Meaningless for MySQL.
  180. * @param string $table the table name. Meaningless for MySQL.
  181. * @return string the SQL statement for checking integrity
  182. */
  183. public function checkIntegrity($check = true, $schema = '', $table = '')
  184. {
  185. return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function buildLimit($limit, $offset)
  191. {
  192. $sql = '';
  193. if ($this->hasLimit($limit)) {
  194. $sql = 'LIMIT ' . $limit;
  195. if ($this->hasOffset($offset)) {
  196. $sql .= ' OFFSET ' . $offset;
  197. }
  198. } elseif ($this->hasOffset($offset)) {
  199. // limit is not optional in MySQL
  200. // http://stackoverflow.com/a/271650/1106908
  201. // http://dev.mysql.com/doc/refman/5.0/en/select.html#idm47619502796240
  202. $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
  203. }
  204. return $sql;
  205. }
  206. /**
  207. * {@inheritdoc}
  208. */
  209. protected function hasLimit($limit)
  210. {
  211. // In MySQL limit argument must be nonnegative integer constant
  212. return ctype_digit((string) $limit);
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. protected function hasOffset($offset)
  218. {
  219. // In MySQL offset argument must be nonnegative integer constant
  220. $offset = (string) $offset;
  221. return ctype_digit($offset) && $offset !== '0';
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. protected function prepareInsertValues($table, $columns, $params = [])
  227. {
  228. list($names, $placeholders, $values, $params) = parent::prepareInsertValues($table, $columns, $params);
  229. if (!$columns instanceof Query && empty($names)) {
  230. $tableSchema = $this->db->getSchema()->getTableSchema($table);
  231. if ($tableSchema !== null) {
  232. $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : [reset($tableSchema->columns)->name];
  233. foreach ($columns as $name) {
  234. $names[] = $this->db->quoteColumnName($name);
  235. $placeholders[] = 'DEFAULT';
  236. }
  237. }
  238. }
  239. return [$names, $placeholders, $values, $params];
  240. }
  241. /**
  242. * {@inheritdoc}
  243. * @see https://downloads.mysql.com/docs/refman-5.1-en.pdf
  244. */
  245. public function upsert($table, $insertColumns, $updateColumns, &$params)
  246. {
  247. $insertSql = $this->insert($table, $insertColumns, $params);
  248. list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
  249. if (empty($uniqueNames)) {
  250. return $insertSql;
  251. }
  252. if ($updateColumns === true) {
  253. $updateColumns = [];
  254. foreach ($updateNames as $name) {
  255. $updateColumns[$name] = new Expression('VALUES(' . $this->db->quoteColumnName($name) . ')');
  256. }
  257. } elseif ($updateColumns === false) {
  258. $name = $this->db->quoteColumnName(reset($uniqueNames));
  259. $updateColumns = [$name => new Expression($this->db->quoteTableName($table) . '.' . $name)];
  260. }
  261. list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
  262. return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
  263. }
  264. /**
  265. * {@inheritdoc}
  266. * @since 2.0.8
  267. */
  268. public function addCommentOnColumn($table, $column, $comment)
  269. {
  270. // Strip existing comment which may include escaped quotes
  271. $definition = trim(preg_replace("/COMMENT '(?:''|[^'])*'/i", '',
  272. $this->getColumnDefinition($table, $column)));
  273. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  274. . ' CHANGE ' . $this->db->quoteColumnName($column)
  275. . ' ' . $this->db->quoteColumnName($column)
  276. . (empty($definition) ? '' : ' ' . $definition)
  277. . ' COMMENT ' . $this->db->quoteValue($comment);
  278. }
  279. /**
  280. * {@inheritdoc}
  281. * @since 2.0.8
  282. */
  283. public function addCommentOnTable($table, $comment)
  284. {
  285. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
  286. }
  287. /**
  288. * {@inheritdoc}
  289. * @since 2.0.8
  290. */
  291. public function dropCommentFromColumn($table, $column)
  292. {
  293. return $this->addCommentOnColumn($table, $column, '');
  294. }
  295. /**
  296. * {@inheritdoc}
  297. * @since 2.0.8
  298. */
  299. public function dropCommentFromTable($table)
  300. {
  301. return $this->addCommentOnTable($table, '');
  302. }
  303. /**
  304. * Gets column definition.
  305. *
  306. * @param string $table table name
  307. * @param string $column column name
  308. * @return null|string the column definition
  309. * @throws Exception in case when table does not contain column
  310. */
  311. private function getColumnDefinition($table, $column)
  312. {
  313. $quotedTable = $this->db->quoteTableName($table);
  314. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  315. if ($row === false) {
  316. throw new Exception("Unable to find column '$column' in table '$table'.");
  317. }
  318. if (isset($row['Create Table'])) {
  319. $sql = $row['Create Table'];
  320. } else {
  321. $row = array_values($row);
  322. $sql = $row[1];
  323. }
  324. if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
  325. foreach ($matches[1] as $i => $c) {
  326. if ($c === $column) {
  327. return $matches[2][$i];
  328. }
  329. }
  330. }
  331. return null;
  332. }
  333. }