Passed
Push — master ( 4b0ebc...2d633f )
by Def
22:28 queued 07:36
created

Schema::loadTableSchema()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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