Test Failed
Pull Request — master (#94)
by Wilmer
14:06 queued 02:52
created

SchemaPDOMysql::loadTableDefaultValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql\PDO;
6
7
use JsonException;
8
use PDO;
9
use PDOException;
10
use Throwable;
11
use Yiisoft\Arrays\ArrayHelper;
12
use Yiisoft\Db\Cache\SchemaCache;
13
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...
14
use Yiisoft\Db\Constraint\Constraint;
15
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
16
use Yiisoft\Db\Constraint\IndexConstraint;
17
use Yiisoft\Db\Exception\Exception;
18
use Yiisoft\Db\Exception\InvalidCallException;
19
use Yiisoft\Db\Exception\InvalidConfigException;
20
use Yiisoft\Db\Exception\NotSupportedException;
21
use Yiisoft\Db\Expression\Expression;
22
use Yiisoft\Db\Mysql\ColumnSchema;
23
use Yiisoft\Db\Mysql\ColumnSchemaBuilder;
24
use Yiisoft\Db\Mysql\TableSchema;
25
use Yiisoft\Db\Schema\Schema;
26
27
use function array_change_key_case;
28
use function array_map;
29
use function array_merge;
30
use function array_values;
31
use function bindec;
32
use function explode;
33
use function md5;
34
use function preg_match;
35
use function preg_match_all;
36
use function serialize;
37
use function str_replace;
38
use function stripos;
39
use function strtolower;
40
use function trim;
41
42
/**
43
 * The class Schema is the class for retrieving metadata from a Mysql database (version 5.7 and above).
44
 *
45
 * @psalm-type ColumnArray = array{
46
 *   table_schema: string,
47
 *   table_name: string,
48
 *   column_name: string,
49
 *   data_type: string,
50
 *   type_type: string|null,
51
 *   character_maximum_length: int,
52
 *   column_comment: string|null,
53
 *   modifier: int,
54
 *   is_nullable: bool,
55
 *   column_default: mixed,
56
 *   is_autoinc: bool,
57
 *   sequence_name: string|null,
58
 *   enum_values: array<array-key, float|int|string>|string|null,
59
 *   numeric_precision: int|null,
60
 *   numeric_scale: int|null,
61
 *   size: string|null,
62
 *   is_pkey: bool|null,
63
 *   dimension: int
64
 * }
65
 *
66
 * @psalm-type ColumnInfoArray = array{
67
 *   field: string,
68
 *   type: string,
69
 *   collation: string|null,
70
 *   null: string,
71
 *   key: string,
72
 *   default: string|null,
73
 *   extra: string,
74
 *   privileges: string,
75
 *   comment: string
76
 * }
77
 *
78
 * @psalm-type RowConstraint = array{
79
 *   constraint_name: string,
80
 *   column_name: string,
81
 *   referenced_table_name: string,
82
 *   referenced_column_name: string
83
 * }
84
 *
85
 * @psalm-type ConstraintArray = array<
86
 *   array-key,
87
 *   array {
88
 *     name: string,
89
 *     column_name: string,
90
 *     type: string,
91
 *     foreign_table_schema: string|null,
92
 *     foreign_table_name: string|null,
93
 *     foreign_column_name: string|null,
94
 *     on_update: string,
95
 *     on_delete: string,
96
 *     check_expr: string
97
 *   }
98
 * >
99
 */
100
final class SchemaPDOMysql extends Schema
101
{
102
    /** @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...
103
    private array $typeMap = [
104
        'tinyint' => self::TYPE_TINYINT,
105
        'bit' => self::TYPE_INTEGER,
106
        'smallint' => self::TYPE_SMALLINT,
107
        'mediumint' => self::TYPE_INTEGER,
108
        'int' => self::TYPE_INTEGER,
109
        'integer' => self::TYPE_INTEGER,
110
        'bigint' => self::TYPE_BIGINT,
111
        'float' => self::TYPE_FLOAT,
112
        'double' => self::TYPE_DOUBLE,
113
        'real' => self::TYPE_FLOAT,
114
        'decimal' => self::TYPE_DECIMAL,
115
        'numeric' => self::TYPE_DECIMAL,
116
        'tinytext' => self::TYPE_TEXT,
117
        'mediumtext' => self::TYPE_TEXT,
118
        'longtext' => self::TYPE_TEXT,
119
        'longblob' => self::TYPE_BINARY,
120
        'blob' => self::TYPE_BINARY,
121
        'text' => self::TYPE_TEXT,
122
        'varchar' => self::TYPE_STRING,
123
        'string' => self::TYPE_STRING,
124
        'char' => self::TYPE_CHAR,
125
        'datetime' => self::TYPE_DATETIME,
126
        'year' => self::TYPE_DATE,
127
        'date' => self::TYPE_DATE,
128
        'time' => self::TYPE_TIME,
129
        'timestamp' => self::TYPE_TIMESTAMP,
130
        'enum' => self::TYPE_STRING,
131
        'varbinary' => self::TYPE_BINARY,
132
        'json' => self::TYPE_JSON,
133
    ];
134
135
    public function __construct(private ConnectionPDOInterface $db, SchemaCache $schemaCache)
136
    {
137
        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

137
        parent::/** @scrutinizer ignore-call */ 
138
                __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

137
        parent::__construct(/** @scrutinizer ignore-type */ $schemaCache);
Loading history...
138
    }
139
140
    /**
141
     * Create a column schema builder instance giving the type and value precision.
142
     *
143
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
144
     *
145
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
146
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
147
     *
148
     * @return ColumnSchemaBuilder column schema builder instance
149
     */
150
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
151
    {
152
        return new ColumnSchemaBuilder($type, $length, $this->db->getQuoter());
153
    }
154
155
    /**
156
     * @throws Exception|InvalidConfigException|Throwable
157
     */
158
    public function createSavepoint(string $name): void
159
    {
160
        $this->db->createCommand("SAVEPOINT $name")->execute();
161
    }
162
163
    /**
164
     * Returns all unique indexes for the given table.
165
     *
166
     * Each array element is of the following structure:
167
     *
168
     * ```php
169
     * [
170
     *     'IndexName1' => ['col1' [, ...]],
171
     *     'IndexName2' => ['col2' [, ...]],
172
     * ]
173
     * ```
174
     *
175
     * @param TableSchema $table the table metadata.
176
     *
177
     * @throws Exception|InvalidConfigException|Throwable
178
     *
179
     * @return array all unique indexes for the given table.
180
     */
181
    public function findUniqueIndexes(TableSchema $table): array
182
    {
183
        $sql = $this->getCreateTableSql($table);
184
185
        $uniqueIndexes = [];
186
187
        $regexp = '/UNIQUE KEY\s+`(.+)`\s*\((`.+`)+\)/mi';
188
189
        if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
190
            foreach ($matches as $match) {
191
                $indexName = $match[1];
192
                $indexColumns = array_map('trim', explode('`,`', trim($match[2], '`')));
193
                $uniqueIndexes[$indexName] = $indexColumns;
194
            }
195
        }
196
197
        return $uniqueIndexes;
198
    }
