Test Failed
Pull Request — master (#188)
by Def
15:41 queued 02:37
created

Schema::loadColumnSchema()   F

Complexity

Conditions 18
Paths 276

Size

Total Lines 64
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 19.6314

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 18
eloc 39
nc 276
nop 1
dl 0
loc 64
ccs 29
cts 35
cp 0.8286
crap 19.6314
rs 3.0833
c 4
b 1
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql;
6
7
use Throwable;
8
use Yiisoft\Db\Constraint\CheckConstraint;
9
use Yiisoft\Db\Constraint\Constraint;
10
use Yiisoft\Db\Constraint\DefaultValueConstraint;
11
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
12
use Yiisoft\Db\Constraint\IndexConstraint;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidConfigException;
15
use Yiisoft\Db\Helper\ArrayHelper;
16
use Yiisoft\Db\Schema\AbstractSchema;
17
use Yiisoft\Db\Schema\ColumnSchemaBuilderInterface;
18
use Yiisoft\Db\Schema\ColumnSchemaInterface;
19
use Yiisoft\Db\Schema\TableSchemaInterface;
20
21
use function array_map;
22
use function explode;
23
use function is_array;
24
use function md5;
25
use function preg_match;
26
use function serialize;
27
use function str_replace;
28
use function strcasecmp;
29
use function stripos;
30
31
/**
32
 * Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
33
 *
34
 * @psalm-type ColumnArray = array{
35
 *   column_name: string,
36
 *   is_nullable: string,
37
 *   data_type: string,
38
 *   column_default: mixed,
39
 *   is_identity: string,
40
 *   is_computed: string,
41
 *   comment: null|string
42
 * }
43
 *
44
 * @psalm-type ConstraintArray = array<
45
 *   array-key,
46
 *   array {
47
 *     name: string,
48
 *     column_name: string,
49
 *     type: string,
50
 *     foreign_table_schema: string|null,
51
 *     foreign_table_name: string|null,
52
 *     foreign_column_name: string|null,
53
 *     on_update: string,
54
 *     on_delete: string,
55
 *     check_expr: string,
56
 *     default_expr: string
57
 *   }
58
 * >
59
 */
60
final class Schema extends AbstractSchema
61
{
62
    public const DEFAULTS = 'defaults';
63
64
    /**
65
     * @var string|null the default schema used for the current session.
66
     */
67
    protected string|null $defaultSchema = 'dbo';
68
69
    /**
70
     * @var array mapping from physical column types (keys) to abstract column types (values)
71
     *
72
     * @psalm-var string[]
73
     */
74
    private array $typeMap = [
75
        /** exact numbers */
76
        'bigint' => self::TYPE_BIGINT,
77
        'numeric' => self::TYPE_DECIMAL,
78
        'bit' => self::TYPE_SMALLINT,
79
        'smallint' => self::TYPE_SMALLINT,
80
        'decimal' => self::TYPE_DECIMAL,
81
        'smallmoney' => self::TYPE_MONEY,
82
        'int' => self::TYPE_INTEGER,
83
        'tinyint' => self::TYPE_TINYINT,
84
        'money' => self::TYPE_MONEY,
85
86
        /** approximate numbers */
87
        'float' => self::TYPE_FLOAT,
88
        'double' => self::TYPE_DOUBLE,
89
        'real' => self::TYPE_FLOAT,
90
91
        /** date and time */
92
        'date' => self::TYPE_DATE,
93
        'datetimeoffset' => self::TYPE_DATETIME,
94
        'datetime2' => self::TYPE_DATETIME,
95
        'smalldatetime' => self::TYPE_DATETIME,
96
        'datetime' => self::TYPE_DATETIME,
97
        'time' => self::TYPE_TIME,
98
99
        /** character strings */
100
        'char' => self::TYPE_CHAR,
101
        'varchar' => self::TYPE_STRING,
102
        'text' => self::TYPE_TEXT,
103
104
        /** unicode character strings */
105
        'nchar' => self::TYPE_CHAR,
106
        'nvarchar' => self::TYPE_STRING,
107
        'ntext' => self::TYPE_TEXT,
108
109
        /** binary strings */
110
        'binary' => self::TYPE_BINARY,
111
        'varbinary' => self::TYPE_BINARY,
112
        'image' => self::TYPE_BINARY,
113
114
        /**
115
         * other data types 'cursor' type cannot be used with tables
116
         */
117
        'timestamp' => self::TYPE_TIMESTAMP,
118
        'hierarchyid' => self::TYPE_STRING,
119
        'uniqueidentifier' => self::TYPE_STRING,
120
        'sql_variant' => self::TYPE_STRING,
121
        'xml' => self::TYPE_STRING,
122
        'table' => self::TYPE_STRING,
123
    ];
124
125
    /**
126
     * Resolves the table name and schema name (if any).
127
     *
128
     * @param string $name the table name.
129
     *
130
     * @return TableSchemaInterface resolved table, schema, etc. names.
131
     *
132
     * also see case `wrongBehaviour` in \Yiisoft\Db\TestSupport\TestCommandTrait::batchInsertSqlProviderTrait
133
     */
134 227
    protected function resolveTableName(string $name): TableSchemaInterface
135
    {
136 227
        $resolvedName = new TableSchema();
137
138 227
        $parts = array_reverse(
139 227
            $this->db->getQuoter()->getTableNameParts($name)
140 227
        );
141
142 227
        $resolvedName->name($parts[0] ?? '');
143 227
        $resolvedName->schemaName($parts[1] ?? $this->defaultSchema);
144 227
        $resolvedName->catalogName($parts[2] ?? null);
145 227
        $resolvedName->serverName($parts[3] ?? null);
146
147 227
        if (empty($parts[2]) && $resolvedName->getSchemaName() === $this->defaultSchema) {
148 221
            $resolvedName->fullName($parts[0]);
149
        } else {
150 7
            $resolvedName->fullName(implode('.', array_reverse($parts)));
151
        }
152
153 227
        return $resolvedName;
154
    }
155
156
    /**
157
     * Returns all schema names in the database, including the default one but not system schemas.
158
     *
159
     * This method should be overridden by child classes in order to support this feature because the default
160
     * implementation simply throws an exception.
161
     *
162
     * @throws Exception|InvalidConfigException|Throwable
163
     *
164
     * @return array All schema names in the database, except system schemas.
165
     *
166
     * @link https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-principals-transact-sql
167
     */
168 1
    protected function findSchemaNames(): array
169
    {
170 1
        $sql = <<<SQL
171
        SELECT [s].[name]
172
        FROM [sys].[schemas] AS [s]
173
        INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
174
        WHERE [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
175
        ORDER BY [s].[name] ASC
176 1
        SQL;
177
178 1
        return $this->db->createCommand($sql)->queryColumn();
179
    }
180
181 153
    protected function findTableComment(TableSchemaInterface $tableSchema): void
182
    {
183 153
        $schemaName = $tableSchema->getSchemaName()
184 153
            ? "N'" . (string) $tableSchema->getSchemaName() . "'" : 'SCHEMA_NAME()';
185 153
        $tableName = 'N' . (string) $this->db->getQuoter()->quoteValue($tableSchema->getName());
186
187 153
        $sql = <<<SQL
188 153
        SELECT [value]
189
        FROM fn_listextendedproperty (
190
            N'MS_description',
191 153
            'SCHEMA', $schemaName,
192 153
            'TABLE', $tableName,
193
            DEFAULT, DEFAULT)
194 153
        SQL;
195
196 153
        $comment = $this->db->createCommand($sql)->queryScalar();
197
198 153
        $tableSchema->comment(is_string($comment) ? $comment : null);
199
    }
200
201
    /**
202
     * Returns all table names in the database.
203
     *
204
     * This method should be overridden by child classes in order to support this feature because the default
205
     * implementation simply throws an exception.
206
     *
207
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
208
     *
209
     * @throws Exception|InvalidConfigException|Throwable
210
     *
211
     * @return array All table names in the database. The names have NO schema name prefix.
212
     */
213 11
    protected function findTableNames(string $schema = ''): array
214
    {
215 11
        if ($schema === '') {
216 11
            $schema = $this->defaultSchema;
217
        }
218
219 11
        $sql = <<<SQL
220
        SELECT [t].[table_name]
221
        FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
222
        WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
223
        ORDER BY [t].[table_name]
224 11
        SQL;
225
226 11
        $tables = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
227
228 11
        return array_map(static fn (string $item): string => '[' . $item . ']', $tables);
229
    }
230
231
    /**
232
     * Loads the metadata for the specified table.
233
     *
234
     * @param string $name table name.
235
     *
236
     * @throws Exception|InvalidConfigException|Throwable
237
     *
238
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table does not exist.
239
     */
240 153
    protected function loadTableSchema(string $name): TableSchemaInterface|null
241
    {
242 153
        $table = $this->resolveTableName($name);
243 153
        $this->findPrimaryKeys($table);
244 153
        $this->findTableComment($table);
245
246 153
        if ($this->findColumns($table)) {
247 133
            $this->findForeignKeys($table);
248 133
            return $table;
249
        }
250
251 35
        return null;
252
    }
253
254
    /**
255
     * Loads a primary key for the given table.
256
     *
257
     * @param string $tableName table name.
258
     *
259
     * @throws Exception|InvalidConfigException|Throwable
260
     *
261
     * @return Constraint|null The primary key for the given table, `null` if the table has no primary key.
262
     */
263 50
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
264
    {
265
        /** @var mixed */
266 50
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
267 50
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
268
    }
269
270
    /**
271
     * Loads all foreign keys for the given table.
272
     *
273
     * @param string $tableName table name.
274
     *
275
     * @throws Exception|InvalidConfigException|Throwable
276
     *
277
     * @return array The foreign keys for the given table.
278
     */
279 8
    protected function loadTableForeignKeys(string $tableName): array
280
    {
281
        /** @var mixed */
282 8
        $tableForeingKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
283 8
        return is_array($tableForeingKeys) ? $tableForeingKeys : [];
284
    }
285
286
    /**
287
     * Loads all indexes for the given table.
288
     *
289
     * @param string $tableName table name.
290
     *
291
     * @throws Exception|InvalidConfigException|Throwable
292
     *
293
     * @return array indexes for the given table.
294
     */
295 39
    protected function loadTableIndexes(string $tableName): array
296
    {
297 39
        $sql = <<<SQL
298
        SELECT
299
            [i].[name] AS [name],
300
            [iccol].[name] AS [column_name],
301
            [i].[is_unique] AS [index_is_unique],
302
            [i].[is_primary_key] AS [index_is_primary]
303
        FROM [sys].[indexes] AS [i]
304
        INNER JOIN [sys].[index_columns] AS [ic]
305
            ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
306
        INNER JOIN [sys].[columns] AS [iccol]
307
            ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
308
        WHERE [i].[object_id] = OBJECT_ID(:fullName)
309
        ORDER BY [ic].[key_ordinal] ASC
310 39
        SQL;
311
312 39
        $resolvedName = $this->resolveTableName($tableName);
313 39
        $indexes = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
314
315
        /** @psalm-var array[] $indexes */
316 39
        $indexes = $this->normalizeRowKeyCase($indexes, true);
317 39
        $indexes = ArrayHelper::index($indexes, null, ['name']);
318
319 39
        $result = [];
320
321
        /**
322
         * @psalm-var array<
323
         *   string,
324
         *   array<
325
         *     array-key,
326
         *     array{array-key, name: string, column_name: string, index_is_unique: string, index_is_primary: string}
327
         *   >
328
         * > $indexes
329
         */
330 39
        foreach ($indexes as $name => $index) {
331 36
            $result[] = (new IndexConstraint())
332 36
                ->primary((bool) $index[0]['index_is_primary'])
333 36
                ->unique((bool) $index[0]['index_is_unique'])
334 36
                ->columnNames(ArrayHelper::getColumn($index, 'column_name'))
335 36
                ->name($name);
336
        }
337
338 39
        return $result;
339
    }
340
341
    /**
342
     * Loads all unique constraints for the given table.
343
     *
344
     * @param string $tableName table name.
345
     *
346
     * @throws Exception|InvalidConfigException|Throwable
347
     *
348
     * @return array The unique constraints for the given table.
349
     */
350 17
    protected function loadTableUniques(string $tableName): array
351
    {
352
        /** @var mixed */
353 17
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
354 17
        return is_array($tableUniques) ? $tableUniques : [];
355
    }
356
357
    /**
358
     * Loads all check constraints for the given table.
359
     *
360
     * @param string $tableName table name.
361
     *
362
     * @throws Exception|InvalidConfigException|Throwable
363
     *
364
     * @return array The check constraints for the given table.
365
     */
366 17
    protected function loadTableChecks(string $tableName): array
367
    {
368
        /** @var mixed */
369 17
        $tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
370 17
        return is_array($tableCheck) ? $tableCheck : [];
371
    }
372
373
    /**
374
     * Loads all default value constraints for the given table.
375
     *
376
     * @param string $tableName table name.
377
     *
378
     * @throws Exception|InvalidConfigException|Throwable
379
     *
380
     * @return array The default value constraints for the given table.
381
     */
382 16
    protected function loadTableDefaultValues(string $tableName): array
383
    {
384
        /** @var mixed */
385 16
        $tableDefault = $this->loadTableConstraints($tableName, self::DEFAULTS);
386 16
        return is_array($tableDefault) ? $tableDefault : [];
387
    }
388
389
    /**
390
     * Creates a column schema for the database.
391
     *
392
     * This method may be overridden by child classes to create a DBMS-specific column schema.
393
     *
394
     * @return ColumnSchema column schema instance.
395
     */
396 133
    protected function createColumnSchema(): ColumnSchema
397
    {
398 133
        return new ColumnSchema();
399
    }
400
401
    /**
402
     * Loads the column information into a {@see ColumnSchemaInterface} object.
403
     *
404
     * @psalm-param ColumnArray $info The column information.
405
     *
406
     * @return ColumnSchemaInterface the column schema object.
407
     */
408 133
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
409
    {
410 133
        $column = $this->createColumnSchema();
411
412 133
        $column->name($info['column_name']);
413 133
        $column->allowNull($info['is_nullable'] === 'YES');
414 133
        $column->dbType($info['data_type']);
415 133
        $column->enumValues([]); // mssql has only vague equivalents to enum
416 133
        $column->primaryKey(false); // primary key will be determined in findColumns() method
417 133
        $column->autoIncrement($info['is_identity'] === '1');
418 133
        $column->computed($info['is_computed'] === '1');
419 133
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
420 133
        $column->comment($info['comment'] ?? '');
421 133
        $column->type(self::TYPE_STRING);
422
423 133
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
424 133
            $type = $matches[1];
425
426 133
            if (isset($this->typeMap[$type])) {
427 133
                $column->type($this->typeMap[$type]);
428
            }
429
430 133
            if (!empty($matches[2])) {
431 94
                $values = explode(',', $matches[2]);
432 94
                $column->precision((int) $values[0]);
433 94
                $column->size((int) $values[0]);
434
435 94
                if (isset($values[1])) {
436
                    $column->scale((int) $values[1]);
437
                }
438
439 94
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
440
                    $column->type(self::TYPE_BOOLEAN);
441 94
                } elseif ($type === 'bit') {
442
                    if ($column->getSize() > 32) {
443
                        $column->type(self::TYPE_BIGINT);
444
                    } elseif ($column->getSize() === 32) {
445
                        $column->type(self::TYPE_INTEGER);
446
                    }
447
                }
448
            }
449
        }
450
451 133
        $column->phpType($this->getColumnPhpType($column));
452
453 133
        if ($info['column_default'] === '(NULL)') {
454 7
            $info['column_default'] = null;
455
        }
456
457 133
        if (!$column->isPrimaryKey() && ($column->getType() !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
458 133
            $value = $info['column_default'];
459
            if ($info['column_default'] !== null) {
460
                $value = (string) $value;
461 133
                /**
462
                 * convert from MSSQL column_default format, e.g. ('1') -> 1, ('string') -> string
463
                 * exclude cases for functions as default value. Example: (getdate())
464
                 */
465
                $offset = (str_starts_with($value, "('") && str_ends_with($value, "')")) ? 2 : 1;
466
                $value = substr($value, $offset, -$offset);
467
            }
468
            $column->defaultValue($column->phpTypecast($value));
469
        }
470
471
        return $column;
472
    }
473 153
474
    /**
475 153
     * Collects the metadata of table columns.
476
     *
477 153
     * @param TableSchemaInterface $table the table metadata.
478 153
     *
479
     * @throws Throwable
480 153
     *
481
     * @return bool whether the table exists in the database.
482
     */
483
    protected function findColumns(TableSchemaInterface $table): bool
484
    {
485
        $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
486 153
487 153
        $whereParams = [':table_name' => $table->getName()];
488
        $whereSql = '[t1].[table_name] = :table_name';
489
490 153
        if ($table->getCatalogName() !== null) {
491
            $columnsTableName = "{$table->getCatalogName()}.$columnsTableName";
492 153
            $whereSql .= ' AND [t1].[table_catalog] = :catalog';
493 153
            $whereParams[':catalog'] = $table->getCatalogName();
494
        }
495
496
        if ($table->getSchemaName() !== null) {
497
            $whereSql .= " AND [t1].[table_schema] = '{$table->getSchemaName()}'";
498
        }
499
500
        $columnsTableName = $this->db->getQuoter()->quoteTableName($columnsTableName);
501
502
        $sql = <<<SQL
503
        SELECT
504
            [t1].[column_name],
505
            [t1].[is_nullable],
506
        CASE WHEN [t1].[data_type] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
507
        CASE WHEN [t1].[character_maximum_length] = NULL OR [t1].[character_maximum_length] = -1 THEN
508
            [t1].[data_type]
509
        ELSE
510
            [t1].[data_type] + '(' + LTRIM(RTRIM(CONVERT(CHAR,[t1].[character_maximum_length]))) + ')'
511
        END
512
        ELSE
513
            [t1].[data_type]
514
        END AS 'data_type',
515
        [t1].[column_default],
516
        COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
517
        COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsComputed') AS is_computed,
518 153
        (
519 153
        SELECT CONVERT(VARCHAR, [t2].[value])
520 153
        FROM [sys].[extended_properties] AS [t2]
521
        WHERE
522
        [t2].[class] = 1 AND
523
        [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
524 153
        [t2].[name] = 'MS_Description' AND
525
        [t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
526 153
        [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
527 153
        ) as comment
528
        FROM $columnsTableName AS [t1]
529
        WHERE $whereSql
530
        SQL;
531
532
        try {
533 133
            /** @psalm-var ColumnArray[] */
534 133
            $columns = $this->db->createCommand($sql, $whereParams)->queryAll();
535 133
536 80
            if (empty($columns)) {
537 80
                return false;
538 80
            }
539
        } catch (Exception) {
540
            return false;
541
        }
542 133
543 73
        foreach ($columns as $column) {
544
            $column = $this->loadColumnSchema($column);
545
            foreach ($table->getPrimaryKey() as $primaryKey) {
546 133
                if (strcasecmp($column->getName(), $primaryKey) === 0) {
547
                    $column->primaryKey(true);
548
                    break;
549 133
                }
550
            }
551
552
            if ($column->isPrimaryKey() && $column->isAutoIncrement()) {
553
                $table->sequenceName('');
554
            }
555
556
            $table->columns($column->getName(), $column);
557
        }
558
559
        return true;
560
    }
561 153
562
    /**
563 153
     * Collects the constraint details for the given table and constraint type.
564 153
     *
565
     * @param string $type either PRIMARY KEY or UNIQUE.
566 153
     *
567 153
     * @throws Exception|InvalidConfigException|Throwable
568
     *
569
     * @return array each entry contains index_name and field_name.
570
     */
571
    protected function findTableConstraints(TableSchemaInterface $table, string $type): array
572 153
    {
573 153
        $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
574
        $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
575 153
576 153
        $catalogName = $table->getCatalogName();
577
        if ($catalogName !== null) {
578
            $keyColumnUsageTableName = $catalogName . '.' . $keyColumnUsageTableName;
579 153
            $tableConstraintsTableName = $catalogName . '.' . $tableConstraintsTableName;
580 153
        }
581
582
        $keyColumnUsageTableName = $this->db->getQuoter()->quoteTableName($keyColumnUsageTableName);
583
        $tableConstraintsTableName = $this->db->getQuoter()->quoteTableName($tableConstraintsTableName);
584
585
        $sql = <<<SQL
586
        SELECT
587
            [kcu].[constraint_name] AS [index_name],
588 153
            [kcu].[column_name] AS [field_name]
589
        FROM $keyColumnUsageTableName AS [kcu]
590 153
        LEFT JOIN $tableConstraintsTableName AS [tc] ON
591 153
            [kcu].[table_schema] = [tc].[table_schema] AND
592 153
            [kcu].[table_name] = [tc].[table_name] AND
593 153
            [kcu].[constraint_name] = [tc].[constraint_name]
594 153
        WHERE
595 153
            [tc].[constraint_type] = :type AND
596 153
            [kcu].[table_name] = :tableName AND
597 153
            [kcu].[table_schema] = :schemaName
598
        SQL;
599
600
        return $this->db->createCommand(
601
            $sql,
602
            [
603
                ':tableName' => $table->getName(),
604
                ':schemaName' => $table->getSchemaName(),
605
                ':type' => $type,
606
            ]
607 153
        )->queryAll();
608
    }
609
610 153
    /**
611
     * Collects the primary key column details for the given table.
612 153
     *
613 80
     * @param TableSchemaInterface $table the table metadata
614
     *
615
     * @throws Exception|InvalidConfigException|Throwable
616
     */
617
    protected function findPrimaryKeys(TableSchemaInterface $table): void
618
    {
619
        /** @psalm-var array<array-key, array{index_name: string, field_name: string}> $primaryKeys */
620
        $primaryKeys = $this->findTableConstraints($table, 'PRIMARY KEY');
621
622
        foreach ($primaryKeys as $row) {
623
            $table->primaryKey($row['field_name']);
624 133
        }
625
    }
626 133
627 133
    /**
628 133
     * Collects the foreign key column details for the given table.
629 133
     *
630
     * @param TableSchemaInterface $table the table metadata
631 133
     *
632 133
     * @throws Exception|InvalidConfigException|Throwable
633
     */
634
    protected function findForeignKeys(TableSchemaInterface $table): void
635 133
    {
636
        $catalogName = $table->getCatalogName();
637
        $fk = [];
638
        $object = $table->getName();
639
        $schemaName = $table->getSchemaName();
640
641
        if ($schemaName !== null) {
642
            $object = $schemaName . '.' . $object;
643 133
        }
644
645
        if ($catalogName !== null) {
646
            $object = $catalogName . '.' . $object;
647
        }
648
649
        /**
650
         * Please refer to the following page for more details:
651
         * {@see http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx}
652
         */
653
        $sql = <<<SQL
654
        SELECT
655
        [fk].[name] AS [fk_name],
656
        [cp].[name] AS [fk_column_name],
657 133
        OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
658
        [cr].[name] AS [uq_column_name]
659
        FROM [sys].[foreign_keys] AS [fk]
660
        INNER JOIN [sys].[foreign_key_columns] AS [fkc]
661
            ON [fk].[object_id] = [fkc].[constraint_object_id]
662
        INNER JOIN [sys].[columns] AS [cp]
663
            ON [fk].[parent_object_id] = [cp].[object_id] AND [fkc].[parent_column_id] = [cp].[column_id]
664
        INNER JOIN [sys].[columns] AS [cr]
665 133
            ON [fk].[referenced_object_id] = [cr].[object_id] AND [fkc].[referenced_column_id] = [cr].[column_id]
666 133
        WHERE [fk].[parent_object_id] = OBJECT_ID(:object)
667
        SQL;
668 133
669 10
        /**
670 10
         * @psalm-var array<
671 10
         *   array-key,
672
         *   array{fk_name: string, fk_column_name: string, uq_table_name: string, uq_column_name: string}
673
         * > $rows
674 10
         */
675 10
        $rows = $this->db->createCommand($sql, [':object' => $object])->queryAll();
676
        $table->foreignKeys([]);
677
678
        foreach ($rows as $row) {
679
            if (!isset($table->getForeignKeys()[$row['fk_name']])) {
680
                $fk[$row['fk_name']][] = $row['uq_table_name'];
681
                $table->foreignKeys($fk);
682 4
            }
683
684 4
            $fk[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
685 1
            $table->foreignKeys($fk);
686
        }
687
    }
688 4
689
    /**
690
     * @throws Exception|InvalidConfigException|Throwable
691
     */
692
    protected function findViewNames(string $schema = ''): array
693 4
    {
694
        if ($schema === '') {
695 4
            $schema = $this->defaultSchema;
696
        }
697 4
698
        $sql = <<<SQL
699
        SELECT [t].[table_name]
700
        FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
701
        WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
702
        ORDER BY [t].[table_name]
703
        SQL;
704
705
        $views = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
706
707
        return array_map(static fn (string $item): string => '[' . $item . ']', $views);
708
    }
709
710
    /**
711
     * Returns all unique indexes for the given table.
712
     *
713
     * Each array element is of the following structure:
714
     *
715
     * ```php
716
     * [
717
     *     'IndexName1' => ['col1' [, ...]],
718 1
     *     'IndexName2' => ['col2' [, ...]],
719
     * ]
720 1
     * ```
721
     *
722
     * @param TableSchemaInterface $table the table metadata.
723 1
     *
724
     * @throws Exception|InvalidConfigException|Throwable
725 1
     *
726 1
     * @return array all unique indexes for the given table.
727
     */
728
    public function findUniqueIndexes(TableSchemaInterface $table): array
729 1
    {
730
        $result = [];
731
732
        /** @psalm-var array<array-key, array{index_name: string, field_name: string}> $tableUniqueConstraints */
733
        $tableUniqueConstraints = $this->findTableConstraints($table, 'UNIQUE');
734
735
        foreach ($tableUniqueConstraints as $row) {
736
            $result[$row['index_name']][] = $row['field_name'];
737
        }
738
739
        return $result;
740
    }
741
742
    /**
743
     * Loads multiple types of constraints and returns the specified ones.
744
     *
745
     * @param string $tableName table name.
746
     * @param string $returnType return type:
747 108
     * - primaryKey
748
     * - foreignKeys
749 108
     * - uniques
750
     * - checks
751
     * - defaults
752
     *
753
     * @throws Exception|InvalidConfigException|Throwable
754
     *
755
     * @return mixed constraints.
756
     */
757
    private function loadTableConstraints(string $tableName, string $returnType): mixed
758
    {
759
        $sql = <<<SQL
760
        SELECT
761
            [o].[name] AS [name],
762
            COALESCE([ccol].[name], [dcol].[name], [fccol].[name], [kiccol].[name]) AS [column_name],
763
            RTRIM([o].[type]) AS [type],
764
            OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [foreign_table_schema],
765
            OBJECT_NAME([f].[referenced_object_id]) AS [foreign_table_name],
766
            [ffccol].[name] AS [foreign_column_name],
767
            [f].[update_referential_action_desc] AS [on_update],
768
            [f].[delete_referential_action_desc] AS [on_delete],
769
            [c].[definition] AS [check_expr],
770
            [d].[definition] AS [default_expr]
771
        FROM (SELECT OBJECT_ID(:fullName) AS [object_id]) AS [t]
772
        INNER JOIN [sys].[objects] AS [o]
773
            ON [o].[parent_object_id] = [t].[object_id] AND [o].[type] IN ('PK', 'UQ', 'C', 'D', 'F')
774
        LEFT JOIN [sys].[check_constraints] AS [c]
775
            ON [c].[object_id] = [o].[object_id]
776
        LEFT JOIN [sys].[columns] AS [ccol]
777
            ON [ccol].[object_id] = [c].[parent_object_id] AND [ccol].[column_id] = [c].[parent_column_id]
778
        LEFT JOIN [sys].[default_constraints] AS [d]
779
            ON [d].[object_id] = [o].[object_id]
780
        LEFT JOIN [sys].[columns] AS [dcol]
781
            ON [dcol].[object_id] = [d].[parent_object_id] AND [dcol].[column_id] = [d].[parent_column_id]
782
        LEFT JOIN [sys].[key_constraints] AS [k]
783
            ON [k].[object_id] = [o].[object_id]
784
        LEFT JOIN [sys].[index_columns] AS [kic]
785
            ON [kic].[object_id] = [k].[parent_object_id] AND [kic].[index_id] = [k].[unique_index_id]
786
        LEFT JOIN [sys].[columns] AS [kiccol]
787 108
            ON [kiccol].[object_id] = [kic].[object_id] AND [kiccol].[column_id] = [kic].[column_id]
788
        LEFT JOIN [sys].[foreign_keys] AS [f]
789 108
            ON [f].[object_id] = [o].[object_id]
790 108
        LEFT JOIN [sys].[foreign_key_columns] AS [fc]
791
            ON [fc].[constraint_object_id] = [o].[object_id]
792
        LEFT JOIN [sys].[columns] AS [fccol]
793 108
            ON [fccol].[object_id] = [fc].[parent_object_id] AND [fccol].[column_id] = [fc].[parent_column_id]
794 108
        LEFT JOIN [sys].[columns] AS [ffccol]
795
            ON [ffccol].[object_id] = [fc].[referenced_object_id] AND [ffccol].[column_id] = [fc].[referenced_column_id]
796 108
        ORDER BY [kic].[key_ordinal] ASC, [fc].[constraint_column_id] ASC
797 108
        SQL;
798 108
799 108
        $resolvedName = $this->resolveTableName($tableName);
800 108
        $constraints = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
801 108
802 108
        /** @psalm-var array[] $constraints */
803
        $constraints = $this->normalizeRowKeyCase($constraints, true);
804
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
805 108
806
        $result = [
807
            self::PRIMARY_KEY => null,
808
            self::FOREIGN_KEYS => [],
809
            self::UNIQUES => [],
810 99
            self::CHECKS => [],
811
            self::DEFAULTS => [],
812 99
        ];
813
814 65
        /** @psalm-var array<array-key, array> $constraints */
815 65
        foreach ($constraints as $type => $names) {
816 65
            /**
817 65
             * @psalm-var object|string|null $name
818 93
             * @psalm-var ConstraintArray $constraint
819 23
             */
820 23
            foreach ($names as $name => $constraint) {
821 23
                switch ($type) {
822 23
                    case 'PK':
823 23
                        /** @var Constraint */
824 23
                        $result[self::PRIMARY_KEY] = (new Constraint())
825 23
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
826 23
                            ->name($name);
827 23
                        break;
828 77
                    case 'F':
829 71
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
830 71
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
831 71
                            ->foreignTableName($constraint[0]['foreign_table_name'])
832 71
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
833 41
                            ->onDelete(str_replace('_', '', $constraint[0]['on_delete']))
834 19
                            ->onUpdate(str_replace('_', '', $constraint[0]['on_update']))
835 19
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
836 19
                            ->name($name);
837 19
                        break;
838 19
                    case 'UQ':
839 38
                        $result[self::UNIQUES][] = (new Constraint())
840 38
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
841 38
                            ->name($name);
842 38
                        break;
843 38
                    case 'C':
844 38
                        $result[self::CHECKS][] = (new CheckConstraint())
845
                            ->expression($constraint[0]['check_expr'])
846
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
847
                            ->name($name);
848
                        break;
849 108
                    case 'D':
850 108
                        $result[self::DEFAULTS][] = (new DefaultValueConstraint())
851
                            ->value($constraint[0]['default_expr'])
852
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
853 108
                            ->name($name);
854
                        break;
855
                }
856 8
            }
857
        }
858
859
        foreach ($result as $type => $data) {
860 8
            $this->setTableMetadata($tableName, $type, $data);
861
        }
862
863
        return $result[$returnType];
864
    }
865
866
    public function createColumnSchemaBuilder(
867
        string $type,
868
        array|int|string $length = null
869
    ): ColumnSchemaBuilderInterface {
870 255
        return new ColumnSchemaBuilder($type, $length);
871
    }
872 255
873
    /**
874
     * Returns the cache key for the specified table name.
875
     *
876
     * @param string $name the table name.
877
     *
878
     * @return array the cache key.
879
     */
880
    protected function getCacheKey(string $name): array
881
    {
882 256
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
883
    }
884 256
885
    /**
886
     * Returns the cache tag name.
887
     *
888
     * This allows {@see refresh()} to invalidate all cached table schemas.
889
     *
890
     * @return string the cache tag name.
891
     */
892
    protected function getCacheTag(): string
893
    {
894
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
895
    }
896
}
897