|
- <?php
-
-
- namespace yii\db\mssql;
-
- use yii\db\ColumnSchema;
-
-
- class Schema extends \yii\db\Schema
- {
-
-
- public $defaultSchema = 'dbo';
-
-
- public $typeMap = [
-
- 'bigint' => self::TYPE_BIGINT,
- 'numeric' => self::TYPE_DECIMAL,
- 'bit' => self::TYPE_SMALLINT,
- 'smallint' => self::TYPE_SMALLINT,
- 'decimal' => self::TYPE_DECIMAL,
- 'smallmoney' => self::TYPE_MONEY,
- 'int' => self::TYPE_INTEGER,
- 'tinyint' => self::TYPE_SMALLINT,
- 'money' => self::TYPE_MONEY,
-
- 'float' => self::TYPE_FLOAT,
- 'double' => self::TYPE_DOUBLE,
- 'real' => self::TYPE_FLOAT,
-
- 'date' => self::TYPE_DATE,
- 'datetimeoffset' => self::TYPE_DATETIME,
- 'datetime2' => self::TYPE_DATETIME,
- 'smalldatetime' => self::TYPE_DATETIME,
- 'datetime' => self::TYPE_DATETIME,
- 'time' => self::TYPE_TIME,
-
- 'char' => self::TYPE_CHAR,
- 'varchar' => self::TYPE_STRING,
- 'text' => self::TYPE_TEXT,
-
- 'nchar' => self::TYPE_CHAR,
- 'nvarchar' => self::TYPE_STRING,
- 'ntext' => self::TYPE_TEXT,
-
- 'binary' => self::TYPE_BINARY,
- 'varbinary' => self::TYPE_BINARY,
- 'image' => self::TYPE_BINARY,
-
-
- 'timestamp' => self::TYPE_TIMESTAMP,
- 'hierarchyid' => self::TYPE_STRING,
- 'uniqueidentifier' => self::TYPE_STRING,
- 'sql_variant' => self::TYPE_STRING,
- 'xml' => self::TYPE_STRING,
- 'table' => self::TYPE_STRING,
- ];
-
-
-
-
- public function createSavepoint($name)
- {
- $this->db->createCommand("SAVE TRANSACTION $name")->execute();
- }
-
-
-
- public function releaseSavepoint($name)
- {
-
- }
-
-
-
- public function rollBackSavepoint($name)
- {
- $this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
- }
-
-
-
- public function quoteSimpleTableName($name)
- {
- return strpos($name, '[') === false ? "[{$name}]" : $name;
- }
-
-
-
- public function quoteSimpleColumnName($name)
- {
- return strpos($name, '[') === false && $name !== '*' ? "[{$name}]" : $name;
- }
-
-
-
- public function createQueryBuilder()
- {
- return new QueryBuilder($this->db);
- }
-
-
-
- public function loadTableSchema($name)
- {
- $table = new TableSchema();
- $this->resolveTableNames($table, $name);
- $this->findPrimaryKeys($table);
- if ($this->findColumns($table)) {
- $this->findForeignKeys($table);
-
- return $table;
- } else {
- return null;
- }
- }
-
-
-
- protected function resolveTableNames($table, $name)
- {
- $parts = explode('.', str_replace(['[', ']'], '', $name));
- $partCount = count($parts);
- if ($partCount === 4) {
-
- $table->catalogName = $parts[1];
- $table->schemaName = $parts[2];
- $table->name = $parts[3];
- $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
- } elseif ($partCount === 3) {
-
- $table->catalogName = $parts[0];
- $table->schemaName = $parts[1];
- $table->name = $parts[2];
- $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
- } elseif ($partCount === 2) {
-
- $table->schemaName = $parts[0];
- $table->name = $parts[1];
- $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
- } else {
-
- $table->schemaName = $this->defaultSchema;
- $table->fullName = $table->name = $parts[0];
- }
- }
-
-
-
- protected function loadColumnSchema($info)
- {
- $column = $this->createColumnSchema();
-
- $column->name = $info['column_name'];
- $column->allowNull = $info['is_nullable'] === 'YES';
- $column->dbType = $info['data_type'];
- $column->enumValues = [];
- $column->isPrimaryKey = null;
- $column->autoIncrement = $info['is_identity'] == 1;
- $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
- $column->comment = $info['comment'] === null ? '' : $info['comment'];
-
- $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);
-
- if ($info['column_default'] === '(NULL)') {
- $info['column_default'] = null;
- }
- if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
- $column->defaultValue = $column->phpTypecast($info['column_default']);
- }
-
- return $column;
- }
-
-
-
- protected function findColumns($table)
- {
- $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
- $whereSql = "[t1].[table_name] = '{$table->name}'";
- if ($table->catalogName !== null) {
- $columnsTableName = "{$table->catalogName}.{$columnsTableName}";
- $whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
- }
- if ($table->schemaName !== null) {
- $whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
- }
- $columnsTableName = $this->quoteTableName($columnsTableName);
-
- $sql = <<<SQL
- SELECT
- [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
- FROM {$columnsTableName} AS [t1]
- LEFT OUTER JOIN [sys].[extended_properties] AS [t2] ON
- [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID') 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'
- WHERE {$whereSql}
- SQL;
-
- try {
- $columns = $this->db->createCommand($sql)->queryAll();
- if (empty($columns)) {
- return false;
- }
- } catch (\Exception $e) {
- return false;
- }
- foreach ($columns as $column) {
- $column = $this->loadColumnSchema($column);
- foreach ($table->primaryKey as $primaryKey) {
- if (strcasecmp($column->name, $primaryKey) === 0) {
- $column->isPrimaryKey = true;
- break;
- }
- }
- if ($column->isPrimaryKey && $column->autoIncrement) {
- $table->sequenceName = '';
- }
- $table->columns[$column->name] = $column;
- }
-
- return true;
- }
-
-
-
- protected function findTableConstraints($table, $type)
- {
- $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
- $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
- if ($table->catalogName !== null) {
- $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
- $tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
- }
- $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
- $tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
-
- $sql = <<<SQL
- SELECT
- [kcu].[constraint_name] AS [index_name],
- [kcu].[column_name] AS [field_name]
- FROM {$keyColumnUsageTableName} AS [kcu]
- LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
- [kcu].[table_schema] = [tc].[table_schema] AND
- [kcu].[table_name] = [tc].[table_name] AND
- [kcu].[constraint_name] = [tc].[constraint_name]
- WHERE
- [tc].[constraint_type] = :type AND
- [kcu].[table_name] = :tableName AND
- [kcu].[table_schema] = :schemaName
- SQL;
-
- return $this->db
- ->createCommand($sql, [
- ':tableName' => $table->name,
- ':schemaName' => $table->schemaName,
- ':type' => $type,
- ])
- ->queryAll();
- }
-
-
-
- protected function findPrimaryKeys($table)
- {
- $result = [];
- foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
- $result[] = $row['field_name'];
- }
- $table->primaryKey = $result;
- }
-
-
-
- protected function findForeignKeys($table)
- {
- $referentialConstraintsTableName = 'INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS';
- $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
- if ($table->catalogName !== null) {
- $referentialConstraintsTableName = $table->catalogName . '.' . $referentialConstraintsTableName;
- $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
- }
- $referentialConstraintsTableName = $this->quoteTableName($referentialConstraintsTableName);
- $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
-
-
-
- $sql = <<<SQL
- SELECT
- [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].[unique_constraint_name] AND
- [kcu2].[ordinal_position] = [kcu1].[ordinal_position]
- WHERE [kcu1].[table_name] = :tableName AND [kcu1].[table_schema] = :schemaName
- SQL;
-
- $rows = $this->db->createCommand($sql, [
- ':tableName' => $table->name,
- ':schemaName' => $table->schemaName,
- ])->queryAll();
- $table->foreignKeys = [];
- foreach ($rows as $row) {
- $table->foreignKeys[] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']];
- }
- }
-
-
-
- protected function findTableNames($schema = '')
- {
- if ($schema === '') {
- $schema = $this->defaultSchema;
- }
-
- $sql = <<<SQL
- SELECT [t].[table_name]
- FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
- WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
- ORDER BY [t].[table_name]
- SQL;
-
- return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
- }
-
-
-
- public function findUniqueIndexes($table)
- {
- $result = [];
- foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
- $result[$row['index_name']][] = $row['field_name'];
- }
- return $result;
- }
- }
|