Test Failed
Pull Request — master (#66)
by Wilmer
18:24 queued 07:05
created

SchemaPDOMssql::loadColumnSchema()   C

Complexity

Conditions 15
Paths 92

Size

Total Lines 53
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 15
eloc 33
c 1
b 0
f 0
nc 92
nop 1
dl 0
loc 53
rs 5.9166

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\PDO;
6
7
use Throwable;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Db\Cache\SchemaCache;
10
use Yiisoft\Db\Connection\ConnectionPDOInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\ConnectionPDOInterface 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...
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\InvalidCallException;
18
use Yiisoft\Db\Exception\InvalidConfigException;
19
use Yiisoft\Db\Mssql\ColumnSchema;
20
use Yiisoft\Db\Mssql\PDO;
21
use Yiisoft\Db\Mssql\TableSchema;
22
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
23
use Yiisoft\Db\Schema\Schema;
24
use Yiisoft\Db\View\ViewInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\View\ViewInterface 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...
25
26
use function array_map;
27
use function count;
28
use function explode;
29
use function preg_match;
30
use function preg_match_all;
31
use function str_replace;
32
use function strcasecmp;
33
use function stripos;
34
use function version_compare;
35
36
/**
37
 * Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
38
 *
39
 * @psalm-type ConstraintArray = array<
40
 *   array-key,
41
 *   array {
42
 *     name: string,
43
 *     column_name: string,
44
 *     type: string,
45
 *     foreign_table_schema: string|null,
46
 *     foreign_table_name: string|null,
47
 *     foreign_column_name: string|null,
48
 *     on_update: string,
49
 *     on_delete: string,
50
 *     check_expr: string,
51
 *     default_expr?: string
52
 *   }
53
 * >
54
 */
55
final class SchemaPDOMssql extends Schema implements ViewInterface
56
{
57
    /**
58
     * @var string|null the default schema used for the current session.
59
     */
60
    protected ?string $defaultSchema = 'dbo';
61
62
    /**
63
     * @var array mapping from physical column types (keys) to abstract column types (values)
64
     */
65
    private array $typeMap = [
66
        /** exact numbers */
67
        'bigint' => self::TYPE_BIGINT,
68
        'numeric' => self::TYPE_DECIMAL,
69
        'bit' => self::TYPE_SMALLINT,
70
        'smallint' => self::TYPE_SMALLINT,
71
        'decimal' => self::TYPE_DECIMAL,
72
        'smallmoney' => self::TYPE_MONEY,
73
        'int' => self::TYPE_INTEGER,
74
        'tinyint' => self::TYPE_TINYINT,
75
        'money' => self::TYPE_MONEY,
76
77
        /** approximate numbers */
78
        'float' => self::TYPE_FLOAT,
79
        'double' => self::TYPE_DOUBLE,
80
        'real' => self::TYPE_FLOAT,
81
82
        /** date and time */
83
        'date' => self::TYPE_DATE,
84
        'datetimeoffset' => self::TYPE_DATETIME,
85
        'datetime2' => self::TYPE_DATETIME,
86
        'smalldatetime' => self::TYPE_DATETIME,
87
        'datetime' => self::TYPE_DATETIME,
88
        'time' => self::TYPE_TIME,
89
90
        /** character strings */
91
        'char' => self::TYPE_CHAR,
92
        'varchar' => self::TYPE_STRING,
93
        'text' => self::TYPE_TEXT,
94
95
        /** unicode character strings */
96
        'nchar' => self::TYPE_CHAR,
97
        'nvarchar' => self::TYPE_STRING,
98
        'ntext' => self::TYPE_TEXT,
99
100
        /** binary strings */
101
        'binary' => self::TYPE_BINARY,
102
        'varbinary' => self::TYPE_BINARY,
103
        'image' => self::TYPE_BINARY,
104
105
        /**
106
         * other data types 'cursor' type cannot be used with tables
107
         */
108
        'timestamp' => self::TYPE_TIMESTAMP,
109
        'hierarchyid' => self::TYPE_STRING,
110
        'uniqueidentifier' => self::TYPE_STRING,
111
        'sql_variant' => self::TYPE_STRING,
112
        'xml' => self::TYPE_STRING,
113
        'table' => self::TYPE_STRING,
114
    ];
115
116
    private ?string $serverVersion = null;
0 ignored issues
show
introduced by
The private property $serverVersion is not used, and could be removed.
Loading history...
117
    private array $viewNames = [];
118
119
    public function __construct(private ConnectionPDOInterface $db, SchemaCache $schemaCache)
120
    {
121
        parent::__construct($schemaCache);
0 ignored issues
show
Bug introduced by
The call to Yiisoft\Db\Schema\Schema::__construct() has too few arguments starting with schemaCache. ( Ignorable by Annotation )

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

121
        parent::/** @scrutinizer ignore-call */ 
122
                __construct($schemaCache);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
$schemaCache of type Yiisoft\Db\Cache\SchemaCache is incompatible with the type Yiisoft\Db\Connection\ConnectionInterface expected by parameter $db of Yiisoft\Db\Schema\Schema::__construct(). ( Ignorable by Annotation )

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

121
        parent::__construct(/** @scrutinizer ignore-type */ $schemaCache);
Loading history...
122
    }
123
124
    /**
125
     * Resolves the table name and schema name (if any).
126
     *
127
     * @param string $name the table name.
128
     *
129
     * @return TableSchema resolved table, schema, etc. names.
130
     */
131
    protected function resolveTableName(string $name): TableSchema
132
    {
133
        $resolvedName = new TableSchema();
134
135
        $parts = $this->getTableNameParts($name);
136
137
        $partCount = count($parts);
138
139
        if ($partCount === 4) {
140
            /** server name, catalog name, schema name and table name passed */
141
            $resolvedName->catalogName($parts[1]);
142
            $resolvedName->schemaName($parts[2]);
143
            $resolvedName->name($parts[3]);
144
            $resolvedName->fullName(
145
                $resolvedName->getCatalogName() . '.' . $resolvedName->getSchemaName() . '.' . $resolvedName->getName()
146
            );
147
        } elseif ($partCount === 3) {
148
            /** catalog name, schema name and table name passed */
149
            $resolvedName->catalogName($parts[0]);
150
            $resolvedName->schemaName($parts[1]);
151
            $resolvedName->name($parts[2]);
152
            $resolvedName->fullName(
153
                $resolvedName->getCatalogName() . '.' . $resolvedName->getSchemaName() . '.' . $resolvedName->getName()
154
            );
155
        } elseif ($partCount === 2) {
156
            /** only schema name and table name passed */
157
            $resolvedName->schemaName($parts[0]);
158
            $resolvedName->name($parts[1]);
159
            $resolvedName->fullName(
160
                ($resolvedName->getSchemaName() !== $this->defaultSchema
161
                    ? $resolvedName->getSchemaName() . '.' : '') . $resolvedName->getName()
162
            );
163
        } else {
164
            /** only table name passed */
165
            $resolvedName->schemaName($this->defaultSchema);
166
            $resolvedName->name($parts[0]);
167
            $resolvedName->fullName($resolvedName->getName());
168
        }
169
170
        return $resolvedName;
171
    }
172
173
    /**
174
     * Splits full table name into parts.
175
     *
176
     * @param string $name
177
     *
178
     * @return array
179
     */
180
    protected function getTableNameParts(string $name): array
181
    {
182
        $parts = [$name];
183
184
        preg_match_all('/([^.\[\]]+)|\[([^\[\]]+)]/', $name, $matches);
185
186
        if (isset($matches[0]) && !empty($matches[0])) {
187
            $parts = $matches[0];
188
        }
189
190
        return str_replace(['[', ']'], '', $parts);
191
    }
192
193
    /**
194
     * Returns all schema names in the database, including the default one but not system schemas.
195
     *
196
     * This method should be overridden by child classes in order to support this feature because the default
197
     * implementation simply throws an exception.
198
     *
199
     * @throws Exception|InvalidConfigException|Throwable
200
     *
201
     * @return array all schema names in the database, except system schemas.
202
     *
203
     * {@see https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-principals-transact-sql}
204
     */
205
    protected function findSchemaNames(): array
206
    {
207
        $sql = <<<SQL
208
        SELECT [s].[name]
209
        FROM [sys].[schemas] AS [s]
210
        INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
211
        WHERE [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
212
        ORDER BY [s].[name] ASC
213
        SQL;
214
215
        return $this->db->createCommand($sql)->queryColumn();
216
    }
217
218
    /**
219
     * Returns all table names in the database.
220
     *
221
     * This method should be overridden by child classes in order to support this feature because the default
222
     * implementation simply throws an exception.
223
     *
224
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
225
     *
226
     * @throws Exception|InvalidConfigException|Throwable
227
     *
228
     * @return array all table names in the database. The names have NO schema name prefix.
229
     */
230
    protected function findTableNames(string $schema = ''): array
231
    {
232
        if ($schema === '') {
233
            $schema = $this->defaultSchema;
234
        }
235
236
        $sql = <<<SQL
237
SELECT [t].[table_name]
238
FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
239
WHERE [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
240
ORDER BY [t].[table_name]
241
SQL;
242
243
        $tables = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
244
245
        return array_map(static function ($item) {
246
            return '[' . $item . ']';
247
        }, $tables);
248
    }
249
250
    /**
251
     * Loads the metadata for the specified table.
252
     *
253
     * @param string $name table name.
254
     *
255
     * @throws Exception|InvalidConfigException|Throwable
256
     *
257
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
258
     */
259
    protected function loadTableSchema(string $name): ?TableSchema
260
    {
261
        $table = new TableSchema();
262
263
        $this->resolveTableNames($table, $name);
264
        $this->findPrimaryKeys($table);
265
266
        if ($this->findColumns($table)) {
267
            $this->findForeignKeys($table);
268
                return $table;
269
        }
270
271
        return null;
272
    }
273
274
    /**
275
     * Loads a primary key for the given table.
276
     *
277
     * @param string $tableName table name.
278
     *
279
     * @throws Exception|InvalidConfigException|Throwable
280
     *
281
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.
282
     */
283
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
284
    {
285
        return $this->loadTableConstraints($tableName, 'primaryKey');
286
    }
287
288
    /**
289
     * Loads all foreign keys for the given table.
290
     *
291
     * @param string $tableName table name.
292
     *
293
     * @throws Exception|InvalidConfigException|Throwable
294
     *
295
     * @return ForeignKeyConstraint[] foreign keys for the given table.
296
     */
297
    protected function loadTableForeignKeys(string $tableName): array
298
    {
299
        return $this->loadTableConstraints($tableName, 'foreignKeys');
300
    }
301
302
    /**
303
     * Loads all indexes for the given table.
304
     *
305
     * @param string $tableName table name.
306
     *
307
     * @throws Exception|InvalidConfigException|Throwable
308
     *
309
     * @return array indexes for the given table.
310
     */
311
    protected function loadTableIndexes(string $tableName): array
312
    {
313
        $sql = <<<SQL
314
SELECT
315
    [i].[name] AS [name],
316
    [iccol].[name] AS [column_name],
317
    [i].[is_unique] AS [index_is_unique],
318
    [i].[is_primary_key] AS [index_is_primary]
319
FROM [sys].[indexes] AS [i]
320
INNER JOIN [sys].[index_columns] AS [ic]
321
    ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
322
INNER JOIN [sys].[columns] AS [iccol]
323
    ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
324
WHERE [i].[object_id] = OBJECT_ID(:fullName)
325
ORDER BY [ic].[key_ordinal] ASC
326
SQL;
327
        $resolvedName = $this->resolveTableName($tableName);
328
        $indexes = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
329
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
330
        $indexes = ArrayHelper::index($indexes, null, 'name');
331
332
        $result = [];
333
334
        foreach ($indexes as $name => $index) {
335
            $result[] = (new IndexConstraint())
336
                ->primary((bool) $index[0]['index_is_primary'])
337
                ->unique((bool) $index[0]['index_is_unique'])
338
                ->columnNames(ArrayHelper::getColumn($index, 'column_name'))
339
                ->name($name);
340
        }
341
342
        return $result;
343
    }
344
345
    /**
346
     * Loads all unique constraints for the given table.
347
     *
348
     * @param string $tableName table name.
349
     *
350
     * @throws Exception|InvalidConfigException|Throwable
351
     *
352
     * @return Constraint[] unique constraints for the given table.
353
     */
354
    protected function loadTableUniques(string $tableName): array
355
    {
356
        return $this->loadTableConstraints($tableName, 'uniques');
357
    }
358
359
    /**
360
     * Loads all check constraints for the given table.
361
     *
362
     * @param string $tableName table name.
363
     *
364
     * @throws Exception|InvalidConfigException|Throwable
365
     *
366
     * @return CheckConstraint[] check constraints for the given table.
367
     */
368
    protected function loadTableChecks(string $tableName): array
369
    {
370
        return $this->loadTableConstraints($tableName, 'checks');
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 DefaultValueConstraint[] default value constraints for the given table.
381
     */
382
    protected function loadTableDefaultValues(string $tableName): array
383
    {
384
        return $this->loadTableConstraints($tableName, 'defaults');
385
    }
386
387
    /**
388
     * Creates a new savepoint.
389
     *
390
     * @param string $name the savepoint name.
391
     *
392
     * @throws Exception|InvalidConfigException|Throwable
393
     */
394
    public function createSavepoint(string $name): void
395
    {
396
        $this->db->createCommand("SAVE TRANSACTION $name")->execute();
397
    }
398
399
    /**
400
     * Releases an existing savepoint.
401
     *
402
     * @param string $name the savepoint name.
403
     */
404
    public function releaseSavepoint(string $name): void
405
    {
406
        /** does nothing as MSSQL does not support this */
407
    }
408
409
    /**
410
     * Rolls back to a previously created savepoint.
411
     *
412
     * @param string $name the savepoint name.
413
     *
414
     * @throws Exception|InvalidConfigException|Throwable
415
     */
416
    public function rollBackSavepoint(string $name): void
417
    {
418
        $this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
419
    }
420
421
    /**
422
     * Creates a column schema for the database.
423
     *
424
     * This method may be overridden by child classes to create a DBMS-specific column schema.
425
     *
426
     * @return ColumnSchema column schema instance.
427
     */
428
    protected function createColumnSchema(): ColumnSchema
429
    {
430
        return new ColumnSchema();
431
    }
432
433
    /**
434
     * Resolves the table name and schema name (if any).
435
     *
436
     * @param TableSchema $table the table metadata object.
437
     * @param string $name the table name
438
     */
439
    protected function resolveTableNames(TableSchema $table, string $name): void
440
    {
441
        $parts = $this->getTableNameParts($name);
442
443
        $partCount = count($parts);
444
445
        if ($partCount === 4) {
446
            /** server name, catalog name, schema name and table name passed */
447
            $table->catalogName($parts[1]);
448
            $table->schemaName($parts[2]);
449
            $table->name($parts[3]);
450
            $table->fullName($table->getCatalogName() . '.' . $table->getSchemaName() . '.' . $table->getName());
451
        } elseif ($partCount === 3) {
452
            /** catalog name, schema name and table name passed */
453
            $table->catalogName($parts[0]);
454
            $table->schemaName($parts[1]);
455
            $table->name($parts[2]);
456
            $table->fullName($table->getCatalogName() . '.' . $table->getSchemaName() . '.' . $table->getName());
457
        } elseif ($partCount === 2) {
458
            /** only schema name and table name passed */
459
            $table->schemaName($parts[0]);
460
            $table->name($parts[1]);
461
            $table->fullName(
462
                $table->getSchemaName() !== $this->defaultSchema
463
                ? $table->getSchemaName() . '.' . $table->getName() : $table->getName()
464
            );
465
        } else {
466
            /** only table name passed */
467
            $table->schemaName($this->defaultSchema);
468
            $table->name($parts[0]);
469
            $table->fullName($table->getName());
470
        }
471
    }
472
473
    /**
474
     * Loads the column information into a {@see ColumnSchema} object.
475
     *
476
     * @param array $info column information.
477
     *
478
     * @return ColumnSchema the column schema object.
479
     */
480
    protected function loadColumnSchema(array $info): ColumnSchema
481
    {
482
        $column = $this->createColumnSchema();
483
484
        $column->name($info['column_name']);
485
        $column->allowNull($info['is_nullable'] === 'YES');
486
        $column->dbType($info['data_type']);
487
        $column->enumValues([]); // mssql has only vague equivalents to enum
488
        $column->primaryKey(false); // primary key will be determined in findColumns() method
489
        $column->autoIncrement($info['is_identity'] === 1);
490
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
491
        $column->comment($info['comment'] ?? '');
492
        $column->type(self::TYPE_STRING);
493
494
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
495
            $type = $matches[1];
496
497
            if (isset($this->typeMap[$type])) {
498
                $column->type($this->typeMap[$type]);
499
            }
500
501
            if (!empty($matches[2])) {
502
                $values = explode(',', $matches[2]);
503
                $column->precision((int) $values[0]);
504
                $column->size((int) $values[0]);
505
506
                if (isset($values[1])) {
507
                    $column->scale((int) $values[1]);
508
                }
509
510
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
511
                    $column->type('boolean');
512
                } elseif ($type === 'bit') {
513
                    if ($column->getSize() > 32) {
514
                        $column->type('bigint');
515
                    } elseif ($column->getSize() === 32) {
516
                        $column->type('integer');
517
                    }
518
                }
519
            }
520
        }
521
522
        $column->phpType($this->getColumnPhpType($column));
523
524
        if ($info['column_default'] === '(NULL)') {
525
            $info['column_default'] = null;
526
        }
527
528
        if (!$column->isPrimaryKey() && ($column->getType() !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
529
            $column->defaultValue($column->defaultPhpTypecast($info['column_default']));
530
        }
531
532
        return $column;
533
    }
534
535
    /**
536
     * Collects the metadata of table columns.
537
     *
538
     * @param TableSchema $table the table metadata.
539
     *
540
     * @throws Throwable
541
     *
542
     * @return bool whether the table exists in the database.
543
     */
544
    protected function findColumns(TableSchema $table): bool
545
    {
546
        $columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
547
        $whereSql = '[t1].[table_name] = ' . $this->db->getQuoter()->quoteValue($table->getName());
548
549
        if ($table->getCatalogName() !== null) {
550
            $columnsTableName = "{$table->getCatalogName()}.$columnsTableName";
551
            $whereSql .= " AND [t1].[table_catalog] = '{$table->getCatalogName()}'";
552
        }
553
554
        if ($table->getSchemaName() !== null) {
555
            $whereSql .= " AND [t1].[table_schema] = '{$table->getSchemaName()}'";
556
        }
557
558
        $columnsTableName = $this->db->getQuoter()->quoteTableName($columnsTableName);
559
560
        $sql = <<<SQL
561
        SELECT
562
            [t1].[column_name],
563
            [t1].[is_nullable],
564
        CASE WHEN [t1].[data_type] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
565
        CASE WHEN [t1].[character_maximum_length] = NULL OR [t1].[character_maximum_length] = -1 THEN
566
            [t1].[data_type]
567
        ELSE
568
            [t1].[data_type] + '(' + LTRIM(RTRIM(CONVERT(CHAR,[t1].[character_maximum_length]))) + ')'
569
        END
570
        ELSE
571
            [t1].[data_type]
572
        END AS 'data_type',
573
        [t1].[column_default],
574
        COLUMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
575
        (
576
        SELECT CONVERT(VARCHAR, [t2].[value])
577
        FROM [sys].[extended_properties] AS [t2]
578
        WHERE
579
        [t2].[class] = 1 AND
580
        [t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
581
        [t2].[name] = 'MS_Description' AND
582
        [t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
583
        [t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
584
        ) as comment
585
        FROM $columnsTableName AS [t1]
586
        WHERE $whereSql
587
        SQL;
588
589
        try {
590
            $columns = $this->db->createCommand($sql)->queryAll();
591
592
            if (empty($columns)) {
593
                return false;
594
            }
595
        } catch (Exception $e) {
596
            return false;
597
        }
598
599
        foreach ($columns as $column) {
600
            $column = $this->loadColumnSchema($column);
601
            foreach ($table->getPrimaryKey() as $primaryKey) {
602
                if (strcasecmp($column->getName(), $primaryKey) === 0) {
603
                    $column->primaryKey(true);
604
                    break;
605
                }
606
            }
607
608
            if ($column->isPrimaryKey() && $column->isAutoIncrement()) {
609
                $table->sequenceName('');
610
            }
611
612
            $table->columns($column->getName(), $column);
613
        }
614
615
        return true;
616
    }
617
618
    /**
619
     * Collects the constraint details for the given table and constraint type.
620
     *
621
     * @param TableSchema $table
622
     * @param string $type either PRIMARY KEY or UNIQUE.
623
     *
624
     * @throws Exception|InvalidConfigException|Throwable
625
     *
626
     * @return array each entry contains index_name and field_name.
627
     */
628
    protected function findTableConstraints(TableSchema $table, string $type): array
629
    {
630
        $keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
631
        $tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
632
633
        if ($table->getCatalogName() !== null) {
634
            $keyColumnUsageTableName = $table->getCatalogName() . '.' . $keyColumnUsageTableName;
635
            $tableConstraintsTableName = $table->getCatalogName() . '.' . $tableConstraintsTableName;
636
        }
637
638
        $keyColumnUsageTableName = $this->db->getQuoter()->quoteTableName($keyColumnUsageTableName);
639
        $tableConstraintsTableName = $this->db->getQuoter()->quoteTableName($tableConstraintsTableName);
640
641
        $sql = <<<SQL
642
        SELECT
643
            [kcu].[constraint_name] AS [index_name],
644
            [kcu].[column_name] AS [field_name]
645
        FROM $keyColumnUsageTableName AS [kcu]
646
        LEFT JOIN $tableConstraintsTableName AS [tc] ON
647
            [kcu].[table_schema] = [tc].[table_schema] AND
648
            [kcu].[table_name] = [tc].[table_name] AND
649
            [kcu].[constraint_name] = [tc].[constraint_name]
650
        WHERE
651
            [tc].[constraint_type] = :type AND
652
            [kcu].[table_name] = :tableName AND
653
            [kcu].[table_schema] = :schemaName
654
        SQL;
655
656
        return $this->db->createCommand(
657
            $sql,
658
            [
659
                ':tableName' => $table->getName(),
660
                ':schemaName' => $table->getSchemaName(),
661
                ':type' => $type,
662
            ]
663
        )->queryAll();
664
    }
665
666
    /**
667
     * Collects the primary key column details for the given table.
668
     *
669
     * @param TableSchema $table the table metadata
670
     *
671
     * @throws Exception|InvalidConfigException|Throwable
672
     */
673
    protected function findPrimaryKeys(TableSchema $table): void
674
    {
675
        foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
676
            $table->primaryKey($row['field_name']);
677
        }
678
    }
679
680
    /**
681
     * Collects the foreign key column details for the given table.
682
     *
683
     * @param TableSchema $table the table metadata
684
     *
685
     * @throws Exception|InvalidConfigException|Throwable
686
     */
687
    protected function findForeignKeys(TableSchema $table): void
688
    {
689
        $object = $table->getName();
690
691
        if ($table->getSchemaName() !== null) {
692
            $object = $table->getSchemaName() . '.' . $object;
693
        }
694
695
        if ($table->getCatalogName() !== null) {
696
            $object = $table->getCatalogName() . '.' . $object;
697
        }
698
699
        /**
700
         * Please refer to the following page for more details:
701
         * {@see http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx}
702
         */
703
        $sql = <<<SQL
704
SELECT
705
	[fk].[name] AS [fk_name],
706
	[cp].[name] AS [fk_column_name],
707
	OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
708
	[cr].[name] AS [uq_column_name]
709
FROM
710
	[sys].[foreign_keys] AS [fk]
711
	INNER JOIN [sys].[foreign_key_columns] AS [fkc] ON
712
		[fk].[object_id] = [fkc].[constraint_object_id]
713
	INNER JOIN [sys].[columns] AS [cp] ON
714
		[fk].[parent_object_id] = [cp].[object_id] AND
715
		[fkc].[parent_column_id] = [cp].[column_id]
716
	INNER JOIN [sys].[columns] AS [cr] ON
717
		[fk].[referenced_object_id] = [cr].[object_id] AND
718
		[fkc].[referenced_column_id] = [cr].[column_id]
719
WHERE
720
	[fk].[parent_object_id] = OBJECT_ID(:object)
721
SQL;
722
723
        $rows = $this->db->createCommand($sql, [':object' => $object])->queryAll();
724
725
        $table->foreignKeys([]);
726
727
        foreach ($rows as $row) {
728
            if (!isset($table->getForeignKeys()[$row['fk_name']])) {
729
                $fk[$row['fk_name']][] = $row['uq_table_name'];
730
                $table->foreignKeys($fk);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fk seems to be defined later in this foreach loop on line 729. Are you sure it is defined here?
Loading history...
731
            }
732
733
            $fk[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
734
            $table->foreignKeys($fk);
735
        }
736
    }
737
738
    public function findViewNames(string $schema = ''): array
739
    {
740
        if ($schema === '') {
741
            $schema = $this->defaultSchema;
742
        }
743
744
        $sql = <<<SQL
745
        SELECT [t].[table_name]
746
        FROM [INFORMATION_SCHEMA].[TABLES] AS [t]
747
        WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
748
        ORDER BY [t].[table_name]
749
        SQL;
750
751
        $views = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
752
753
        return array_map(static function ($item) {
754
            return '[' . $item . ']';
755
        }, $views);
756
    }
757
758
    /**
759
     * Returns all unique indexes for the given table.
760
     *
761
     * Each array element is of the following structure:
762
     *
763
     * ```php
764
     * [
765
     *     'IndexName1' => ['col1' [, ...]],
766
     *     'IndexName2' => ['col2' [, ...]],
767
     * ]
768
     * ```
769
     *
770
     * @param TableSchema $table the table metadata.
771
     *
772
     * @throws Exception|InvalidConfigException|Throwable
773
     *
774
     * @return array all unique indexes for the given table.
775
     */
776
    public function findUniqueIndexes(TableSchema $table): array
777
    {
778
        $result = [];
779
780
        foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
781
            $result[$row['index_name']][] = $row['field_name'];
782
        }
783
784
        return $result;
785
    }
786
787
    /**
788
     * Loads multiple types of constraints and returns the specified ones.
789
     *
790
     * @param string $tableName table name.
791
     * @param string $returnType return type:
792
     * - primaryKey
793
     * - foreignKeys
794
     * - uniques
795
     * - checks
796
     * - defaults
797
     *
798
     * @throws Exception|InvalidConfigException|Throwable
799
     *
800
     * @return mixed constraints.
801
     */
802
    private function loadTableConstraints(string $tableName, string $returnType): mixed
803
    {
804
        $sql = <<<SQL
805
SELECT
806
    [o].[name] AS [name],
807
    COALESCE([ccol].[name], [dcol].[name], [fccol].[name], [kiccol].[name]) AS [column_name],
808
    RTRIM([o].[type]) AS [type],
809
    OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [foreign_table_schema],
810
    OBJECT_NAME([f].[referenced_object_id]) AS [foreign_table_name],
811
    [ffccol].[name] AS [foreign_column_name],
812
    [f].[update_referential_action_desc] AS [on_update],
813
    [f].[delete_referential_action_desc] AS [on_delete],
814
    [c].[definition] AS [check_expr],
815
    [d].[definition] AS [default_expr]
816
FROM (SELECT OBJECT_ID(:fullName) AS [object_id]) AS [t]
817
INNER JOIN [sys].[objects] AS [o]
818
    ON [o].[parent_object_id] = [t].[object_id] AND [o].[type] IN ('PK', 'UQ', 'C', 'D', 'F')
819
LEFT JOIN [sys].[check_constraints] AS [c]
820
    ON [c].[object_id] = [o].[object_id]
821
LEFT JOIN [sys].[columns] AS [ccol]
822
    ON [ccol].[object_id] = [c].[parent_object_id] AND [ccol].[column_id] = [c].[parent_column_id]
823
LEFT JOIN [sys].[default_constraints] AS [d]
824
    ON [d].[object_id] = [o].[object_id]
825
LEFT JOIN [sys].[columns] AS [dcol]
826
    ON [dcol].[object_id] = [d].[parent_object_id] AND [dcol].[column_id] = [d].[parent_column_id]
827
LEFT JOIN [sys].[key_constraints] AS [k]
828
    ON [k].[object_id] = [o].[object_id]
829
LEFT JOIN [sys].[index_columns] AS [kic]
830
    ON [kic].[object_id] = [k].[parent_object_id] AND [kic].[index_id] = [k].[unique_index_id]
831
LEFT JOIN [sys].[columns] AS [kiccol]
832
    ON [kiccol].[object_id] = [kic].[object_id] AND [kiccol].[column_id] = [kic].[column_id]
833
LEFT JOIN [sys].[foreign_keys] AS [f]
834
    ON [f].[object_id] = [o].[object_id]
835
LEFT JOIN [sys].[foreign_key_columns] AS [fc]
836
    ON [fc].[constraint_object_id] = [o].[object_id]
837
LEFT JOIN [sys].[columns] AS [fccol]
838
    ON [fccol].[object_id] = [fc].[parent_object_id] AND [fccol].[column_id] = [fc].[parent_column_id]
839
LEFT JOIN [sys].[columns] AS [ffccol]
840
    ON [ffccol].[object_id] = [fc].[referenced_object_id] AND [ffccol].[column_id] = [fc].[referenced_column_id]
841
ORDER BY [kic].[key_ordinal] ASC, [fc].[constraint_column_id] ASC
842
SQL;
843
844
        $resolvedName = $this->resolveTableName($tableName);
845
        $constraints = $this->db->createCommand($sql, [':fullName' => $resolvedName->getFullName()])->queryAll();
846
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
847
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
848
        $result = [
849
            'primaryKey' => null,
850
            'foreignKeys' => [],
851
            'uniques' => [],
852
            'checks' => [],
853
            'defaults' => [],
854
        ];
855
856
        /** @psalm-var array<array-key, array> $constraints */
857
        foreach ($constraints as $type => $names) {
858
            /**
859
             * @psalm-var object|string|null $name
860
             * @psalm-var ConstraintArray $constraint
861
             */
862
            foreach ($names as $name => $constraint) {
863
                switch ($type) {
864
                    case 'PK':
865
                        /** @var Constraint */
866
                        $result['primaryKey'] = (new Constraint())
867
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
868
                            ->name($name);
869
                        break;
870
                    case 'F':
871
                        $result['foreignKeys'][] = (new ForeignKeyConstraint())
872
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
873
                            ->foreignTableName($constraint[0]['foreign_table_name'])
874
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
875
                            ->onDelete(str_replace('_', '', $constraint[0]['on_delete']))
876
                            ->onUpdate(str_replace('_', '', $constraint[0]['on_update']))
877
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
878
                            ->name($name);
879
                        break;
880
                    case 'UQ':
881
                        $result['uniques'][] = (new Constraint())
882
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
883
                            ->name($name);
884
                        break;
885
                    case 'C':
886
                        $result['checks'][] = (new CheckConstraint())
887
                            ->expression($constraint[0]['check_expr'])
888
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
889
                            ->name($name);
890
                        break;
891
                    case 'D':
892
                        $result['defaults'][] = (new DefaultValueConstraint())
893
                            ->value($constraint[0]['default_expr'])
894
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
895
                            ->name($name);
896
                        break;
897
                }
898
            }
899
        }
900
        foreach ($result as $type => $data) {
901
            $this->setTableMetadata($tableName, $type, $data);
902
        }
903
904
        return $result[$returnType];
905
    }
906
907
    /**
908
     * Executes the INSERT command, returning primary key values.
909
     *
910
     * @param string $table the table that new rows will be inserted into.
911
     * @param array $columns the column data (name => value) to be inserted into the table.
912
     *
913
     * @throws Exception|InvalidCallException|InvalidConfigException|Throwable
914
     *
915
     * @return array|false primary key values or false if the command fails.
916
     */
917
    public function insert(string $table, array $columns): bool|array
918
    {
919
        $command = $this->db->createCommand()->insert($table, $columns);
920
        if (!$command->execute()) {
921
            return false;
922
        }
923
924
        $isVersion2005orLater = version_compare($this->db->getServerVersion(), '9', '>=');
925
        $inserted = $isVersion2005orLater ? $command->getPdoStatement()->fetch() : [];
926
        $tableSchema = $this->getTableSchema($table);
927
928
        $result = [];
929
        foreach ($tableSchema->getPrimaryKey() as $name) {
930
            /**
931
             * {@see https://github.com/yiisoft/yii2/issues/13828 & https://github.com/yiisoft/yii2/issues/17474
932
             */
933
            if (isset($inserted[$name])) {
934
                $result[$name] = $inserted[$name];
935
            } elseif ($tableSchema->getColumns()[$name]->isAutoIncrement()) {
936
                // for a version earlier than 2005
937
                $result[$name] = $this->getLastInsertID($tableSchema->getSequenceName());
0 ignored issues
show
Bug introduced by
It seems like $tableSchema->getSequenceName() can also be of type null; however, parameter $sequenceName of Yiisoft\Db\Mssql\PDO\Sch...ssql::getLastInsertID() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

937
                $result[$name] = $this->getLastInsertID(/** @scrutinizer ignore-type */ $tableSchema->getSequenceName());
Loading history...
938
            } elseif (isset($columns[$name])) {
939
                $result[$name] = $columns[$name];
940
            } else {
941
                $result[$name] = $tableSchema->getColumns()[$name]->getDefaultValue();
942
            }
943
        }
944
945
        return $result;
946
    }
947
948
    /**
949
     * Create a column schema builder instance giving the type and value precision.
950
     *
951
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
952
     *
953
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
954
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
955
     *
956
     * @return ColumnSchemaBuilder column schema builder instance
957
     */
958
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
959
    {
960
        return new ColumnSchemaBuilder($type, $length);
961
    }
962
963
    public function setTransactionIsolationLevel(string $level): void
964
    {
965
        $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
966
    }
967
968
    /**
969
     * Returns the actual name of a given table name.
970
     *
971
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
972
     * {@see ConnectionInterface::tablePrefix}.
973
     *
974
     * @param string $name the table name to be converted.
975
     *
976
     * @return string the real name of the given table name.
977
     */
978
    public function getRawTableName(string $name): string
979
    {
980
        if (str_contains($name, '{{')) {
981
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
982
983
            return str_replace('%', $this->db->getTablePrefix(), $name);
984
        }
985
986
        return $name;
987
    }
988
989
    /**
990
     * Returns the cache key for the specified table name.
991
     *
992
     * @param string $name the table name.
993
     *
994
     * @return array the cache key.
995
     */
996
    protected function getCacheKey(string $name): array
997
    {
998
        return [
999
            __CLASS__,
1000
            $this->db->getDriver()->getDsn(),
1001
            $this->db->getDriver()->getUsername(),
1002
            $this->getRawTableName($name),
1003
        ];
1004
    }
1005
1006
    /**
1007
     * Returns the cache tag name.
1008
     *
1009
     * This allows {@see refresh()} to invalidate all cached table schemas.
1010
     *
1011
     * @return string the cache tag name.
1012
     */
1013
    protected function getCacheTag(): string
1014
    {
1015
        return md5(serialize([
1016
            __CLASS__,
1017
            $this->db->getDriver()->getDsn(),
1018
            $this->db->getDriver()->getUsername(),
1019
        ]));
1020
    }
1021
1022
    /**
1023
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
1024
     */
1025
    public function supportsSavepoint(): bool
1026
    {
1027
        return $this->db->isSavepointEnabled();
1028
    }
1029
1030
    /**
1031
     * Changes row's array key case to lower if PDO one is set to uppercase.
1032
     *
1033
     * @param array $row row's array or an array of row's arrays.
1034
     * @param bool $multiple whether multiple rows or a single row passed.
1035
     *
1036
     * @throws Exception
1037
     *
1038
     * @return array normalized row or rows.
1039
     */
1040
    protected function normalizePdoRowKeyCase(array $row, bool $multiple): array
1041
    {
1042
        if ($this->db->getSlavePdo()?->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_UPPER) {
1043
            return $row;
1044
        }
1045
1046
        if ($multiple) {
1047
            return array_map(static function (array $row) {
1048
                return array_change_key_case($row, CASE_LOWER);
1049
            }, $row);
1050
        }
1051
1052
        return array_change_key_case($row, CASE_LOWER);
1053
    }
1054
1055
    public function getLastInsertID(string $sequenceName = ''): string
1056
    {
1057
        if ($this->db->isActive()) {
1058
            return $this->db->getPDO()->lastInsertId(
1059
                $sequenceName === '' ? null : $this->db->getQuoter()->quoteTableName($sequenceName)
1060
            );
1061
        }
1062
1063
        throw new InvalidCallException('DB Connection is not active.');
1064
    }
1065
1066
    public function getViewNames(string $schema = '', bool $refresh = false): array
1067
    {
1068
        if (!isset($this->viewNames[$schema]) || $refresh) {
1069
            $this->viewNames[$schema] = $this->findViewNames($schema);
1070
        }
1071
1072
        return $this->viewNames[$schema];
1073
    }
1074
}
1075