Schema.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 <[email protected]>
  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. 'real' => self::TYPE_FLOAT,
  38. // date and time
  39. 'date' => self::TYPE_DATE,
  40. 'datetimeoffset' => self::TYPE_DATETIME,
  41. 'datetime2' => self::TYPE_DATETIME,
  42. 'smalldatetime' => self::TYPE_DATETIME,
  43. 'datetime' => self::TYPE_DATETIME,
  44. 'time' => self::TYPE_TIME,
  45. // character strings
  46. 'char' => self::TYPE_STRING,
  47. 'varchar' => self::TYPE_STRING,
  48. 'text' => self::TYPE_TEXT,
  49. // unicode character strings
  50. 'nchar' => self::TYPE_STRING,
  51. 'nvarchar' => self::TYPE_STRING,
  52. 'ntext' => self::TYPE_TEXT,
  53. // binary strings
  54. 'binary' => self::TYPE_BINARY,
  55. 'varbinary' => self::TYPE_BINARY,
  56. 'image' => self::TYPE_BINARY,
  57. // other data types
  58. // 'cursor' type cannot be used with tables
  59. 'timestamp' => self::TYPE_TIMESTAMP,
  60. 'hierarchyid' => self::TYPE_STRING,
  61. 'uniqueidentifier' => self::TYPE_STRING,
  62. 'sql_variant' => self::TYPE_STRING,
  63. 'xml' => self::TYPE_STRING,
  64. 'table' => self::TYPE_STRING,
  65. ];
  66. /**
  67. * Quotes a table name for use in a query.
  68. * A simple table name has no schema prefix.
  69. * @param string $name table name.
  70. * @return string the properly quoted table name.
  71. */
  72. public function quoteSimpleTableName($name)
  73. {
  74. return strpos($name, '[') === false ? "[{$name}]" : $name;
  75. }
  76. /**
  77. * Quotes a column name for use in a query.
  78. * A simple column name has no prefix.
  79. * @param string $name column name.
  80. * @return string the properly quoted column name.
  81. */
  82. public function quoteSimpleColumnName($name)
  83. {
  84. return strpos($name, '[') === false && $name !== '*' ? "[{$name}]" : $name;
  85. }
  86. /**
  87. * Creates a query builder for the MSSQL database.
  88. * @return QueryBuilder query builder interface.
  89. */
  90. public function createQueryBuilder()
  91. {
  92. return new QueryBuilder($this->db);
  93. }
  94. /**
  95. * Loads the metadata for the specified table.
  96. * @param string $name table name
  97. * @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
  98. */
  99. public function loadTableSchema($name)
  100. {
  101. $table = new TableSchema();
  102. $this->resolveTableNames($table, $name);
  103. $this->findPrimaryKeys($table);
  104. if ($this->findColumns($table)) {
  105. $this->findForeignKeys($table);
  106. return $table;
  107. } else {
  108. return null;
  109. }
  110. }
  111. /**
  112. * Resolves the table name and schema name (if any).
  113. * @param TableSchema $table the table metadata object
  114. * @param string $name the table name
  115. */
  116. protected function resolveTableNames($table, $name)
  117. {
  118. $parts = explode('.', str_replace(['[', ']'], '', $name));
  119. $partCount = count($parts);
  120. if ($partCount == 3) {
  121. // catalog name, schema name and table name passed
  122. $table->catalogName = $parts[0];
  123. $table->schemaName = $parts[1];
  124. $table->name = $parts[2];
  125. $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
  126. } elseif ($partCount == 2) {
  127. // only schema name and table name passed
  128. $table->schemaName = $parts[0];
  129. $table->name = $parts[1];
  130. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  131. } else {
  132. // only table name passed
  133. $table->schemaName = $this->defaultSchema;
  134. $table->fullName = $table->name = $parts[0];
  135. }
  136. }
  137. /**
  138. * Loads the column information into a [[ColumnSchema]] object.
  139. * @param array $info column information
  140. * @return ColumnSchema the column schema object
  141. */
  142. protected function loadColumnSchema($info)
  143. {
  144. $column = new ColumnSchema();
  145. $column->name = $info['column_name'];
  146. $column->allowNull = $info['is_nullable'] == 'YES';
  147. $column->dbType = $info['data_type'];
  148. $column->enumValues = []; // mssql has only vague equivalents to enum
  149. $column->isPrimaryKey = null; // primary key will be determined in findColumns() method
  150. $column->autoIncrement = $info['is_identity'] == 1;
  151. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  152. $column->comment = $info['comment'] === null ? '' : $info['comment'];
  153. $column->type = self::TYPE_STRING;
  154. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  155. $type = $matches[1];
  156. if (isset($this->typeMap[$type])) {
  157. $column->type = $this->typeMap[$type];
  158. }
  159. if (!empty($matches[2])) {
  160. $values = explode(',', $matches[2]);
  161. $column->size = $column->precision = (int)$values[0];
  162. if (isset($values[1])) {
  163. $column->scale = (int)$values[1];
  164. }
  165. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  166. $column->type = 'boolean';
  167. } elseif ($type === 'bit') {
  168. if ($column->size > 32) {
  169. $column->type = 'bigint';
  170. } elseif ($column->size === 32) {
  171. $column->type = 'integer';
  172. }
  173. }
  174. }
  175. }
  176. $column->phpType = $this->getColumnPhpType($column);
  177. if ($info['column_default'] == '(NULL)') {
  178. $info['column_default'] = null;
  179. }
  180. if ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP') {
  181. $column->defaultValue = $column->typecast($info['column_default']);
  182. }
  183. return $column;
  184. }
  185. /**
  186. * Collects the metadata of table columns.
  187. * @param TableSchema $table the table metadata
  188. * @return boolean whether the table exists in the database
  189. */
  190. protected function findColumns($table)
  191. {
  192. $columnsTableName = 'information_schema.columns';
  193. $whereSql = "[t1].[table_name] = '{$table->name}'";
  194. if ($table->catalogName !== null) {
  195. $columnsTableName = "{$table->catalogName}.{$columnsTableName}";
  196. $whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
  197. }
  198. if ($table->schemaName !== null) {
  199. $whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
  200. }
  201. $columnsTableName = $this->quoteTableName($columnsTableName);
  202. $sql = <<<SQL
  203. SELECT
  204. [t1].[column_name], [t1].[is_nullable], [t1].[data_type], [t1].[column_default],
  205. COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
  206. CONVERT(VARCHAR, [t2].[value]) AS comment
  207. FROM {$columnsTableName} AS [t1]
  208. LEFT OUTER JOIN [sys].[extended_properties] AS [t2] ON
  209. [t1].[ordinal_position] = [t2].[minor_id] AND
  210. OBJECT_NAME([t2].[major_id]) = [t1].[table_name] AND
  211. [t2].[class] = 1 AND
  212. [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
  213. [t2].[name] = 'MS_Description'
  214. WHERE {$whereSql}
  215. SQL;
  216. try {
  217. $columns = $this->db->createCommand($sql)->queryAll();
  218. } catch (\Exception $e) {
  219. return false;
  220. }
  221. foreach ($columns as $column) {
  222. $column = $this->loadColumnSchema($column);
  223. foreach ($table->primaryKey as $primaryKey) {
  224. if (strcasecmp($column->name, $primaryKey) === 0) {
  225. $column->isPrimaryKey = true;
  226. break;
  227. }
  228. }
  229. if ($column->isPrimaryKey && $column->autoIncrement) {
  230. $table->sequenceName = '';
  231. }
  232. $table->columns[$column->name] = $column;
  233. }
  234. return true;
  235. }
  236. /**
  237. * Collects the primary key column details for the given table.
  238. * @param TableSchema $table the table metadata
  239. */
  240. protected function findPrimaryKeys($table)
  241. {
  242. $keyColumnUsageTableName = 'information_schema.key_column_usage';
  243. $tableConstraintsTableName = 'information_schema.table_constraints';
  244. if ($table->catalogName !== null) {
  245. $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
  246. $tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
  247. }
  248. $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
  249. $tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
  250. $sql = <<<SQL
  251. SELECT
  252. [kcu].[column_name] AS [field_name]
  253. FROM {$keyColumnUsageTableName} AS [kcu]
  254. LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
  255. [kcu].[table_name] = [tc].[table_name] AND
  256. [kcu].[constraint_name] = [tc].[constraint_name]
  257. WHERE
  258. [tc].[constraint_type] = 'PRIMARY KEY' AND
  259. [kcu].[table_name] = :tableName AND
  260. [kcu].[table_schema] = :schemaName
  261. SQL;
  262. $table->primaryKey = $this->db
  263. ->createCommand($sql, [':tableName' => $table->name, ':schemaName' => $table->schemaName])
  264. ->queryColumn();
  265. }
  266. /**
  267. * Collects the foreign key column details for the given table.
  268. * @param TableSchema $table the table metadata
  269. */
  270. protected function findForeignKeys($table)
  271. {
  272. $referentialConstraintsTableName = 'information_schema.referential_constraints';
  273. $keyColumnUsageTableName = 'information_schema.key_column_usage';
  274. if ($table->catalogName !== null) {
  275. $referentialConstraintsTableName = $table->catalogName . '.' . $referentialConstraintsTableName;
  276. $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
  277. }
  278. $referentialConstraintsTableName = $this->quoteTableName($referentialConstraintsTableName);
  279. $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
  280. // please refer to the following page for more details:
  281. // http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
  282. $sql = <<<SQL
  283. SELECT
  284. [kcu1].[column_name] AS [fk_column_name],
  285. [kcu2].[table_name] AS [uq_table_name],
  286. [kcu2].[column_name] AS [uq_column_name]
  287. FROM {$referentialConstraintsTableName} AS [rc]
  288. JOIN {$keyColumnUsageTableName} AS [kcu1] ON
  289. [kcu1].[constraint_catalog] = [rc].[constraint_catalog] AND
  290. [kcu1].[constraint_schema] = [rc].[constraint_schema] AND
  291. [kcu1].[constraint_name] = [rc].[constraint_name]
  292. JOIN {$keyColumnUsageTableName} AS [kcu2] ON
  293. [kcu2].[constraint_catalog] = [rc].[constraint_catalog] AND
  294. [kcu2].[constraint_schema] = [rc].[constraint_schema] AND
  295. [kcu2].[constraint_name] = [rc].[constraint_name] AND
  296. [kcu2].[ordinal_position] = [kcu1].[ordinal_position]
  297. WHERE [kcu1].[table_name] = :tableName
  298. SQL;
  299. $rows = $this->db->createCommand($sql, [':tableName' => $table->name])->queryAll();
  300. $table->foreignKeys = [];
  301. foreach ($rows as $row) {
  302. $table->foreignKeys[] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']];
  303. }
  304. }
  305. /**
  306. * Returns all table names in the database.
  307. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  308. * @return array all table names in the database. The names have NO schema name prefix.
  309. */
  310. protected function findTableNames($schema = '')
  311. {
  312. if ($schema === '') {
  313. $schema = $this->defaultSchema;
  314. }
  315. $sql = <<<SQL
  316. SELECT [t].[table]
  317. FROM [information_schema].[tables] AS [t]
  318. WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'BASE TABLE'
  319. SQL;
  320. return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
  321. }
  322. }