Passed
Pull Request — master (#76)
by Wilmer
06:35
created

Schema   F

Complexity

Total Complexity 72

Size/Duplication

Total Lines 723
Duplicated Lines 0 %

Test Coverage

Coverage 77.88%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 309
dl 0
loc 723
ccs 169
cts 217
cp 0.7788
rs 2.64
c 6
b 1
f 0
wmc 72

19 Methods

Rating   Name   Duplication   Size   Complexity  
A findTableNames() 0 9 2
D loadColumnSchema() 0 75 19
A loadTableUniques() 0 5 2
B findColumns() 0 43 9
A resolveTableName() 0 18 3
B loadTableConstraints() 0 112 7
B findConstraints() 0 70 9
A createColumnSchema() 0 3 1
A getCreateTableSql() 0 17 2
A loadTableForeignKeys() 0 5 2
A resolveTableNames() 0 11 2
A loadTableChecks() 0 3 1
A loadTableSchema() 0 13 2
A loadTableIndexes() 0 41 3
A createQueryBuilder() 0 3 1
A loadTableDefaultValues() 0 3 1
A createColumnSchemaBuilder() 0 3 1
A findUniqueIndexes() 0 17 3
A loadTablePrimaryKey() 0 5 2

How to fix   Complexity   

Complex Class

Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use JsonException;
8
use PDO;
9
use PDOException;
10
use Throwable;
11
use Yiisoft\Arrays\ArrayHelper;
12
use Yiisoft\Db\Constraint\Constraint;
13
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
14
use Yiisoft\Db\Constraint\ConstraintFinderTrait;
15
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
16
use Yiisoft\Db\Constraint\IndexConstraint;
17
use Yiisoft\Db\Exception\Exception;
18
use Yiisoft\Db\Exception\InvalidConfigException;
19
use Yiisoft\Db\Exception\NotSupportedException;
20
use Yiisoft\Db\Expression\Expression;
21
use Yiisoft\Db\Schema\Schema as AbstractSchema;
22
23
use function array_change_key_case;
24
use function array_map;
25
use function array_merge;
26
use function array_values;
27
use function bindec;
28
use function explode;
29
use function preg_match;
30
use function preg_match_all;
31
use function str_replace;
32
use function stripos;
33
use function strpos;
34
use function strtolower;
35
use function trim;
36
use function version_compare;
37
38
/**
39
 * @psalm-type ColumnArray = array{
40
 *   table_schema: string,
41
 *   table_name: string,
42
 *   column_name: string,
43
 *   data_type: string,
44
 *   type_type: string|null,
45
 *   character_maximum_length: int,
46
 *   column_comment: string|null,
47
 *   modifier: int,
48
 *   is_nullable: bool,
49
 *   column_default: mixed,
50
 *   is_autoinc: bool,
51
 *   sequence_name: string|null,
52
 *   enum_values: array<array-key, float|int|string>|string|null,
53
 *   numeric_precision: int|null,
54
 *   numeric_scale: int|null,
55
 *   size: string|null,
56
 *   is_pkey: bool|null,
57
 *   dimension: int
58
 * }
59
 *
60
 * @psalm-type ColumnInfoArray = array{
61
 *   field: string,
62
 *   type: string,
63
 *   collation: string|null,
64
 *   null: string,
65
 *   key: string,
66
 *   default: string|null,
67
 *   extra: string,
68
 *   privileges: string,
69
 *   comment: string
70
 * }
71
 *
72
 * @psalm-type RowConstraint = array{
73
 *   constraint_name: string,
74
 *   column_name: string,
75
 *   referenced_table_name: string,
76
 *   referenced_column_name: string
77
 * }
78
 *
79
 * @psalm-type ConstraintArray = array<
80
 *   array-key,
81
 *   array {
82
 *     name: string,
83
 *     column_name: string,
84
 *     type: string,
85
 *     foreign_table_schema: string|null,
86
 *     foreign_table_name: string|null,
87
 *     foreign_column_name: string|null,
88
 *     on_update: string,
89
 *     on_delete: string,
90
 *     check_expr: string
91
 *   }
92
 * >
93
 */
94
final class Schema extends AbstractSchema implements ConstraintFinderInterface
95
{
96 58
    use ConstraintFinderTrait;
97
98 58
    /** @var array<array-key, string> $typeMap */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, string> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, string>.
Loading history...
99
    private array $typeMap = [
100 58
        'tinyint' => self::TYPE_TINYINT,
101
        'bit' => self::TYPE_INTEGER,
102 58
        'smallint' => self::TYPE_SMALLINT,
103
        'mediumint' => self::TYPE_INTEGER,
104
        'int' => self::TYPE_INTEGER,
105
        'integer' => self::TYPE_INTEGER,
106 58
        'bigint' => self::TYPE_BIGINT,
107 58
        'float' => self::TYPE_FLOAT,
108
        'double' => self::TYPE_DOUBLE,
109
        'real' => self::TYPE_FLOAT,
110 58
        'decimal' => self::TYPE_DECIMAL,
111 58
        'numeric' => self::TYPE_DECIMAL,
112
        'tinytext' => self::TYPE_TEXT,
113 58
        'mediumtext' => self::TYPE_TEXT,
114
        'longtext' => self::TYPE_TEXT,
115
        'longblob' => self::TYPE_BINARY,
116
        'blob' => self::TYPE_BINARY,
117
        'text' => self::TYPE_TEXT,
118
        'varchar' => self::TYPE_STRING,
119
        'string' => self::TYPE_STRING,
120
        'char' => self::TYPE_CHAR,
121
        'datetime' => self::TYPE_DATETIME,
122
        'year' => self::TYPE_DATE,
123
        'date' => self::TYPE_DATE,
124
        'time' => self::TYPE_TIME,
125
        'timestamp' => self::TYPE_TIMESTAMP,
126
        'enum' => self::TYPE_STRING,
127
        'varbinary' => self::TYPE_BINARY,
128
        'json' => self::TYPE_JSON,
129
    ];
130 3
131
    /**
132 3
     * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in
133
     * case starting and ending characters are different.
134 3
     */
135
    protected $tableQuoteCharacter = '`';
136
137
    /**
138 3
     * @var string|string[] character used to quote column names. An array of 2 characters can be used in case starting
139
     * and ending characters are different.
140
     */
141
    protected $columnQuoteCharacter = '`';
142
143
    /**
144
     * Resolves the table name and schema name (if any).
145
     *
146
     * @param string $name the table name.
147
     *
148
     * @return TableSchema
149
     *
150 82
     * {@see TableSchema}
151
     */
152 82
    protected function resolveTableName(string $name): TableSchema
153
    {
154 82
        $resolvedName = new TableSchema();
155
156 82
        $parts = explode('.', str_replace('`', '', $name));
157 77
158
        if (isset($parts[1])) {
159 77
            $resolvedName->schemaName($parts[0]);
160
            $resolvedName->name($parts[1]);
161
        } else {
162 13
            $resolvedName->schemaName($this->defaultSchema);
163
            $resolvedName->name($name);
164
        }
165
166
        $resolvedName->fullName(($resolvedName->getSchemaName() !== $this->defaultSchema ?
167
            (string) $resolvedName->getSchemaName() . '.' : '') . (string) $resolvedName->getName());
168
169
        return $resolvedName;
170
    }
171
172
    /**
173
     * Returns all table names in the database.
174
     *
175
     * This method should be overridden by child classes in order to support this feature because the default
176 31
     * implementation simply throws an exception.
177
     *
178 31
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
179
     *
180
     * @throws Exception|InvalidConfigException|Throwable
181
     *
182
     * @return array all table names in the database. The names have NO schema name prefix.
183
     */
184
    protected function findTableNames(string $schema = ''): array
185
    {
186
        $sql = 'SHOW TABLES';
187
188
        if ($schema !== '') {
189
            $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
190
        }
191
192 4
        return $this->getDb()->createCommand($sql)->queryColumn();
193
    }
194 4
195
    /**
196
     * Loads the metadata for the specified table.
197
     *
198
     * @param string $name table name.
199
     *
200
     * @throws Exception|Throwable
201
     *
202
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
203
     */
204
    protected function loadTableSchema(string $name): ?TableSchema
205
    {
206
        $table = new TableSchema();
207
208 28
        $this->resolveTableNames($table, $name);
209
210 28
        if ($this->findColumns($table)) {
211
            $this->findConstraints($table);
212
213
            return $table;
214
        }
215
216
        return null;
217
    }
218
219
    /**
220
     * Loads a primary key for the given table.
221 28
     *
222
     * @param string $tableName table name.
223 28
     *
224 28
     * @throws Exception|InvalidConfigException|Throwable
225 28
     *
226 28
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.*
227
     */
228 28
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
229 28
    {
230 28
        $tablePrimaryKey = $this->loadTableConstraints($tableName, 'primaryKey');
231
232 28
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
233 28
    }
234
235 28
    /**
236 28
     * Loads all foreign keys for the given table.
237 28
     *
238 28
     * @param string $tableName table name.
239
     *
240 28
     * @throws Exception|InvalidConfigException|Throwable
241
     *
242
     * @return array|ForeignKeyConstraint[] foreign keys for the given table.
243 28
     */
244
    protected function loadTableForeignKeys(string $tableName): array
245
    {
246
        $tableForeignKeys = $this->loadTableConstraints($tableName, 'foreignKeys');
247
248
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
249
    }
250
251
    /**
252
     * Loads all indexes for the given table.
253
     *
254
     * @param string $tableName table name.
255
     *
256
     * @throws Exception|InvalidConfigException|Throwable
257 13
     *
258
     * @return IndexConstraint[] indexes for the given table.
259 13
     */
260
    protected function loadTableIndexes(string $tableName): array
261
    {
262
        $sql = <<<'SQL'
263
SELECT
264
    `s`.`INDEX_NAME` AS `name`,
265
    `s`.`COLUMN_NAME` AS `column_name`,
266
    `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
267
    `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
268
FROM `information_schema`.`STATISTICS` AS `s`
269
WHERE `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND `s`.`TABLE_NAME` = :tableName
270
ORDER BY `s`.`SEQ_IN_INDEX` ASC
271 12
SQL;
272
273 12
        $resolvedName = $this->resolveTableName($tableName);
274
275
        $indexes = $this->getDb()->createCommand($sql, [
276
            ':schemaName' => $resolvedName->getSchemaName(),
277
            ':tableName' => $resolvedName->getName(),
278
        ])->queryAll();
279
280
        /** @var array<array-key, array<array-key, mixed>> $indexes */
281
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
282
        $indexes = ArrayHelper::index($indexes, null, 'name');
283
        $result = [];
284
285 12
        /**
286
         * @psalm-var object|string|null $name
287 12
         * @psalm-var array<array-key, array<array-key, mixed>> $index
288
         */
289
        foreach ($indexes as $name => $index) {
290
            $ic = new IndexConstraint();
291
292
            $ic->primary((bool) $index[0]['index_is_primary']);
293
            $ic->unique((bool) $index[0]['index_is_unique']);
294
            $ic->name($name !== 'PRIMARY' ? $name : null);
295 58
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
296
297 58
            $result[] = $ic;
298
        }
299
300
        return $result;
301
    }
302
303
    /**
304
     * Loads all unique constraints for the given table.
305
     *
306 82
     * @param string $tableName table name.
307
     *
308 82
     * @throws Exception|InvalidConfigException|Throwable
309
     *
310 82
     * @return array|Constraint[] unique constraints for the given table.
311
     */
312
    protected function loadTableUniques(string $tableName): array
313
    {
314
        $tableUniques = $this->loadTableConstraints($tableName, 'uniques');
315 82
316 82
        return is_array($tableUniques) ? $tableUniques : [];
317
    }
318 82
319
    /**
320
     * Loads all check constraints for the given table.
321
     *
322
     * @param string $tableName table name.
323
     *
324
     * @throws NotSupportedException
325
     *
326
     * @return array check constraints for the given table.
327 78
     */
328
    protected function loadTableChecks(string $tableName): array
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

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

328
    protected function loadTableChecks(/** @scrutinizer ignore-unused */ string $tableName): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
329 78
    {
330
        throw new NotSupportedException('MySQL does not support check constraints.');
331 78
    }
332 78
333 78
    /**
334 78
     * Loads all default value constraints for the given table.
335 78
     *
336 78
     * @param string $tableName table name.
337 78
     *
338 78
     * @throws NotSupportedException
339
     *
340 78
     * @return array default value constraints for the given table.
341 78
     */
342
    protected function loadTableDefaultValues(string $tableName): array
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

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

342
    protected function loadTableDefaultValues(/** @scrutinizer ignore-unused */ string $tableName): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
343 78
    {
344 78
        throw new NotSupportedException('MySQL does not support default value constraints.');
345
    }
346
347 78
    /**
348 77
     * Creates a query builder for the MySQL database.
349 20
     *
350
     * @return QueryBuilder query builder instance
351 20
     */
352 20
    public function createQueryBuilder(): QueryBuilder
353
    {
354
        return new QueryBuilder($this->getDb());
355 20
    }
356
357 77
    /**
358 77
     * Resolves the table name and schema name (if any).
359 77
     *
360
     * @param TableSchema $table the table metadata object.
361 77
     * @param string $name the table name.
362 24
     */
363
    protected function resolveTableNames(TableSchema $table, string $name): void
364
    {
365 77
        $parts = explode('.', str_replace('`', '', $name));
366 21
367 77
        if (isset($parts[1])) {
368 20
            $table->schemaName($parts[0]);
369
            $table->name($parts[1]);
370 20
            $table->fullName((string) $table->getSchemaName() . '.' . (string) $table->getName());
371
        } else {
372
            $table->name($parts[0]);
373
            $table->fullName($parts[0]);
374
        }
375
    }
376
377
    /**
378 78
     * Loads the column information into a {@see ColumnSchema} object.
379
     *
380 78
     * @var array $info column information.
381
     *
382
     * @throws JsonException
383
     *
384
     * @return ColumnSchema the column schema object.
385
     */
386
    protected function loadColumnSchema(array $info): ColumnSchema
387
    {
388 75
        $column = $this->createColumnSchema();
389 75
390
        /** @psalm-var ColumnInfoArray $info */
391 24
        $column->name($info['field']);
392 24
        $column->allowNull($info['null'] === 'YES');
393 72
        $column->primaryKey(strpos($info['key'], 'PRI') !== false);
394 20
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
395
        $column->comment($info['comment']);
396 72
        $column->dbType($info['type']);
397
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
398
        $column->type(self::TYPE_STRING);
399
400 78
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
401
            $type = strtolower($matches[1]);
402
403
            if (isset($this->typeMap[$type])) {
404
                $column->type($this->typeMap[$type]);
405
            }
406
407
            if (!empty($matches[2])) {
408
                if ($type === 'enum') {
409
                    preg_match_all("/'[^']*'/", $matches[2], $values);
410
411
                    foreach ($values[0] as $i => $value) {
412 82
                        $values[$i] = trim($value, "'");
413
                    }
414 82
415
                    $column->enumValues($values);
416
                } else {
417 82
                    $values = explode(',', $matches[2]);
418 13
                    $column->precision((int) $values[0]);
419 13
                    $column->size((int) $values[0]);
420
421 13
                    if (isset($values[1])) {
422
                        $column->scale((int) $values[1]);
423
                    }
424
425
                    if ($column->getSize() === 1 && $type === 'tinyint') {
426
                        $column->type('boolean');
427 13
                    } elseif ($type === 'bit') {
428
                        if ($column->getSize() > 32) {
429
                            $column->type('bigint');
430
                        } elseif ($column->getSize() === 32) {
431
                            $column->type('integer');
432
                        }
433 77
                    }
434 77
                }
435 76
            }
436
        }
437
438 77
        $column->phpType($this->getColumnPhpType($column));
439 77
440
        if (!$column->isPrimaryKey()) {
441 77
            /**
442 53
             * When displayed in the INFORMATION_SCHEMA.COLUMNS table, a default CURRENT TIMESTAMP is displayed
443 53
             * as CURRENT_TIMESTAMP up until MariaDB 10.2.2, and as current_timestamp() from MariaDB 10.2.3.
444 51
             *
445
             * See details here: https://mariadb.com/kb/en/library/now/#description
446
             */
447
            if (
448
                ($column->getType() === 'timestamp' || $column->getType() === 'datetime')
449 77
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
450
            ) {
451
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
452
                    ? '(' . $matches[1] . ')' : '')));
453
            } elseif (isset($type) && $type === 'bit') {
454
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
455
            } else {
456
                $column->defaultValue($column->phpTypecast($info['default']));
457
            }
