Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

Schema::createSavepoint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

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