QueryBuilder.php 15 KB

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