458
        }
459
460
        return $column;
461
    }
462
463
    /**
464
     * Collects the metadata of table columns.
465
     *
466
     * @param TableSchema $table the table metadata.
467
     *
468
     * @throws Exception|Throwable if DB query fails.
469
     *
470
     * @return bool whether the table exists in the database.
471
     */
472
    protected function findColumns(TableSchema $table): bool
473
    {
474
        $tableName = $table->getFullName() ?? '';
475
476
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($tableName);
477
478
        try {
479
            $columns = $this->getDb()->createCommand($sql)->queryAll();
480
        } catch (Exception $e) {
481
            $previous = $e->getPrevious();
482
483
            if ($previous instanceof PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
484
                /**
485
                 * table does not exist.
486 77
                 *
487
                 * https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
488
                 */
489 77
                return false;
490
            }
491
492
            throw $e;
493
        }
494
495
        $slavePdo = $this->getDb()->getSlavePdo();
496
497
        /** @psalm-var ColumnInfoArray $info */
498
        foreach ($columns as $info) {
499
            if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_LOWER) {
500
                $info = array_change_key_case($info, CASE_LOWER);
501
            }
502
503
            $column = $this->loadColumnSchema($info);
504
            $table->columns($column->getName(), $column);
505
506
            if ($column->isPrimaryKey()) {
507 77
                $table->primaryKey($column->getName());
508
                if ($column->isAutoIncrement()) {
509 77
                    $table->sequenceName('');
510 77
                }
511
            }
512 77
        }