199
200
    /**
201
     * Returns the ID of the last inserted row or sequence value.
202
     *
203
     * @param string $sequenceName name of the sequence object (required by some DBMS)
204
     *
205
     * @throws InvalidCallException if the DB connection is not active
206
     *
207
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
208
     *
209
     * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
210
     */
211
    public function getLastInsertID(string $sequenceName = ''): string
212
    {
213
        $pdo = $this->db->getPDO();
214
215
        if ($this->db->isActive() && $pdo !== null) {
216
            return $pdo->lastInsertId(
217
                $sequenceName === '' ? null : $this->db->getQuoter()->quoteTableName($sequenceName)
218
            );
219
        }
220
221
        throw new InvalidCallException('DB Connection is not active.');
222
    }
223
224
    /**
225
     * Returns the actual name of a given table name.
226
     *
227
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
228
     * {@see ConnectionInterface::tablePrefix}.
229
     *
230
     * @param string $name the table name to be converted.
231
     *
232
     * @return string the real name of the given table name.
233
     */
234
    public function getRawTableName(string $name): string
235
    {
236
        if (str_contains($name, '{{')) {
237
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
238
239
            return str_replace('%', $this->db->getTablePrefix(), $name);
240
        }
241
242
        return $name;
243
    }
244
245
    public function rollBackSavepoint(string $name): void
