Schema.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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\base\InvalidConfigException;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Constraint;
  11. use yii\db\ConstraintFinderInterface;
  12. use yii\db\ConstraintFinderTrait;
  13. use yii\db\Exception;
  14. use yii\db\Expression;
  15. use yii\db\ForeignKeyConstraint;
  16. use yii\db\IndexConstraint;
  17. use yii\db\TableSchema;
  18. use yii\helpers\ArrayHelper;
  19. /**
  20. * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
  21. *
  22. * @author Qiang Xue <qiang.xue@gmail.com>
  23. * @since 2.0
  24. */
  25. class Schema extends \yii\db\Schema implements ConstraintFinderInterface
  26. {
  27. use ConstraintFinderTrait;
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public $columnSchemaClass = 'yii\db\mysql\ColumnSchema';
  32. /**
  33. * @var bool whether MySQL used is older than 5.1.
  34. */
  35. private $_oldMysql;
  36. /**
  37. * @var array mapping from physical column types (keys) to abstract column types (values)
  38. */
  39. public $typeMap = [
  40. 'tinyint' => self::TYPE_TINYINT,
  41. 'bit' => self::TYPE_INTEGER,
  42. 'smallint' => self::TYPE_SMALLINT,
  43. 'mediumint' => self::TYPE_INTEGER,
  44. 'int' => self::TYPE_INTEGER,
  45. 'integer' => self::TYPE_INTEGER,
  46. 'bigint' => self::TYPE_BIGINT,
  47. 'float' => self::TYPE_FLOAT,
  48. 'double' => self::TYPE_DOUBLE,
  49. 'real' => self::TYPE_FLOAT,
  50. 'decimal' => self::TYPE_DECIMAL,
  51. 'numeric' => self::TYPE_DECIMAL,
  52. 'tinytext' => self::TYPE_TEXT,
  53. 'mediumtext' => self::TYPE_TEXT,
  54. 'longtext' => self::TYPE_TEXT,
  55. 'longblob' => self::TYPE_BINARY,
  56. 'blob' => self::TYPE_BINARY,
  57. 'text' => self::TYPE_TEXT,
  58. 'varchar' => self::TYPE_STRING,
  59. 'string' => self::TYPE_STRING,
  60. 'char' => self::TYPE_CHAR,
  61. 'datetime' => self::TYPE_DATETIME,
  62. 'year' => self::TYPE_DATE,
  63. 'date' => self::TYPE_DATE,
  64. 'time' => self::TYPE_TIME,
  65. 'timestamp' => self::TYPE_TIMESTAMP,
  66. 'enum' => self::TYPE_STRING,
  67. 'varbinary' => self::TYPE_BINARY,
  68. 'json' => self::TYPE_JSON,
  69. ];
  70. /**
  71. * {@inheritdoc}
  72. */
  73. protected $tableQuoteCharacter = '`';
  74. /**
  75. * {@inheritdoc}
  76. */
  77. protected $columnQuoteCharacter = '`';
  78. /**
  79. * {@inheritdoc}
  80. */
  81. protected function resolveTableName($name)
  82. {
  83. $resolvedName = new TableSchema();
  84. $parts = explode('.', str_replace('`', '', $name));
  85. if (isset($parts[1])) {
  86. $resolvedName->schemaName = $parts[0];
  87. $resolvedName->name = $parts[1];
  88. } else {
  89. $resolvedName->schemaName = $this->defaultSchema;
  90. $resolvedName->name = $name;
  91. }
  92. $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
  93. return $resolvedName;
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. protected function findTableNames($schema = '')
  99. {
  100. $sql = 'SHOW TABLES';
  101. if ($schema !== '') {
  102. $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
  103. }
  104. return $this->db->createCommand($sql)->queryColumn();
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. protected function loadTableSchema($name)
  110. {
  111. $table = new TableSchema();
  112. $this->resolveTableNames($table, $name);
  113. if ($this->findColumns($table)) {
  114. $this->findConstraints($table);
  115. return $table;
  116. }
  117. return null;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. protected function loadTablePrimaryKey($tableName)
  123. {
  124. return $this->loadTableConstraints($tableName, 'primaryKey');
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. protected function loadTableForeignKeys($tableName)
  130. {
  131. return $this->loadTableConstraints($tableName, 'foreignKeys');
  132. }
  133. /**
  134. * {@inheritdoc}
  135. */
  136. protected function loadTableIndexes($tableName)
  137. {
  138. static $sql = <<<'SQL'
  139. SELECT
  140. `s`.`INDEX_NAME` AS `name`,
  141. `s`.`COLUMN_NAME` AS `column_name`,
  142. `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
  143. `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
  144. FROM `information_schema`.`STATISTICS` AS `s`
  145. WHERE `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND `s`.`TABLE_NAME` = :tableName
  146. ORDER BY `s`.`SEQ_IN_INDEX` ASC
  147. SQL;
  148. $resolvedName = $this->resolveTableName($tableName);
  149. $indexes = $this->db->createCommand($sql, [
  150. ':schemaName' => $resolvedName->schemaName,
  151. ':tableName' => $resolvedName->name,
  152. ])->queryAll();
  153. $indexes = $this->normalizePdoRowKeyCase($indexes, true);
  154. $indexes = ArrayHelper::index($indexes, null, 'name');
  155. $result = [];
  156. foreach ($indexes as $name => $index) {
  157. $result[] = new IndexConstraint([
  158. 'isPrimary' => (bool) $index[0]['index_is_primary'],
  159. 'isUnique' => (bool) $index[0]['index_is_unique'],
  160. 'name' => $name !== 'PRIMARY' ? $name : null,
  161. 'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
  162. ]);
  163. }
  164. return $result;
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. protected function loadTableUniques($tableName)
  170. {
  171. return $this->loadTableConstraints($tableName, 'uniques');
  172. }
  173. /**
  174. * {@inheritdoc}
  175. * @throws NotSupportedException if this method is called.
  176. */
  177. protected function loadTableChecks($tableName)
  178. {
  179. throw new NotSupportedException('MySQL does not support check constraints.');
  180. }
  181. /**
  182. * {@inheritdoc}
  183. * @throws NotSupportedException if this method is called.
  184. */
  185. protected function loadTableDefaultValues($tableName)
  186. {
  187. throw new NotSupportedException('MySQL does not support default value constraints.');
  188. }
  189. /**
  190. * Creates a query builder for the MySQL database.
  191. * @return QueryBuilder query builder instance
  192. */
  193. public function createQueryBuilder()
  194. {
  195. return new QueryBuilder($this->db);
  196. }
  197. /**
  198. * Resolves the table name and schema name (if any).
  199. * @param TableSchema $table the table metadata object
  200. * @param string $name the table name
  201. */
  202. protected function resolveTableNames($table, $name)
  203. {
  204. $parts = explode('.', str_replace('`', '', $name));
  205. if (isset($parts[1])) {
  206. $table->schemaName = $parts[0];
  207. $table->name = $parts[1];
  208. $table->fullName = $table->schemaName . '.' . $table->name;
  209. } else {
  210. $table->fullName = $table->name = $parts[0];
  211. }
  212. }
  213. /**
  214. * Loads the column information into a [[ColumnSchema]] object.
  215. * @param array $info column information
  216. * @return ColumnSchema the column schema object
  217. */
  218. protected function loadColumnSchema($info)
  219. {
  220. $column = $this->createColumnSchema();
  221. $column->name = $info['field'];
  222. $column->allowNull = $info['null'] === 'YES';
  223. $column->isPrimaryKey = strpos($info['key'], 'PRI') !== false;
  224. $column->autoIncrement = stripos($info['extra'], 'auto_increment') !== false;
  225. $column->comment = $info['comment'];
  226. $column->dbType = $info['type'];
  227. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  228. $column->type = self::TYPE_STRING;
  229. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  230. $type = strtolower($matches[1]);
  231. if (isset($this->typeMap[$type])) {
  232. $column->type = $this->typeMap[$type];
  233. }
  234. if (!empty($matches[2])) {
  235. if ($type === 'enum') {
  236. preg_match_all("/'[^']*'/", $matches[2], $values);
  237. foreach ($values[0] as $i => $value) {
  238. $values[$i] = trim($value, "'");
  239. }
  240. $column->enumValues = $values;
  241. } else {
  242. $values = explode(',', $matches[2]);
  243. $column->size = $column->precision = (int) $values[0];
  244. if (isset($values[1])) {
  245. $column->scale = (int) $values[1];
  246. }
  247. if ($column->size === 1 && $type === 'bit') {
  248. $column->type = 'boolean';
  249. } elseif ($type === 'bit') {
  250. if ($column->size > 32) {
  251. $column->type = 'bigint';
  252. } elseif ($column->size === 32) {
  253. $column->type = 'integer';
  254. }
  255. }
  256. }
  257. }
  258. }
  259. $column->phpType = $this->getColumnPhpType($column);
  260. if (!$column->isPrimaryKey) {
  261. if (($column->type === 'timestamp' || $column->type ==='datetime') && $info['default'] === 'CURRENT_TIMESTAMP') {
  262. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  263. } elseif (isset($type) && $type === 'bit') {
  264. $column->defaultValue = bindec(trim($info['default'], 'b\''));
  265. } else {
  266. $column->defaultValue = $column->phpTypecast($info['default']);
  267. }
  268. }
  269. return $column;
  270. }
  271. /**
  272. * Collects the metadata of table columns.
  273. * @param TableSchema $table the table metadata
  274. * @return bool whether the table exists in the database
  275. * @throws \Exception if DB query fails
  276. */
  277. protected function findColumns($table)
  278. {
  279. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
  280. try {
  281. $columns = $this->db->createCommand($sql)->queryAll();
  282. } catch (\Exception $e) {
  283. $previous = $e->getPrevious();
  284. if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
  285. // table does not exist
  286. // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
  287. return false;
  288. }
  289. throw $e;
  290. }
  291. foreach ($columns as $info) {
  292. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
  293. $info = array_change_key_case($info, CASE_LOWER);
  294. }
  295. $column = $this->loadColumnSchema($info);
  296. $table->columns[$column->name] = $column;
  297. if ($column->isPrimaryKey) {
  298. $table->primaryKey[] = $column->name;
  299. if ($column->autoIncrement) {
  300. $table->sequenceName = '';
  301. }
  302. }
  303. }
  304. return true;
  305. }
  306. /**
  307. * Gets the CREATE TABLE sql string.
  308. * @param TableSchema $table the table metadata
  309. * @return string $sql the result of 'SHOW CREATE TABLE'
  310. */
  311. protected function getCreateTableSql($table)
  312. {
  313. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
  314. if (isset($row['Create Table'])) {
  315. $sql = $row['Create Table'];
  316. } else {
  317. $row = array_values($row);
  318. $sql = $row[1];
  319. }
  320. return $sql;
  321. }
  322. /**
  323. * Collects the foreign key column details for the given table.
  324. * @param TableSchema $table the table metadata
  325. * @throws \Exception
  326. */
  327. protected function findConstraints($table)
  328. {
  329. $sql = <<<'SQL'
  330. SELECT
  331. kcu.constraint_name,
  332. kcu.column_name,
  333. kcu.referenced_table_name,
  334. kcu.referenced_column_name
  335. FROM information_schema.referential_constraints AS rc
  336. JOIN information_schema.key_column_usage AS kcu ON
  337. (
  338. kcu.constraint_catalog = rc.constraint_catalog OR
  339. (kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
  340. ) AND
  341. kcu.constraint_schema = rc.constraint_schema AND
  342. kcu.constraint_name = rc.constraint_name
  343. WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
  344. AND rc.table_name = :tableName AND kcu.table_name = :tableName1
  345. SQL;
  346. try {
  347. $rows = $this->db->createCommand($sql, [':tableName' => $table->name, ':tableName1' => $table->name])->queryAll();
  348. $constraints = [];
  349. foreach ($rows as $row) {
  350. $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
  351. $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
  352. }
  353. $table->foreignKeys = [];
  354. foreach ($constraints as $name => $constraint) {
  355. $table->foreignKeys[$name] = array_merge(
  356. [$constraint['referenced_table_name']],
  357. $constraint['columns']
  358. );
  359. }
  360. } catch (\Exception $e) {
  361. $previous = $e->getPrevious();
  362. if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
  363. throw $e;
  364. }
  365. // table does not exist, try to determine the foreign keys using the table creation sql
  366. $sql = $this->getCreateTableSql($table);
  367. $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  368. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  369. foreach ($matches as $match) {
  370. $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
  371. $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
  372. $constraint = [str_replace('`', '', $match[2])];
  373. foreach ($fks as $k => $name) {
  374. $constraint[$name] = $pks[$k];
  375. }
  376. $table->foreignKeys[md5(serialize($constraint))] = $constraint;
  377. }
  378. $table->foreignKeys = array_values($table->foreignKeys);
  379. }
  380. }
  381. }
  382. /**
  383. * Returns all unique indexes for the given table.
  384. *
  385. * Each array element is of the following structure:
  386. *
  387. * ```php
  388. * [
  389. * 'IndexName1' => ['col1' [, ...]],
  390. * 'IndexName2' => ['col2' [, ...]],
  391. * ]
  392. * ```
  393. *
  394. * @param TableSchema $table the table metadata
  395. * @return array all unique indexes for the given table.
  396. */
  397. public function findUniqueIndexes($table)
  398. {
  399. $sql = $this->getCreateTableSql($table);
  400. $uniqueIndexes = [];
  401. $regexp = '/UNIQUE KEY\s+\`(.+)\`\s*\((\`.+\`)+\)/mi';
  402. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  403. foreach ($matches as $match) {
  404. $indexName = $match[1];
  405. $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
  406. $uniqueIndexes[$indexName] = $indexColumns;
  407. }
  408. }
  409. return $uniqueIndexes;
  410. }
  411. /**
  412. * {@inheritdoc}
  413. */
  414. public function createColumnSchemaBuilder($type, $length = null)
  415. {
  416. return new ColumnSchemaBuilder($type, $length, $this->db);
  417. }
  418. /**
  419. * @return bool whether the version of the MySQL being used is older than 5.1.
  420. * @throws InvalidConfigException
  421. * @throws Exception
  422. * @since 2.0.13
  423. */
  424. protected function isOldMysql()
  425. {
  426. if ($this->_oldMysql === null) {
  427. $version = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
  428. $this->_oldMysql = version_compare($version, '5.1', '<=');
  429. }
  430. return $this->_oldMysql;
  431. }
  432. /**
  433. * Loads multiple types of constraints and returns the specified ones.
  434. * @param string $tableName table name.
  435. * @param string $returnType return type:
  436. * - primaryKey
  437. * - foreignKeys
  438. * - uniques
  439. * @return mixed constraints.
  440. */
  441. private function loadTableConstraints($tableName, $returnType)
  442. {
  443. static $sql = <<<'SQL'
  444. SELECT
  445. `kcu`.`CONSTRAINT_NAME` AS `name`,
  446. `kcu`.`COLUMN_NAME` AS `column_name`,
  447. `tc`.`CONSTRAINT_TYPE` AS `type`,
  448. CASE
  449. WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
  450. ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
  451. END AS `foreign_table_schema`,
  452. `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
  453. `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
  454. `rc`.`UPDATE_RULE` AS `on_update`,
  455. `rc`.`DELETE_RULE` AS `on_delete`,
  456. `kcu`.`ORDINAL_POSITION` AS `position`
  457. FROM
  458. `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
  459. `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`,
  460. `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
  461. WHERE
  462. `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `kcu`.`TABLE_NAME` = :tableName
  463. AND `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `rc`.`TABLE_NAME` = :tableName AND `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
  464. AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
  465. UNION
  466. SELECT
  467. `kcu`.`CONSTRAINT_NAME` AS `name`,
  468. `kcu`.`COLUMN_NAME` AS `column_name`,
  469. `tc`.`CONSTRAINT_TYPE` AS `type`,
  470. NULL AS `foreign_table_schema`,
  471. NULL AS `foreign_table_name`,
  472. NULL AS `foreign_column_name`,
  473. NULL AS `on_update`,
  474. NULL AS `on_delete`,
  475. `kcu`.`ORDINAL_POSITION` AS `position`
  476. FROM
  477. `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
  478. `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
  479. WHERE
  480. `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`TABLE_NAME` = :tableName
  481. AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
  482. ORDER BY `position` ASC
  483. SQL;
  484. $resolvedName = $this->resolveTableName($tableName);
  485. $constraints = $this->db->createCommand($sql, [
  486. ':schemaName' => $resolvedName->schemaName,
  487. ':tableName' => $resolvedName->name,
  488. ])->queryAll();
  489. $constraints = $this->normalizePdoRowKeyCase($constraints, true);
  490. $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
  491. $result = [
  492. 'primaryKey' => null,
  493. 'foreignKeys' => [],
  494. 'uniques' => [],
  495. ];
  496. foreach ($constraints as $type => $names) {
  497. foreach ($names as $name => $constraint) {
  498. switch ($type) {
  499. case 'PRIMARY KEY':
  500. $result['primaryKey'] = new Constraint([
  501. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  502. ]);
  503. break;
  504. case 'FOREIGN KEY':
  505. $result['foreignKeys'][] = new ForeignKeyConstraint([
  506. 'name' => $name,
  507. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  508. 'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
  509. 'foreignTableName' => $constraint[0]['foreign_table_name'],
  510. 'foreignColumnNames' => ArrayHelper::getColumn($constraint, 'foreign_column_name'),
  511. 'onDelete' => $constraint[0]['on_delete'],
  512. 'onUpdate' => $constraint[0]['on_update'],
  513. ]);
  514. break;
  515. case 'UNIQUE':
  516. $result['uniques'][] = new Constraint([
  517. 'name' => $name,
  518. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  519. ]);
  520. break;
  521. }
  522. }
  523. }
  524. foreach ($result as $type => $data) {
  525. $this->setTableMetadata($tableName, $type, $data);
  526. }
  527. return $result[$returnType];
  528. }
  529. }