Schema.php 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\db\mssql;

use yii\db\ColumnSchema;

/**
13
 * Schema is the class for retrieving metadata from a MS SQL Server databases (version 2008 and above).
14 15 16 17 18 19 20
 *
 * @author Timur Ruziev <resurtm@gmail.com>
 * @since 2.0
 */
class Schema extends \yii\db\Schema
{
	/**
21
	 * @var string the default schema used for the current session.
22
	 */
23
	public $defaultSchema = 'dbo';
24 25 26
	/**
	 * @var array mapping from physical column types (keys) to abstract column types (values)
	 */
Alexander Makarov committed
27
	public $typeMap = [
28
		// exact numbers
29 30
		'bigint' => self::TYPE_BIGINT,
		'numeric' => self::TYPE_DECIMAL,
31 32
		'bit' => self::TYPE_SMALLINT,
		'smallint' => self::TYPE_SMALLINT,
33 34
		'decimal' => self::TYPE_DECIMAL,
		'smallmoney' => self::TYPE_MONEY,
35
		'int' => self::TYPE_INTEGER,
36 37 38
		'tinyint' => self::TYPE_SMALLINT,
		'money' => self::TYPE_MONEY,

39
		// approximate numbers
40 41
		'float' => self::TYPE_FLOAT,
		'real' => self::TYPE_FLOAT,
42 43

		// date and time
44
		'date' => self::TYPE_DATE,
45 46 47 48
		'datetimeoffset' => self::TYPE_DATETIME,
		'datetime2' => self::TYPE_DATETIME,
		'smalldatetime' => self::TYPE_DATETIME,
		'datetime' => self::TYPE_DATETIME,
49
		'time' => self::TYPE_TIME,
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

		// character strings
		'char' => self::TYPE_STRING,
		'varchar' => self::TYPE_STRING,
		'text' => self::TYPE_TEXT,

		// unicode character strings
		'nchar' => self::TYPE_STRING,
		'nvarchar' => self::TYPE_STRING,
		'ntext' => self::TYPE_TEXT,

		// binary strings
		'binary' => self::TYPE_BINARY,
		'varbinary' => self::TYPE_BINARY,
		'image' => self::TYPE_BINARY,

		// other data types
		// 'cursor' type cannot be used with tables
68
		'timestamp' => self::TYPE_TIMESTAMP,
69 70 71 72 73
		'hierarchyid' => self::TYPE_STRING,
		'uniqueidentifier' => self::TYPE_STRING,
		'sql_variant' => self::TYPE_STRING,
		'xml' => self::TYPE_STRING,
		'table' => self::TYPE_STRING,
Alexander Makarov committed
74
	];
75 76 77 78 79 80 81 82 83

	/**
	 * Quotes a table name for use in a query.
	 * A simple table name has no schema prefix.
	 * @param string $name table name.
	 * @return string the properly quoted table name.
	 */
	public function quoteSimpleTableName($name)
	{
84
		return strpos($name, '[') === false ? "[{$name}]" : $name;
85 86 87 88 89 90 91 92 93 94
	}

	/**
	 * Quotes a column name for use in a query.
	 * A simple column name has no prefix.
	 * @param string $name column name.
	 * @return string the properly quoted column name.
	 */
	public function quoteSimpleColumnName($name)
	{
95
		return strpos($name, '[') === false && $name !== '*' ? "[{$name}]" : $name;
96 97 98 99 100 101 102 103 104 105 106 107 108 109
	}

	/**
	 * Creates a query builder for the MSSQL database.
	 * @return QueryBuilder query builder interface.
	 */
	public function createQueryBuilder()
	{
		return new QueryBuilder($this->db);
	}

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
110
	 * @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
111 112 113 114 115 116 117
	 */
	public function loadTableSchema($name)
	{
		$table = new TableSchema();
		$this->resolveTableNames($table, $name);
		$this->findPrimaryKeys($table);
		if ($this->findColumns($table)) {
118
			$this->findForeignKeys($table);
119
			return $table;
120 121
		} else {
			return null;
122 123 124
		}
	}

125 126 127 128 129 130 131
	/**
	 * Resolves the table name and schema name (if any).
	 * @param TableSchema $table the table metadata object
	 * @param string $name the table name
	 */
	protected function resolveTableNames($table, $name)
	{
Alexander Makarov committed
132
		$parts = explode('.', str_replace(['[', ']'], '', $name));
133 134
		$partCount = count($parts);
		if ($partCount == 3) {
135
			// catalog name, schema name and table name passed
136 137 138
			$table->catalogName = $parts[0];
			$table->schemaName = $parts[1];
			$table->name = $parts[2];
139
			$table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
140
		} elseif ($partCount == 2) {
141
			// only schema name and table name passed
142 143
			$table->schemaName = $parts[0];
			$table->name = $parts[1];
144
			$table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
145
		} else {
146 147 148
			// only table name passed
			$table->schemaName = $this->defaultSchema;
			$table->fullName = $table->name = $parts[0];
149 150 151 152 153 154 155 156 157 158 159 160
		}
	}