246
    {
247
        $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
248
    }
249
250
    /**
251
     * @throws Exception|InvalidConfigException|Throwable
252
     */
253
    public function releaseSavepoint(string $name): void
254
    {
255
        $this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
256
    }
257
258
    public function setTransactionIsolationLevel(string $level): void
259
    {
260
        $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
261
    }
262
263
    public function supportsSavepoint(): bool
264
    {
265
        return $this->db->isSavepointEnabled();
266
    }
267
268
    /**
269
     * Collects the metadata of table columns.
270
     *
271
     * @param TableSchema $table the table metadata.
272
     *
273
     * @throws Exception|Throwable if DB query fails.
274
     *
275
     * @return bool whether the table exists in the database.
276
     */
277
    protected function findColumns(TableSchema $table): bool
278
    {
279
        $tableName = $table->getFullName() ?? '';
280
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->db->getQuoter()->quoteTableName($tableName);
281
282
        try {
283
            $columns = $this->db->createCommand($sql)->queryAll();
284
        } catch (Exception $e) {
285
            $previous = $e->getPrevious();
286
287
            if ($previous instanceof PDOException && str_contains($previous->getMessage(), 'SQLSTATE[42S02')) {
288
                /**
289
                 * table does not exist.
290
                 *
291
                 * https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
292
                 */
293
                return false;
294
            }
295
296
            throw $e;
297
        }
298
299
        $slavePdo = $this->db->getSlavePdo();
300
301
        /** @psalm-var ColumnInfoArray $info */
302
        foreach ($columns as $info) {
303
            if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_LOWER) {
304
                $info = array_change_key_case($info, CASE_LOWER);
305
            }
306
307
            $column = $this->loadColumnSchema($info);
308
            $table->columns($column->getName(), $column);
309
310
            if ($column->isPrimaryKey()) {
311
                $table->primaryKey($column->getName());
312
                if ($column->isAutoIncrement()) {
313
                    $table->sequenceName('');
314
                }
315
            }
316
        }
317
318
        return true;
319
    }
320
321
    /**
322
     * Collects the foreign key column details for the given table.
323
     *
324
     * @param TableSchema $table the table metadata.
325
     *
326
     * @throws Exception|Throwable
327
     */
328
    protected function findConstraints(TableSchema $table): void
