Passed
Pull Request — 2.2 (#20040)
by Wilmer
05:12
created

Schema::findTableNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 13
ccs 0
cts 6
cp 0
crap 6
rs 9.9666
c 0
b 0
f 0
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
        $column = $this->createColumnSchema();
379
380
        $column->name = $info['column_name'];
381
        $column->allowNull = $info['is_nullable'] === 'YES';
382
        $column->dbType = $info['data_type'];
383
        $column->enumValues = []; // mssql has only vague equivalents to enum
384
        $column->isPrimaryKey = null; // primary key will be determined in findColumns() method
385
        $column->autoIncrement = $info['is_identity'] == 1;
386
        $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...
387
        $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
388
        $column->comment = $info['comment'] === null ? '' : $info['comment'];
389
        $column->type = self::TYPE_STRING;
390
391
        if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
392
            $type = $matches[1];
393
394
            if (isset($this->typeMap[$type])) {
395
                $column->type = $this->typeMap[$type];
396
            }
397
398
            if ($type === 'bit') {
399
                $column->type = 'boolean';
400
            }
401
402
            if (!empty($matches[2])) {
403
                $values = explode(',', $matches[2]);
404
                $column->size = $column->precision = (int) $values[0];
405
406
                if (isset($values[1])) {
407
                    $column->scale = (int) $values[1];
408
                }
409
            }
410
        }
411
412
        $column->phpType = $this->getColumnPhpType($column);
413
414
        if ($info['column_default'] === '(NULL)') {
415
            $info['column_default'] = null;
416
        }
417
        if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
418
            $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

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