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.

Schema.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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_CHAR,
  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. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
  191. $info = array_change_key_case($info, CASE_LOWER);
  192. }
  193. $column = $this->loadColumnSchema($info);
  194. $table->columns[$column->name] = $column;
  195. if ($column->isPrimaryKey) {
  196. $table->primaryKey[] = $column->name;
  197. if ($column->autoIncrement) {
  198. $table->sequenceName = '';
  199. }
  200. }
  201. }
  202. return true;
  203. }
  204. /**
  205. * Gets the CREATE TABLE sql string.
  206. * @param TableSchema $table the table metadata
  207. * @return string $sql the result of 'SHOW CREATE TABLE'
  208. */
  209. protected function getCreateTableSql($table)
  210. {
  211. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
  212. if (isset($row['Create Table'])) {
  213. $sql = $row['Create Table'];
  214. } else {
  215. $row = array_values($row);
  216. $sql = $row[1];
  217. }
  218. return $sql;
  219. }
  220. /**
  221. * Collects the foreign key column details for the given table.
  222. * @param TableSchema $table the table metadata
  223. */
  224. protected function findConstraints($table)
  225. {
  226. $sql = <<<SQL
  227. SELECT
  228. kcu.constraint_name,
  229. kcu.column_name,
  230. kcu.referenced_table_name,
  231. kcu.referenced_column_name
  232. FROM information_schema.referential_constraints AS rc
  233. JOIN information_schema.key_column_usage AS kcu ON
  234. (
  235. kcu.constraint_catalog = rc.constraint_catalog OR
  236. (kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
  237. ) AND
  238. kcu.constraint_schema = rc.constraint_schema AND
  239. kcu.constraint_name = rc.constraint_name
  240. WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
  241. AND rc.table_name = :tableName AND kcu.table_name = :tableName1
  242. SQL;
  243. try {
  244. $rows = $this->db->createCommand($sql, [':tableName' => $table->name, ':tableName1' => $table->name])->queryAll();
  245. $constraints = [];
  246. foreach ($rows as $row) {
  247. $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
  248. $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
  249. }
  250. $table->foreignKeys = [];
  251. foreach ($constraints as $constraint) {
  252. $table->foreignKeys[] = array_merge(
  253. [$constraint['referenced_table_name']],
  254. $constraint['columns']
  255. );
  256. }
  257. } catch (\Exception $e) {
  258. $previous = $e->getPrevious();
  259. if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
  260. throw $e;
  261. }
  262. // table does not exist, try to determine the foreign keys using the table creation sql
  263. $sql = $this->getCreateTableSql($table);
  264. $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  265. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  266. foreach ($matches as $match) {
  267. $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
  268. $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
  269. $constraint = [str_replace('`', '', $match[2])];
  270. foreach ($fks as $k => $name) {
  271. $constraint[$name] = $pks[$k];
  272. }
  273. $table->foreignKeys[md5(serialize($constraint))] = $constraint;
  274. }
  275. $table->foreignKeys = array_values($table->foreignKeys);
  276. }
  277. }
  278. }
  279. /**
  280. * Returns all unique indexes for the given table.
  281. * Each array element is of the following structure:
  282. *
  283. * ```php
  284. * [
  285. * 'IndexName1' => ['col1' [, ...]],
  286. * 'IndexName2' => ['col2' [, ...]],
  287. * ]
  288. * ```
  289. *
  290. * @param TableSchema $table the table metadata
  291. * @return array all unique indexes for the given table.
  292. */
  293. public function findUniqueIndexes($table)
  294. {
  295. $sql = $this->getCreateTableSql($table);
  296. $uniqueIndexes = [];
  297. $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
  298. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  299. foreach ($matches as $match) {
  300. $indexName = str_replace('`', '', $match[1]);
  301. $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
  302. $uniqueIndexes[$indexName] = $indexColumns;
  303. }
  304. }
  305. return $uniqueIndexes;
  306. }
  307. /**
  308. * Returns all table names in the database.
  309. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  310. * @return array all table names in the database. The names have NO schema name prefix.
  311. */
  312. protected function findTableNames($schema = '')
  313. {
  314. $sql = 'SHOW TABLES';
  315. if ($schema !== '') {
  316. $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
  317. }
  318. return $this->db->createCommand($sql)->queryColumn();
  319. }
  320. /**
  321. * @inheritdoc
  322. */
  323. public function createColumnSchemaBuilder($type, $length = null)
  324. {
  325. return new ColumnSchemaBuilder($type, $length, $this->db);
  326. }
  327. }