QueryBuilder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  142. * The sequence will be reset such that the primary key of the next new row inserted
  143. * will have the specified value or 1.
  144. * @param string $tableName the name of the table whose primary key sequence will be reset
  145. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  146. * the next new row's primary key will have a value 1.
  147. * @return string the SQL statement for resetting sequence
  148. * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
  149. */
  150. public function resetSequence($tableName, $value = null)
  151. {
  152. $table = $this->db->getTableSchema($tableName);
  153. if ($table !== null && $table->sequenceName !== null) {
  154. $tableName = $this->db->quoteTableName($tableName);
  155. if ($value === null) {
  156. $key = reset($table->primaryKey);
  157. $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
  158. } else {
  159. $value = (int) $value;
  160. }
  161. return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
  162. } elseif ($table === null) {
  163. throw new InvalidArgumentException("Table not found: $tableName");
  164. }
  165. throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
  166. }
  167. /**
  168. * Builds a SQL statement for enabling or disabling integrity check.
  169. * @param bool $check whether to turn on or off the integrity check.
  170. * @param string $schema the schema of the tables. Meaningless for MySQL.
  171. * @param string $table the table name. Meaningless for MySQL.
  172. * @return string the SQL statement for checking integrity
  173. */
  174. public function checkIntegrity($check = true, $schema = '', $table = '')
  175. {
  176. return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function buildLimit($limit, $offset)
  182. {
  183. $sql = '';
  184. if ($this->hasLimit($limit)) {
  185. $sql = 'LIMIT ' . $limit;
  186. if ($this->hasOffset($offset)) {
  187. $sql .= ' OFFSET ' . $offset;
  188. }
  189. } elseif ($this->hasOffset($offset)) {
  190. // limit is not optional in MySQL
  191. // https://stackoverflow.com/questions/255517/mysql-offset-infinite-rows/271650#271650
  192. // https://dev.mysql.com/doc/refman/5.7/en/select.html#idm46193796386608
  193. $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
  194. }
  195. return $sql;
  196. }
  197. /**
  198. * {@inheritdoc}
  199. */
  200. protected function hasLimit($limit)
  201. {
  202. // In MySQL limit argument must be nonnegative integer constant
  203. return ctype_digit((string) $limit);
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. protected function hasOffset($offset)
  209. {
  210. // In MySQL offset argument must be nonnegative integer constant
  211. $offset = (string) $offset;
  212. return ctype_digit($offset) && $offset !== '0';
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. protected function prepareInsertValues($table, $columns, $params = [])
  218. {
  219. list($names, $placeholders, $values, $params) = parent::prepareInsertValues($table, $columns, $params);
  220. if (!$columns instanceof Query && empty($names)) {
  221. $tableSchema = $this->db->getSchema()->getTableSchema($table);
  222. if ($tableSchema !== null) {
  223. if (!empty($tableSchema->primaryKey)) {
  224. $columns = $tableSchema->primaryKey;
  225. $defaultValue = 'NULL';
  226. } else {
  227. $columns = [reset($tableSchema->columns)->name];
  228. $defaultValue = 'DEFAULT';
  229. }
  230. foreach ($columns as $name) {
  231. $names[] = $this->db->quoteColumnName($name);
  232. $placeholders[] = $defaultValue;
  233. }
  234. }
  235. }
  236. return [$names, $placeholders, $values, $params];
  237. }
  238. /**
  239. * {@inheritdoc}
  240. * @see https://downloads.mysql.com/docs/refman-5.1-en.pdf
  241. */
  242. public function upsert($table, $insertColumns, $updateColumns, &$params)
  243. {
  244. $insertSql = $this->insert($table, $insertColumns, $params);
  245. list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
  246. if (empty($uniqueNames)) {
  247. return $insertSql;
  248. }
  249. if ($updateNames === []) {
  250. // there are no columns to update
  251. $updateColumns = false;
  252. }
  253. if ($updateColumns === true) {
  254. $updateColumns = [];
  255. foreach ($updateNames as $name) {
  256. $updateColumns[$name] = new Expression('VALUES(' . $this->db->quoteColumnName($name) . ')');
  257. }
  258. } elseif ($updateColumns === false) {
  259. $name = $this->db->quoteColumnName(reset($uniqueNames));
  260. $updateColumns = [$name => new Expression($this->db->quoteTableName($table) . '.' . $name)];
  261. }
  262. list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
  263. return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
  264. }
  265. /**
  266. * {@inheritdoc}
  267. * @since 2.0.8
  268. */
  269. public function addCommentOnColumn($table, $column, $comment)
  270. {
  271. // Strip existing comment which may include escaped quotes
  272. $definition = trim(preg_replace("/COMMENT '(?:''|[^'])*'/i", '', $this->getColumnDefinition($table, $column)));
  273. $checkRegex = '/CHECK *(\(([^()]|(?-2))*\))/';
  274. $check = preg_match($checkRegex, $definition, $checkMatches);
  275. if ($check === 1) {
  276. $definition = preg_replace($checkRegex, '', $definition);
  277. }
  278. $alterSql = '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. if ($check === 1) {
  284. $alterSql .= ' ' . $checkMatches[0];
  285. }
  286. return $alterSql;
  287. }
  288. /**
  289. * {@inheritdoc}
  290. * @since 2.0.8
  291. */
  292. public function addCommentOnTable($table, $comment)
  293. {
  294. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
  295. }
  296. /**
  297. * {@inheritdoc}
  298. * @since 2.0.8
  299. */
  300. public function dropCommentFromColumn($table, $column)
  301. {
  302. return $this->addCommentOnColumn($table, $column, '');
  303. }
  304. /**
  305. * {@inheritdoc}
  306. * @since 2.0.8
  307. */
  308. public function dropCommentFromTable($table)
  309. {
  310. return $this->addCommentOnTable($table, '');
  311. }
  312. /**
  313. * Gets column definition.
  314. *
  315. * @param string $table table name
  316. * @param string $column column name
  317. * @return string|null the column definition
  318. * @throws Exception in case when table does not contain column
  319. */
  320. private function getColumnDefinition($table, $column)
  321. {
  322. $quotedTable = $this->db->quoteTableName($table);
  323. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
  324. if ($row === false) {
  325. throw new Exception("Unable to find column '$column' in table '$table'.");
  326. }
  327. if (isset($row['Create Table'])) {
  328. $sql = $row['Create Table'];
  329. } else {
  330. $row = array_values($row);
  331. $sql = $row[1];
  332. }
  333. if (preg_match_all('/^\s*[`"](.*?)[`"]\s+(.*?),?$/m', $sql, $matches)) {
  334. foreach ($matches[1] as $i => $c) {
  335. if ($c === $column) {
  336. return $matches[2][$i];
  337. }
  338. }
  339. }
  340. return null;
  341. }
  342. /**
  343. * Checks the ability to use fractional seconds.
  344. *
  345. * @return bool
  346. * @see https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
  347. */
  348. private function supportsFractionalSeconds()
  349. {
  350. // use cache to prevent opening MySQL connection
  351. // https://github.com/yiisoft/yii2/issues/13749#issuecomment-481657224
  352. $key = [__METHOD__, $this->db->dsn];
  353. $cache = null;
  354. $schemaCache = (\Yii::$app && is_string($this->db->schemaCache)) ? \Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  355. // If the `$schemaCache` is an instance of `DbCache` we don't use it to avoid a loop
  356. if ($this->db->enableSchemaCache && $schemaCache instanceof CacheInterface && !($schemaCache instanceof DbCache)) {
  357. $cache = $schemaCache;
  358. }
  359. $version = $cache ? $cache->get($key) : null;
  360. if (!$version) {
  361. $version = $this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION);
  362. if ($cache) {
  363. $cache->set($key, $version, $this->db->schemaCacheDuration);
  364. }
  365. }
  366. return version_compare($version, '5.6.4', '>=');
  367. }
  368. /**
  369. * Returns the map for default time type.
  370. * If the version of MySQL is lower than 5.6.4, then the types will be without fractional seconds,
  371. * otherwise with fractional seconds.
  372. *
  373. * @return array
  374. */
  375. private function defaultTimeTypeMap()
  376. {
  377. $map = [
  378. Schema::TYPE_DATETIME => 'datetime',
  379. Schema::TYPE_TIMESTAMP => 'timestamp',
  380. Schema::TYPE_TIME => 'time',
  381. ];
  382. if ($this->supportsFractionalSeconds()) {
  383. $map = [
  384. Schema::TYPE_DATETIME => 'datetime(0)',
  385. Schema::TYPE_TIMESTAMP => 'timestamp(0)',
  386. Schema::TYPE_TIME => 'time(0)',
  387. ];
  388. }
  389. return $map;
  390. }
  391. }