513
514 77
        return true;
515 24
    }
516 24
517
    /**
518
     * Gets the CREATE TABLE sql string.
519 77
     *
520
     * @param TableSchema $table the table metadata.
521 77
     *
522 24
     * @throws Exception|InvalidConfigException|Throwable
523 24
     *
524 24
     * @return string $sql the result of 'SHOW CREATE TABLE'.
525
     */
526
    protected function getCreateTableSql(TableSchema $table): string
527
    {
528
        $tableName = $table->getFullName() ?? '';
529
530
        /** @var array<array-key, string> $row */
531
        $row = $this->getDb()->createCommand(
532
            'SHOW CREATE TABLE ' . $this->quoteTableName($tableName)
533
        )->queryOne();
534
535
        if (isset($row['Create Table'])) {
536
            $sql = $row['Create Table'];
537
        } else {
538
            $row = array_values($row);
0 ignored issues
show
Bug introduced by
$row of type false is incompatible with the type array expected by parameter $array of array_values(). ( Ignorable by Annotation )

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

538
            $row = array_values(/** @scrutinizer ignore-type */ $row);
Loading history...
539
            $sql = $row[1];
540
        }
541
542
        return $sql;
543
    }
544
545
    /**
546
     * Collects the foreign key column details for the given table.
547
     *
548
     * @param TableSchema $table the table metadata.
549
     *
550
     * @throws Exception|Throwable
551
     */
