Schema.php 23 KB

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