QueryBuilder.php 15 KB

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