329
    {
330
        $sql = <<<SQL
331
        SELECT
332
            `kcu`.`CONSTRAINT_NAME` AS `constraint_name`,
333
            `kcu`.`COLUMN_NAME` AS `column_name`,
334
            `kcu`.`REFERENCED_TABLE_NAME` AS `referenced_table_name`,
335
            `kcu`.`REFERENCED_COLUMN_NAME` AS `referenced_column_name`
336
        FROM `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`
337
        JOIN `information_schema`.`KEY_COLUMN_USAGE` AS `kcu` ON
338
            (
339
                `kcu`.`CONSTRAINT_CATALOG` = `rc`.`CONSTRAINT_CATALOG` OR
340
                (
341
                    `kcu`.`CONSTRAINT_CATALOG` IS NULL AND
342
                    `rc`.`CONSTRAINT_CATALOG` IS NULL
343
                )
344
            ) AND
345
            `kcu`.`CONSTRAINT_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
346
            `kcu`.`CONSTRAINT_NAME` = `rc`.`CONSTRAINT_NAME` AND
347
            `kcu`.`TABLE_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA` AND
348
            `kcu`.`TABLE_NAME` = `rc`.`TABLE_NAME`
349
        WHERE
350
            `rc`.`CONSTRAINT_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
351
            `rc`.`TABLE_NAME` = :tableName
352
        SQL;
353
354
        try {
355
            $rows = $this->db->createCommand($sql, [
356
                ':schemaName' => $table->getSchemaName(),
357
                ':tableName' => $table->getName(),
358
            ])->queryAll();
359
360
            $constraints = [];
361
362
            /**  @psalm-var RowConstraint $row */
363
            foreach ($rows as $row) {
364
                $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
365
                $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
366
            }
367
368
            $table->foreignKeys([]);
369
370
            /**
371
             * @var array{referenced_table_name: string, columns: array} $constraint
372
             */
373
            foreach ($constraints as $name => $constraint) {
374
                $table->foreignKey($name, array_merge(
375
                    [$constraint['referenced_table_name']],
376
                    $constraint['columns']
377
                ));
378
            }
379
        } catch (Exception $e) {
380
            $previous = $e->getPrevious();
381
382
            if (!$previous instanceof PDOException || !str_contains($previous->getMessage(), 'SQLSTATE[42S02')) {
383
                throw $e;
384
            }
385
386
            // table does not exist, try to determine the foreign keys using the table creation sql
387
            $sql = $this->getCreateTableSql($table);
388
            $regexp = '/FOREIGN KEY\s+\(([^)]+)\)\s+REFERENCES\s+([^(^\s]+)\s*\(([^)]+)\)/mi';
389
390
            if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
391
                foreach ($matches as $match) {
392
                    $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
393
                    $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
394
                    $constraint = [str_replace('`', '', $match[2])];
395
396
                    foreach ($fks as $k => $name) {
397
                        $constraint[$name] = $pks[$k];
398
                    }
399
400
                    $table->foreignKey(md5(serialize($constraint)), $constraint);
401
                }
402
                $table->foreignKeys(array_values($table->getForeignKeys()));
403
            }
404
        }
405
    }
406
407
    /**
408
     * Returns all table names in the database.
409
     *
410
     * This method should be overridden by child classes in order to support this feature because the default
411
     * implementation simply throws an exception.
412
     *
413
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
414
     *
415
     * @throws Exception|InvalidConfigException|Throwable
416
     *
417
     * @return array all table names in the database. The names have NO schema name prefix.
418
     */
419
    protected function findTableNames(string $schema = ''): array
420
    {
421
        $sql = 'SHOW TABLES';
422
423
        if ($schema !== '') {
424
            $sql .= ' FROM ' . $this->db->getQuoter()->quoteSimpleTableName($schema);
425
        }
426
427
        return $this->db->createCommand($sql)->queryColumn();
428
    }
429
430
    /**
431
     * Returns the cache key for the specified table name.
432
     *
433
     * @param string $name the table name.
434
     *
435
     * @return array the cache key.
436
     */
437
    protected function getCacheKey(string $name): array
438
    {
439
        return [
440
            __CLASS__,
441
            $this->db->getDriver()->getDsn(),
442
            $this->db->getDriver()->getUsername(),
443
            $this->getRawTableName($name),
444
        ];
445
    }
446
447
    /**
448
     * Returns the cache tag name.
449
     *
450
     * This allows {@see refresh()} to invalidate all cached table schemas.
451
     *
452
     * @return string the cache tag name.
453
     */
454
    protected function getCacheTag(): string
455
    {
456
        return md5(serialize([
457
            __CLASS__,
458
            $this->db->getDriver()->getDsn(),
459
            $this->db->getDriver()->getUsername(),
460
        ]));
461
    }
462
463
    /**
464
     * Gets the CREATE TABLE sql string.
465
     *
466
     * @param TableSchema $table the table metadata.
467
     *
468
     * @throws Exception|InvalidConfigException|Throwable
469
     *
470
     * @return string $sql the result of 'SHOW CREATE TABLE'.
471
     */
472
    protected function getCreateTableSql(TableSchema $table): string
473
    {
474
        $tableName = $table->getFullName() ?? '';
475
476
        /** @var array<array-key, string> $row */
477
        $row = $this->db->createCommand(
478
            'SHOW CREATE TABLE ' . $this->db->getQuoter()->quoteTableName($tableName)
479
        )->queryOne();
480
481
        if (isset($row['Create Table'])) {
482
            $sql = $row['Create Table'];
483
        } else {
484
            $row = array_values($row);
485
            $sql = $row[1];
486
        }
487
488
        return $sql;
489
    }
