QueryBuilder.php 14 KB

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