Passed
Pull Request — master (#268)
by Sergei
03:52
created

Schema::createColumnSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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
            /**
218
             * @psalm-var NormalizePragmaForeignKeyList $foreignKeysById
219
             * @psalm-var int $id
220
             */
221 11
            foreach ($foreignKeysById as $id => $foreignKey) {
222 11
                if ($foreignKey[0]['to'] === null) {
223 5
                    $primaryKey = $this->getTablePrimaryKey($table);
224
225 5
                    if ($primaryKey !== null) {
226
                        /** @psalm-var string $primaryKeyColumnName */
227 5
                        foreach ((array) $primaryKey->getColumnNames() as $i => $primaryKeyColumnName) {
228 5
                            $foreignKey[$i]['to'] = $primaryKeyColumnName;
229
                        }
230
                    }
231
                }
232
233 11
                $fk = (new ForeignKeyConstraint())
234 11
                    ->name((string) $id)
235 11
                    ->columnNames(array_column($foreignKey, 'from'))
236 11
                    ->foreignTableName($table)
237 11
                    ->foreignColumnNames(array_column($foreignKey, 'to'))
238 11
                    ->onDelete($foreignKey[0]['on_delete'])
239 11
                    ->onUpdate($foreignKey[0]['on_update']);
240
241 11
                $result[] = $fk;
242
            }
243
        }
244
245 123
        return $result;
246
    }
247
248
    /**
249
     * Loads all indexes for the given table.
250
     *
251
     * @param string $tableName The table name.
252
     *
253
     * @throws Exception
254
     * @throws InvalidArgumentException
255
     * @throws InvalidConfigException
256
     * @throws Throwable
257
     *
258
     * @return array Indexes for the given table.
259
     *
260
     * @psalm-return array|IndexConstraint[]
261
     */
262 14
    protected function loadTableIndexes(string $tableName): array
263
    {
264 14
        $tableIndexes = $this->loadTableConstraints($tableName, self::INDEXES);
265
266 14
        return is_array($tableIndexes) ? $tableIndexes : [];
267
    }
268
269
    /**
270
     * Loads all unique constraints for the given table.
271
     *
272
     * @param string $tableName The table name.
273
     *
274
     * @throws Exception
275
     * @throws InvalidArgumentException
276
     * @throws InvalidConfigException
277
     * @throws Throwable
278
     *
279
     * @return array Unique constraints for the given table.
280
     *
281
     * @psalm-return array|Constraint[]
282
     */
283 15
    protected function loadTableUniques(string $tableName): array
284
    {
285 15
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
286
287 15
        return is_array($tableUniques) ? $tableUniques : [];
288
    }
289
290
    /**
291
     * Loads all check constraints for the given table.
292
     *
293
     * @param string $tableName The table name.
294
     *
295
     * @throws Exception
296
     * @throws InvalidArgumentException
297
     * @throws InvalidConfigException
298
     * @throws Throwable
299
     *
300
     * @return CheckConstraint[] Check constraints for the given table.
301
     */
302 15
    protected function loadTableChecks(string $tableName): array
303
    {
304 15
        $sql = $this->db->createCommand(
305 15
            'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName',
306 15
            [':tableName' => $tableName],
307 15
        )->queryScalar();
308
309 15
        $sql = ($sql === false || $sql === null) ? '' : (string) $sql;
310
311
        /** @psalm-var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */
312 15
        $code = (new SqlTokenizer($sql))->tokenize();
313 15
        $pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize();
314 15
        $result = [];
315
316 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

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

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