Schema   F
last analyzed

Complexity

Total Complexity 95

Size/Duplication

Total Lines 799
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 428
c 1
b 0
f 0
dl 0
loc 799
ccs 0
cts 314
cp 0
rs 2
wmc 95

28 Methods

Rating   Name   Duplication   Size   Complexity  
A findSchemaNames() 0 11 1
A findTableNames() 0 13 2
A loadTableIndexes() 0 34 2
A loadTableUniques() 0 3 1
A releaseSavepoint() 0 2 1
A createSavepoint() 0 3 1
A loadTableChecks() 0 3 1
A loadTableSchema() 0 11 2
A loadTablePrimaryKey() 0 3 1
A getSchemaMetadata() 0 18 4
A resolveTableName() 0 29 5
A createQueryBuilder() 0 3 1
A resolveTableNames() 0 25 5
A rollBackSavepoint() 0 3 1
A getTableNameParts() 0 11 4
A loadTableDefaultValues() 0 3 1
A loadTableForeignKeys() 0 3 1
A findTableConstraints() 0 33 2
B insert() 0 27 7
A findViewNames() 0 14 2
C loadTableConstraints() 0 103 9
A findPrimaryKeys() 0 7 2
F loadColumnSchema() 0 59 19
A createColumnSchemaBuilder() 0 3 1
A findUniqueIndexes() 0 8 2
A findForeignKeys() 0 42 5
A quoteColumnName() 0 7 2
B findColumns() 0 66 10

How to fix   Complexity   

Complex Class

Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.

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
8
namespace yii\db\mssql;
9
10
use Yii;
11
use yii\db\CheckConstraint;
12
use yii\db\Constraint;
13
use yii\db\ConstraintFinderInterface;
14
use yii\db\ConstraintFinderTrait;
15
use yii\db\DefaultValueConstraint;
16
use yii\db\ForeignKeyConstraint;
17
use yii\db\IndexConstraint;
18
use yii\db\ViewFinderTrait;
19
use yii\helpers\ArrayHelper;
20
21
/**
22
 * Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
23
 *
24
 * @author Timur Ruziev <[email protected]>
25
 * @since 2.0
26
 */