490
491
    public function insert(string $table, array $columns): bool|array
492
    {
493
        $command = $this->db->createCommand()->insert($table, $columns);
494
        $tablePrimaryKey = [];
495
496
        if (!$command->execute()) {
497
            return false;
498
        }
499
500
        $tableSchema = $this->getTableSchema($table);
501
        $result = [];
502
503
        if ($tableSchema !== null) {
504
            $tablePrimaryKey = $tableSchema->getPrimaryKey();
505
        }
506
507
        /** @var string $name */
508
        foreach ($tablePrimaryKey as $name) {
509
            if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
510
                $result[$name] = $this->getLastInsertID((string) $tableSchema?->getSequenceName());
511
                break;
512
            }
513
514
            /** @var mixed */
515
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
516
        }
517
518
        return $result;
519
    }
520
521
    /**
522
     * Loads the column information into a {@see ColumnSchema} object.
523
     *
524
     * @param array $info column information.
525
     *
526
     * @throws JsonException
527
     *
528
     * @return ColumnSchema the column schema object.
529
     */
530
    protected function loadColumnSchema(array $info): ColumnSchema
531
    {
532
        $column = $this->createColumnSchema();
533
534
        /** @psalm-var ColumnInfoArray $info */
535
        $column->name($info['field']);
536
        $column->allowNull($info['null'] === 'YES');
537
        $column->primaryKey(str_contains($info['key'], 'PRI'));
538
        $column->autoIncrement(stripos($info['extra'], 'auto_increment') !== false);
539
        $column->comment($info['comment']);
540
        $column->dbType($info['type']);
541
        $column->unsigned(stripos($column->getDbType(), 'unsigned') !== false);
542
        $column->type(self::TYPE_STRING);
543
544
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
545
            $type = strtolower($matches[1]);
546
547
            if (isset($this->typeMap[$type])) {
548
                $column->type($this->typeMap[$type]);
549
            }
550
551
            if (!empty($matches[2])) {
552
                if ($type === 'enum') {
553
                    preg_match_all("/'[^']*'/", $matches[2], $values);
554
555
                    foreach ($values[0] as $i => $value) {
556
                        $values[$i] = trim($value, "'");
557
                    }
558
559
                    $column->enumValues($values);
560
                } else {
561
                    $values = explode(',', $matches[2]);
562
                    $column->precision((int) $values[0]);
563
                    $column->size((int) $values[0]);
564
565
                    if (isset($values[1])) {
566
                        $column->scale((int) $values[1]);
567
                    }
568
569
                    if ($column->getSize() === 1 && $type === 'tinyint') {
570
                        $column->type('boolean');
571
                    } elseif ($type === 'bit') {
572
                        if ($column->getSize() > 32) {
573
                            $column->type('bigint');
574
                        } elseif ($column->getSize() === 32) {
575
                            $column->type('integer');
576
                        }
577
                    }
578
                }
579
            }
580
        }
581
582
        $column->phpType($this->getColumnPhpType($column));
583
584
        if (!$column->isPrimaryKey()) {
585
            /**
586
             * When displayed in the INFORMATION_SCHEMA.COLUMNS table, a default CURRENT TIMESTAMP is displayed
587
             * as CURRENT_TIMESTAMP up until MariaDB 10.2.2, and as current_timestamp() from MariaDB 10.2.3.
588
             *
589
             * See details here: https://mariadb.com/kb/en/library/now/#description
590
             */
591
            if (
592
                ($column->getType() === 'timestamp' || $column->getType() === 'datetime')
593
                && preg_match('/^current_timestamp(?:\((\d*)\))?$/i', (string) $info['default'], $matches)
594
            ) {
595
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP' . (!empty($matches[1])
596
                    ? '(' . $matches[1] . ')' : '')));
597
            } elseif (isset($type) && $type === 'bit') {
598
                $column->defaultValue(bindec(trim((string) $info['default'], 'b\'')));
599
            } else {
600
                $column->defaultValue($column->phpTypecast($info['default']));
601
            }
602
        }
603
604
        return $column;
605
    }