552
    protected function findConstraints(TableSchema $table): void
553 77
    {
554
        $sql = <<<'SQL'
555
SELECT
556
    `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
557
    `kcu`.`COLUMN_NAME` AS `column_name`,
558
    `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
559
    `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
560
FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
561
JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
562
    (
563
        `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
564
        (`kcu`.`CONSTRAINT_CATALOG` IS NULL AND `rc`.`CONSTRAINT_CATALOG` IS NULL)
565
    ) AND
566
    `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
567
    `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME`
568
WHERE `rc`.`CONSTRAINT_SCHEMA` = database() AND `kcu`.`TABLE_SCHEMA` = database()
569
AND `rc`.`TABLE_NAME` = :tableName AND `kcu`.`TABLE_NAME` = :tableName1
570
SQL;
571
572
        try {
573
            $rows = $this->getDb()->createCommand(
574
                $sql,
575
                [':tableName' => $table->getName(), ':tableName1' => $table->getName()]
576
            )->queryAll();
577
578
            $constraints = [];
579
580
            /**  @psalm-var RowConstraint $row */
581
            foreach ($rows as $row) {
582
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
583
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
584
            }
585
586
            $table->foreignKeys([]);
587
588
            /**
589
             * @var string $name
590
             * @var array{referenced_table_name: string, columns: array} $constraint
591
             */
592
            foreach ($constraints as $name => $constraint) {
593
                $table->foreignKey($name, array_merge(
594
                    [$constraint['referenced_table_name']],
595
                    $constraint['columns']
596
                ));
597
            }
598
        } catch (Exception $e) {
599
            $previous = $e->getPrevious();
600
601
            if (!$previous instanceof PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
602
                throw $e;
603
            }
604 3
605
            // table does not exist, try to determine the foreign keys using the table creation sql
606 3
            $sql = $this->getCreateTableSql($table);
607
            $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
608
609
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
610
                foreach ($matches as $match) {
611
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
612
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
613
                    $constraint = [str_replace('`', '', $match[2])];
