Schema.php 21 KB

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