606
607
    /**
608
     * Loads all check constraints for the given table.
609
     *
610
     * @param string $tableName table name.
611
     *
612
     * @throws NotSupportedException
613
     *
614
     * @return array check constraints for the given table.
615
     */
616
    protected function loadTableChecks(string $tableName): array
617
    {
618
        throw new NotSupportedException('MySQL does not support check constraints.');
619
    }
620
621
    /**
622
     * Loads multiple types of constraints and returns the specified ones.
623
     *
624
     * @param string $tableName table name.
625
     * @param string $returnType return type:
626
     * - primaryKey
627
     * - foreignKeys
628
     * - uniques
629
     *
630
     * @throws Exception|InvalidConfigException|Throwable
631
     *
632
     * @return array|Constraint|null (Constraint|ForeignKeyConstraint)[]|Constraint|null constraints.
633
     */
634
    private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null
635
    {
636
        $sql = <<<SQL
637
        SELECT
638
            `kcu`.`CONSTRAINT_NAME` AS `name`,
639
            `kcu`.`COLUMN_NAME` AS `column_name`,
640
            `tc`.`CONSTRAINT_TYPE` AS `type`,
641
        CASE
642
            WHEN :schemaName IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
643
        ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
644
        END AS `foreign_table_schema`,
645
            `kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
646
            `kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
647
            `rc`.`UPDATE_RULE` AS `on_update`,
648
            `rc`.`DELETE_RULE` AS `on_delete`,
649
            `kcu`.`ORDINAL_POSITION` AS `position`
650
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
651
        JOIN `information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc` ON
652
            `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
653
            `rc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
654
            `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
655
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
656
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
657
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
658
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
659
            `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
660
        WHERE
661
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
662
            `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
663
            `kcu`.`TABLE_NAME` = :tableName
664
        UNION
665
        SELECT
666
            `kcu`.`CONSTRAINT_NAME` AS `name`,
667
            `kcu`.`COLUMN_NAME` AS `column_name`,
668
            `tc`.`CONSTRAINT_TYPE` AS `type`,
669
        NULL AS `foreign_table_schema`,
670
        NULL AS `foreign_table_name`,
671
        NULL AS `foreign_column_name`,
672
        NULL AS `on_update`,
673
        NULL AS `on_delete`,
674
            `kcu`.`ORDINAL_POSITION` AS `position`
675
        FROM `information_schema`.`KEY_COLUMN_USAGE` AS `kcu`
676
        JOIN `information_schema`.`TABLE_CONSTRAINTS` AS `tc` ON
677
            `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND
678
            `tc`.`TABLE_NAME` = `kcu`.`TABLE_NAME` AND
679
            `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND
680
            `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
681
        WHERE
682
            `kcu`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
683
            `kcu`.`TABLE_NAME` = :tableName
684
        ORDER BY `position` ASC
685
        SQL;
686
687
        $resolvedName = $this->resolveTableName($tableName);
688
689
        $constraints = $this->db->createCommand($sql, [
690
            ':schemaName' => $resolvedName->getSchemaName(),
691
            ':tableName' => $resolvedName->getName(),
692
        ])->queryAll();
693
694
        /** @var array<array-key, array> $constraints */
695
        $constraints = $this->normalizePdoRowKeyCase($constraints, true);
696
        $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
697
698
        $result = [
699
            'primaryKey' => null,
700
            'foreignKeys' => [],
701
            'uniques' => [],
702
        ];
703
704
        /**
705
         * @var string $type
706
         * @var array $names
707
         */
708
        foreach ($constraints as $type => $names) {
709
            /**
710
             * @psalm-var object|string|null $name
711
             * @psalm-var ConstraintArray $constraint
712
             */
713
            foreach ($names as $name => $constraint) {
714
                switch ($type) {
715
                    case 'PRIMARY KEY':
716
                        $ct = (new Constraint())
717
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'));
718
719
                        $result['primaryKey'] = $ct;
720
721
                        break;
722
                    case 'FOREIGN KEY':
723
                        $fk = (new ForeignKeyConstraint())
724
                            ->foreignSchemaName($constraint[0]['foreign_table_schema'])
725
                            ->foreignTableName($constraint[0]['foreign_table_name'])
726
                            ->foreignColumnNames(ArrayHelper::getColumn($constraint, 'foreign_column_name'))
727
                            ->onDelete($constraint[0]['on_delete'])
728
                            ->onUpdate($constraint[0]['on_update'])
729
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
730
                            ->name($name);
731
732
                        $result['foreignKeys'][] = $fk;
733
734
                        break;
735
                    case 'UNIQUE':
736
                        $ct = (new Constraint())
737
                            ->columnNames(ArrayHelper::getColumn($constraint, 'column_name'))
738
                            ->name($name);
739
740
                        $result['uniques'][] = $ct;
741
742
                        break;
743
                }
744
            }
745
        }
746
747
        foreach ($result as $type => $data) {
748
            $this->setTableMetadata($tableName, $type, $data);
749
        }
750
751
        return $result[$returnType];
752
    }
