Schema.php 8.1 KB

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