Passed
Pull Request — master (#268)
by
unknown
17:03 queued 12:53
created

Schema::loadTablePrimaryKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use Throwable;
8
use Yiisoft\Db\Constraint\CheckConstraint;
9
use Yiisoft\Db\Constraint\Constraint;
10
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
11
use Yiisoft\Db\Constraint\IndexConstraint;
12
use Yiisoft\Db\Driver\Pdo\AbstractPdoSchema;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidArgumentException;
15
use Yiisoft\Db\Exception\InvalidConfigException;
16
use Yiisoft\Db\Exception\NotSupportedException;
17
use Yiisoft\Db\Expression\Expression;
18
use Yiisoft\Db\Helper\DbArrayHelper;
19
use Yiisoft\Db\Schema\Builder\ColumnInterface;
20
use Yiisoft\Db\Schema\ColumnSchemaInterface;
21
use Yiisoft\Db\Schema\TableSchemaInterface;
22
23
use function array_column;
24
use function array_merge;
25
use function count;
26
use function explode;
27
use function md5;
28
use function preg_match;
29
use function preg_replace;
30
use function serialize;
31
use function strncasecmp;
32
use function strtolower;
33
34
/**
35
 * Implements the SQLite Server specific schema, supporting SQLite 3.3.0 or higher.
36
 *
37
 * @psalm-type Column = array<array-key, array{seqno:string, cid:string, name:string}>
38
 * @psalm-type NormalizePragmaForeignKeyList = array<
39
 *   string,
40
 *   array<
41
 *     array-key,
42
 *     array{
43
 *       id:string,
44
 *       cid:string,
45
 *       seq:string,
46
 *       table:string,
47
 *       from:string,
48
 *       to:string|null,
49
 *       on_update:string,
50
 *       on_delete:string
51
 *     }
52
 *   >
53
 * >
54
 * @psalm-type PragmaForeignKeyList = array<
55
 *   string,
56
 *   array{
57
 *     id:string,
58
 *     cid:string,
59
 *     seq:string,
60
 *     table:string,
61
 *     from:string,
62
 *     to:string|null,
63
 *     on_update:string,
64
 *     on_delete:string
65
 *   }
66
 * >
67
 * @psalm-type PragmaIndexInfo = array<array-key, array{seqno:string, cid:string, name:string}>
68
 * @psalm-type PragmaIndexList = array<
69
 *   array-key,
70
 *   array{seq:string, name:string, unique:string, origin:string, partial:string}
71
 * >
72
 * @psalm-type PragmaTableInfo = array<
73
 *   array-key,
74
 *   array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string}
75
 * >
76
 */
77
final class Schema extends AbstractPdoSchema
78
{
79
    /**
80
     * @var array Mapping from physical column types (keys) to abstract column types (values).
81
     *
82
     * @psalm-var array<array-key, string> $typeMap
83
     */
84
    private array $typeMap = [
85
        'tinyint' => self::TYPE_TINYINT,
86
        'bit' => self::TYPE_SMALLINT,
87
        'boolean' => self::TYPE_BOOLEAN,
88
        'bool' => self::TYPE_BOOLEAN,
89
        'smallint' => self::TYPE_SMALLINT,
90
        'mediumint' => self::TYPE_INTEGER,
91
        'int' => self::TYPE_INTEGER,
92
        'integer' => self::TYPE_INTEGER,
93
        'bigint' => self::TYPE_BIGINT,
94
        'float' => self::TYPE_FLOAT,
95
        'double' => self::TYPE_DOUBLE,
96
        'real' => self::TYPE_FLOAT,
97
        'decimal' => self::TYPE_DECIMAL,
98
        'numeric' => self::TYPE_DECIMAL,
99
        'tinytext' => self::TYPE_TEXT,
100
        'mediumtext' => self::TYPE_TEXT,
101
        'longtext' => self::TYPE_TEXT,
102
        'text' => self::TYPE_TEXT,
103
        'varchar' => self::TYPE_STRING,
104
        'string' => self::TYPE_STRING,
105
        'char' => self::TYPE_CHAR,
106
        'blob' => self::TYPE_BINARY,
107
        'datetime' => self::TYPE_DATETIME,
108
        'year' => self::TYPE_DATE,
109
        'date' => self::TYPE_DATE,
110
        'time' => self::TYPE_TIME,
111
        'timestamp' => self::TYPE_TIMESTAMP,
112
        'enum' => self::TYPE_STRING,
113
    ];
114
115 15
    public function createColumn(string $type, array|int|string $length = null): ColumnInterface
116
    {
117 15
        return new Column($type, $length);
118
    }
119
120
    /**
121
     * Returns all table names in the database.
122
     *
123
     * This method should be overridden by child classes to support this feature because the default implementation
124
     * simply throws an exception.
125
     *
126
     * @param string $schema The schema of the tables.
127
     * Defaults to empty string, meaning the current or default schema.
128
     *
129
     * @throws Exception
130
     * @throws InvalidConfigException
131
     * @throws Throwable
132
     *
133
     * @return array All tables name in the database. The names have NO schema name prefix.
134
     */
135 10
    protected function findTableNames(string $schema = ''): array
136
    {
137 10
        return $this->db
138 10
           ->createCommand(
139 10
               "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name"
140 10
           )
141 10
           ->queryColumn();
142
    }
143
144
    /**
145
     * Loads the metadata for the specified table.
146
     *
147
     * @param string $name The table name.
148
     *
149
     * @throws Exception
150
     * @throws InvalidArgumentException
151
     * @throws InvalidConfigException
152
     * @throws Throwable
153
     *
154
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
155
     */
156 157
    protected function loadTableSchema(string $name): TableSchemaInterface|null
157
    {
158 157
        $table = new TableSchema();
159
160 157
        $table->name($name);
161 157
        $table->fullName($name);
162
163 157
        if ($this->findColumns($table)) {
164 114
            $this->findConstraints($table);
165
166 114
            return $table;
167
        }
168
169 65
        return null;
170
    }
171
172
    /**
173
     * Loads a primary key for the given table.
174
     *
175
     * @param string $tableName The table name.
176
     *
177
     * @throws Exception
178
     * @throws InvalidArgumentException
179
     * @throws InvalidConfigException
180
     * @throws Throwable
181
     *
182
     * @return Constraint|null Primary key for the given table, `null` if the table has no primary key.
183
     */
184 54
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
185
    {
186 54
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
187
188 54
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
189
    }
190
191
    /**
192
     * Loads all foreign keys for the given table.
193
     *
194
     * @param string $tableName The table name.
195
     *
196
     * @throws Exception
197
     * @throws InvalidConfigException
198
     * @throws Throwable
199
     *
200
     * @return ForeignKeyConstraint[] Foreign keys for the given table.
201
     */
202 123
    protected function loadTableForeignKeys(string $tableName): array
203
    {
204 123
        $result = [];
205
        /** @psalm-var PragmaForeignKeyList $foreignKeysList */
206 123
        $foreignKeysList = $this->getPragmaForeignKeyList($tableName);
207
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
208 123
        $foreignKeysList = $this->normalizeRowKeyCase($foreignKeysList, true);
209
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
210 123
        $foreignKeysList = DbArrayHelper::index($foreignKeysList, null, ['table']);
211 123
        DbArrayHelper::multisort($foreignKeysList, 'seq');
212
213
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
214 123
        foreach ($foreignKeysList as $table => $foreignKeys) {
215 11
            $foreignKeysById = DbArrayHelper::index($foreignKeys, null, ['id']);
216
217
            /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysById */
218 11
            foreach ($foreignKeysById as $id => $foreignKey) {
219 11
                if ($foreignKey[0]['to'] === null) {
220 5
                    $primaryKey = $this->getTablePrimaryKey($table);
221
222 5
                    if ($primaryKey !== null) {
223
                        /** @psalm-var string $primaryKeyName */
224 5
                        foreach ((array) $primaryKey->getColumnNames() as $i => $primaryKeyName) {
225 5
                            $foreignKey[$i]['to'] = $primaryKeyName;
226
                        }
227
                    }
228
                }
229
230 11
                $fk = (new ForeignKeyConstraint())
231 11
                    ->columnNames(array_column($foreignKey, 'from'))
232 11
                    ->foreignTableName($table)
233 11
                    ->foreignColumnNames(array_column($foreignKey, 'to'))
234 11
                    ->onDelete($foreignKey[0]['on_delete'])
235 11
                    ->onUpdate($foreignKey[0]['on_update']);
236
237 11
                $result[(int) $id] = $fk;
238
            }
239
        }
240
241 123
        return $result;
242
    }
243
244
    /**
245
     * Loads all indexes for the given table.
246
     *
247
     * @param string $tableName The table name.
248
     *
249
     * @throws Exception
250
     * @throws InvalidArgumentException
251
     * @throws InvalidConfigException
252
     * @throws Throwable
253
     *
254
     * @return array Indexes for the given table.
255
     *
256
     * @psalm-return array|IndexConstraint[]
257
     */
258 14
    protected function loadTableIndexes(string $tableName): array
259
    {
260 14
        $tableIndexes = $this->loadTableConstraints($tableName, self::INDEXES);
261
262 14
        return is_array($tableIndexes) ? $tableIndexes : [];
263
    }
264
265
    /**
266
     * Loads all unique constraints for the given table.
267
     *
268
     * @param string $tableName The table name.
269
     *
270
     * @throws Exception
271
     * @throws InvalidArgumentException
272
     * @throws InvalidConfigException
273
     * @throws Throwable
274
     *
275
     * @return array Unique constraints for the given table.
276
     *
277
     * @psalm-return array|Constraint[]
278
     */
279 15
    protected function loadTableUniques(string $tableName): array
280
    {
281 15
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
282
283 15
        return is_array($tableUniques) ? $tableUniques : [];
284
    }
285
286
    /**
287
     * Loads all check constraints for the given table.
288
     *
289
     * @param string $tableName The table name.
290
     *
291
     * @throws Exception
292
     * @throws InvalidArgumentException
293
     * @throws InvalidConfigException
294
     * @throws Throwable
295
     *
296
     * @return CheckConstraint[] Check constraints for the given table.
297
     */
298 15
    protected function loadTableChecks(string $tableName): array
299
    {
300 15
        $sql = $this->db->createCommand(
301 15
            'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName',
302 15
            [':tableName' => $tableName],
303 15
        )->queryScalar();
304
305 15
        $sql = ($sql === false || $sql === null) ? '' : (string) $sql;
306
307
        /** @psalm-var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */
308 15
        $code = (new SqlTokenizer($sql))->tokenize();
309 15
        $pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize();
310 15
        $result = [];
311
312 15
        if ($code[0] instanceof SqlToken && $code[0]->matches($pattern, 0, $firstMatchIndex, $lastMatchIndex)) {
0 ignored issues
show
Bug introduced by
The method matches() does not exist on null. ( Ignorable by Annotation )

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

312
        if ($code[0] instanceof SqlToken && $code[0]->/** @scrutinizer ignore-call */ matches($pattern, 0, $firstMatchIndex, $lastMatchIndex)) {

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

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

Loading history...
313 15
            $offset = 0;
314 15
            $createTableToken = $code[0][(int) $lastMatchIndex - 1];
315 15
            $sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()');
316
317
            while (
318 15
                $createTableToken instanceof SqlToken &&
319 15
                $createTableToken->matches($sqlTokenizerAnyCheck->tokenize(), (int) $offset, $firstMatchIndex, $offset)
320
            ) {
321 4
                $name = null;
322 4
                $checkSql = (string) $createTableToken[(int) $offset - 1];
323 4
                $pattern = (new SqlTokenizer('CONSTRAINT any'))->tokenize();
324
325
                if (
326 4
                    isset($createTableToken[(int) $firstMatchIndex - 2])
327 4
                    && $createTableToken->matches($pattern, (int) $firstMatchIndex - 2)
328
                ) {
329 1
                    $sqlToken = $createTableToken[(int) $firstMatchIndex - 1];
330 1
                    $name = $sqlToken?->getContent();
331
                }
332
333 4
                $result[] = (new CheckConstraint())->name($name)->expression($checkSql);
334
            }
335
        }
336
337 15
        return $result;
338
    }
339
340
    /**
341
     * Loads all default value constraints for the given table.
342
     *
343
     * @param string $tableName The table name.
344
     *
345
     * @throws NotSupportedException
346
     *
347
     * @return array Default value constraints for the given table.
348
     */
349 13
    protected function loadTableDefaultValues(string $tableName): array
350
    {
351 13
        throw new NotSupportedException('SQLite does not support default value constraints.');
352
    }
353
354
    /**
355
     * Collects the table column metadata.
356
     *
357
     * @param TableSchemaInterface $table The table metadata.
358
     *
359
     * @throws Exception
360
     * @throws InvalidConfigException
361
     * @throws Throwable
362
     *
363
     * @return bool Whether the table exists in the database.
364
     */
365 157
    protected function findColumns(TableSchemaInterface $table): bool
366
    {
367
        /** @psalm-var PragmaTableInfo $columns */
368 157
        $columns = $this->getPragmaTableInfo($table->getName());
369
370 157
        foreach ($columns as $info) {
371 114
            $column = $this->loadColumnSchema($info);
372 114
            $table->column($column->getName(), $column);
373
374 114
            if ($column->isPrimaryKey()) {
375 75
                $table->primaryKey($column->getName());
376
            }
377
        }
378
379 157
        $column = count($table->getPrimaryKey()) === 1 ? $table->getColumn($table->getPrimaryKey()[0]) : null;
380
381 157
        if ($column !== null && !strncasecmp($column->getDbType() ?? '', 'int', 3)) {
382 70
            $table->sequenceName('');
383 70
            $column->autoIncrement(true);
384
        }
385
386 157
        return !empty($columns);
387
    }
388
389
    /**
390
     * Collects the foreign key column details for the given table.
391
     *
392
     * @param TableSchemaInterface $table The table metadata.
393
     *
394
     * @throws Exception
395
     * @throws InvalidConfigException
396
     * @throws Throwable
397
     */
398 114
    protected function findConstraints(TableSchemaInterface $table): void
399
    {
400
        /** @psalm-var ForeignKeyConstraint[] $foreignKeysList */
401 114
        $foreignKeysList = $this->getTableForeignKeys($table->getName(), true);
402
403 114
        foreach ($foreignKeysList as $id => $foreignKey) {
404
            /** @var array<string> $columnNames */
405 6
            $columnNames = (array) $foreignKey->getColumnNames();
406 6
            $columnNames = array_combine($columnNames, $foreignKey->getForeignColumnNames());
407
408 6
            $foreignReference = array_merge([$foreignKey->getForeignTableName()], $columnNames);
409
410 6
            $table->foreignKey($id, $foreignReference);
411
        }
412
    }
413
414
    /**
415
     * Returns all unique indexes for the given table.
416
     *
417
     * Each array element is of the following structure:
418
     *
419
     * ```php
420
     * [
421
     *     'IndexName1' => ['col1' [, ...]],
422
     *     'IndexName2' => ['col2' [, ...]],
423
     * ]
424
     * ```
425
     *
426
     * @param TableSchemaInterface $table The table metadata.
427
     *
428
     * @throws Exception
429
     * @throws InvalidConfigException
430
     * @throws Throwable
431
     *
432
     * @return array All unique indexes for the given table.
433
     */
434 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
435
    {
436
        /** @psalm-var PragmaIndexList $indexList */
437 1
        $indexList = $this->getPragmaIndexList($table->getName());
438 1
        $uniqueIndexes = [];
439
440 1
        foreach ($indexList as $index) {
441 1
            $indexName = $index['name'];
442
            /** @psalm-var PragmaIndexInfo $indexInfo */
443 1
            $indexInfo = $this->getPragmaIndexInfo($index['name']);
444
445 1
            if ($index['unique']) {
446 1
                $uniqueIndexes[$indexName] = [];
447 1
                foreach ($indexInfo as $row) {
448 1
                    $uniqueIndexes[$indexName][] = $row['name'];
449
                }
450
            }
451
        }
452
453 1
        return $uniqueIndexes;
454
    }
455
456
    /**
457
     * @throws NotSupportedException
458
     */
459 1
    public function getSchemaDefaultValues(string $schema = '', bool $refresh = false): array
460
    {
461 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
462
    }
463
464
    /**
465
     * Loads the column information into a {@see ColumnSchemaInterface} object.
466
     *
467
     * @param array $info The column information.
468
     *
469
     * @return ColumnSchemaInterface The column schema object.
470
     *
471
     * @psalm-param array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string} $info
472
     */
473 114
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
474
    {
475 114
        $column = $this->createColumnSchema($info['name']);
476 114
        $column->allowNull(!$info['notnull']);
477 114
        $column->primaryKey($info['pk'] != '0');
478 114
        $column->dbType(strtolower($info['type']));
479 114
        $column->unsigned(str_contains($column->getDbType() ?? '', 'unsigned'));
480 114
        $column->type(self::TYPE_STRING);
481
482 114
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType() ?? '', $matches)) {
483 114
            $type = strtolower($matches[1]);
484
485 114
            if (isset($this->typeMap[$type])) {
486 114
                $column->type($this->typeMap[$type]);
487
            }
488
489 114
            if (!empty($matches[2])) {
490 99
                $values = explode(',', $matches[2]);
491 99
                $column->precision((int) $values[0]);
492 99
                $column->size((int) $values[0]);
493
494 99
                if (isset($values[1])) {
495 31
                    $column->scale((int) $values[1]);
496
                }
497
498 99
                if (($type === 'tinyint' || $type === 'bit') && $column->getSize() === 1) {
499 25
                    $column->type(self::TYPE_BOOLEAN);
500 99
                } elseif ($type === 'bit') {
501 4
                    if ($column->getSize() > 32) {
502 4
                        $column->type(self::TYPE_BIGINT);
503 4
                    } elseif ($column->getSize() === 32) {
504 4
                        $column->type(self::TYPE_INTEGER);
505
                    }
506
                }
507
            }
508
        }
509
510 114
        $column->phpType($this->getColumnPhpType($column));
511 114
        $column->defaultValue($this->normalizeDefaultValue($info['dflt_value'], $column));
512
513 114
        return $column;
514
    }
515
516
    /**
517
     * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database.
518
     *
519
     * @param string|null $defaultValue The default value retrieved from the database.
520
     * @param ColumnSchemaInterface $column The column schema object.
521
     *
522
     * @return mixed The normalized default value.
523
     */
524 114
    private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed
525
    {
526 114
        if ($column->isPrimaryKey() || in_array($defaultValue, [null, '', 'null', 'NULL'], true)) {
527 110
            return null;
528
        }
529
530 76
        if (in_array($defaultValue, ['CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)) {
531 25
            return new Expression($defaultValue);
0 ignored issues
show
Bug introduced by
It seems like $defaultValue can also be of type null; however, parameter $expression of Yiisoft\Db\Expression\Expression::__construct() 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

531
            return new Expression(/** @scrutinizer ignore-type */ $defaultValue);
Loading history...
532
        }
533
534 76
        $value = preg_replace('/^([\'"])(.*)\1$/s', '$2', $defaultValue);
535
536 76
        return $column->phpTypecast($value);
537
    }
538
539
    /**
540
     * Returns table columns info.
541
     *
542
     * @param string $tableName The table name.
543
     *
544
     * @throws Exception
545
     * @throws InvalidConfigException
546
     * @throws Throwable
547
     *
548
     * @return array The table columns info.
549
     */
550 54
    private function loadTableColumnsInfo(string $tableName): array
551
    {
552 54
        $tableColumns = $this->getPragmaTableInfo($tableName);
553
        /** @psalm-var PragmaTableInfo $tableColumns */
554 54
        $tableColumns = $this->normalizeRowKeyCase($tableColumns, true);
555
556 54
        return DbArrayHelper::index($tableColumns, 'cid');
557
    }
558
559
    /**
560
     * Loads multiple types of constraints and returns the specified ones.
561
     *
562
     * @param string $tableName The table name.
563
     * @param string $returnType Return type: (primaryKey, indexes, uniques).
564
     *
565
     * @throws Exception
566
     * @throws InvalidConfigException
567
     * @throws Throwable
568
     *
569
     * @psalm-return Constraint[]|IndexConstraint[]|Constraint|null
570
     */
571 83
    private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null
572
    {
573 83
        $indexList = $this->getPragmaIndexList($tableName);
574
        /** @psalm-var PragmaIndexList $indexes */
575 83
        $indexes = $this->normalizeRowKeyCase($indexList, true);
576 83
        $result = [
577 83
            self::PRIMARY_KEY => null,
578 83
            self::INDEXES => [],
579 83
            self::UNIQUES => [],
580 83
        ];
581
582 83
        foreach ($indexes as $index) {
583
            /** @psalm-var Column $columns */
584 64
            $columns = $this->getPragmaIndexInfo($index['name']);
585
586 64
            if ($index['origin'] === 'pk') {
587 29
                $result[self::PRIMARY_KEY] = (new Constraint())
588 29
                    ->columnNames(DbArrayHelper::getColumn($columns, 'name'));
589
            }
590
591 64
            if ($index['origin'] === 'u') {
592 59
                $result[self::UNIQUES][] = (new Constraint())
593 59
                    ->name($index['name'])
594 59
                    ->columnNames(DbArrayHelper::getColumn($columns, 'name'));
595
            }
596
597 64
            $result[self::INDEXES][] = (new IndexConstraint())
598 64
                ->primary($index['origin'] === 'pk')
599 64
                ->unique((bool) $index['unique'])
600 64
                ->name($index['name'])
601 64
                ->columnNames(DbArrayHelper::getColumn($columns, 'name'));
602
        }
603
604 83
        if (!isset($result[self::PRIMARY_KEY])) {
605
            /**
606
             * Extra check for PK in case of `INTEGER PRIMARY KEY` with ROWID.
607
             *
608
             * @link https://www.sqlite.org/lang_createtable.html#primkeyconst
609
             *
610
             * @psalm-var PragmaTableInfo $tableColumns
611
             */
612 54
            $tableColumns = $this->loadTableColumnsInfo($tableName);
613
614 54
            foreach ($tableColumns as $tableColumn) {
615 54
                if ($tableColumn['pk'] > 0) {
616 34
                    $result[self::PRIMARY_KEY] = (new Constraint())->columnNames([$tableColumn['name']]);
617 34
                    break;
618
                }
619
            }
620
        }
621
622 83
        foreach ($result as $type => $data) {
623 83
            $this->setTableMetadata($tableName, $type, $data);
624
        }
625
626 83
        return $result[$returnType];
627
    }
628
629
    /**
630
     * Creates a column schema for the database.
631
     *
632
     * This method may be overridden by child classes to create a DBMS-specific column schema.
633
     *
634
     * @param string $name Name of the column.
635
     */
636 114
    private function createColumnSchema(string $name): ColumnSchemaInterface
637
    {
638 114
        return new ColumnSchema($name);
639
    }
640
641
    /**
642
     * @throws Exception
643
     * @throws InvalidConfigException
644
     * @throws Throwable
645
     */
646 123
    private function getPragmaForeignKeyList(string $tableName): array
647
    {
648 123
        return $this->db->createCommand(
649 123
            'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
650 123
        )->queryAll();
651
    }
652
653
    /**
654
     * @throws Exception
655
     * @throws InvalidConfigException
656
     * @throws Throwable
657
     */
658 65
    private function getPragmaIndexInfo(string $name): array
659
    {
660 65
        $column = $this->db
661 65
            ->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')')
662 65
            ->queryAll();
663
        /** @psalm-var Column $column */
664 65
        $column = $this->normalizeRowKeyCase($column, true);
665 65
        DbArrayHelper::multisort($column, 'seqno');
666
667 65
        return $column;
668
    }
669
670
    /**
671
     * @throws Exception
672
     * @throws InvalidConfigException
673
     * @throws Throwable
674
     */
675 84
    private function getPragmaIndexList(string $tableName): array
676
    {
677 84
        return $this->db
678 84
            ->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')')
679 84
            ->queryAll();
680
    }
681
682
    /**
683
     * @throws Exception
684
     * @throws InvalidConfigException
685
     * @throws Throwable
686
     */
687 166
    private function getPragmaTableInfo(string $tableName): array
688
    {
689 166
        return $this->db->createCommand(
690 166
            'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
691 166
        )->queryAll();
692
    }
693
694
    /**
695
     * @throws Exception
696
     * @throws InvalidConfigException
697
     * @throws Throwable
698
     */
699 1
    protected function findViewNames(string $schema = ''): array
700
    {
701
        /** @psalm-var string[][] $views */
702 1
        $views = $this->db->createCommand(
703 1
            <<<SQL
704
            SELECT name as view FROM sqlite_master WHERE type = 'view' AND name NOT LIKE 'sqlite_%'
705 1
            SQL,
706 1
        )->queryAll();
707
708 1
        foreach ($views as $key => $view) {
709 1
            $views[$key] = $view['view'];
710
        }
711
712 1
        return $views;
713
    }
714
715
    /**
716
     * Returns the cache key for the specified table name.
717
     *
718
     * @param string $name the table name.
719
     *
720
     * @return array The cache key.
721
     */
722 224
    protected function getCacheKey(string $name): array
723
    {
724 224
        return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]);
725
    }
726
727
    /**
728
     * Returns the cache tag name.
729
     *
730
     * This allows {@see refresh()} to invalidate all cached table schemas.
731
     *
732
     * @return string The cache tag name.
733
     */
734 208
    protected function getCacheTag(): string
735
    {
736 208
        return md5(serialize(array_merge([self::class], $this->generateCacheKey())));
737
    }
738
}
739