436 lines
15KB

  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\ColumnSchema;
  9. /**
  10. * Schema is the class for retrieving metadata from a MS SQL Server databases (version 2008 and above).
  11. *
  12. * @author Timur Ruziev <resurtm@gmail.com>
  13. * @since 2.0
  14. */
  15. class Schema extends \yii\db\Schema
  16. {
  17. /**
  18. * @var string the default schema used for the current session.
  19. */
  20. public $defaultSchema = 'dbo';
  21. /**
  22. * @var array mapping from physical column types (keys) to abstract column types (values)
  23. */
  24. public $typeMap = [
  25. // exact numbers
  26. 'bigint' => self::TYPE_BIGINT,
  27. 'numeric' => self::TYPE_DECIMAL,
  28. 'bit' => self::TYPE_SMALLINT,
  29. 'smallint' => self::TYPE_SMALLINT,
  30. 'decimal' => self::TYPE_DECIMAL,
  31. 'smallmoney' => self::TYPE_MONEY,
  32. 'int' => self::TYPE_INTEGER,
  33. 'tinyint' => self::TYPE_SMALLINT,
  34. 'money' => self::TYPE_MONEY,
  35. // approximate numbers
  36. 'float' => self::TYPE_FLOAT,
  37. 'double' => self::TYPE_DOUBLE,
  38. 'real' => self::TYPE_FLOAT,
  39. // date and time
  40. 'date' => self::TYPE_DATE,
  41. 'datetimeoffset' => self::TYPE_DATETIME,
  42. 'datetime2' => self::TYPE_DATETIME,
  43. 'smalldatetime' => self::TYPE_DATETIME,
  44. 'datetime' => self::TYPE_DATETIME,
  45. 'time' => self::TYPE_TIME,
  46. // character strings
  47. 'char' => self::TYPE_CHAR,
  48. 'varchar' => self::TYPE_STRING,
  49. 'text' => self::TYPE_TEXT,
  50. // unicode character strings
  51. 'nchar' => self::TYPE_CHAR,
  52. 'nvarchar' => self::TYPE_STRING,
  53. 'ntext' => self::TYPE_TEXT,
  54. // binary strings
  55. 'binary' => self::TYPE_BINARY,
  56. 'varbinary' => self::TYPE_BINARY,
  57. 'image' => self::TYPE_BINARY,
  58. // other data types
  59. // 'cursor' type cannot be used with tables
  60. 'timestamp' => self::TYPE_TIMESTAMP,
  61. 'hierarchyid' => self::TYPE_STRING,
  62. 'uniqueidentifier' => self::TYPE_STRING,
  63. 'sql_variant' => self::TYPE_STRING,
  64. 'xml' => self::TYPE_STRING,
  65. 'table' => self::TYPE_STRING,
  66. ];
  67. /**
  68. * @inheritdoc
  69. */
  70. public function createSavepoint($name)
  71. {
  72. $this->db->createCommand("SAVE TRANSACTION $name")->execute();
  73. }
  74. /**
  75. * @inheritdoc
  76. */
  77. public function releaseSavepoint($name)
  78. {
  79. // does nothing as MSSQL does not support this
  80. }
  81. /**
  82. * @inheritdoc
  83. */
  84. public function rollBackSavepoint($name)
  85. {
  86. $this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
  87. }
  88. /**
  89. * Quotes a table name for use in a query.
  90. * A simple table name has no schema prefix.
  91. * @param string $name table name.
  92. * @return string the properly quoted table name.
  93. */
  94. public function quoteSimpleTableName($name)
  95. {
  96. return strpos($name, '[') === false ? "[{$name}]" : $name;
  97. }
  98. /**
  99. * Quotes a column name for use in a query.
  100. * A simple column name has no prefix.
  101. * @param string $name column name.
  102. * @return string the properly quoted column name.
  103. */
  104. public function quoteSimpleColumnName($name)
  105. {
  106. return strpos($name, '[') === false && $name !== '*' ? "[{$name}]" : $name;
  107. }
  108. /**
  109. * Creates a query builder for the MSSQL database.
  110. * @return QueryBuilder query builder interface.
  111. */
  112. public function createQueryBuilder()
  113. {
  114. return new QueryBuilder($this->db);
  115. }
  116. /**
  117. * Loads the metadata for the specified table.
  118. * @param string $name table name
  119. * @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
  120. */
  121. public function loadTableSchema($name)
  122. {
  123. $table = new TableSchema();
  124. $this->resolveTableNames($table, $name);
  125. $this->findPrimaryKeys($table);
  126. if ($this->findColumns($table)) {
  127. $this->findForeignKeys($table);
  128. return $table;
  129. } else {
  130. return null;
  131. }
  132. }
  133. /**
  134. * Resolves the table name and schema name (if any).
  135. * @param TableSchema $table the table metadata object
  136. * @param string $name the table name
  137. */
  138. protected function resolveTableNames($table, $name)
  139. {
  140. $parts = explode('.', str_replace(['[', ']'], '', $name));
  141. $partCount = count($parts);
  142. if ($partCount === 4) {
  143. // server name, catalog name, schema name and table name passed
  144. $table->catalogName = $parts[1];
  145. $table->schemaName = $parts[2];
  146. $table->name = $parts[3];
  147. $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
  148. } elseif ($partCount === 3) {
  149. // catalog name, schema name and table name passed
  150. $table->catalogName = $parts[0];
  151. $table->schemaName = $parts[1];
  152. $table->name = $parts[2];
  153. $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
  154. } elseif ($partCount === 2) {
  155. // only schema name and table name passed
  156. $table->schemaName = $parts[0];
  157. $table->name = $parts[1];
  158. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  159. } else {
  160. // only table name passed
  161. $table->schemaName = $this->defaultSchema;
  162. $table->fullName = $table->name = $parts[0];
  163. }
  164. }
  165. /**
  166. * Loads the column information into a [[ColumnSchema]] object.
  167. * @param array $info column information
  168. * @return ColumnSchema the column schema object
  169. */
  170. protected function loadColumnSchema($info)
  171. {
  172. $column = $this->createColumnSchema();
  173. $column->name = $info['column_name'];
  174. $column->allowNull = $info['is_nullable'] === 'YES';
  175. $column->dbType = $info['data_type'];
  176. $column->enumValues = []; // mssql has only vague equivalents to enum
  177. $column->isPrimaryKey = null; // primary key will be determined in findColumns() method
  178. $column->autoIncrement = $info['is_identity'] == 1;
  179. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  180. $column->comment = $info['comment'] === null ? '' : $info['comment'];
  181. $column->type = self::TYPE_STRING;
  182. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  183. $type = $matches[1];
  184. if (isset($this->typeMap[$type])) {
  185. $column->type = $this->typeMap[$type];
  186. }
  187. if (!empty($matches[2])) {
  188. $values = explode(',', $matches[2]);
  189. $column->size = $column->precision = (int) $values[0];
  190. if (isset($values[1])) {
  191. $column->scale = (int) $values[1];
  192. }
  193. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  194. $column->type = 'boolean';
  195. } elseif ($type === 'bit') {
  196. if ($column->size > 32) {
  197. $column->type = 'bigint';
  198. } elseif ($column->size === 32) {
  199. $column->type = 'integer';
  200. }
  201. }
  202. }
  203. }
  204. $column->phpType = $this->getColumnPhpType($column);
  205. if ($info['column_default'] === '(NULL)') {
  206. $info['column_default'] = null;
  207. }
  208. if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
  209. $column->defaultValue = $column->phpTypecast($info['column_default']);
  210. }
  211. return $column;
  212. }
  213. /**
  214. * Collects the metadata of table columns.
  215. * @param TableSchema $table the table metadata
  216. * @return boolean whether the table exists in the database
  217. */
  218. protected function findColumns($table)
  219. {
  220. $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
  221. $whereSql = "[t1].[table_name] = '{$table->name}'";
  222. if ($table->catalogName !== null) {
  223. $columnsTableName = "{$table->catalogName}.{$columnsTableName}";
  224. $whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
  225. }
  226. if ($table->schemaName !== null) {
  227. $whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
  228. }
  229. $columnsTableName = $this->quoteTableName($columnsTableName);
  230. $sql = <<<SQL
  231. SELECT
  232. [t1].[column_name], [t1].[is_nullable], [t1].[data_type], [t1].[column_default],
  233. COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
  234. CONVERT(VARCHAR, [t2].[value]) AS comment
  235. FROM {$columnsTableName} AS [t1]
  236. LEFT OUTER JOIN [sys].[extended_properties] AS [t2] ON
  237. [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID') AND
  238. OBJECT_NAME([t2].[major_id]) = [t1].[table_name] AND
  239. [t2].[class] = 1 AND
  240. [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
  241. [t2].[name] = 'MS_Description'
  242. WHERE {$whereSql}
  243. SQL;
  244. try {
  245. $columns = $this->db->createCommand($sql)->queryAll();
  246. if (empty($columns)) {
  247. return false;
  248. }
  249. } catch (\Exception $e) {
  250. return false;
  251. }
  252. foreach ($columns as $column) {
  253. $column = $this->loadColumnSchema($column);
  254. foreach ($table->primaryKey as $primaryKey) {
  255. if (strcasecmp($column->name, $primaryKey) === 0) {
  256. $column->isPrimaryKey = true;
  257. break;
  258. }
  259. }
  260. if ($column->isPrimaryKey && $column->autoIncrement) {
  261. $table->sequenceName = '';
  262. }
  263. $table->columns[$column->name] = $column;
  264. }
  265. return true;
  266. }
  267. /**
  268. * Collects the constraint details for the given table and constraint type.
  269. * @param TableSchema $table
  270. * @param string $type either PRIMARY KEY or UNIQUE
  271. * @return array each entry contains index_name and field_name
  272. * @since 2.0.4
  273. */
  274. protected function findTableConstraints($table, $type)
  275. {
  276. $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
  277. $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
  278. if ($table->catalogName !== null) {
  279. $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
  280. $tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
  281. }
  282. $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
  283. $tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
  284. $sql = <<<SQL
  285. SELECT
  286. [kcu].[constraint_name] AS [index_name],
  287. [kcu].[column_name] AS [field_name]
  288. FROM {$keyColumnUsageTableName} AS [kcu]
  289. LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
  290. [kcu].[table_schema] = [tc].[table_schema] AND
  291. [kcu].[table_name] = [tc].[table_name] AND
  292. [kcu].[constraint_name] = [tc].[constraint_name]
  293. WHERE
  294. [tc].[constraint_type] = :type AND
  295. [kcu].[table_name] = :tableName AND
  296. [kcu].[table_schema] = :schemaName
  297. SQL;
  298. return $this->db
  299. ->createCommand($sql, [
  300. ':tableName' => $table->name,
  301. ':schemaName' => $table->schemaName,
  302. ':type' => $type,
  303. ])
  304. ->queryAll();
  305. }
  306. /**
  307. * Collects the primary key column details for the given table.
  308. * @param TableSchema $table the table metadata
  309. */
  310. protected function findPrimaryKeys($table)
  311. {
  312. $result = [];
  313. foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
  314. $result[] = $row['field_name'];
  315. }
  316. $table->primaryKey = $result;
  317. }
  318. /**
  319. * Collects the foreign key column details for the given table.
  320. * @param TableSchema $table the table metadata
  321. */
  322. protected function findForeignKeys($table)
  323. {
  324. $referentialConstraintsTableName = 'INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS';
  325. $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
  326. if ($table->catalogName !== null) {
  327. $referentialConstraintsTableName = $table->catalogName . '.' . $referentialConstraintsTableName;
  328. $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
  329. }
  330. $referentialConstraintsTableName = $this->quoteTableName($referentialConstraintsTableName);
  331. $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
  332. // please refer to the following page for more details:
  333. // http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
  334. $sql = <<<SQL
  335. SELECT
  336. [kcu1].[column_name] AS [fk_column_name],
  337. [kcu2].[table_name] AS [uq_table_name],
  338. [kcu2].[column_name] AS [uq_column_name]
  339. FROM {$referentialConstraintsTableName} AS [rc]
  340. JOIN {$keyColumnUsageTableName} AS [kcu1] ON
  341. [kcu1].[constraint_catalog] = [rc].[constraint_catalog] AND
  342. [kcu1].[constraint_schema] = [rc].[constraint_schema] AND
  343. [kcu1].[constraint_name] = [rc].[constraint_name]
  344. JOIN {$keyColumnUsageTableName} AS [kcu2] ON
  345. [kcu2].[constraint_catalog] = [rc].[constraint_catalog] AND
  346. [kcu2].[constraint_schema] = [rc].[constraint_schema] AND
  347. [kcu2].[constraint_name] = [rc].[unique_constraint_name] AND
  348. [kcu2].[ordinal_position] = [kcu1].[ordinal_position]
  349. WHERE [kcu1].[table_name] = :tableName AND [kcu1].[table_schema] = :schemaName
  350. SQL;
  351. $rows = $this->db->createCommand($sql, [
  352. ':tableName' => $table->name,
  353. ':schemaName' => $table->schemaName,
  354. ])->queryAll();
  355. $table->foreignKeys = [];
  356. foreach ($rows as $row) {
  357. $table->foreignKeys[] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']];
  358. }
  359. }
  360. /**
  361. * Returns all table names in the database.
  362. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  363. * @return array all table names in the database. The names have NO schema name prefix.
  364. */
  365. protected function findTableNames($schema = '')
  366. {
  367. if ($schema === '') {
  368. $schema = $this->defaultSchema;
  369. }
  370. $sql = <<<SQL
  371. SELECT [t].[table_name]
  372. FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
  373. WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
  374. ORDER BY [t].[table_name]
  375. SQL;
  376. return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
  377. }
  378. /**
  379. * Returns all unique indexes for the given table.
  380. * Each array element is of the following structure:
  381. *
  382. * ```php
  383. * [
  384. * 'IndexName1' => ['col1' [, ...]],
  385. * 'IndexName2' => ['col2' [, ...]],
  386. * ]
  387. * ```
  388. *
  389. * @param TableSchema $table the table metadata
  390. * @return array all unique indexes for the given table.
  391. * @since 2.0.4
  392. */
  393. public function findUniqueIndexes($table)
  394. {
  395. $result = [];
  396. foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
  397. $result[$row['index_name']][] = $row['field_name'];
  398. }
  399. return $result;
  400. }
  401. }