Schema.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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\mssql;
  8. use yii\db\CheckConstraint;
  9. use yii\db\ColumnSchema;
  10. use yii\db\Constraint;
  11. use yii\db\ConstraintFinderInterface;
  12. use yii\db\ConstraintFinderTrait;
  13. use yii\db\DefaultValueConstraint;
  14. use yii\db\ForeignKeyConstraint;
  15. use yii\db\IndexConstraint;
  16. use yii\db\ViewFinderTrait;
  17. use yii\helpers\ArrayHelper;
  18. /**
  19. * Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
  20. *
  21. * @author Timur Ruziev <resurtm@gmail.com>
  22. * @since 2.0
  23. */
  24. class Schema extends \yii\db\Schema implements ConstraintFinderInterface
  25. {
  26. use ViewFinderTrait;
  27. use ConstraintFinderTrait;
  28. /**
  29. * @var string the default schema used for the current session.
  30. */
  31. public $defaultSchema = 'dbo';
  32. /**
  33. * @var array mapping from physical column types (keys) to abstract column types (values)
  34. */
  35. public $typeMap = [
  36. // exact numbers
  37. 'bigint' => self::TYPE_BIGINT,
  38. 'numeric' => self::TYPE_DECIMAL,
  39. 'bit' => self::TYPE_SMALLINT,
  40. 'smallint' => self::TYPE_SMALLINT,
  41. 'decimal' => self::TYPE_DECIMAL,
  42. 'smallmoney' => self::TYPE_MONEY,
  43. 'int' => self::TYPE_INTEGER,
  44. 'tinyint' => self::TYPE_TINYINT,
  45. 'money' => self::TYPE_MONEY,
  46. // approximate numbers
  47. 'float' => self::TYPE_FLOAT,
  48. 'double' => self::TYPE_DOUBLE,
  49. 'real' => self::TYPE_FLOAT,
  50. // date and time
  51. 'date' => self::TYPE_DATE,
  52. 'datetimeoffset' => self::TYPE_DATETIME,
  53. 'datetime2' => self::TYPE_DATETIME,
  54. 'smalldatetime' => self::TYPE_DATETIME,
  55. 'datetime' => self::TYPE_DATETIME,
  56. 'time' => self::TYPE_TIME,
  57. // character strings
  58. 'char' => self::TYPE_CHAR,
  59. 'varchar' => self::TYPE_STRING,
  60. 'text' => self::TYPE_TEXT,
  61. // unicode character strings
  62. 'nchar' => self::TYPE_CHAR,
  63. 'nvarchar' => self::TYPE_STRING,
  64. 'ntext' => self::TYPE_TEXT,
  65. // binary strings
  66. 'binary' => self::TYPE_BINARY,
  67. 'varbinary' => self::TYPE_BINARY,
  68. 'image' => self::TYPE_BINARY,
  69. // other data types
  70. // 'cursor' type cannot be used with tables
  71. 'timestamp' => self::TYPE_TIMESTAMP,
  72. 'hierarchyid' => self::TYPE_STRING,
  73. 'uniqueidentifier' => self::TYPE_STRING,
  74. 'sql_variant' => self::TYPE_STRING,
  75. 'xml' => self::TYPE_STRING,
  76. 'table' => self::TYPE_STRING,
  77. ];
  78. /**
  79. * {@inheritdoc}
  80. */
  81. protected $tableQuoteCharacter = ['[', ']'];
  82. /**
  83. * {@inheritdoc}
  84. */
  85. protected $columnQuoteCharacter = ['[', ']'];
  86. /**
  87. * Resolves the table name and schema name (if any).
  88. * @param string $name the table name
  89. * @return TableSchema resolved table, schema, etc. names.
  90. */
  91. protected function resolveTableName($name)
  92. {
  93. $resolvedName = new TableSchema();
  94. $parts = explode('.', str_replace(['[', ']'], '', $name));
  95. $partCount = count($parts);
  96. if ($partCount === 4) {
  97. // server name, catalog name, schema name and table name passed
  98. $resolvedName->catalogName = $parts[1];
  99. $resolvedName->schemaName = $parts[2];
  100. $resolvedName->name = $parts[3];
  101. $resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
  102. } elseif ($partCount === 3) {
  103. // catalog name, schema name and table name passed
  104. $resolvedName->catalogName = $parts[0];
  105. $resolvedName->schemaName = $parts[1];
  106. $resolvedName->name = $parts[2];
  107. $resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
  108. } elseif ($partCount === 2) {
  109. // only schema name and table name passed
  110. $resolvedName->schemaName = $parts[0];
  111. $resolvedName->name = $parts[1];
  112. $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
  113. } else {
  114. // only table name passed
  115. $resolvedName->schemaName = $this->defaultSchema;
  116. $resolvedName->fullName = $resolvedName->name = $parts[0];
  117. }
  118. return $resolvedName;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. * @see https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-principals-transact-sql
  123. */
  124. protected function findSchemaNames()
  125. {
  126. static $sql = <<<'SQL'
  127. SELECT [s].[name]
  128. FROM [sys].[schemas] AS [s]
  129. INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
  130. WHERE [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
  131. ORDER BY [s].[name] ASC
  132. SQL;
  133. return $this->db->createCommand($sql)->queryColumn();
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. protected function findTableNames($schema = '')
  139. {
  140. if ($schema === '') {
  141. $schema = $this->defaultSchema;
  142. }
  143. $sql = <<<'SQL'
  144. SELECT [t].[table_name]
  145. FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
  146. WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
  147. ORDER BY [t].[table_name]
  148. SQL;
  149. return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. protected function loadTableSchema($name)
  155. {
  156. $table = new TableSchema();
  157. $this->resolveTableNames($table, $name);
  158. $this->findPrimaryKeys($table);
  159. if ($this->findColumns($table)) {
  160. $this->findForeignKeys($table);
  161. return $table;
  162. }
  163. return null;
  164. }
  165. /**
  166. * {@inheritdoc}
  167. */
  168. protected function loadTablePrimaryKey($tableName)
  169. {
  170. return $this->loadTableConstraints($tableName, 'primaryKey');
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. protected function loadTableForeignKeys($tableName)
  176. {
  177. return $this->loadTableConstraints($tableName, 'foreignKeys');
  178. }
  179. /**
  180. * {@inheritdoc}
  181. */
  182. protected function loadTableIndexes($tableName)
  183. {
  184. static $sql = <<<'SQL'
  185. SELECT
  186. [i].[name] AS [name],
  187. [iccol].[name] AS [column_name],
  188. [i].[is_unique] AS [index_is_unique],
  189. [i].[is_primary_key] AS [index_is_primary]
  190. FROM [sys].[indexes] AS [i]
  191. INNER JOIN [sys].[index_columns] AS [ic]
  192. ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
  193. INNER JOIN [sys].[columns] AS [iccol]
  194. ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
  195. WHERE [i].[object_id] = OBJECT_ID(:fullName)
  196. ORDER BY [ic].[key_ordinal] ASC
  197. SQL;
  198. $resolvedName = $this->resolveTableName($tableName);
  199. $indexes = $this->db->createCommand($sql, [
  200. ':fullName' => $resolvedName->fullName,
  201. ])->queryAll();
  202. $indexes = $this->normalizePdoRowKeyCase($indexes, true);
  203. $indexes = ArrayHelper::index($indexes, null, 'name');
  204. $result = [];
  205. foreach ($indexes as $name => $index) {
  206. $result[] = new IndexConstraint([
  207. 'isPrimary' => (bool) $index[0]['index_is_primary'],
  208. 'isUnique' => (bool) $index[0]['index_is_unique'],
  209. 'name' => $name,
  210. 'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
  211. ]);
  212. }
  213. return $result;
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. protected function loadTableUniques($tableName)
  219. {
  220. return $this->loadTableConstraints($tableName, 'uniques');
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. protected function loadTableChecks($tableName)
  226. {
  227. return $this->loadTableConstraints($tableName, 'checks');
  228. }
  229. /**
  230. * {@inheritdoc}
  231. */
  232. protected function loadTableDefaultValues($tableName)
  233. {
  234. return $this->loadTableConstraints($tableName, 'defaults');
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. public function createSavepoint($name)
  240. {
  241. $this->db->createCommand("SAVE TRANSACTION $name")->execute();
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. public function releaseSavepoint($name)
  247. {
  248. // does nothing as MSSQL does not support this
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. public function rollBackSavepoint($name)
  254. {
  255. $this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
  256. }
  257. /**
  258. * Creates a query builder for the MSSQL database.
  259. * @return QueryBuilder query builder interface.
  260. */
  261. public function createQueryBuilder()
  262. {
  263. return new QueryBuilder($this->db);
  264. }
  265. /**
  266. * Resolves the table name and schema name (if any).
  267. * @param TableSchema $table the table metadata object
  268. * @param string $name the table name
  269. */
  270. protected function resolveTableNames($table, $name)
  271. {
  272. $parts = explode('.', str_replace(['[', ']'], '', $name));
  273. $partCount = count($parts);
  274. if ($partCount === 4) {
  275. // server name, catalog name, schema name and table name passed
  276. $table->catalogName = $parts[1];
  277. $table->schemaName = $parts[2];
  278. $table->name = $parts[3];
  279. $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
  280. } elseif ($partCount === 3) {
  281. // catalog name, schema name and table name passed
  282. $table->catalogName = $parts[0];
  283. $table->schemaName = $parts[1];
  284. $table->name = $parts[2];
  285. $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
  286. } elseif ($partCount === 2) {
  287. // only schema name and table name passed
  288. $table->schemaName = $parts[0];
  289. $table->name = $parts[1];
  290. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  291. } else {
  292. // only table name passed
  293. $table->schemaName = $this->defaultSchema;
  294. $table->fullName = $table->name = $parts[0];
  295. }
  296. }
  297. /**
  298. * Loads the column information into a [[ColumnSchema]] object.
  299. * @param array $info column information
  300. * @return ColumnSchema the column schema object
  301. */
  302. protected function loadColumnSchema($info)
  303. {
  304. $column = $this->createColumnSchema();
  305. $column->name = $info['column_name'];
  306. $column->allowNull = $info['is_nullable'] === 'YES';
  307. $column->dbType = $info['data_type'];
  308. $column->enumValues = []; // mssql has only vague equivalents to enum
  309. $column->isPrimaryKey = null; // primary key will be determined in findColumns() method
  310. $column->autoIncrement = $info['is_identity'] == 1;
  311. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  312. $column->comment = $info['comment'] === null ? '' : $info['comment'];
  313. $column->type = self::TYPE_STRING;
  314. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  315. $type = $matches[1];
  316. if (isset($this->typeMap[$type])) {
  317. $column->type = $this->typeMap[$type];
  318. }
  319. if (!empty($matches[2])) {
  320. $values = explode(',', $matches[2]);
  321. $column->size = $column->precision = (int) $values[0];
  322. if (isset($values[1])) {
  323. $column->scale = (int) $values[1];
  324. }
  325. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  326. $column->type = 'boolean';
  327. } elseif ($type === 'bit') {
  328. if ($column->size > 32) {
  329. $column->type = 'bigint';
  330. } elseif ($column->size === 32) {
  331. $column->type = 'integer';
  332. }
  333. }
  334. }
  335. }
  336. $column->phpType = $this->getColumnPhpType($column);
  337. if ($info['column_default'] === '(NULL)') {
  338. $info['column_default'] = null;
  339. }
  340. if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
  341. $column->defaultValue = $column->phpTypecast($info['column_default']);
  342. }
  343. return $column;
  344. }
  345. /**
  346. * Collects the metadata of table columns.
  347. * @param TableSchema $table the table metadata
  348. * @return bool whether the table exists in the database
  349. */
  350. protected function findColumns($table)
  351. {
  352. $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
  353. $whereSql = "[t1].[table_name] = '{$table->name}'";
  354. if ($table->catalogName !== null) {
  355. $columnsTableName = "{$table->catalogName}.{$columnsTableName}";
  356. $whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
  357. }
  358. if ($table->schemaName !== null) {
  359. $whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
  360. }
  361. $columnsTableName = $this->quoteTableName($columnsTableName);
  362. $sql = <<<SQL
  363. SELECT
  364. [t1].[column_name],
  365. [t1].[is_nullable],
  366. [t1].[data_type],
  367. [t1].[column_default],
  368. COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
  369. (
  370. SELECT CONVERT(VARCHAR, [t2].[value])
  371. FROM [sys].[extended_properties] AS [t2]
  372. WHERE
  373. [t2].[class] = 1 AND
  374. [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
  375. [t2].[name] = 'MS_Description' AND
  376. [t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
  377. [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
  378. ) as comment
  379. FROM {$columnsTableName} AS [t1]
  380. WHERE {$whereSql}
  381. SQL;
  382. try {
  383. $columns = $this->db->createCommand($sql)->queryAll();
  384. if (empty($columns)) {
  385. return false;
  386. }
  387. } catch (\Exception $e) {
  388. return false;
  389. }
  390. foreach ($columns as $column) {
  391. $column = $this->loadColumnSchema($column);
  392. foreach ($table->primaryKey as $primaryKey) {
  393. if (strcasecmp($column->name, $primaryKey) === 0) {
  394. $column->isPrimaryKey = true;
  395. break;
  396. }
  397. }
  398. if ($column->isPrimaryKey && $column->autoIncrement) {
  399. $table->sequenceName = '';
  400. }
  401. $table->columns[$column->name] = $column;
  402. }
  403. return true;
  404. }
  405. /**
  406. * Collects the constraint details for the given table and constraint type.
  407. * @param TableSchema $table
  408. * @param string $type either PRIMARY KEY or UNIQUE
  409. * @return array each entry contains index_name and field_name
  410. * @since 2.0.4
  411. */
  412. protected function findTableConstraints($table, $type)
  413. {
  414. $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
  415. $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
  416. if ($table->catalogName !== null) {
  417. $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
  418. $tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
  419. }
  420. $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
  421. $tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
  422. $sql = <<<SQL
  423. SELECT
  424. [kcu].[constraint_name] AS [index_name],
  425. [kcu].[column_name] AS [field_name]
  426. FROM {$keyColumnUsageTableName} AS [kcu]
  427. LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
  428. [kcu].[table_schema] = [tc].[table_schema] AND
  429. [kcu].[table_name] = [tc].[table_name] AND
  430. [kcu].[constraint_name] = [tc].[constraint_name]
  431. WHERE
  432. [tc].[constraint_type] = :type AND
  433. [kcu].[table_name] = :tableName AND
  434. [kcu].[table_schema] = :schemaName
  435. SQL;
  436. return $this->db
  437. ->createCommand($sql, [
  438. ':tableName' => $table->name,
  439. ':schemaName' => $table->schemaName,
  440. ':type' => $type,
  441. ])
  442. ->queryAll();
  443. }
  444. /**
  445. * Collects the primary key column details for the given table.
  446. * @param TableSchema $table the table metadata
  447. */
  448. protected function findPrimaryKeys($table)
  449. {
  450. $result = [];
  451. foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
  452. $result[] = $row['field_name'];
  453. }
  454. $table->primaryKey = $result;
  455. }
  456. /**
  457. * Collects the foreign key column details for the given table.
  458. * @param TableSchema $table the table metadata
  459. */
  460. protected function findForeignKeys($table)
  461. {
  462. $object = $table->name;
  463. if ($table->schemaName !== null) {
  464. $object = $table->schemaName . '.' . $object;
  465. }
  466. if ($table->catalogName !== null) {
  467. $object = $table->catalogName . '.' . $object;
  468. }
  469. // please refer to the following page for more details:
  470. // http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
  471. $sql = <<<'SQL'
  472. SELECT
  473. [fk].[name] AS [fk_name],
  474. [cp].[name] AS [fk_column_name],
  475. OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
  476. [cr].[name] AS [uq_column_name]
  477. FROM
  478. [sys].[foreign_keys] AS [fk]
  479. INNER JOIN [sys].[foreign_key_columns] AS [fkc] ON
  480. [fk].[object_id] = [fkc].[constraint_object_id]
  481. INNER JOIN [sys].[columns] AS [cp] ON
  482. [fk].[parent_object_id] = [cp].[object_id] AND
  483. [fkc].[parent_column_id] = [cp].[column_id]
  484. INNER JOIN [sys].[columns] AS [cr] ON
  485. [fk].[referenced_object_id] = [cr].[object_id] AND
  486. [fkc].[referenced_column_id] = [cr].[column_id]
  487. WHERE
  488. [fk].[parent_object_id] = OBJECT_ID(:object)
  489. SQL;
  490. $rows = $this->db->createCommand($sql, [
  491. ':object' => $object,
  492. ])->queryAll();
  493. $table->foreignKeys = [];
  494. foreach ($rows as $row) {
  495. $table->foreignKeys[$row['fk_name']] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']];
  496. }
  497. }
  498. /**
  499. * {@inheritdoc}
  500. */
  501. protected function findViewNames($schema = '')
  502. {
  503. if ($schema === '') {
  504. $schema = $this->defaultSchema;
  505. }
  506. $sql = <<<'SQL'
  507. SELECT [t].[table_name]
  508. FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
  509. WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
  510. ORDER BY [t].[table_name]
  511. SQL;
  512. return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
  513. }
  514. /**
  515. * Returns all unique indexes for the given table.
  516. *
  517. * Each array element is of the following structure:
  518. *
  519. * ```php
  520. * [
  521. * 'IndexName1' => ['col1' [, ...]],
  522. * 'IndexName2' => ['col2' [, ...]],
  523. * ]
  524. * ```
  525. *
  526. * @param TableSchema $table the table metadata
  527. * @return array all unique indexes for the given table.
  528. * @since 2.0.4
  529. */
  530. public function findUniqueIndexes($table)
  531. {
  532. $result = [];
  533. foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
  534. $result[$row['index_name']][] = $row['field_name'];
  535. }
  536. return $result;
  537. }
  538. /**
  539. * Loads multiple types of constraints and returns the specified ones.
  540. * @param string $tableName table name.
  541. * @param string $returnType return type:
  542. * - primaryKey
  543. * - foreignKeys
  544. * - uniques
  545. * - checks
  546. * - defaults
  547. * @return mixed constraints.
  548. */
  549. private function loadTableConstraints($tableName, $returnType)
  550. {
  551. static $sql = <<<'SQL'
  552. SELECT
  553. [o].[name] AS [name],
  554. COALESCE([ccol].[name], [dcol].[name], [fccol].[name], [kiccol].[name]) AS [column_name],
  555. RTRIM([o].[type]) AS [type],
  556. OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [foreign_table_schema],
  557. OBJECT_NAME([f].[referenced_object_id]) AS [foreign_table_name],
  558. [ffccol].[name] AS [foreign_column_name],
  559. [f].[update_referential_action_desc] AS [on_update],
  560. [f].[delete_referential_action_desc] AS [on_delete],
  561. [c].[definition] AS [check_expr],
  562. [d].[definition] AS [default_expr]
  563. FROM (SELECT OBJECT_ID(:fullName) AS [object_id]) AS [t]
  564. INNER JOIN [sys].[objects] AS [o]
  565. ON [o].[parent_object_id] = [t].[object_id] AND [o].[type] IN ('PK', 'UQ', 'C', 'D', 'F')
  566. LEFT JOIN [sys].[check_constraints] AS [c]
  567. ON [c].[object_id] = [o].[object_id]
  568. LEFT JOIN [sys].[columns] AS [ccol]
  569. ON [ccol].[object_id] = [c].[parent_object_id] AND [ccol].[column_id] = [c].[parent_column_id]
  570. LEFT JOIN [sys].[default_constraints] AS [d]
  571. ON [d].[object_id] = [o].[object_id]
  572. LEFT JOIN [sys].[columns] AS [dcol]
  573. ON [dcol].[object_id] = [d].[parent_object_id] AND [dcol].[column_id] = [d].[parent_column_id]
  574. LEFT JOIN [sys].[key_constraints] AS [k]
  575. ON [k].[object_id] = [o].[object_id]
  576. LEFT JOIN [sys].[index_columns] AS [kic]
  577. ON [kic].[object_id] = [k].[parent_object_id] AND [kic].[index_id] = [k].[unique_index_id]
  578. LEFT JOIN [sys].[columns] AS [kiccol]
  579. ON [kiccol].[object_id] = [kic].[object_id] AND [kiccol].[column_id] = [kic].[column_id]
  580. LEFT JOIN [sys].[foreign_keys] AS [f]
  581. ON [f].[object_id] = [o].[object_id]
  582. LEFT JOIN [sys].[foreign_key_columns] AS [fc]
  583. ON [fc].[constraint_object_id] = [o].[object_id]
  584. LEFT JOIN [sys].[columns] AS [fccol]
  585. ON [fccol].[object_id] = [fc].[parent_object_id] AND [fccol].[column_id] = [fc].[parent_column_id]
  586. LEFT JOIN [sys].[columns] AS [ffccol]
  587. ON [ffccol].[object_id] = [fc].[referenced_object_id] AND [ffccol].[column_id] = [fc].[referenced_column_id]
  588. ORDER BY [kic].[key_ordinal] ASC, [fc].[constraint_column_id] ASC
  589. SQL;
  590. $resolvedName = $this->resolveTableName($tableName);
  591. $constraints = $this->db->createCommand($sql, [
  592. ':fullName' => $resolvedName->fullName,
  593. ])->queryAll();
  594. $constraints = $this->normalizePdoRowKeyCase($constraints, true);
  595. $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
  596. $result = [
  597. 'primaryKey' => null,
  598. 'foreignKeys' => [],
  599. 'uniques' => [],
  600. 'checks' => [],
  601. 'defaults' => [],
  602. ];
  603. foreach ($constraints as $type => $names) {
  604. foreach ($names as $name => $constraint) {
  605. switch ($type) {
  606. case 'PK':
  607. $result['primaryKey'] = new Constraint([
  608. 'name' => $name,
  609. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  610. ]);
  611. break;
  612. case 'F':
  613. $result['foreignKeys'][] = new ForeignKeyConstraint([
  614. 'name' => $name,
  615. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  616. 'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
  617. 'foreignTableName' => $constraint[0]['foreign_table_name'],
  618. 'foreignColumnNames' => ArrayHelper::getColumn($constraint, 'foreign_column_name'),
  619. 'onDelete' => str_replace('_', '', $constraint[0]['on_delete']),
  620. 'onUpdate' => str_replace('_', '', $constraint[0]['on_update']),
  621. ]);
  622. break;
  623. case 'UQ':
  624. $result['uniques'][] = new Constraint([
  625. 'name' => $name,
  626. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  627. ]);
  628. break;
  629. case 'C':
  630. $result['checks'][] = new CheckConstraint([
  631. 'name' => $name,
  632. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  633. 'expression' => $constraint[0]['check_expr'],
  634. ]);
  635. break;
  636. case 'D':
  637. $result['defaults'][] = new DefaultValueConstraint([
  638. 'name' => $name,
  639. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  640. 'value' => $constraint[0]['default_expr'],
  641. ]);
  642. break;
  643. }
  644. }
  645. }
  646. foreach ($result as $type => $data) {
  647. $this->setTableMetadata($tableName, $type, $data);
  648. }
  649. return $result[$returnType];
  650. }
  651. }