Test Failed
Pull Request — dev (#91)
by Def
03:11
created

Schema::getViewNames()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 3
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql;
6
7
use Throwable;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Db\Cache\SchemaCache;
10
use Yiisoft\Db\Connection\ConnectionInterface;
11
use Yiisoft\Db\Constraint\CheckConstraint;
12
use Yiisoft\Db\Constraint\Constraint;
13
use Yiisoft\Db\Constraint\DefaultValueConstraint;
14
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
15
use Yiisoft\Db\Constraint\IndexConstraint;
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
19
use Yiisoft\Db\Schema\Schema as AbstractSchema;
20
use Yiisoft\Db\Schema\TableSchemaInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\TableSchemaInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
22
use function array_change_key_case;
23
use function array_map;
24
use function count;
25
use function explode;
26
use function is_array;
27
use function md5;
28
use function preg_match;
29
use function preg_match_all;
30
use function preg_replace;
31
use function serialize;
32
use function str_contains;
33
use function str_replace;
34
use function strcasecmp;
35
use function stripos;
36
37
/**
38
 * Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
39
 *
40
 * @psalm-type ColumnArray = array{
41
 *   column_name: string,
42
 *   is_nullable: string,
43
 *   data_type: string,
44
 *   column_default: mixed,
45
 *   is_identity: string,
46
 *   comment: null|string
47
 * }
48
 *
49
 * @psalm-type ConstraintArray = array<
50
 *   array-key,
51
 *   array {
52
 *     name: string,
53
 *     column_name: string,
54
 *     type: string,
55
 *     foreign_table_schema: string|null,
56
 *     foreign_table_name: string|null,
57
 *     foreign_column_name: string|null,
58
 *     on_update: string,
59
 *     on_delete: string,
60
 *     check_expr: string,
61
 *     default_expr: string
62
 *   }
63
 * >
64
 */
65
final class Schema extends AbstractSchema
66
{
67
    public const DEFAULTS = 'defaults';
68
69
    /**
70
     * @var string|null the default schema used for the current session.
71
     */
72
    protected ?string $defaultSchema = 'dbo';
73
74
    /**
75
     * @var array mapping from physical column types (keys) to abstract column types (values)
76
     *
77
     * @psalm-var string[]
78
     */
79
    private array $typeMap = [
80
        /** exact numbers */
81
        'bigint' => self::TYPE_BIGINT,
82
        'numeric' => self::TYPE_DECIMAL,
83
        'bit' => self::TYPE_SMALLINT,
84
        'smallint' => self::TYPE_SMALLINT,
85
        'decimal' => self::TYPE_DECIMAL,
86
        'smallmoney' => self::TYPE_MONEY,
87
        'int' => self::TYPE_INTEGER,
88
        'tinyint' => self::TYPE_TINYINT,
89
        'money' => self::TYPE_MONEY,
90
91
        /** approximate numbers */
92
        'float' => self::TYPE_FLOAT,
93
        'double' => self::TYPE_DOUBLE,
94
        'real' => self::TYPE_FLOAT,
95
96
        /** date and time */
97
        'date' => self::TYPE_DATE,
98
        'datetimeoffset' => self::TYPE_DATETIME,
99
        'datetime2' => self::TYPE_DATETIME,
100
        'smalldatetime' => self::TYPE_DATETIME,
101
        'datetime' => self::TYPE_DATETIME,
102
        'time' => self::TYPE_TIME,
103
104
        /** character strings */
105
        'char' => self::TYPE_CHAR,
106
        'varchar' => self::TYPE_STRING,
107
        'text' => self::TYPE_TEXT,
108
109
        /** unicode character strings */
110
        'nchar' => self::TYPE_CHAR,
111
        'nvarchar' => self::TYPE_STRING,
112
        'ntext' => self::TYPE_TEXT,
113
114
        /** binary strings */
115
        'binary' => self::TYPE_BINARY,
116
        'varbinary' => self::TYPE_BINARY,
117
        'image' => self::TYPE_BINARY,
118
119
        /**
120
         * other data types 'cursor' type cannot be used with tables
121
         */
122
        'timestamp' => self::TYPE_TIMESTAMP,
123
        'hierarchyid' => self::TYPE_STRING,
124
        'uniqueidentifier' => self::TYPE_STRING,
125
        'sql_variant' => self::TYPE_STRING,
126
        'xml' => self::TYPE_STRING,
127
        'table' => self::TYPE_STRING,
128
    ];
129
130
    public function __construct(private ConnectionInterface $db, SchemaCache $schemaCache)
131
    {
132 388
        parent::__construct($schemaCache);
133
    }
134 388
135
    /**
136
     * Resolves the table name and schema name (if any).
137
     *
138
     * @param string $name the table name.
139
     *
140
     * @return TableSchemaInterface resolved table, schema, etc. names.
141
     *
142
     * @todo Review this method and see if it can be simplified @darkdef.
143
     */
144
    protected function resolveTableName(string $name): TableSchemaInterface
145
    {
146 90
        $resolvedName = new TableSchema();
147
        $parts = $this->getTableNameParts($name);
148 90
        $partCount = count($parts);
149 90
150 90
        if ($partCount === 4) {
151
            /** server name, catalog name, schema name and table name passed - not coverage tests */
152 90
            $resolvedName->catalogName($parts[1]);
0 ignored issues
show
Bug introduced by
The method catalogName() does not exist on Yiisoft\Db\Mssql\TableSchema. ( Ignorable by Annotation )

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

152
            $resolvedName->/** @scrutinizer ignore-call */ 
153
                           catalogName($parts[1]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
153
            $resolvedName->schemaName($parts[2]);
154
            $resolvedName->name($parts[3]);
155
            $resolvedName->fullName(
156
                (string) $resolvedName->getCatalogName() . '.' .
0 ignored issues
show
Bug introduced by
The method getCatalogName() does not exist on Yiisoft\Db\Mssql\TableSchema. ( Ignorable by Annotation )

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

156
                (string) $resolvedName->/** @scrutinizer ignore-call */ getCatalogName() . '.' .

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
157
                (string) $resolvedName->getSchemaName() . '.' .
158
                $resolvedName->getName()
159
            );
160
        } elseif ($partCount === 3) {
161
            /** catalog name, schema name and table name passed - not coverage tests */
162 90
            $resolvedName->catalogName($parts[0]);
163
            $resolvedName->schemaName($parts[1]);
164
            $resolvedName->name($parts[2]);
165
            $resolvedName->fullName(
166
                (string) $resolvedName->getCatalogName() . '.' .
167
                (string) $resolvedName->getSchemaName() . '.' .
168
                $resolvedName->getName()
169
            );
170
        } elseif ($partCount === 2) {
171
            /** only schema name and table name passed - not coverage tests */
172 90
            $resolvedName->schemaName($parts[0]);
173
            $resolvedName->name($parts[1]);
174
            $resolvedName->fullName(
175
                (
176
                    $resolvedName->getSchemaName() !== $this->defaultSchema
177
                    ? (string) $resolvedName->getSchemaName() . '.' : ''
178
                ) . $resolvedName->getName()
179
            );
180
        } else {
181
            /** only table name passed */
182
            $resolvedName->schemaName($this->defaultSchema);
183
            $resolvedName->name($parts[0]);
184 90
            $resolvedName->fullName($resolvedName->getName());
185 90
        }
186 90
187
        return $resolvedName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $resolvedName returns the type Yiisoft\Db\Mssql\TableSchema which is incompatible with the type-hinted return Yiisoft\Db\Schema\TableSchemaInterface.
Loading history...
188
    }
189 90
190
    /**
191
     * Splits full table name into parts.
192
     *
193
     * @param string $name
194
     *
195
     * @return array
196
     *
197
     * @psalm-return string[]
198
     */
199
    protected function getTableNameParts(string $name): array
200
    {
201 177
        $parts = [$name];
202
203 177
        preg_match_all('/([^.\[\]]+)|\[([^\[\]]+)]/', $name, $matches);
204
205 177
        if (isset($matches[0]) && !empty($matches[0])) {
206
            $parts = $matches[0];
207 177
        }
208 177
209
        /** @psalm-var string[] */
210
        return str_replace(['[', ']'], '', $parts);
211
    }
212 177
213
    /**
214
     * Returns all schema names in the database, including the default one but not system schemas.
215
     *
216
     * This method should be overridden by child classes in order to support this feature because the default
217
     * implementation simply throws an exception.
218
     *
219
     * @throws Exception|InvalidConfigException|Throwable
220
     *
221
     * @return array all schema names in the database, except system schemas.
222
     *
223
     * {@see https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-principals-transact-sql}
224
     */
225
    protected function findSchemaNames(): array
226
    {
227 1
        $sql = <<<SQL
228
        SELECT [s].[name]
229 1
        FROM [sys].[schemas] AS [s]
230
        INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
231
        WHERE [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
232
        ORDER BY [s].[name] ASC
233
        SQL;
234
235
        $schemaNames = $this->db->createCommand($sql)->queryColumn();
236
        if (!$schemaNames) {
237 1
            return [];
238 1
        }
239
240
        return $schemaNames;
241
    }
242 1
243
    /**
244
     * Returns all table names in the database.
245
     *
246
     * This method should be overridden by child classes in order to support this feature because the default
247
     * implementation simply throws an exception.
248
     *
249
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
250
     *
251
     * @throws Exception|InvalidConfigException|Throwable
252
     *
253
     * @return array all table names in the database. The names have NO schema name prefix.
254
     */
255
    protected function findTableNames(string $schema = ''): array
256
    {
257 11
        if ($schema === '') {
258
            $schema = $this->defaultSchema;
259 11
        }
260 11
261
        $sql = <<<SQL
262
        SELECT [t].[table_name]
263 11
        FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
264
        WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
265
        ORDER BY [t].[table_name]
266
        SQL;
267
268
        $tables = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
269
        if (!$tables) {
270 11
            return [];
271 11
        }
272
273
        return array_map(static fn (string $item): string => '[' . $item . ']', $tables);
274
    }
275 11
276
    /**
277
     * Loads the metadata for the specified table.
278
     *
279
     * @param string $name table name.
280
     *
281
     * @throws Exception|InvalidConfigException|Throwable
282
     *
283
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table does not exist.
284
     */
285
    protected function loadTableSchema(string $name): ?TableSchemaInterface
286
    {
287 111
        $table = new TableSchema();
288
289 111
        $this->resolveTableNames($table, $name);
290
        $this->findPrimaryKeys($table);
291 111
292 111
        if ($this->findColumns($table)) {
293
            $this->findForeignKeys($table);
294 111
            return $table;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $table returns the type Yiisoft\Db\Mssql\TableSchema which is incompatible with the type-hinted return Yiisoft\Db\Schema\TableSchemaInterface|null.
Loading history...
295 102
        }
296 102
297
        return null;
298
    }
299 19
300
    /**
301
     * Loads a primary key for the given table.
302
     *
303
     * @param string $tableName table name.
304
     *
305
     * @throws Exception|InvalidConfigException|Throwable
306
     *
307
     * @return Constraint|null The primary key for the given table, `null` if the table has no primary key.
308
     */
309
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
310
    {
311 32
        /** @var mixed */
312
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
313
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
314 32
    }
315 32
316
    /**
317
     * Loads all foreign keys for the given table.
318
     *
319
     * @param string $tableName table name.
320
     *
321
     * @throws Exception|InvalidConfigException|Throwable
322
     *
323
     * @return array The foreign keys for the given table.
324
     */
325
    protected function loadTableForeignKeys(string $tableName): array
326
    {
327 5
        /** @var mixed */
328
        $tableForeingKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS);
329
        return is_array($tableForeingKeys) ? $tableForeingKeys : [];
330 5
    }
331 5
332
    /**
333
     * Loads all indexes for the given table.
334
     *
335
     * @param string $tableName table name.
336
     *
337
     * @throws Exception|InvalidConfigException|Throwable
338
     *
339
     * @return array indexes for the given table.
340
     */
341
    protected function loadTableIndexes(string $tableName): array
342
    {
343 30
        $sql = <<<SQL
344
        SELECT
345 30
            [i].[name] AS [name],
346
            [iccol].[name] AS [column_name],
347
            [i].[is_unique] AS [index_is_unique],
348
            [i].[is_primary_key] AS [index_is_primary]
349
        FROM [sys].[indexes] AS [i]
350
        INNER JOIN [sys].[index_columns] AS [ic]
351
            ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
352
        INNER JOIN [sys].[columns] AS [iccol]
353
            ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
354
        WHERE [i].[object_id] = OBJECT_ID(:fullName)
355
        ORDER BY [ic].[key_ordinal] ASC
356
        SQL;
357
358
        $resolvedName = $this->resolveTableName($tableName);
359
        $indexes = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
360 30
361 30
        /** @psalm-var array[] $indexes */
362
        $indexes = $this->normalizeRowKeyCase($indexes, true);
363
        $indexes = ArrayHelper::index($indexes, null, 'name');
364 30
365 30
        $result = [];
366
367 30
        /**
368
         * @psalm-var array<
369
         *   string,
370
         *   array<
371
         *     array-key,
372
         *     array{array-key, name: string, column_name: string, index_is_unique: string, index_is_primary: string}
373
         *   >
374
         * > $indexes
375
         */
376
        foreach ($indexes as $name => $index) {
377
            $result[] = (new IndexConstraint())
378 30
                ->primary((bool) $index[0]['index_is_primary'])
379 27
                ->unique((bool) $index[0]['index_is_unique'])
380 27
                ->columnNames(ArrayHelper::getColumn($index, 'column_name'))
381 27
                ->name($name);
382 27
        }
383 27
384
        return $result;
385
    }
386 30
387
    /**
388
     * Loads all unique constraints for the given table.
389
     *
390
     * @param string $tableName table name.
391
     *
392
     * @throws Exception|InvalidConfigException|Throwable
393
     *
394
     * @return array The unique constraints for the given table.
395
     */
396
    protected function loadTableUniques(string $tableName): array
397
    {
398 14
        /** @var mixed */
399
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
400
        return is_array($tableUniques) ? $tableUniques : [];
401 14
    }
402 14
403
    /**
404
     * Loads all check constraints for the given table.
405
     *
406
     * @param string $tableName table name.
407
     *
408
     * @throws Exception|InvalidConfigException|Throwable
409
     *
410
     * @return array The check constraints for the given table.
411
     */
412
    protected function loadTableChecks(string $tableName): array
413
    {
414 14
        /** @var mixed */
415
        $tableCheck = $this->loadTableConstraints($tableName, self::CHECKS);
416
        return is_array($tableCheck) ? $tableCheck : [];
417 14
    }
418 14
419
    /**
420
     * Loads all default value constraints for the given table.
421
     *
422
     * @param string $tableName table name.
423
     *
424
     * @throws Exception|InvalidConfigException|Throwable
425
     *
426
     * @return array The default value constraints for the given table.
427
     */
428
    protected function loadTableDefaultValues(string $tableName): array
429
    {
430 14
        /** @var mixed */
431
        $tableDefault = $this->loadTableConstraints($tableName, self::DEFAULTS);
432
        return is_array($tableDefault) ? $tableDefault : [];
433 14
    }
434 14
435
    /**
436
     * Creates a column schema for the database.
437
     *
438
     * This method may be overridden by child classes to create a DBMS-specific column schema.
439
     *
440
     * @return ColumnSchema column schema instance.
441
     */
442
    protected function createColumnSchema(): ColumnSchema
443
    {
444 102
        return new ColumnSchema();
445
    }
446 102
447
    /**
448
     * Resolves the table name and schema name (if any).
449
     *
450
     * @param TableSchemaInterface $table the table metadata object.
451
     * @param string $name the table name
452
     *
453
     * @todo Review this method and see if it can be simplified @darkdef.
454
     */
455
    protected function resolveTableNames(TableSchemaInterface $table, string $name): void
456
    {
457 111
        $parts = $this->getTableNameParts($name);
458
459 111
        $partCount = count($parts);
460
461 111
        if ($partCount === 4) {
462
            /** server name, catalog name, schema name and table name passed - no coverage tests */
463 111
            $table->catalogName($parts[1]);
464
            $table->schemaName($parts[2]);
465
            $table->name($parts[3]);
466
            $table->fullName(
467
                (string) $table->getCatalogName() . '.' . (string) $table->getSchemaName() . '.' . $table->getName()
468
            );
469
        } elseif ($partCount === 3) {
470
            /** catalog name, schema name and table name passed - no coverage tests */
471 111
            $table->catalogName($parts[0]);
472
            $table->schemaName($parts[1]);
473
            $table->name($parts[2]);
474
            $table->fullName(
475
                (string) $table->getCatalogName() . '.' . (string) $table->getSchemaName() . '.' . $table->getName()
476
            );
477
        } elseif ($partCount === 2) {
478
            /** only schema name and table name passed - no coverage tests */
479 111
            $table->schemaName($parts[0]);
480
            $table->name($parts[1]);
481 3
            $table->fullName(
482 3
                $table->getSchemaName() !== $this->defaultSchema
483 3
                ? (string) $table->getSchemaName() . '.' . $table->getName() : $table->getName()
484 3
            );
485 3
        } else {
486
            /** only table name passed */
487
            $table->schemaName($this->defaultSchema);
488
            $table->name($parts[0]);
489 108
            $table->fullName($table->getName());
490 108
        }
491 108
    }
492
493
    /**
494
     * Loads the column information into a {@see ColumnSchema} object.
495
     *
496
     * @psalm-param ColumnArray $info The column information.
497
     *
498
     * @return ColumnSchema the column schema object.
499
     */
500
    protected function loadColumnSchema(array $info): ColumnSchema
501
    {
502 102
        $column = $this->createColumnSchema();
503
504 102
        $column->name($info['column_name']);
505
        $column->allowNull($info['is_nullable'] === 'YES');
506 102
        $column->dbType($info['data_type']);
507 102
        $column->enumValues([]); // mssql has only vague equivalents to enum
508 102
        $column->primaryKey(false); // primary key will be determined in findColumns() method
509 102
        $column->autoIncrement($info['is_identity'] === '1');
510 102
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
511 102
        $column->comment($info['comment'] ?? '');
512 102
        $column->type(self::TYPE_STRING);
513 102
514 102
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
515
            $type = $matches[1];
516 102
517 102
            if (isset($this->typeMap[$type])) {
518
                $column->type($this->typeMap[$type]);
519 102
            }
520 102
521
            if (!empty($matches[2])) {
522
                $values = explode(',', $matches[2]);
523 102
                $column->precision((int) $values[0]);
524 86
                $column->size((int) $values[0]);
525 86
526 86
                if (isset($values[1])) {
527
                    $column->scale((int) $values[1]);
528 86
                }
529
530
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
531
                    $column->type(self::TYPE_BOOLEAN);
532 86
                } elseif ($type === 'bit') {
533
                    if ($column->getSize() > 32) {
534 86
                        $column->type(self::TYPE_BIGINT);
535
                    } elseif ($column->getSize() === 32) {
536
                        $column->type(self::TYPE_INTEGER);
537
                    }
538
                }
539
            }
540
        }
541
542
        $column->phpType($this->getColumnPhpType($column));
543
544 102
        if ($info['column_default'] === '(NULL)') {
545
            $info['column_default'] = null;
546 102
        }
547 4
548
        if (!$column->isPrimaryKey() && ($column->getType() !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
549
            $column->defaultValue($column->defaultPhpTypecast($info['column_default']));
550 102
        }
551 102
552
        return $column;
553
    }
554 102
555
    /**
556
     * Collects the metadata of table columns.
557
     *
558
     * @param TableSchemaInterface $table the table metadata.
559
     *
560
     * @throws Throwable
561
     *
562
     * @return bool whether the table exists in the database.
563
     */
564
    protected function findColumns(TableSchemaInterface $table): bool
565
    {
566 111
        $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
567
        $whereSql = '[t1].[table_name] = ' . (string) $this->db->getQuoter()->quoteValue($table->getName());
568 111
569 111
        if ($table->getCatalogName() !== null) {
570
            $columnsTableName = "{$table->getCatalogName()}.$columnsTableName";
571 111
            $whereSql .= " AND [t1].[table_catalog] = '{$table->getCatalogName()}'";
572
        }
573
574
        if ($table->getSchemaName() !== null) {
575
            $whereSql .= " AND [t1].[table_schema] = '{$table->getSchemaName()}'";
576 111
        }
577 111
578
        $columnsTableName = $this->db->getQuoter()->quoteTableName($columnsTableName);
579
580 111
        $sql = <<<SQL
581
        SELECT
582 111
            [t1].[column_name],
583
            [t1].[is_nullable],
584
        CASE WHEN [t1].[data_type] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
585
        CASE WHEN [t1].[character_maximum_length] = NULL OR [t1].[character_maximum_length] = -1 THEN
586
            [t1].[data_type]
587
        ELSE
588
            [t1].[data_type] + '(' + LTRIM(RTRIM(CONVERT(CHAR,[t1].[character_maximum_length]))) + ')'
589
        END
590
        ELSE
591
            [t1].[data_type]
592
        END AS 'data_type',
593
        [t1].[column_default],
594
        COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
595
        (
596
        SELECT CONVERT(VARCHAR, [t2].[value])
597
        FROM [sys].[extended_properties] AS [t2]
598
        WHERE
599
        [t2].[class] = 1 AND
600
        [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
601
        [t2].[name] = 'MS_Description' AND
602
        [t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
603
        [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
604
        ) as comment
605
        FROM $columnsTableName AS [t1]
606
        WHERE $whereSql
607
        SQL;
608
609
        try {
610
            /** @psalm-var ColumnArray[] */
611
            $columns = $this->db->createCommand($sql)->queryAll();
612
613 111
            if (empty($columns)) {
614
                return false;
615 111
            }
616 111
        } catch (Exception) {
617
            return false;
618
        }
619
620
        foreach ($columns as $column) {
621
            $column = $this->loadColumnSchema($column);
622 102
            foreach ($table->getPrimaryKey() as $primaryKey) {
623 102
                if (strcasecmp($column->getName(), $primaryKey) === 0) {
624 102
                    $column->primaryKey(true);
625 68
                    break;
626 68
                }
627 68
            }
628
629
            if ($column->isPrimaryKey() && $column->isAutoIncrement()) {
630
                $table->sequenceName('');
631 102
            }
632 67
633
            $table->columns($column->getName(), $column);
634
        }
635 102
636
        return true;
637
    }
638 102
639
    /**
640
     * Collects the constraint details for the given table and constraint type.
641
     *
642
     * @param TableSchemaInterface $table
643
     * @param string $type either PRIMARY KEY or UNIQUE.
644
     *
645
     * @throws Exception|InvalidConfigException|Throwable
646
     *
647
     * @return array each entry contains index_name and field_name.
648
     */
649
    protected function findTableConstraints(TableSchemaInterface $table, string $type): array
650
    {
651 111
        $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
652
        $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
653 111
654 111
        $catalogName = $table->getCatalogName();
655
        if ($catalogName !== null) {
656 111
            $keyColumnUsageTableName = $catalogName . '.' . $keyColumnUsageTableName;
657
            $tableConstraintsTableName = $catalogName . '.' . $tableConstraintsTableName;
658
        }
659
660
        $keyColumnUsageTableName = $this->db->getQuoter()->quoteTableName($keyColumnUsageTableName);
661 111
        $tableConstraintsTableName = $this->db->getQuoter()->quoteTableName($tableConstraintsTableName);
662 111
663
        $sql = <<<SQL
664 111
        SELECT
665
            [kcu].[constraint_name] AS [index_name],
666
            [kcu].[column_name] AS [field_name]
667
        FROM $keyColumnUsageTableName AS [kcu]
668
        LEFT JOIN $tableConstraintsTableName AS [tc] ON
669
            [kcu].[table_schema] = [tc].[table_schema] AND
670
            [kcu].[table_name] = [tc].[table_name] AND
671
            [kcu].[constraint_name] = [tc].[constraint_name]
672
        WHERE
673
            [tc].[constraint_type] = :type AND
674
            [kcu].[table_name] = :tableName AND
675
            [kcu].[table_schema] = :schemaName
676
        SQL;
677
678
        return $this->db->createCommand(
679 111
            $sql,
680
            [
681
                ':tableName' => $table->getName(),
682 111
                ':schemaName' => $table->getSchemaName(),
683 111
                ':type' => $type,
684
            ]
685
        )->queryAll();
686 111
    }
687
688
    /**
689
     * Collects the primary key column details for the given table.
690
     *
691
     * @param TableSchemaInterface $table the table metadata
692
     *
693
     * @throws Exception|InvalidConfigException|Throwable
694
     */
695
    protected function findPrimaryKeys(TableSchemaInterface $table): void
696 111
    {
697
        /** @psalm-var array<array-key, array{index_name: string, field_name: string}> $primaryKeys */
698
        $primaryKeys = $this->findTableConstraints($table, 'PRIMARY KEY');
699 111
700
        foreach ($primaryKeys as $row) {
701 111
            $table->primaryKey($row['field_name']);
702 68
        }
703
    }
704
705
    /**
706
     * Collects the foreign key column details for the given table.
707
     *
708
     * @param TableSchemaInterface $table the table metadata
709
     *
710
     * @throws Exception|InvalidConfigException|Throwable
711
     */
712
    protected function findForeignKeys(TableSchemaInterface $table): void
713 102
    {
714
        $catalogName = $table->getCatalogName();
715 102
        $fk = [];
716 102
        $object = $table->getName();
717 102
        $schemaName = $table->getSchemaName();
718 102
719
        if ($schemaName !== null) {
720 102
            $object = $schemaName . '.' . $object;
721 102
        }
722
723
        if ($catalogName !== null) {
724 102
            $object = $catalogName . '.' . $object;
725
        }
726
727
        /**
728
         * Please refer to the following page for more details:
729
         * {@see http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx}
730
         */
731
        $sql = <<<SQL
732 102
        SELECT
733
        [fk].[name] AS [fk_name],
734
        [cp].[name] AS [fk_column_name],
735
        OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
736
        [cr].[name] AS [uq_column_name]
737
        FROM [sys].[foreign_keys] AS [fk]
738
        INNER JOIN [sys].[foreign_key_columns] AS [fkc]
739
            ON [fk].[object_id] = [fkc].[constraint_object_id]
740
        INNER JOIN [sys].[columns] AS [cp]
741
            ON [fk].[parent_object_id] = [cp].[object_id] AND [fkc].[parent_column_id] = [cp].[column_id]
742
        INNER JOIN [sys].[columns] AS [cr]
743
            ON [fk].[referenced_object_id] = [cr].[object_id] AND [fkc].[referenced_column_id] = [cr].[column_id]
744
        WHERE [fk].[parent_object_id] = OBJECT_ID(:object)
745
        SQL;
746
747
        /**
748
         * @psalm-var array<
749
         *   array-key,
750
         *   array{fk_name: string, fk_column_name: string, uq_table_name: string, uq_column_name: string}
751
         * > $rows
752
         */
753
        $rows = $this->db->createCommand($sql, [':object' => $object])->queryAll();
754 102
        $table->foreignKeys([]);
755 102
756
        foreach ($rows as $row) {
757 102
            if (!isset($table->getForeignKeys()[$row['fk_name']])) {
758 5
                $fk[$row['fk_name']][] = $row['uq_table_name'];
759 5
                $table->foreignKeys($fk);
760 5
            }
761
762
            $fk[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
763 5
            $table->foreignKeys($fk);
764 5
        }
765
    }
766
767
    /**
768
     * @throws Exception|InvalidConfigException|Throwable
769
     */
770
    protected function findViewNames(string $schema = ''): array
771 3
    {
772
        if ($schema === '') {
773 3
            $schema = $this->defaultSchema;
774 1
        }
775
776
        $sql = <<<SQL
777 3
        SELECT [t].[table_name]
778
        FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
779
        WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
780
        ORDER BY [t].[table_name]
781
        SQL;
782
783
        $views = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
784 3
        if (!$views) {
785 3
            return [];
786
        }
787
788
        return array_map(static fn (string $item): string => '[' . $item . ']', $views);
789 3
    }
790
791
    /**
792
     * Returns all unique indexes for the given table.
793
     *
794
     * Each array element is of the following structure:
795
     *
796
     * ```php
797
     * [
798
     *     'IndexName1' => ['col1' [, ...]],
799
     *     'IndexName2' => ['col2' [, ...]],
800
     * ]
801
     * ```
802
     *
803
     * @param TableSchemaInterface $table the table metadata.
804
     *
805
     * @throws Exception|InvalidConfigException|Throwable
806
     *
807
     * @return array all unique indexes for the given table.
808
     */
809
    public function findUniqueIndexes(TableSchemaInterface $table): array
810 1
    {
811
        $result = [];
812 1
813
        /** @psalm-var array<array-key, array{index_name: string, field_name: string}> $tableUniqueConstraints */
814
        $tableUniqueConstraints = $this->findTableConstraints($table, 'UNIQUE');
815 1
816
        foreach ($tableUniqueConstraints as $row) {
817 1
            $result[$row['index_name']][] = $row['field_name'];
818 1
        }
819
820
        return $result;
821 1
    }
822
823
    /**
824
     * Loads multiple types of constraints and returns the specified ones.
825
     *
826
     * @param string $tableName table name.
827
     * @param string $returnType return type:
828
     * - primaryKey
829
     * - foreignKeys
830
     * - uniques
831
     * - checks
832
     * - defaults
833
     *
834
     * @throws Exception|InvalidConfigException|Throwable
835
     *
836
     * @return mixed constraints.
837
     */
838
    private function loadTableConstraints(string $tableName, string $returnType): mixed
839 79
    {
840
        $sql = <<<SQL
841 79
        SELECT
842
            [o].[name] AS [name],
843
            COALESCE([ccol].[name], [dcol].[name], [fccol].[name], [kiccol].[name]) AS [column_name],
844
            RTRIM([o].[type]) AS [type],
845
            OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [foreign_table_schema],
846
            OBJECT_NAME([f].[referenced_object_id]) AS [foreign_table_name],
847
            [ffccol].[name] AS [foreign_column_name],
848
            [f].[update_referential_action_desc] AS [on_update],
849
            [f].[delete_referential_action_desc] AS [on_delete],
850
            [c].[definition] AS [check_expr],
851
            [d].[definition] AS [default_expr]
852
        FROM (SELECT OBJECT_ID(:fullName) AS [object_id]) AS [t]
853
        INNER JOIN [sys].[objects] AS [o]
854
            ON [o].[parent_object_id] = [t].[object_id] AND [o].[type] IN ('PK', 'UQ', 'C', 'D', 'F')
855
        LEFT JOIN [sys].[check_constraints] AS [c]
856
            ON [c].[object_id] = [o].[object_id]
857
        LEFT JOIN [sys].[columns] AS [ccol]
858
            ON [ccol].[object_id] = [c].[parent_object_id] AND [ccol].[column_id] = [c].[parent_column_id]
859
        LEFT JOIN [sys].[default_constraints] AS [d]
860
            ON [d].[object_id] = [o].[object_id]
861
        LEFT JOIN [sys].[columns] AS [dcol]
862
            ON [dcol].[object_id] = [d].[parent_object_id] AND [dcol].[column_id] = [d].[parent_column_id]
863
        LEFT JOIN [sys].[key_constraints] AS [k]
864
            ON [k].[object_id] = [o].[object_id]
865
        LEFT JOIN [sys].[index_columns] AS [kic]
866
            ON [kic].[object_id] = [k].[parent_object_id] AND [kic].[index_id] = [k].[unique_index_id]
867
        LEFT JOIN [sys].[columns] AS [kiccol]
868
            ON [kiccol].[object_id] = [kic].[object_id] AND [kiccol].[column_id] = [kic].[column_id]
869
        LEFT JOIN [sys].[foreign_keys] AS [f]
870
            ON [f].[object_id] = [o].[object_id]
871
        LEFT JOIN [sys].[foreign_key_columns] AS [fc]
872
            ON [fc].[constraint_object_id] = [o].[object_id]
873
        LEFT JOIN [sys].[columns] AS [fccol]
874
            ON [fccol].[object_id] = [fc].[parent_object_id] AND [fccol].[column_id] = [fc].[parent_column_id]
875
        LEFT JOIN [sys].[columns] AS [ffccol]
876
            ON [ffccol].[object_id] = [fc].[referenced_object_id] AND [ffccol].[column_id] = [fc].[referenced_column_id]
877
        ORDER BY [kic].[key_ordinal] ASC, [fc].[constraint_column_id] ASC
878
        SQL;
879
880
        $resolvedName = $this->resolveTableName($tableName);
881 79
        $constraints = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
882 79
883
        /** @psalm-var array[] $constraints */
884
        $constraints = $this->normalizeRowKeyCase($constraints, true);
885 79
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
886 79
887
        $result = [
888 79
            self::PRIMARY_KEY => null,
889
            self::FOREIGN_KEYS => [],
890 79
            self::UNIQUES => [],
891 79
            self::CHECKS => [],
892 79
            self::DEFAULTS => [],
893 79
        ];
894
895
        /** @psalm-var array<array-key, array> $constraints */
896
        foreach ($constraints as $type => $names) {
897 79
            /**
898
             * @psalm-var object|string|null $name
899
             * @psalm-var ConstraintArray $constraint
900
             */
901
            foreach ($names as $name => $constraint) {
902 79
                switch ($type) {
903 79
                    case 'PK':
904 79
                        /** @var Constraint */
905
                        $result[self::PRIMARY_KEY] = (new Constraint())
906 58
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
907 58
                            ->name($name);
908 58
                        break;
909 58
                    case 'F':
910 79
                        $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint())
911 21
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
912 21
                            ->foreignTableName($constraint[0]['foreign_table_name'])
913 21
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
914 21
                            ->onDelete(str_replace('_', '', $constraint[0]['on_delete']))
915 21
                            ->onUpdate(str_replace('_', '', $constraint[0]['on_update']))
916 21
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
917 21
                            ->name($name);
918 21
                        break;
919 21
                    case 'UQ':
920 64
                        $result[self::UNIQUES][] = (new Constraint())
921 62
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
922 62
                            ->name($name);
923 62
                        break;
924 62
                    case 'C':
925 36
                        $result[self::CHECKS][] = (new CheckConstraint())
926 18
                            ->expression($constraint[0]['check_expr'])
927 18
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
928 18
                            ->name($name);
929 18
                        break;
930 18
                    case 'D':
931 35
                        $result[self::DEFAULTS][] = (new DefaultValueConstraint())
932 35
                            ->value($constraint[0]['default_expr'])
933 35
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
934 35
                            ->name($name);
935 35
                        break;
936 35
                }
937
            }
938
        }
939
940
        foreach ($result as $type => $data) {
941 79
            $this->setTableMetadata($tableName, $type, $data);
942 79
        }
943
944
        return $result[$returnType];
945 79
    }
946
947
    /**
948
     * Create a column schema builder instance giving the type and value precision.
949
     *
950
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
951
     *
952
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
953
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
954
     *
955
     * @return ColumnSchemaBuilder column schema builder instance
956
     *
957
     * @psalm-param array<array-key, string>|int|null|string $length
958
     */
959
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
960 3
    {
961
        return new ColumnSchemaBuilder($type, $length);
962 3
    }
963
964
    /**
965
     * Returns the actual name of a given table name.
966
     *
967
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
968
     * {@see ConnectionInterface::tablePrefix}.
969
     *
970
     * @param string $name the table name to be converted.
971
     *
972
     * @return string the real name of the given table name.
973
     */
974
    public function getRawTableName(string $name): string
975 177
    {
976
        if (str_contains($name, '{{')) {
977 177
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
978 24
979
            return str_replace('%', $this->db->getTablePrefix(), $name);
980 24
        }
981
982
        return $name;
983 177
    }
984
985
    /**
986
     * Returns the cache key for the specified table name.
987
     *
988
     * @param string $name the table name.
989
     *
990
     * @return array the cache key.
991
     */
992
    protected function getCacheKey(string $name): array
993 177
    {
994
        return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
995 177
    }
996
997
    /**
998
     * Returns the cache tag name.
999
     *
1000
     * This allows {@see refresh()} to invalidate all cached table schemas.
1001
     *
1002
     * @return string the cache tag name.
1003
     */
1004
    protected function getCacheTag(): string
1005 177
    {
1006
        return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey())));
1007 177
    }
1008
1009
    /**
1010
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
1011
     */
1012
    public function supportsSavepoint(): bool
1013 5
    {
1014
        return $this->db->isSavepointEnabled();
1015 5
    }
1016
1017
    /**
1018
     * Changes row's array key case to lower.
1019
     *
1020
     * @param array $row row's array or an array of row's arrays.
1021
     * @param bool $multiple whether multiple rows or a single row passed.
1022
     *
1023
     * @return array normalized row or rows.
1024
     */
1025
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
1026 90
    {
1027
        if ($multiple) {
1028 90
            return array_map(static function (array $row) {
1029 90
                return array_change_key_case($row, CASE_LOWER);
1030 87
            }, $row);
1031
        }
1032
1033
        return array_change_key_case($row, CASE_LOWER);
1034
    }
1035
1036
    /**
1037
     * @inheritDoc
1038
     */
1039
    public function getLastInsertID(?string $sequenceName = null): string
1040
    {
1041
        return $this->db->getLastInsertID($sequenceName);
1042
    }
1043
}
1044