614
615
                    foreach ($fks as $k => $name) {
616
                        $constraint[$name] = $pks[$k];
617
                    }
618
619
                    $table->foreignKey(\md5(\serialize($constraint)), $constraint);
620
                }
621
                $table->foreignKeys(array_values($table->getForeignKeys()));
622
            }
623
        }
624
    }
625
626
    /**
627
     * Returns all unique indexes for the given table.
628
     *
629
     * Each array element is of the following structure:
630
     *
631
     * ```php
632
     * [
633
     *     'IndexName1' => ['col1' [, ...]],
634
     *     'IndexName2' => ['col2' [, ...]],
635
     * ]
636
     * ```
637
     *
638
     * @param TableSchema $table the table metadata.
639
     *
640
     * @throws Exception|InvalidConfigException|Throwable
641 48
     *
642
     * @return array all unique indexes for the given table.
643 48
     */
644
    public function findUniqueIndexes(TableSchema $table): array
645
    {
646
        $sql = $this->getCreateTableSql($table);
647
648
        $uniqueIndexes = [];
649
650
        $regexp = '/UNIQUE KEY\s+\`(.+)\`\s*\((\`.+\`)+\)/mi';
651
652
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
653
            foreach ($matches as $match) {
654
                $indexName = $match[1];
655
                $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
656
                $uniqueIndexes[$indexName] = $indexColumns;
657
            }
658
        }