27
class Schema extends \yii\db\Schema implements ConstraintFinderInterface
28
{
29
    use ViewFinderTrait;
30
    use ConstraintFinderTrait;
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public $columnSchemaClass = 'yii\db\mssql\ColumnSchema';
36
    /**
37
     * @var string the default schema used for the current session.
38
     */
39
    public $defaultSchema = 'dbo';
40
    /**
41
     * @var array mapping from physical column types (keys) to abstract column types (values)
42
     */
43
    public $typeMap = [
44
        // exact numbers
45
        'bigint' => self::TYPE_BIGINT,
46
        'numeric' => self::TYPE_DECIMAL,
47
        'bit' => self::TYPE_SMALLINT,
48
        'smallint' => self::TYPE_SMALLINT,
49
        'decimal' => self::TYPE_DECIMAL,
50
        'smallmoney' => self::TYPE_MONEY,
51
        'int' => self::TYPE_INTEGER,
52
        'tinyint' => self::TYPE_TINYINT,
53
        'money' => self::TYPE_MONEY,
54
        // approximate numbers
55
        'float' => self::TYPE_FLOAT,
56
        'double' => self::TYPE_DOUBLE,
57
        'real' => self::TYPE_FLOAT,
58
        // date and time
59
        'date' => self::TYPE_DATE,
60
        'datetimeoffset' => self::TYPE_DATETIME,
61
        'datetime2' => self::TYPE_DATETIME,
62
        'smalldatetime' => self::TYPE_DATETIME,
63
        'datetime' => self::TYPE_DATETIME,
64
        'time' => self::TYPE_TIME,
65
        // character strings
66
        'char' => self::TYPE_CHAR,
67
        'varchar' => self::TYPE_STRING,
68
        'text' => self::TYPE_TEXT,
69
        // unicode character strings
70
        'nchar' => self::TYPE_CHAR,
71
        'nvarchar' => self::TYPE_STRING,
72
        'ntext' => self::TYPE_TEXT,
73
        // binary strings
74
        'binary' => self::TYPE_BINARY,
75
        'varbinary' => self::TYPE_BINARY,
76
        'image' => self::TYPE_BINARY,
77
        // other data types
78
        // 'cursor' type cannot be used with tables
79
        'timestamp' => self::TYPE_TIMESTAMP,
80
        'hierarchyid' => self::TYPE_STRING,
81
        'uniqueidentifier' => self::TYPE_STRING,
82
        'sql_variant' => self::TYPE_STRING,
83
        'xml' => self::TYPE_STRING,
84
        'table' => self::TYPE_STRING,
85
    ];
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    protected $tableQuoteCharacter = ['[', ']'];
91
    /**
92
     * {@inheritdoc}
93
     */
94
    protected $columnQuoteCharacter = ['[', ']'];
95
96
97
    /**
98
     * Resolves the table name and schema name (if any).
99
     * @param string $name the table name
100
     * @return TableSchema resolved table, schema, etc. names.
101
     */
102
    protected function resolveTableName($name)
103
    {
104
        $resolvedName = new TableSchema();
105
        $parts = $this->getTableNameParts($name);
106
        $partCount = count($parts);
107
        if ($partCount === 4) {
108
            // server name, catalog name, schema name and table name passed
109
            $resolvedName->catalogName = $parts[1];
110
            $resolvedName->schemaName = $parts[2];
111
            $resolvedName->name = $parts[3];
112
            $resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
113
        } elseif ($partCount === 3) {
114
            // catalog name, schema name and table name passed
115
            $resolvedName->catalogName = $parts[0];
116
            $resolvedName->schemaName = $parts[1];
117
            $resolvedName->name = $parts[2];
118
            $resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
119
        } elseif ($partCount === 2) {
120
            // only schema name and table name passed
121
            $resolvedName->schemaName = $parts[0];
122
            $resolvedName->name = $parts[1];
123
            $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
124
        } else {
125
            // only table name passed
126
            $resolvedName->schemaName = $this->defaultSchema;
127
            $resolvedName->fullName = $resolvedName->name = $parts[0];
128
        }
129
130
        return $resolvedName;
131
    }
132
133
    /**
134
     * {@inheritDoc}
135
     * @param string $name
136
     * @return array
137
     * @since 2.0.22
138
     */
139
    protected function getTableNameParts($name)
140
    {
141
        $parts = [$name];
142
        preg_match_all('/([^.\[\]]+)|\[([^\[\]]+)\]/', $name, $matches);
143
        if (isset($matches[0]) && is_array($matches[0]) && !empty($matches[0])) {
144
            $parts = $matches[0];
145
        }
146
147
        $parts = str_replace(['[', ']'], '', $parts);
148
149
        return $parts;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     * @see https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-principals-transact-sql
155
     */
156
    protected function findSchemaNames()
157
    {
158
        static $sql = <<<'SQL'
159
SELECT [s].[name]
160
FROM [sys].[schemas] AS [s]
161
INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
162
WHERE [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
163
ORDER BY [s].[name] ASC
164
SQL;
165
166
        return $this->db->createCommand($sql)->queryColumn();
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    protected function findTableNames($schema = '')
173
    {
174
        if ($schema === '') {
175
            $schema = $this->defaultSchema;
176
        }
177
178
        $sql = <<<'SQL'
179
SELECT [t].[table_name]
180
FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
181
WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
182
ORDER BY [t].[table_name]
183
SQL;
184
        return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190
    protected function loadTableSchema($name)
191
    {
192
        $table = new TableSchema();
193
        $this->resolveTableNames($table, $name);
194
        $this->findPrimaryKeys($table);
195
        if ($this->findColumns($table)) {
196
            $this->findForeignKeys($table);
197
            return $table;
198
        }
199
200
        return null;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    protected function getSchemaMetadata($schema, $type, $refresh)
207
    {
208
        $metadata = [];
209
        $methodName = 'getTable' . ucfirst($type);
210
        $tableNames = array_map(function ($table) {
211
            return $this->quoteSimpleTableName($table);
212
        }, $this->getTableNames($schema, $refresh));
213
        foreach ($tableNames as $name) {
214
            if ($schema !== '') {
215
                $name = $schema . '.' . $name;
216
            }
217
            $tableMetadata = $this->$methodName($name, $refresh);
218
            if ($tableMetadata !== null) {
219
                $metadata[] = $tableMetadata;
220
            }
221
        }
222
223
        return $metadata;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    protected function loadTablePrimaryKey($tableName)
230
    {
231
        return $this->loadTableConstraints($tableName, 'primaryKey');
232
    }
233
234
    /**
235
     * {@inheritdoc}
236
     */
237
    protected function loadTableForeignKeys($tableName)
238
    {
239
        return $this->loadTableConstraints($tableName, 'foreignKeys');
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    protected function loadTableIndexes($tableName)
246
    {
247
        static $sql = <<<'SQL'
248
SELECT
249
    [i].[name] AS [name],
250
    [iccol].[name] AS [column_name],
251
    [i].[is_unique] AS [index_is_unique],
252
    [i].[is_primary_key] AS [index_is_primary]
253
FROM [sys].[indexes] AS [i]
254
INNER JOIN [sys].[index_columns] AS [ic]
255
    ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
256
INNER JOIN [sys].[columns] AS [iccol]
257
    ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
258
WHERE [i].[object_id] = OBJECT_ID(:fullName)
259
ORDER BY [ic].[key_ordinal] ASC
260
SQL;
261
262
        $resolvedName = $this->resolveTableName($tableName);
263
        $indexes = $this->db->createCommand($sql, [
264
            ':fullName' => $resolvedName->fullName,
265
        ])->queryAll();
266
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
267
        $indexes = ArrayHelper::index($indexes, null, 'name');
268
        $result = [];
269
        foreach ($indexes as $name => $index) {
270
            $result[] = new IndexConstraint([
271
                'isPrimary' => (bool)$index[0]['index_is_primary'],
272
                'isUnique' => (bool)$index[0]['index_is_unique'],
273
                'name' => $name,
274
                'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
275
            ]);
276
        }
277
278
        return $result;
279
    }
280
281
    /**
282
     * {@inheritdoc}
283
     */
284
    protected function loadTableUniques($tableName)
285
    {
286
        return $this->loadTableConstraints($tableName, 'uniques');
287
    }
288
289
    /**
290
     * {@inheritdoc}
291
     */
292
    protected function loadTableChecks($tableName)
293
    {
294
        return $this->loadTableConstraints($tableName, 'checks');
295
    }
296
297
    /**
298
     * {@inheritdoc}
299
     */
300
    protected function loadTableDefaultValues($tableName)
301
    {
302
        return $this->loadTableConstraints($tableName, 'defaults');
303
    }
304
305
    /**
306
     * {@inheritdoc}
307
     */
308
    public function createSavepoint($name)
309
    {
310
        $this->db->createCommand("SAVE TRANSACTION $name")->execute();
311
    }
312
313
    /**
314
     * {@inheritdoc}
315
     */
316
    public function releaseSavepoint($name)
317
    {
318
        // does nothing as MSSQL does not support this
319
    }
320
321
    /**
322
     * {@inheritdoc}
323
     */
324
    public function rollBackSavepoint($name)
325
    {
326
        $this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
327
    }
328
329
    /**
330
     * Creates a query builder for the MSSQL database.
331
     * @return QueryBuilder query builder interface.
332
     */
333
    public function createQueryBuilder()
334
    {
335
        return Yii::createObject(QueryBuilder::class, [$this->db]);
336
    }
337
338
    /**
339
     * Resolves the table name and schema name (if any).
340
     * @param TableSchema $table the table metadata object
341
     * @param string $name the table name
342
     */
343
    protected function resolveTableNames($table, $name)
344
    {
345
        $parts = $this->getTableNameParts($name);
346
        $partCount = count($parts);
347
        if ($partCount === 4) {
348
            // server name, catalog name, schema name and table name passed
349
            $table->catalogName = $parts[1];
350
            $table->schemaName = $parts[2];
351
            $table->name = $parts[3];
352
            $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
353
        } elseif ($partCount === 3) {
354
            // catalog name, schema name and table name passed
355
            $table->catalogName = $parts[0];
356
            $table->schemaName = $parts[1];
357
            $table->name = $parts[2];
358
            $table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
359
        } elseif ($partCount === 2) {
360
            // only schema name and table name passed
361
            $table->schemaName = $parts[0];
362
            $table->name = $parts[1];
363
            $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
364
        } else {
365
            // only table name passed
366
            $table->schemaName = $this->defaultSchema;
367
            $table->fullName = $table->name = $parts[0];
368
        }
369
    }
370
371
    /**
372
     * Loads the column information into a [[ColumnSchema]] object.
373
     * @param array $info column information
374
     * @return ColumnSchema the column schema object
375
     */
376
    protected function loadColumnSchema($info)
377
    {
378
        $isVersion2017orLater = version_compare($this->db->getSchema()->getServerVersion(), '14', '>=');
379
        $column = $this->createColumnSchema();
380
381
        $column->name = $info['column_name'];
382
        $column->allowNull = $info['is_nullable'] === 'YES';
383
        $column->dbType = $info['data_type'];
384
        $column->enumValues = []; // mssql has only vague equivalents to enum
385
        $column->isPrimaryKey = null; // primary key will be determined in findColumns() method
386
        $column->autoIncrement = $info['is_identity'] == 1;
387
        $column->isComputed = (bool)$info['is_computed'];
0 ignored issues
show
Bug Best Practice introduced by
The property isComputed does not exist on yii\db\ColumnSchema. Since you implemented __set, consider adding a @property annotation.
Loading history...
388
        $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
389
        $column->comment = $info['comment'] === null ? '' : $info['comment'];
390
        $column->type = self::TYPE_STRING;
391
392
        if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
393
            $type = $matches[1];
394
395
            if (isset($this->typeMap[$type])) {
396
                $column->type = $this->typeMap[$type];
397
            }
398
399
            if ($isVersion2017orLater && $type === 'bit') {
400
                $column->type = 'boolean';
401
            }
402
403
            if (!empty($matches[2])) {
404
                $values = explode(',', $matches[2]);
405
                $column->size = $column->precision = (int) $values[0];
406
407
                if (isset($values[1])) {
408
                    $column->scale = (int) $values[1];
409
                }
410
411
                if ($isVersion2017orLater === false) {
412
                    if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
413
                        $column->type = 'boolean';
414
                    } elseif ($type === 'bit') {
415
                        if ($column->size > 32) {
416
                            $column->type = 'bigint';
417
                        } elseif ($column->size === 32) {
418
                            $column->type = 'integer';
419
                        }
420
                    }
421
                }
422
            }
423
        }
424
425
        $column->phpType = $this->getColumnPhpType($column);
426
427
        if ($info['column_default'] === '(NULL)') {
428
            $info['column_default'] = null;
429
        }
430
        if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
431
            $column->defaultValue = $column->defaultPhpTypecast($info['column_default']);
0 ignored issues
show
Bug introduced by
The method defaultPhpTypecast() does not exist on yii\db\ColumnSchema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

431
            /** @scrutinizer ignore-call */ 
432
            $column->defaultValue = $column->defaultPhpTypecast($info['column_default']);
Loading history...
432
        }
433
434
        return $column;
435
    }
436
437
    /**
438
     * Collects the metadata of table columns.
439
     * @param TableSchema $table the table metadata
440
     * @return bool whether the table exists in the database
441
     */
442
    protected function findColumns($table)
443
    {
444
        $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
445
        $whereSql = '[t1].[table_name] = ' . $this->db->quoteValue($table->name);
446
        if ($table->catalogName !== null) {
447
            $columnsTableName = "{$table->catalogName}.{$columnsTableName}";
448
            $whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
449
        }
450
        if ($table->schemaName !== null) {
451
            $whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
452
        }
453
        $columnsTableName = $this->quoteTableName($columnsTableName);
454
455
        $sql = <<<SQL
456
SELECT
457
 [t1].[column_name],
458
 [t1].[is_nullable],
459
 CASE WHEN [t1].[data_type] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
460
    CASE WHEN [t1].[character_maximum_length] = NULL OR [t1].[character_maximum_length] = -1 THEN
461
        [t1].[data_type]
462
    ELSE
463
        [t1].[data_type] + '(' + LTRIM(RTRIM(CONVERT(CHAR,[t1].[character_maximum_length]))) + ')'
464
    END
465
 ELSE
466
    [t1].[data_type]
467
 END AS 'data_type',
468
 [t1].[column_default],
469
 COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
470
 COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsComputed') AS is_computed,
471
 (
472
    SELECT CONVERT(VARCHAR, [t2].[value])
473
		FROM [sys].[extended_properties] AS [t2]
474
		WHERE
475
			[t2].[class] = 1 AND
476
			[t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
477
			[t2].[name] = 'MS_Description' AND
478
			[t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
479
			[t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
480
 ) as comment
481
FROM {$columnsTableName} AS [t1]
482
WHERE {$whereSql}
483
SQL;
484
485
        try {
486
            $columns = $this->db->createCommand($sql)->queryAll();
487
            if (empty($columns)) {
488
                return false;
489
            }
490
        } catch (\Exception $e) {
491
            return false;
492
        }
493
        foreach ($columns as $column) {
494
            $column = $this->loadColumnSchema($column);
495
            foreach ($table->primaryKey as $primaryKey) {
496
                if (strcasecmp($column->name, $primaryKey) === 0) {
497
                    $column->isPrimaryKey = true;
498
                    break;
499
                }
500
            }
501
            if ($column->isPrimaryKey && $column->autoIncrement) {
502
                $table->sequenceName = '';
503
            }
504
            $table->columns[$column->name] = $column;
505
        }
506
507
        return true;
508
    }
509
510
    /**
511
     * Collects the constraint details for the given table and constraint type.
512
     * @param TableSchema $table
513
     * @param string $type either PRIMARY KEY or UNIQUE
514
     * @return array each entry contains index_name and field_name
515
     * @since 2.0.4
516
     */
517
    protected function findTableConstraints($table, $type)
518
    {
519
        $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
520
        $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
521
        if ($table->catalogName !== null) {
522
            $keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
523
            $tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
524
        }
525
        $keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
526
        $tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
527
528
        $sql = <<<SQL
529
SELECT
530
    [kcu].[constraint_name] AS [index_name],
531
    [kcu].[column_name] AS [field_name]
532
FROM {$keyColumnUsageTableName} AS [kcu]
533
LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
534
    [kcu].[table_schema] = [tc].[table_schema] AND
535
    [kcu].[table_name] = [tc].[table_name] AND
536
    [kcu].[constraint_name] = [tc].[constraint_name]
537
WHERE
538
    [tc].[constraint_type] = :type AND
539
    [kcu].[table_name] = :tableName AND
540
    [kcu].[table_schema] = :schemaName
541
SQL;
542
543
        return $this->db
544
            ->createCommand($sql, [
545
                ':tableName' => $table->name,
546
                ':schemaName' => $table->schemaName,
547
                ':type' => $type,
548
            ])
549
            ->queryAll();
550
    }
551
552
    /**
553
     * Collects the primary key column details for the given table.
554
     * @param TableSchema $table the table metadata
555
     */
556
    protected function findPrimaryKeys($table)
557
    {
558
        $result = [];
559
        foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
560
            $result[] = $row['field_name'];
561
        }
562
        $table->primaryKey = $result;
563
    }
564
565
    /**
566
     * Collects the foreign key column details for the given table.
567
     * @param TableSchema $table the table metadata
568
     */
569
    protected function findForeignKeys($table)
570
    {
571
        $object = $table->name;
572
        if ($table->schemaName !== null) {
573
            $object = $table->schemaName . '.' . $object;
574
        }
575
        if ($table->catalogName !== null) {
576
            $object = $table->catalogName . '.' . $object;
577
        }
578
579
        // please refer to the following page for more details:
580
        // http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
581
        $sql = <<<'SQL'
582
SELECT
583
	[fk].[name] AS [fk_name],
584
	[cp].[name] AS [fk_column_name],
585
	OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
586
	[cr].[name] AS [uq_column_name]
587
FROM
588
	[sys].[foreign_keys] AS [fk]
589
	INNER JOIN [sys].[foreign_key_columns] AS [fkc] ON
590
		[fk].[object_id] = [fkc].[constraint_object_id]
591
	INNER JOIN [sys].[columns] AS [cp] ON
592
		[fk].[parent_object_id] = [cp].[object_id] AND
593
		[fkc].[parent_column_id] = [cp].[column_id]
594
	INNER JOIN [sys].[columns] AS [cr] ON
595
		[fk].[referenced_object_id] = [cr].[object_id] AND
596
		[fkc].[referenced_column_id] = [cr].[column_id]
597
WHERE
598
	[fk].[parent_object_id] = OBJECT_ID(:object)
599
SQL;
600
601
        $rows = $this->db->createCommand($sql, [
602
            ':object' => $object,
603
        ])->queryAll();
604
605
        $table->foreignKeys = [];
606
        foreach ($rows as $row) {
607
            if (!isset($table->foreignKeys[$row['fk_name']])) {
608
                $table->foreignKeys[$row['fk_name']][] = $row['uq_table_name'];
609
            }
610
            $table->foreignKeys[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
611
        }
612
    }
613
614
    /**
615
     * {@inheritdoc}
616
     */
617
    protected function findViewNames($schema = '')
618
    {
619
        if ($schema === '') {
620
            $schema = $this->defaultSchema;
621
        }
622
623
        $sql = <<<'SQL'
624
SELECT [t].[table_name]
625
FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
626
WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
627
ORDER BY [t].[table_name]
628
SQL;
629
630
        return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
631
    }
632
633
    /**
634
     * Returns all unique indexes for the given table.
635
     *
636
     * Each array element is of the following structure:
637
     *
638
     * ```php
639
     * [
640
     *     'IndexName1' => ['col1' [, ...]],
641
     *     'IndexName2' => ['col2' [, ...]],
642
     * ]
643
     * ```
644
     *
645
     * @param TableSchema $table the table metadata
646
     * @return array all unique indexes for the given table.
647
     * @since 2.0.4
648
     */
649
    public function findUniqueIndexes($table)
650
    {
651
        $result = [];
652
        foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
653
            $result[$row['index_name']][] = $row['field_name'];
654
        }
655
656
        return $result;
657
    }
658
659
    /**
660
     * Loads multiple types of constraints and returns the specified ones.
661
     * @param string $tableName table name.
662
     * @param string $returnType return type:
663
     * - primaryKey
664
     * - foreignKeys
665
     * - uniques
666
     * - checks
667
     * - defaults
668
     * @return mixed constraints.
669
     */
670
    private function loadTableConstraints($tableName, $returnType)
671
    {
672
        static $sql = <<<'SQL'
673
SELECT
674
    [o].[name] AS [name],
675
    COALESCE([ccol].[name], [dcol].[name], [fccol].[name], [kiccol].[name]) AS [column_name],
676
    RTRIM([o].[type]) AS [type],
677
    OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [foreign_table_schema],
678
    OBJECT_NAME([f].[referenced_object_id]) AS [foreign_table_name],
679
    [ffccol].[name] AS [foreign_column_name],
680
    [f].[update_referential_action_desc] AS [on_update],
681
    [f].[delete_referential_action_desc] AS [on_delete],
682
    [c].[definition] AS [check_expr],
683
    [d].[definition] AS [default_expr]
684
FROM (SELECT OBJECT_ID(:fullName) AS [object_id]) AS [t]
685
INNER JOIN [sys].[objects] AS [o]
686
    ON [o].[parent_object_id] = [t].[object_id] AND [o].[type] IN ('PK', 'UQ', 'C', 'D', 'F')
687
LEFT JOIN [sys].[check_constraints] AS [c]
688
    ON [c].[object_id] = [o].[object_id]
689
LEFT JOIN [sys].[columns] AS [ccol]
690
    ON [ccol].[object_id] = [c].[parent_object_id] AND [ccol].[column_id] = [c].[parent_column_id]
691
LEFT JOIN [sys].[default_constraints] AS [d]
692
    ON [d].[object_id] = [o].[object_id]
693
LEFT JOIN [sys].[columns] AS [dcol]
694
    ON [dcol].[object_id] = [d].[parent_object_id] AND [dcol].[column_id] = [d].[parent_column_id]
695
LEFT JOIN [sys].[key_constraints] AS [k]
696
    ON [k].[object_id] = [o].[object_id]
697
LEFT JOIN [sys].[index_columns] AS [kic]
698
    ON [kic].[object_id] = [k].[parent_object_id] AND [kic].[index_id] = [k].[unique_index_id]
699
LEFT JOIN [sys].[columns] AS [kiccol]
700
    ON [kiccol].[object_id] = [kic].[object_id] AND [kiccol].[column_id] = [kic].[column_id]
701
LEFT JOIN [sys].[foreign_keys] AS [f]
702
    ON [f].[object_id] = [o].[object_id]
703
LEFT JOIN [sys].[foreign_key_columns] AS [fc]
704
    ON [fc].[constraint_object_id] = [o].[object_id]
705
LEFT JOIN [sys].[columns] AS [fccol]
706
    ON [fccol].[object_id] = [fc].[parent_object_id] AND [fccol].[column_id] = [fc].[parent_column_id]
707
LEFT JOIN [sys].[columns] AS [ffccol]
708
    ON [ffccol].[object_id] = [fc].[referenced_object_id] AND [ffccol].[column_id] = [fc].[referenced_column_id]
709
ORDER BY [kic].[key_ordinal] ASC, [fc].[constraint_column_id] ASC
710
SQL;
711
712
        $resolvedName = $this->resolveTableName($tableName);
713
        $constraints = $this->db->createCommand($sql, [
714
            ':fullName' => $resolvedName->fullName,
715
        ])->queryAll();
716
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
717
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
718
        $result = [
719
            'primaryKey' => null,
720
            'foreignKeys' => [],
721
            'uniques' => [],
722
            'checks' => [],
723
            'defaults' => [],
724
        ];
725
        foreach ($constraints as $type => $names) {
726
            foreach ($names as $name => $constraint) {
727
                switch ($type) {
728
                    case 'PK':
729
                        $result['primaryKey'] = new Constraint([
730
                            'name' => $name,
731
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
732
                        ]);
733
                        break;
734
                    case 'F':
735
                        $result['foreignKeys'][] = new ForeignKeyConstraint([
736
                            'name' => $name,
737
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
738
                            'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
739
                            'foreignTableName' => $constraint[0]['foreign_table_name'],
740
                            'foreignColumnNames' => ArrayHelper::getColumn($constraint, 'foreign_column_name'),
741
                            'onDelete' => str_replace('_', '', $constraint[0]['on_delete']),
742
                            'onUpdate' => str_replace('_', '', $constraint[0]['on_update']),
743
                        ]);
744
                        break;
745
                    case 'UQ':
746
                        $result['uniques'][] = new Constraint([
747
                            'name' => $name,
748
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
749
                        ]);
750
                        break;
751
                    case 'C':
752
                        $result['checks'][] = new CheckConstraint([
753
                            'name' => $name,
754
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
755
                            'expression' => $constraint[0]['check_expr'],
756
                        ]);
757
                        break;
758
                    case 'D':
759
                        $result['defaults'][] = new DefaultValueConstraint([
760
                            'name' => $name,
761
                            'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
762
                            'value' => $constraint[0]['default_expr'],
763
                        ]);
764
                        break;
765
                }
766
            }
767
        }
768
        foreach ($result as $type => $data) {
769
            $this->setTableMetadata($tableName, $type, $data);
770
        }
771
772
        return $result[$returnType];
773
    }
774
775
    /**
776
     * {@inheritdoc}
777
     */
778
    public function quoteColumnName($name)
779
    {
780
        if (preg_match('/^\[.*\]$/', $name)) {
781
            return $name;
782
        }
783
784
        return parent::quoteColumnName($name);
785
    }
786
787
    /**
788
     * Retrieving inserted data from a primary key request of type uniqueidentifier (for SQL Server 2005 or later)
789
     * {@inheritdoc}
790
     */
791
    public function insert($table, $columns)
792
    {
793
        $command = $this->db->createCommand()->insert($table, $columns);
794
        if (!$command->execute()) {
795
            return false;
796
        }
797
798
        $isVersion2005orLater = version_compare($this->db->getSchema()->getServerVersion(), '9', '>=');
799
        $inserted = $isVersion2005orLater ? $command->pdoStatement->fetch() : [];
800
801
        $tableSchema = $this->getTableSchema($table);
802
        $result = [];
803
        foreach ($tableSchema->primaryKey as $name) {
804
            // @see https://github.com/yiisoft/yii2/issues/13828 & https://github.com/yiisoft/yii2/issues/17474
805
            if (isset($inserted[$name])) {
806
                $result[$name] = $inserted[$name];
807
            } elseif ($tableSchema->columns[$name]->autoIncrement) {
808
                // for a version earlier than 2005
809
                $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
810
            } elseif (isset($columns[$name])) {
811
                $result[$name] = $columns[$name];
812
            } else {
813
                $result[$name] = $tableSchema->columns[$name]->defaultValue;
814
            }
815
        }
816
817
        return $result;
818
    }
819
820
    /**
821
     * {@inheritdoc}
822
     */
823
    public function createColumnSchemaBuilder($type, $length = null)
824
    {
825
        return Yii::createObject(ColumnSchemaBuilder::class, [$type, $length, $this->db]);
826
    }
827
}
828