Schema.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. 'varbinary' => self::TYPE_BINARY,
  51. ];
  52. /**
  53. * Quotes a table name for use in a query.
  54. * A simple table name has no schema prefix.
  55. * @param string $name table name
  56. * @return string the properly quoted table name
  57. */
  58. public function quoteSimpleTableName($name)
  59. {
  60. return strpos($name, '`') !== false ? $name : "`$name`";
  61. }
  62. /**
  63. * Quotes a column name for use in a query.
  64. * A simple column name has no prefix.
  65. * @param string $name column name
  66. * @return string the properly quoted column name
  67. */
  68. public function quoteSimpleColumnName($name)
  69. {
  70. return strpos($name, '`') !== false || $name === '*' ? $name : "`$name`";
  71. }
  72. /**
  73. * Creates a query builder for the MySQL database.
  74. * @return QueryBuilder query builder instance
  75. */
  76. public function createQueryBuilder()
  77. {
  78. return new QueryBuilder($this->db);
  79. }
  80. /**
  81. * Loads the metadata for the specified table.
  82. * @param string $name table name
  83. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  84. */
  85. protected function loadTableSchema($name)
  86. {
  87. $table = new TableSchema;
  88. $this->resolveTableNames($table, $name);
  89. if ($this->findColumns($table)) {
  90. $this->findConstraints($table);
  91. return $table;
  92. } else {
  93. return null;
  94. }
  95. }
  96. /**
  97. * Resolves the table name and schema name (if any).
  98. * @param TableSchema $table the table metadata object
  99. * @param string $name the table name
  100. */
  101. protected function resolveTableNames($table, $name)
  102. {
  103. $parts = explode('.', str_replace('`', '', $name));
  104. if (isset($parts[1])) {
  105. $table->schemaName = $parts[0];
  106. $table->name = $parts[1];
  107. $table->fullName = $table->schemaName . '.' . $table->name;
  108. } else {
  109. $table->fullName = $table->name = $parts[0];
  110. }
  111. }
  112. /**
  113. * Loads the column information into a [[ColumnSchema]] object.
  114. * @param array $info column information
  115. * @return ColumnSchema the column schema object
  116. */
  117. protected function loadColumnSchema($info)
  118. {
  119. $column = $this->createColumnSchema();
  120. $column->name = $info['field'];
  121. $column->allowNull = $info['null'] === 'YES';
  122. $column->isPrimaryKey = strpos($info['key'], 'PRI') !== false;
  123. $column->autoIncrement = stripos($info['extra'], 'auto_increment') !== false;
  124. $column->comment = $info['comment'];
  125. $column->dbType = $info['type'];
  126. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  127. $column->type = self::TYPE_STRING;
  128. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  129. $type = strtolower($matches[1]);
  130. if (isset($this->typeMap[$type])) {
  131. $column->type = $this->typeMap[$type];
  132. }
  133. if (!empty($matches[2])) {
  134. if ($type === 'enum') {
  135. preg_match_all("/'[^']*'/", $matches[2], $values);
  136. foreach ($values[0] as $i => $value) {
  137. $values[$i] = trim($value, "'");
  138. }
  139. $column->enumValues = $values;
  140. } else {
  141. $values = explode(',', $matches[2]);
  142. $column->size = $column->precision = (int) $values[0];
  143. if (isset($values[1])) {
  144. $column->scale = (int) $values[1];
  145. }
  146. if ($column->size === 1 && $type === 'bit') {
  147. $column->type = 'boolean';
  148. } elseif ($type === 'bit') {
  149. if ($column->size > 32) {
  150. $column->type = 'bigint';
  151. } elseif ($column->size === 32) {
  152. $column->type = 'integer';
  153. }
  154. }
  155. }
  156. }
  157. }
  158. $column->phpType = $this->getColumnPhpType($column);
  159. if (!$column->isPrimaryKey) {
  160. if ($column->type === 'timestamp' && $info['default'] === 'CURRENT_TIMESTAMP') {
  161. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  162. } elseif (isset($type) && $type === 'bit') {
  163. $column->defaultValue = bindec(trim($info['default'], 'b\''));
  164. } else {
  165. $column->defaultValue = $column->phpTypecast($info['default']);
  166. }
  167. }
  168. return $column;
  169. }
  170. /**
  171. * Collects the metadata of table columns.
  172. * @param TableSchema $table the table metadata
  173. * @return bool whether the table exists in the database
  174. * @throws \Exception if DB query fails
  175. */
  176. protected function findColumns($table)
  177. {
  178. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
  179. try {
  180. $columns = $this->db->createCommand($sql)->queryAll();
  181. } catch (\Exception $e) {
  182. $previous = $e->getPrevious();
  183. if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
  184. // table does not exist
  185. // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
  186. return false;
  187. }
  188. throw $e;
  189. }
  190. foreach ($columns as $info) {
  191. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
  192. $info = array_change_key_case($info, CASE_LOWER);
  193. }
  194. $column = $this->loadColumnSchema($info);
  195. $table->columns[$column->name] = $column;
  196. if ($column->isPrimaryKey) {
  197. $table->primaryKey[] = $column->name;
  198. if ($column->autoIncrement) {
  199. $table->sequenceName = '';
  200. }
  201. }
  202. }
  203. return true;
  204. }
  205. /**
  206. * Gets the CREATE TABLE sql string.
  207. * @param TableSchema $table the table metadata
  208. * @return string $sql the result of 'SHOW CREATE TABLE'
  209. */
  210. protected function getCreateTableSql($table)
  211. {
  212. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
  213. if (isset($row['Create Table'])) {
  214. $sql = $row['Create Table'];
  215. } else {
  216. $row = array_values($row);
  217. $sql = $row[1];
  218. }
  219. return $sql;
  220. }
  221. /**
  222. * Collects the foreign key column details for the given table.
  223. * @param TableSchema $table the table metadata
  224. * @throws \Exception
  225. */
  226. protected function findConstraints($table)
  227. {
  228. $sql = <<<SQL
  229. SELECT
  230. kcu.constraint_name,
  231. kcu.column_name,
  232. kcu.referenced_table_name,
  233. kcu.referenced_column_name
  234. FROM information_schema.referential_constraints AS rc
  235. JOIN information_schema.key_column_usage AS kcu ON
  236. (
  237. kcu.constraint_catalog = rc.constraint_catalog OR
  238. (kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
  239. ) AND
  240. kcu.constraint_schema = rc.constraint_schema AND
  241. kcu.constraint_name = rc.constraint_name
  242. WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
  243. AND rc.table_name = :tableName AND kcu.table_name = :tableName1
  244. SQL;
  245. try {
  246. $rows = $this->db->createCommand($sql, [':tableName' => $table->name, ':tableName1' => $table->name])->queryAll();
  247. $constraints = [];
  248. foreach ($rows as $row) {
  249. $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
  250. $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
  251. }
  252. $table->foreignKeys = [];
  253. foreach ($constraints as $name => $constraint) {
  254. $table->foreignKeys[$name] = array_merge(
  255. [$constraint['referenced_table_name']],
  256. $constraint['columns']
  257. );
  258. }
  259. } catch (\Exception $e) {
  260. $previous = $e->getPrevious();
  261. if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
  262. throw $e;
  263. }
  264. // table does not exist, try to determine the foreign keys using the table creation sql
  265. $sql = $this->getCreateTableSql($table);
  266. $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  267. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  268. foreach ($matches as $match) {
  269. $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
  270. $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
  271. $constraint = [str_replace('`', '', $match[2])];
  272. foreach ($fks as $k => $name) {
  273. $constraint[$name] = $pks[$k];
  274. }
  275. $table->foreignKeys[md5(serialize($constraint))] = $constraint;
  276. }
  277. $table->foreignKeys = array_values($table->foreignKeys);
  278. }
  279. }
  280. }
  281. /**
  282. * Returns all unique indexes for the given table.
  283. * Each array element is of the following structure:
  284. *
  285. * ```php
  286. * [
  287. * 'IndexName1' => ['col1' [, ...]],
  288. * 'IndexName2' => ['col2' [, ...]],
  289. * ]
  290. * ```
  291. *
  292. * @param TableSchema $table the table metadata
  293. * @return array all unique indexes for the given table.
  294. */
  295. public function findUniqueIndexes($table)
  296. {
  297. $sql = $this->getCreateTableSql($table);
  298. $uniqueIndexes = [];
  299. $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
  300. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  301. foreach ($matches as $match) {
  302. $indexName = str_replace('`', '', $match[1]);
  303. $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
  304. $uniqueIndexes[$indexName] = $indexColumns;
  305. }
  306. }
  307. return $uniqueIndexes;
  308. }
  309. /**
  310. * Returns all table names in the database.
  311. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  312. * @return array all table names in the database. The names have NO schema name prefix.
  313. */
  314. protected function findTableNames($schema = '')
  315. {
  316. $sql = 'SHOW TABLES';
  317. if ($schema !== '') {
  318. $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
  319. }
  320. return $this->db->createCommand($sql)->queryColumn();
  321. }
  322. /**
  323. * @inheritdoc
  324. */
  325. public function createColumnSchemaBuilder($type, $length = null)
  326. {
  327. return new ColumnSchemaBuilder($type, $length, $this->db);
  328. }
  329. }