753
754
    /**
755
     * Loads all default value constraints for the given table.
756
     *
757
     * @param string $tableName table name.
758
     *
759
     * @throws NotSupportedException
760
     *
761
     * @return array default value constraints for the given table.
762
     */
763
    protected function loadTableDefaultValues(string $tableName): array
764
    {
765
        throw new NotSupportedException('MySQL does not support default value constraints.');
766
    }
767
768
    /**
769
     * Loads all foreign keys for the given table.
770
     *
771
     * @param string $tableName table name.
772
     *
773
     * @throws Exception|InvalidConfigException|Throwable
774
     *
775
     * @return array foreign keys for the given table.
776
     */
777
    protected function loadTableForeignKeys(string $tableName): array
778
    {
779
        $tableForeignKeys = $this->loadTableConstraints($tableName, 'foreignKeys');
780
781
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
782
    }
783
784
    /**
785
     * Loads all indexes for the given table.
786
     *
787
     * @param string $tableName table name.
788
     *
789
     * @throws Exception|InvalidConfigException|Throwable
790
     *
791
     * @return IndexConstraint[] indexes for the given table.
792
     */
793
    protected function loadTableIndexes(string $tableName): array
794
    {
795
        $sql = <<<SQL
796
        SELECT
797
            `s`.`INDEX_NAME` AS `name`,
798
            `s`.`COLUMN_NAME` AS `column_name`,
799
            `s`.`NON_UNIQUE` ^ 1 AS `index_is_unique`,
800
            `s`.`INDEX_NAME` = 'PRIMARY' AS `index_is_primary`
801
        FROM `information_schema`.`STATISTICS` AS `s`
802
        WHERE
803
            `s`.`TABLE_SCHEMA` = COALESCE(:schemaName, DATABASE()) AND
804
            `s`.`INDEX_SCHEMA` = `s`.`TABLE_SCHEMA` AND
805
            `s`.`TABLE_NAME` = :tableName
806
        ORDER BY `s`.`SEQ_IN_INDEX` ASC
807
        SQL;
808
809
        $resolvedName = $this->resolveTableName($tableName);
810
811
        $indexes = $this->db->createCommand($sql, [
812
            ':schemaName' => $resolvedName->getSchemaName(),
813
            ':tableName' => $resolvedName->getName(),
814
        ])->queryAll();
815
816
        /** @var array[] $indexes */
817
        $indexes = $this->normalizePdoRowKeyCase($indexes, true);
818
        $indexes = ArrayHelper::index($indexes, null, 'name');
819
        $result = [];
820
821
        /**
822
         * @psalm-var object|string|null $name
823
         * @psalm-var array[] $index
824
         */
825
        foreach ($indexes as $name => $index) {
826
            $ic = new IndexConstraint();
827
828
            $ic->primary((bool) $index[0]['index_is_primary']);
829
            $ic->unique((bool) $index[0]['index_is_unique']);
830
            $ic->name($name !== 'PRIMARY' ? $name : null);
831
            $ic->columnNames(ArrayHelper::getColumn($index, 'column_name'));
832
833
            $result[] = $ic;
834
        }
835
836
        return $result;
837
    }