	/**
	 * Loads the column information into a [[ColumnSchema]] object.
	 * @param array $info column information
	 * @return ColumnSchema the column schema object
	 */
	protected function loadColumnSchema($info)
	{
		$column = new ColumnSchema();

resurtm committed
161 162 163
		$column->name = $info['column_name'];
		$column->allowNull = $info['is_nullable'] == 'YES';
		$column->dbType = $info['data_type'];
Alexander Makarov committed
164
		$column->enumValues = []; // mssql has only vague equivalents to enum
165
		$column->isPrimaryKey = null; // primary key will be determined in findColumns() method
resurtm committed
166
		$column->autoIncrement = $info['is_identity'] == 1;
167
		$column->unsigned = stripos($column->dbType, 'unsigned') !== false;
resurtm committed
168
		$column->comment = $info['comment'] === null ? '' : $info['comment'];
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

		$column->type = self::TYPE_STRING;
		if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
			$type = $matches[1];
			if (isset($this->typeMap[$type])) {
				$column->type = $this->typeMap[$type];
			}
			if (!empty($matches[2])) {
				$values = explode(',', $matches[2]);
				$column->size = $column->precision = (int)$values[0];
				if (isset($values[1])) {
					$column->scale = (int)$values[1];
				}
				if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
					$column->type = 'boolean';
				} elseif ($type === 'bit') {
					if ($column->size > 32) {
						$column->type = 'bigint';
					} elseif ($column->size === 32) {
						$column->type = 'integer';
					}
				}
			}
		}

		$column->phpType = $this->getColumnPhpType($column);

resurtm committed
196 197
		if ($info['column_default'] == '(NULL)') {
			$info['column_default'] = null;
198
		}
resurtm committed
199 200
		if ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP') {
			$column->defaultValue = $column->typecast($info['column_default']);
201 202 203 204 205
		}

		return $column;
	}