659
660
        return $uniqueIndexes;
661
    }
662
663
    /**
664
     * Create a column schema builder instance giving the type and value precision.
665
     *
666
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
667
     *
668
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
669
     * @param array|int|string $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
670
     *
671
     * @return ColumnSchemaBuilder column schema builder instance
672
     */
673
    public function createColumnSchemaBuilder(string $type, $length = null): ColumnSchemaBuilder
674
    {
675
        return new ColumnSchemaBuilder($type, $length, $this->getDb());
676
    }
677
678
    /**
679
     * Loads multiple types of constraints and returns the specified ones.
680
     *
681
     * @param string $tableName table name.
682
     * @param string $returnType return type:
683
     * - primaryKey
684
     * - foreignKeys
685 48
     * - uniques
686
     *
687 48
     * @throws Exception|InvalidConfigException|Throwable
688
     *
689
     * @return (Constraint|ForeignKeyConstraint)[]|Constraint|null constraints.
690 48
     *
691 48
     * @psalm-return Constraint|list<Constraint|ForeignKeyConstraint>|null
692
     */
693 48
    private function loadTableConstraints(string $tableName, string $returnType)
694
    {
695 48
        $sql = <<<'SQL'
696 48
SELECT
697
    `kcu`.`CONSTRAINT_NAME` AS `name`,
698
    `kcu`.`COLUMN_NAME` AS `column_name`,
699 48
    `tc`.`CONSTRAINT_TYPE` AS `type`,
700
    CASE
701
        WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
702
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
703
    END AS `foreign_table_schema`,
704 48
    `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
705 48
    `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
706
    `rc`.`UPDATE_RULE` AS `on_update`,
707 48
    `rc`.`DELETE_RULE` AS `on_delete`,
708 37
    `kcu`.`ORDINAL_POSITION` AS `position`
709 37
FROM
710
    `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
711 37
    `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`,
712
    `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
713 37
WHERE
714 46
    `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `kcu`.`TABLE_NAME` = :tableName
715 10
    AND `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `rc`.`TABLE_NAME` = :tableName AND `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
716 10
    AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
717 10
UNION
718 10
SELECT
719 10
    `kcu`.`CONSTRAINT_NAME` AS `name`,
720 10
    `kcu`.`COLUMN_NAME` AS `column_name`,
721 10
    `tc`.`CONSTRAINT_TYPE` AS `type`,
722 10
    NULL AS `foreign_table_schema`,
723
    NULL AS `foreign_table_name`,
724 10
    NULL AS `foreign_column_name`,
725
    NULL AS `on_update`,
726 10
    NULL AS `on_delete`,
727 37
    `kcu`.`ORDINAL_POSITION` AS `position`
728 37
FROM
729 37
    `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
730 37
    `information_schema`.`TABLE_CONSTRAINTS` AS `tc`
731
WHERE
732 37
    `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND `kcu`.`TABLE_NAME` = :tableName
733
    AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = :tableName AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
734 37
ORDER BY `position` ASC
735
SQL;
736
737
        $resolvedName = $this->resolveTableName($tableName);
738
739 48
        $constraints = $this->getDb()->createCommand(
740 48
            $sql,
741
            [
742
                ':schemaName' => $resolvedName->getSchemaName(),
743 48
                ':tableName' => $resolvedName->getName(),
744
            ]
745
        )->queryAll();
746
747
        /** @var array<array-key, array> $constraints */
748
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
749
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
750
751
        $result = [
752
            'primaryKey' => null,
753 78
            'foreignKeys' => [],
754
            'uniques' => [],
755 78
        ];
756
757
        /**
758
         * @var string $type
759
         * @var array $names
760
         */
761
        foreach ($constraints as $type => $names) {
762
            /**
763
             * @psalm-var object|string|null $name
764
             * @psalm-var ConstraintArray $constraint
765
             */
766
            foreach ($names as $name => $constraint) {
767
                switch ($type) {
768
                    case 'PRIMARY KEY':
769
                        $ct = (new Constraint())
770
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
771
772
                        $result['primaryKey'] = $ct;
773
774
                        break;
775
                    case 'FOREIGN KEY':
776
                        $fk = (new ForeignKeyConstraint())
777
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
778
                            ->foreignTableName($constraint[0]['foreign_table_name'])
779
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
780
                            ->onDelete($constraint[0]['on_delete'])
781
                            ->onUpdate($constraint[0]['on_update'])
782
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
783
                            ->name($name);
784
785
                        $result['foreignKeys'][] = $fk;
786
787
                        break;
788
                    case 'UNIQUE':
789
                        $ct = (new Constraint())
790
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
791
                            ->name($name);
792
793
                        $result['uniques'][] = $ct;
794
795
                        break;
796
                }
797
            }
798
        }
799
800
        foreach ($result as $type => $data) {
801
            $this->setTableMetadata($tableName, $type, $data);
802
        }
803
804
        return $result[$returnType];
805
    }
806
807
    /**
808
     * Creates a column schema for the database.
809
     *
810
     * This method may be overridden by child classes to create a DBMS-specific column schema.
811
     *
812
     * @return ColumnSchema column schema instance.
813
     */
814
    private function createColumnSchema(): ColumnSchema
815
    {
816
        return new ColumnSchema();
817
    }
818
}
819