838
839
    /**
840
     * Loads a primary key for the given table.
841
     *
842
     * @param string $tableName table name.
843
     *
844
     * @throws Exception|InvalidConfigException|Throwable
845
     *
846
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.*
847
     */
848
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
849
    {
850
        $tablePrimaryKey = $this->loadTableConstraints($tableName, 'primaryKey');
851
852
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
853
    }
854
855
    /**
856
     * Loads the metadata for the specified table.
857
     *
858
     * @param string $name table name.
859
     *
860
     * @throws Exception|Throwable
861
     *
862
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
863
     */
864
    protected function loadTableSchema(string $name): ?TableSchema
865
    {
866
        $table = new TableSchema();
867
868
        $this->resolveTableNames($table, $name);
869
870
        if ($this->findColumns($table)) {
871
            $this->findConstraints($table);
872
873
            return $table;
874
        }
875
876
        return null;
877
    }
878
879
    /**
880
     * Loads all unique constraints for the given table.
881
     *
882
     * @param string $tableName table name.
883
     *
884
     * @return array unique constraints for the given table.
885
     *
886
     * @throws Exception|InvalidConfigException|Throwable
887
     */
888
    protected function loadTableUniques(string $tableName): array
889
    {
890
        $tableUniques = $this->loadTableConstraints($tableName, 'uniques');
891
892
        return is_array($tableUniques) ? $tableUniques : [];
893
    }
894
895
    /**
896
     * Changes row's array key case to lower if PDO's one is set to uppercase.
897
     *
898
     * @param array $row row's array or an array of row's arrays.
899
     * @param bool $multiple whether multiple rows or a single row passed.
900
     *
901
     * @throws \Exception
902
     *
903
     * @return array normalized row or rows.
904
     */
905
    protected function normalizePdoRowKeyCase(array $row, bool $multiple): array
906
    {
907
        if ($this->db->getSlavePdo()?->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_UPPER) {
908
            return $row;
909
        }
910
911
        if ($multiple) {
912
            return array_map(static function (array $row) {
913
                return array_change_key_case($row, CASE_LOWER);
914
            }, $row);
915
        }
916
917
        return array_change_key_case($row, CASE_LOWER);
918
    }
919
920
    /**
921
     * Resolves the table name and schema name (if any).
922
     *
923
     * @param string $name the table name.
924
     *
925
     * @return TableSchema
926
     *
927
     * {@see TableSchema}
928
     */
929
    protected function resolveTableName(string $name): TableSchema
930
    {
931
        $resolvedName = new TableSchema();
932
933
        $parts = explode('.', str_replace('`', '', $name));
934
935
        if (isset($parts[1])) {
936
            $resolvedName->schemaName($parts[0]);
937
            $resolvedName->name($parts[1]);
938
        } else {
939
            $resolvedName->schemaName($this->defaultSchema);
940
            $resolvedName->name($name);
941
        }
942
943
        $resolvedName->fullName(($resolvedName->getSchemaName() !== $this->defaultSchema ?
944
            (string) $resolvedName->getSchemaName() . '.' : '') . $resolvedName->getName());
945
946
        return $resolvedName;
947
    }
948
949
    /**
950
     * Resolves the table name and schema name (if any).
951
     *
952
     * @param TableSchema $table the table metadata object.
953
     * @param string $name the table name.
954
     */
955
    protected function resolveTableNames(TableSchema $table, string $name): void
956
    {
957
        $parts = explode('.', str_replace('`', '', $name));
958
959
        if (isset($parts[1])) {
960
            $table->schemaName($parts[0]);
961
            $table->name($parts[1]);
962
            $table->fullName((string) $table->getSchemaName() . '.' . $table->getName());
963
        } else {
964
            $table->name($parts[0]);
965
            $table->fullName($parts[0]);
966
        }
967
    }
968
969
    /**
970
     * Creates a column schema for the database.
971
     *
972
     * This method may be overridden by child classes to create a DBMS-specific column schema.
973
     *
974
     * @return ColumnSchema column schema instance.
975
     */
976
    private function createColumnSchema(): ColumnSchema
977
    {
978
        return new ColumnSchema();
979
    }
980
}
981