206 207 208 209 210 211 212
	/**
	 * Collects the metadata of table columns.
	 * @param TableSchema $table the table metadata
	 * @return boolean whether the table exists in the database
	 */
	protected function findColumns($table)
	{
213 214
		$columnsTableName = 'information_schema.columns';
		$whereSql = "[t1].[table_name] = '{$table->name}'";
215
		if ($table->catalogName !== null) {
216 217
			$columnsTableName = "{$table->catalogName}.{$columnsTableName}";
			$whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
218 219
		}
		if ($table->schemaName !== null) {
220
			$whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
221 222 223 224 225
		}
		$columnsTableName = $this->quoteTableName($columnsTableName);

		$sql = <<<SQL
SELECT
resurtm committed
226 227 228
	[t1].[column_name], [t1].[is_nullable], [t1].[data_type], [t1].[column_default],
	COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
	CONVERT(VARCHAR, [t2].[value]) AS comment
229 230 231 232 233 234 235
FROM {$columnsTableName} AS [t1]
LEFT OUTER JOIN [sys].[extended_properties] AS [t2] ON
	[t1].[ordinal_position] = [t2].[minor_id] AND
	OBJECT_NAME([t2].[major_id]) = [t1].[table_name] AND
	[t2].[class] = 1 AND
	[t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
	[t2].[name] = 'MS_Description'
236 237 238 239 240 241 242 243 244 245
WHERE {$whereSql}
SQL;

		try {
			$columns = $this->db->createCommand($sql)->queryAll();
		} catch (\Exception $e) {
			return false;
		}
		foreach ($columns as $column) {
			$column = $this->loadColumnSchema($column);
246 247 248 249
			foreach ($table->primaryKey as $primaryKey) {
				if (strcasecmp($column->name, $primaryKey) === 0) {
					$column->isPrimaryKey = true;
					break;
250
				}
251 252 253 254
			}
			if ($column->isPrimaryKey && $column->autoIncrement) {
				$table->sequenceName = '';
			}
255
			$table->columns[$column->name] = $column;
256 257 258 259 260 261 262 263 264 265
		}
		return true;
	}

	/**
	 * Collects the primary key column details for the given table.
	 * @param TableSchema $table the table metadata
	 */
	protected function findPrimaryKeys($table)
	{
266 267
		$keyColumnUsageTableName = 'information_schema.key_column_usage';
		$tableConstraintsTableName = 'information_schema.table_constraints';
268 269 270 271 272 273 274 275 276
		if ($table->catalogName !== null) {
			$keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
			$tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
		}
		$keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
		$tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);

		$sql = <<<SQL
SELECT
277 278 279 280 281
	[kcu].[column_name] AS [field_name]
FROM {$keyColumnUsageTableName} AS [kcu]
LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
	[kcu].[table_name] = [tc].[table_name] AND
	[kcu].[constraint_name] = [tc].[constraint_name]
282
WHERE
283 284 285
	[tc].[constraint_type] = 'PRIMARY KEY' AND
	[kcu].[table_name] = :tableName AND
	[kcu].[table_schema] = :schemaName
286 287 288
SQL;

		$table->primaryKey = $this->db
Alexander Makarov committed
289
			->createCommand($sql, [':tableName' => $table->name, ':schemaName' => $table->schemaName])
290 291 292 293 294 295 296
			->queryColumn();
	}

	/**
	 * Collects the foreign key column details for the given table.
	 * @param TableSchema $table the table metadata
	 */
297
	protected function findForeignKeys($table)
298
	{
299 300
		$referentialConstraintsTableName = 'information_schema.referential_constraints';
		$keyColumnUsageTableName = 'information_schema.key_column_usage';
301 302 303 304 305 306 307 308 309 310 311
		if ($table->catalogName !== null) {
			$referentialConstraintsTableName = $table->catalogName . '.' . $referentialConstraintsTableName;
			$keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
		}
		$referentialConstraintsTableName = $this->quoteTableName($referentialConstraintsTableName);
		$keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);

		// please refer to the following page for more details:
		// http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
		$sql = <<<SQL
SELECT
312 313 314 315 316 317 318 319 320 321 322 323 324 325
	[kcu1].[column_name] AS [fk_column_name],
	[kcu2].[table_name] AS [uq_table_name],
	[kcu2].[column_name] AS [uq_column_name]
FROM {$referentialConstraintsTableName} AS [rc]
JOIN {$keyColumnUsageTableName} AS [kcu1] ON
	[kcu1].[constraint_catalog] = [rc].[constraint_catalog] AND
	[kcu1].[constraint_schema] = [rc].[constraint_schema] AND
	[kcu1].[constraint_name] = [rc].[constraint_name]
JOIN {$keyColumnUsageTableName} AS [kcu2] ON
	[kcu2].[constraint_catalog] = [rc].[constraint_catalog] AND
	[kcu2].[constraint_schema] = [rc].[constraint_schema] AND
	[kcu2].[constraint_name] = [rc].[constraint_name] AND
	[kcu2].[ordinal_position] = [kcu1].[ordinal_position]
WHERE [kcu1].[table_name] = :tableName
326 327
SQL;

Alexander Makarov committed
328 329
		$rows = $this->db->createCommand($sql, [':tableName' => $table->name])->queryAll();
		$table->foreignKeys = [];
330
		foreach ($rows as $row) {
Alexander Makarov committed
331
			$table->foreignKeys[] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']];
332 333 334 335 336 337
		}
	}

	/**
	 * Returns all table names in the database.
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
338
	 * @return array all table names in the database. The names have NO schema name prefix.
339 340 341
	 */
	protected function findTableNames($schema = '')
	{
342
		if ($schema === '') {
343
			$schema = $this->defaultSchema;
344
		}
345 346

		$sql = <<<SQL
347 348 349
SELECT [t].[table]
FROM [information_schema].[tables] AS [t]
WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'BASE TABLE'
350 351
SQL;

352
		return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
353 354
	}
}