You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
10KB

  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\db\Expression;
  9. use yii\db\TableSchema;
  10. use yii\db\ColumnSchema;
  11. /**
  12. * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class Schema extends \yii\db\Schema
  18. {
  19. /**
  20. * @var array mapping from physical column types (keys) to abstract column types (values)
  21. */
  22. public $typeMap = [
  23. 'tinyint' => self::TYPE_SMALLINT,
  24. 'bit' => self::TYPE_INTEGER,
  25. 'smallint' => self::TYPE_SMALLINT,
  26. 'mediumint' => self::TYPE_INTEGER,
  27. 'int' => self::TYPE_INTEGER,
  28. 'integer' => self::TYPE_INTEGER,
  29. 'bigint' => self::TYPE_BIGINT,
  30. 'float' => self::TYPE_FLOAT,
  31. 'double' => self::TYPE_DOUBLE,
  32. 'real' => self::TYPE_FLOAT,
  33. 'decimal' => self::TYPE_DECIMAL,
  34. 'numeric' => self::TYPE_DECIMAL,
  35. 'tinytext' => self::TYPE_TEXT,
  36. 'mediumtext' => self::TYPE_TEXT,
  37. 'longtext' => self::TYPE_TEXT,
  38. 'longblob' => self::TYPE_BINARY,
  39. 'blob' => self::TYPE_BINARY,
  40. 'text' => self::TYPE_TEXT,
  41. 'varchar' => self::TYPE_STRING,
  42. 'string' => self::TYPE_STRING,
  43. 'char' => self::TYPE_STRING,
  44. 'datetime' => self::TYPE_DATETIME,
  45. 'year' => self::TYPE_DATE,
  46. 'date' => self::TYPE_DATE,
  47. 'time' => self::TYPE_TIME,
  48. 'timestamp' => self::TYPE_TIMESTAMP,
  49. 'enum' => self::TYPE_STRING,
  50. ];
  51. /**
  52. * Quotes a table name for use in a query.
  53. * A simple table name has no schema prefix.
  54. * @param string $name table name
  55. * @return string the properly quoted table name
  56. */
  57. public function quoteSimpleTableName($name)
  58. {
  59. return strpos($name, "`") !== false ? $name : "`" . $name . "`";
  60. }
  61. /**
  62. * Quotes a column name for use in a query.
  63. * A simple column name has no prefix.
  64. * @param string $name column name
  65. * @return string the properly quoted column name
  66. */
  67. public function quoteSimpleColumnName($name)
  68. {
  69. return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
  70. }
  71. /**
  72. * Creates a query builder for the MySQL database.
  73. * @return QueryBuilder query builder instance
  74. */
  75. public function createQueryBuilder()
  76. {
  77. return new QueryBuilder($this->db);
  78. }
  79. /**
  80. * Loads the metadata for the specified table.
  81. * @param string $name table name
  82. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  83. */
  84. protected function loadTableSchema($name)
  85. {
  86. $table = new TableSchema;
  87. $this->resolveTableNames($table, $name);
  88. if ($this->findColumns($table)) {
  89. $this->findConstraints($table);
  90. return $table;
  91. } else {
  92. return null;
  93. }
  94. }
  95. /**
  96. * Resolves the table name and schema name (if any).
  97. * @param TableSchema $table the table metadata object
  98. * @param string $name the table name
  99. */
  100. protected function resolveTableNames($table, $name)
  101. {
  102. $parts = explode('.', str_replace('`', '', $name));
  103. if (isset($parts[1])) {
  104. $table->schemaName = $parts[0];
  105. $table->name = $parts[1];
  106. $table->fullName = $table->schemaName . '.' . $table->name;
  107. } else {
  108. $table->fullName = $table->name = $parts[0];
  109. }
  110. }
  111. /**
  112. * Loads the column information into a [[ColumnSchema]] object.
  113. * @param array $info column information
  114. * @return ColumnSchema the column schema object
  115. */
  116. protected function loadColumnSchema($info)
  117. {
  118. $column = $this->createColumnSchema();
  119. $column->name = $info['Field'];
  120. $column->allowNull = $info['Null'] === 'YES';
  121. $column->isPrimaryKey = strpos($info['Key'], 'PRI') !== false;
  122. $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
  123. $column->comment = $info['Comment'];
  124. $column->dbType = $info['Type'];
  125. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  126. $column->type = self::TYPE_STRING;
  127. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  128. $type = strtolower($matches[1]);
  129. if (isset($this->typeMap[$type])) {
  130. $column->type = $this->typeMap[$type];
  131. }
  132. if (!empty($matches[2])) {
  133. if ($type === 'enum') {
  134. $values = explode(',', $matches[2]);
  135. foreach ($values as $i => $value) {
  136. $values[$i] = trim($value, "'");
  137. }
  138. $column->enumValues = $values;
  139. } else {
  140. $values = explode(',', $matches[2]);
  141. $column->size = $column->precision = (int) $values[0];
  142. if (isset($values[1])) {
  143. $column->scale = (int) $values[1];
  144. }
  145. if ($column->size === 1 && $type === 'bit') {
  146. $column->type = 'boolean';
  147. } elseif ($type === 'bit') {
  148. if ($column->size > 32) {
  149. $column->type = 'bigint';
  150. } elseif ($column->size === 32) {
  151. $column->type = 'integer';
  152. }
  153. }
  154. }
  155. }
  156. }
  157. $column->phpType = $this->getColumnPhpType($column);
  158. if (!$column->isPrimaryKey) {
  159. if ($column->type === 'timestamp' && $info['Default'] === 'CURRENT_TIMESTAMP') {
  160. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  161. } elseif (isset($type) && $type === 'bit') {
  162. $column->defaultValue = bindec(trim($info['Default'],'b\''));
  163. } else {
  164. $column->defaultValue = $column->phpTypecast($info['Default']);
  165. }
  166. }
  167. return $column;
  168. }
  169. /**
  170. * Collects the metadata of table columns.
  171. * @param TableSchema $table the table metadata
  172. * @return boolean whether the table exists in the database
  173. * @throws \Exception if DB query fails
  174. */
  175. protected function findColumns($table)
  176. {
  177. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
  178. try {
  179. $columns = $this->db->createCommand($sql)->queryAll();
  180. } catch (\Exception $e) {
  181. $previous = $e->getPrevious();
  182. if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
  183. // table does not exist
  184. // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
  185. return false;
  186. }
  187. throw $e;
  188. }
  189. foreach ($columns as $info) {
  190. $column = $this->loadColumnSchema($info);
  191. $table->columns[$column->name] = $column;
  192. if ($column->isPrimaryKey) {
  193. $table->primaryKey[] = $column->name;
  194. if ($column->autoIncrement) {
  195. $table->sequenceName = '';
  196. }
  197. }
  198. }
  199. return true;
  200. }
  201. /**
  202. * Gets the CREATE TABLE sql string.
  203. * @param TableSchema $table the table metadata
  204. * @return string $sql the result of 'SHOW CREATE TABLE'
  205. */
  206. protected function getCreateTableSql($table)
  207. {
  208. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
  209. if (isset($row['Create Table'])) {
  210. $sql = $row['Create Table'];
  211. } else {
  212. $row = array_values($row);
  213. $sql = $row[1];
  214. }
  215. return $sql;
  216. }
  217. /**
  218. * Collects the foreign key column details for the given table.
  219. * @param TableSchema $table the table metadata
  220. */
  221. protected function findConstraints($table)
  222. {
  223. $sql = $this->getCreateTableSql($table);
  224. $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  225. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  226. foreach ($matches as $match) {
  227. $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
  228. $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
  229. $constraint = [str_replace('`', '', $match[2])];
  230. foreach ($fks as $k => $name) {
  231. $constraint[$name] = $pks[$k];
  232. }
  233. $table->foreignKeys[] = $constraint;
  234. }
  235. }
  236. }
  237. /**
  238. * Returns all unique indexes for the given table.
  239. * Each array element is of the following structure:
  240. *
  241. * ~~~
  242. * [
  243. * 'IndexName1' => ['col1' [, ...]],
  244. * 'IndexName2' => ['col2' [, ...]],
  245. * ]
  246. * ~~~
  247. *
  248. * @param TableSchema $table the table metadata
  249. * @return array all unique indexes for the given table.
  250. */
  251. public function findUniqueIndexes($table)
  252. {
  253. $sql = $this->getCreateTableSql($table);
  254. $uniqueIndexes = [];
  255. $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
  256. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  257. foreach ($matches as $match) {
  258. $indexName = str_replace('`', '', $match[1]);
  259. $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
  260. $uniqueIndexes[$indexName] = $indexColumns;
  261. }
  262. }
  263. return $uniqueIndexes;
  264. }
  265. /**
  266. * Returns all table names in the database.
  267. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  268. * @return array all table names in the database. The names have NO schema name prefix.
  269. */
  270. protected function findTableNames($schema = '')
  271. {
  272. $sql = 'SHOW TABLES';
  273. if ($schema !== '') {
  274. $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
  275. }
  276. return $this->db->createCommand($sql)->queryColumn();
  277. }
  278. }