Schema.php 28 KB

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