Passed
Branch master (e82d75)
by Wilmer
07:17 queued 02:54
created

Schema::getSchemaDefaultValues()   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 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use Throwable;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Arrays\ArraySorter;
10
use Yiisoft\Db\Constraint\CheckConstraint;
11
use Yiisoft\Db\Constraint\Constraint;
12
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
13
use Yiisoft\Db\Constraint\IndexConstraint;
14
use Yiisoft\Db\Exception\Exception;
15
use Yiisoft\Db\Exception\InvalidArgumentException;
16
use Yiisoft\Db\Exception\InvalidConfigException;
17
use Yiisoft\Db\Exception\NotSupportedException;
18
use Yiisoft\Db\Expression\Expression;
19
use Yiisoft\Db\Schema\ColumnSchema;
20
use Yiisoft\Db\Schema\ColumnSchemaInterface;
21
use Yiisoft\Db\Schema\Schema as AbstractSchema;
22
use Yiisoft\Db\Schema\TableSchemaInterface;
23
use Yiisoft\Db\Transaction\TransactionInterface;
24
25
use function count;
26
use function explode;
27
use function preg_match;
28
use function strncasecmp;
29
use function strtolower;
30
use function trim;
31
32
/**
33
 * Schema is the class for retrieving metadata from a SQLite (2/3) database.
34
 *
35
 * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction. This can be
36
 * either {@see TransactionInterface::READ_UNCOMMITTED} or {@see TransactionInterface::SERIALIZABLE}.
37
 *
38
 * @psalm-type Column = array<array-key, array{seqno:string, cid:string, name:string}>
39
 *
40
 * @psalm-type NormalizePragmaForeignKeyList = array<
41
 *   string,
42
 *   array<
43
 *     array-key,
44
 *     array{
45
 *       id:string,
46
 *       cid:string,
47
 *       seq:string,
48
 *       table:string,
49
 *       from:string,
50
 *       to:string,
51
 *       on_update:string,
52
 *       on_delete:string
53
 *     }
54
 *   >
55
 * >
56
 *
57
 * @psalm-type PragmaForeignKeyList = array<
58
 *   string,
59
 *   array{
60
 *     id:string,
61
 *     cid:string,
62
 *     seq:string,
63
 *     table:string,
64
 *     from:string,
65
 *     to:string,
66
 *     on_update:string,
67
 *     on_delete:string
68
 *   }
69
 * >
70
 *
71
 * @psalm-type PragmaIndexInfo = array<array-key, array{seqno:string, cid:string, name:string}>
72
 *
73
 * @psalm-type PragmaIndexList = array<
74
 *   array-key,
75
 *   array{seq:string, name:string, unique:string, origin:string, partial:string}
76
 * >
77
 *
78
 * @psalm-type PragmaTableInfo = array<
79
 *   array-key,
80
 *   array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string}
81
 * >
82
 */
83
final class Schema extends AbstractSchema
84
{
85
    /**
86
     * @var array mapping from physical column types (keys) to abstract column types (values)
87
     *
88
     * @psalm-var array<array-key, string> $typeMap
89
     */
90
    private array $typeMap = [
91
        'tinyint' => self::TYPE_TINYINT,
92
        'bit' => self::TYPE_SMALLINT,
93
        'boolean' => self::TYPE_BOOLEAN,
94
        'bool' => self::TYPE_BOOLEAN,
95
        'smallint' => self::TYPE_SMALLINT,
96
        'mediumint' => self::TYPE_INTEGER,
97
        'int' => self::TYPE_INTEGER,
98
        'integer' => self::TYPE_INTEGER,
99
        'bigint' => self::TYPE_BIGINT,
100
        'float' => self::TYPE_FLOAT,
101
        'double' => self::TYPE_DOUBLE,
102
        'real' => self::TYPE_FLOAT,
103
        'decimal' => self::TYPE_DECIMAL,
104
        'numeric' => self::TYPE_DECIMAL,
105
        'tinytext' => self::TYPE_TEXT,
106
        'mediumtext' => self::TYPE_TEXT,
107
        'longtext' => self::TYPE_TEXT,
108
        'text' => self::TYPE_TEXT,
109
        'varchar' => self::TYPE_STRING,
110
        'string' => self::TYPE_STRING,
111
        'char' => self::TYPE_CHAR,
112
        'blob' => self::TYPE_BINARY,
113
        'datetime' => self::TYPE_DATETIME,
114
        'year' => self::TYPE_DATE,
115
        'date' => self::TYPE_DATE,
116
        'time' => self::TYPE_TIME,
117
        'timestamp' => self::TYPE_TIMESTAMP,
118
        'enum' => self::TYPE_STRING,
119
    ];
120
121
    /**
122
     * Returns all table names in the database.
123
     *
124
     * This method should be overridden by child classes in order to support this feature because the default
125
     * implementation simply throws an exception.
126
     *
127
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
128
     *
129
     * @throws Exception|InvalidConfigException|Throwable
130
     *
131
     * @return array All table names in the database. The names have NO schema name prefix.
132
     */
133 10
    protected function findTableNames(string $schema = ''): array
134
    {
135 10
        return $this->db
136 10
           ->createCommand(
137 10
               "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name"
138 10
           )
139 10
           ->queryColumn();
140
    }
141
142
    /**
143
     * Loads the metadata for the specified table.
144
     *
145
     * @param string $name table name.
146
     *
147
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
148
     *
149
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table does not exist.
150
     */
151 122
    protected function loadTableSchema(string $name): TableSchemaInterface|null
152
    {
153 122
        $table = new TableSchema();
154
155 122
        $table->name($name);
156 122
        $table->fullName($name);
157
158 122
        if ($this->findColumns($table)) {
159 79
            $this->findConstraints($table);
160
161 79
            return $table;
162
        }
163
164 52
        return null;
165
    }
166
167
    /**
168
     * Loads a primary key for the given table.
169
     *
170
     * @param string $tableName table name.
171
     *
172
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
173
     *
174
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.
175
     */
176 33
    protected function loadTablePrimaryKey(string $tableName): Constraint|null
177
    {
178 33
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
179
180 33
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
181
    }
182
183
    /**
184
     * Loads all foreign keys for the given table.
185
     *
186
     * @param string $tableName table name.
187
     *
188
     * @throws Exception|InvalidConfigException|Throwable
189
     *
190
     * @return ForeignKeyConstraint[] foreign keys for the given table.
191
     */
192 9
    protected function loadTableForeignKeys(string $tableName): array
193
    {
194 9
        $result = [];
195
        /** @psalm-var PragmaForeignKeyList $foreignKeysList */
196 9
        $foreignKeysList = $this->getPragmaForeignKeyList($tableName);
197
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
198 9
        $foreignKeysList = $this->normalizeRowKeyCase($foreignKeysList, true);
199
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
200 9
        $foreignKeysList = ArrayHelper::index($foreignKeysList, null, 'table');
201 9
        ArraySorter::multisort($foreignKeysList, 'seq', SORT_ASC, SORT_NUMERIC);
202
203
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
204 9
        foreach ($foreignKeysList as $table => $foreignKey) {
205 5
            $fk = (new ForeignKeyConstraint())
206 5
                ->columnNames(ArrayHelper::getColumn($foreignKey, 'from'))
207 5
                ->foreignTableName($table)
208 5
                ->foreignColumnNames(ArrayHelper::getColumn($foreignKey, 'to'))
209 5
                ->onDelete($foreignKey[0]['on_delete'] ?? null)
210 5
                ->onUpdate($foreignKey[0]['on_update'] ?? null);
211
212 5
            $result[] = $fk;
213
        }
214
215 9
        return $result;
216
    }
217
218
    /**
219
     * Loads all indexes for the given table.
220
     *
221
     * @param string $tableName table name.
222
     *
223
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
224
     *
225
     * @return array indexes for the given table.
226
     *
227
     * @psalm-return array|IndexConstraint[]
228
     */
229 13
    protected function loadTableIndexes(string $tableName): array
230
    {
231 13
        $tableIndexes = $this->loadTableConstraints($tableName, self::INDEXES);
232
233 13
        return is_array($tableIndexes) ? $tableIndexes : [];
234
    }
235
236
    /**
237
     * Loads all unique constraints for the given table.
238
     *
239
     * @param string $tableName table name.
240
     *
241
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
242
     *
243
     * @return array unique constraints for the given table.
244
     *
245
     * @psalm-return array|Constraint[]
246
     */
247 15
    protected function loadTableUniques(string $tableName): array
248
    {
249 15
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
250
251 15
        return is_array($tableUniques) ? $tableUniques : [];
252
    }
253
254
    /**
255
     * Loads all check constraints for the given table.
256
     *
257
     * @param string $tableName table name.
258
     *
259
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
260
     *
261
     * @return CheckConstraint[] check constraints for the given table.
262
     */
263 15
    protected function loadTableChecks(string $tableName): array
264
    {
265 15
        $sql = $this->db->createCommand(
266 15
            'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName',
267 15
            [':tableName' => $tableName],
268 15
        )->queryScalar();
269
270 15
        $sql = ($sql === false || $sql === null) ? '' : (string) $sql;
271
272
        /** @var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */
273 15
        $code = (new SqlTokenizer($sql))->tokenize();
274 15
        $pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize();
275 15
        $result = [];
276
277 15
        if ($code[0] instanceof SqlToken && $code[0]->matches($pattern, 0, $firstMatchIndex, $lastMatchIndex)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $firstMatchIndex seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $lastMatchIndex seems to be never defined.
Loading history...
278 15
            $offset = 0;
279 15
            $createTableToken = $code[0][(int) $lastMatchIndex - 1];
280 15
            $sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()');
281
282
            while (
283 15
                $createTableToken instanceof SqlToken &&
284 15
                $createTableToken->matches($sqlTokenizerAnyCheck->tokenize(), (int) $offset, $firstMatchIndex, $offset)
285
            ) {
286 4
                $name = null;
287 4
                $checkSql = (string) $createTableToken[(int) $offset - 1];
288 4
                $pattern = (new SqlTokenizer('CONSTRAINT any'))->tokenize();
289
290
                if (
291 4
                    isset($createTableToken[(int) $firstMatchIndex - 2])
292 4
                    && $createTableToken->matches($pattern, (int) $firstMatchIndex - 2)
293
                ) {
294 1
                    $sqlToken = $createTableToken[(int) $firstMatchIndex - 1];
295 1
                    $name = $sqlToken?->getContent();
296
                }
297
298 4
                $result[] = (new CheckConstraint())->name($name)->expression($checkSql);
299
            }
300
        }
301
302 15
        return $result;
303
    }
304
305
    /**
306
     * Loads all default value constraints for the given table.
307
     *
308
     * @param string $tableName table name.
309
     *
310
     * @throws NotSupportedException
311
     *
312
     * @return array default value constraints for the given table.
313
     */
314 13
    protected function loadTableDefaultValues(string $tableName): array
315
    {
316 13
        throw new NotSupportedException('SQLite does not support default value constraints.');
317
    }
318
319
    /**
320
     * Create a column schema builder instance giving the type and value precision.
321
     *
322
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
323
     *
324
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
325
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
326
     *
327
     * @return ColumnSchemaBuilder column schema builder instance.
328
     *
329
     * @psalm-param array<array-key, string>|int|null|string $length
330
     */
331 10
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
332
    {
333 10
        return new ColumnSchemaBuilder($type, $length);
334
    }
335
336
    /**
337
     * Collects the table column metadata.
338
     *
339
     * @param TableSchemaInterface $table the table metadata.
340
     *
341
     * @throws Exception|InvalidConfigException|Throwable
342
     *
343
     * @return bool whether the table exists in the database.
344
     */
345 122
    protected function findColumns(TableSchemaInterface $table): bool
346
    {
347
        /** @psalm-var PragmaTableInfo $columns */
348 122
        $columns = $this->getPragmaTableInfo($table->getName());
349
350 122
        foreach ($columns as $info) {
351 79
            $column = $this->loadColumnSchema($info);
352 79
            $table->columns($column->getName(), $column);
353
354 79
            if ($column->isPrimaryKey()) {
355 52
                $table->primaryKey($column->getName());
356
            }
357
        }
358
359 122
        $column = count($table->getPrimaryKey()) === 1 ? $table->getColumn($table->getPrimaryKey()[0]) : null;
360
361 122
        if ($column !== null && !strncasecmp($column->getDbType(), 'int', 3)) {
362 52
            $table->sequenceName('');
363 52
            $column->autoIncrement(true);
364
        }
365
366 122
        return !empty($columns);
367
    }
368
369
    /**
370
     * Collects the foreign key column details for the given table.
371
     *
372
     * @param TableSchemaInterface $table the table metadata.
373
     *
374
     * @throws Exception|InvalidConfigException|Throwable
375
     */
376 79
    protected function findConstraints(TableSchemaInterface $table): void
377
    {
378
        /** @psalm-var PragmaForeignKeyList $foreignKeysList */
379 79
        $foreignKeysList = $this->getPragmaForeignKeyList($table->getName());
380
381 79
        foreach ($foreignKeysList as $foreignKey) {
382 5
            $id = (int) $foreignKey['id'];
383 5
            $fk = $table->getForeignKeys();
384
385 5
            if (!isset($fk[$id])) {
386 5
                $table->foreignKey($id, ([$foreignKey['table'], $foreignKey['from'] => $foreignKey['to']]));
387
            } else {
388
                /** composite FK */
389 5
                $table->compositeFK($id, $foreignKey['from'], $foreignKey['to']);
390
            }
391
        }
392
    }
393
394
    /**
395
     * Returns all unique indexes for the given table.
396
     *
397
     * Each array element is of the following structure:
398
     *
399
     * ```php
400
     * [
401
     *     'IndexName1' => ['col1' [, ...]],
402
     *     'IndexName2' => ['col2' [, ...]],
403
     * ]
404
     * ```
405
     *
406
     * @param TableSchemaInterface $table the table metadata.
407
     *
408
     * @throws Exception|InvalidConfigException|Throwable
409
     *
410
     * @return array all unique indexes for the given table.
411
     */
412 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
413
    {
414
        /** @psalm-var PragmaIndexList $indexList */
415 1
        $indexList = $this->getPragmaIndexList($table->getName());
416 1
        $uniqueIndexes = [];
417
418 1
        foreach ($indexList as $index) {
419 1
            $indexName = $index['name'];
420
            /** @psalm-var PragmaIndexInfo $indexInfo */
421 1
            $indexInfo = $this->getPragmaIndexInfo($index['name']);
422
423 1
            if ($index['unique']) {
424 1
                $uniqueIndexes[$indexName] = [];
425 1
                foreach ($indexInfo as $row) {
426 1
                    $uniqueIndexes[$indexName][] = $row['name'];
427
                }
428
            }
429
        }
430
431 1
        return $uniqueIndexes;
432
    }
433
434
    /**
435
     * @throws NotSupportedException
436
     */
437 1
    public function getSchemaDefaultValues(string $schema = '', bool $refresh = false): array
438
    {
439 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
440
    }
441
442
    /**
443
     * Loads the column information into a {@see ColumnSchemaInterface} object.
444
     *
445
     * @param array $info column information.
446
     *
447
     * @return ColumnSchemaInterface the column schema object.
448
     *
449
     * @psalm-param array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string} $info
450
     */
451 79
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
452
    {
453 79
        $column = $this->createColumnSchema();
454 79
        $column->name($info['name']);
455 79
        $column->allowNull(!$info['notnull']);
456 79
        $column->primaryKey($info['pk'] != '0');
457 79
        $column->dbType(strtolower($info['type']));
458 79
        $column->unsigned(str_contains($column->getDbType(), 'unsigned'));
459 79
        $column->type(self::TYPE_STRING);
460
461 79
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
462 79
            $type = strtolower($matches[1]);
463
464 79
            if (isset($this->typeMap[$type])) {
465 79
                $column->type($this->typeMap[$type]);
466
            }
467
468 79
            if (!empty($matches[2])) {
469 73
                $values = explode(',', $matches[2]);
470 73
                $column->precision((int) $values[0]);
471 73
                $column->size((int) $values[0]);
472
473 73
                if (isset($values[1])) {
474 28
                    $column->scale((int) $values[1]);
475
                }
476
477 73
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
478 23
                    $column->type(self::TYPE_BOOLEAN);
479 73
                } elseif ($type === 'bit') {
480 4
                    if ($column->getSize() > 32) {
481 4
                        $column->type(self::TYPE_BIGINT);
482 4
                    } elseif ($column->getSize() === 32) {
483 4
                        $column->type(self::TYPE_INTEGER);
484
                    }
485
                }
486
            }
487
        }
488
489 79
        $column->phpType($this->getColumnPhpType($column));
490
491 79
        if (!$column->isPrimaryKey()) {
492 77
            if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
493 74
                $column->defaultValue(null);
494 57
            } elseif ($column->getType() === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
495 22
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP'));
496
            } else {
497 57
                $value = trim($info['dflt_value'], "'\"");
498 57
                $column->defaultValue($column->phpTypecast($value));
499
            }
500
        }
501
502 79
        return $column;
503
    }
504
505
    /**
506
     * Returns table columns info.
507
     *
508
     * @param string $tableName table name.
509
     *
510
     * @throws Exception|InvalidConfigException|Throwable
511
     */
512 37
    private function loadTableColumnsInfo(string $tableName): array
513
    {
514 37
        $tableColumns = $this->getPragmaTableInfo($tableName);
515
        /** @psalm-var PragmaTableInfo $tableColumns */
516 37
        $tableColumns = $this->normalizeRowKeyCase($tableColumns, true);
517
518 37
        return ArrayHelper::index($tableColumns, 'cid');
519
    }
520
521
    /**
522
     * Loads multiple types of constraints and returns the specified ones.
523
     *
524
     * @param string $tableName table name.
525
     * @param string $returnType return type: (primaryKey, indexes, uniques).
526
     *
527
     * @throws Exception|InvalidConfigException|Throwable
528
     *
529
     * @psalm-return (Constraint|IndexConstraint)[]|Constraint|null
530
     */
531 61
    private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null
532
    {
533 61
        $indexList = $this->getPragmaIndexList($tableName);
534
        /** @psalm-var PragmaIndexList $indexes */
535 61
        $indexes = $this->normalizeRowKeyCase($indexList, true);
536 61
        $result = [
537 61
            self::PRIMARY_KEY => null,
538 61
            self::INDEXES => [],
539 61
            self::UNIQUES => [],
540 61
        ];
541
542 61
        foreach ($indexes as $index) {
543
            /** @psalm-var Column $columns */
544 45
            $columns = $this->getPragmaIndexInfo($index['name']);
545
546 45
            if ($index['origin'] === 'pk') {
547 24
                $result[self::PRIMARY_KEY] = (new Constraint())
548 24
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
549
            }
550
551 45
            if ($index['origin'] === 'u') {
552 41
                $result[self::UNIQUES][] = (new Constraint())
553 41
                    ->name($index['name'])
554 41
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
555
            }
556
557 45
            $result[self::INDEXES][] = (new IndexConstraint())
558 45
                ->primary($index['origin'] === 'pk')
559 45
                ->unique((bool) $index['unique'])
560 45
                ->name($index['name'])
561 45
                ->columnNames(ArrayHelper::getColumn($columns, 'name'));
562
        }
563
564 61
        if (!isset($result[self::PRIMARY_KEY])) {
565
            /**
566
             * Additional check for PK in case of INTEGER PRIMARY KEY with ROWID.
567
             *
568
             * {@link https://www.sqlite.org/lang_createtable.html#primkeyconst}
569
             *
570
             * @psalm-var PragmaTableInfo $tableColumns
571
             */
572 37
            $tableColumns = $this->loadTableColumnsInfo($tableName);
573
574 37
            foreach ($tableColumns as $tableColumn) {
575 37
                if ($tableColumn['pk'] > 0) {
576 18
                    $result[self::PRIMARY_KEY] = (new Constraint())->columnNames([$tableColumn['name']]);
577 18
                    break;
578
                }
579
            }
580
        }
581
582 61
        foreach ($result as $type => $data) {
583 61
            $this->setTableMetadata($tableName, $type, $data);
584
        }
585
586 61
        return $result[$returnType];
587
    }
588
589
    /**
590
     * Creates a column schema for the database.
591
     *
592
     * This method may be overridden by child classes to create a DBMS-specific column schema.
593
     *
594
     * @return ColumnSchemaInterface column schema instance.
595
     */
596 79
    private function createColumnSchema(): ColumnSchemaInterface
597
    {
598 79
        return new ColumnSchema();
599
    }
600
601
    /**
602
     * @throws Exception|InvalidConfigException|Throwable
603
     */
604 88
    private function getPragmaForeignKeyList(string $tableName): array
605
    {
606 88
        return $this->db->createCommand(
607 88
            'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName(($tableName)) . ')'
608 88
        )->queryAll();
609
    }
610
611
    /**
612
     * @throws Exception|InvalidConfigException|Throwable
613
     */
614 46
    private function getPragmaIndexInfo(string $name): array
615
    {
616 46
        $column = $this->db
617 46
            ->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')')
618 46
            ->queryAll();
619
        /** @psalm-var Column $column */
620 46
        $column = $this->normalizeRowKeyCase($column, true);
621 46
        ArraySorter::multisort($column, 'seqno', SORT_ASC, SORT_NUMERIC);
622
623 46
        return $column;
624
    }
625
626
    /**
627
     * @throws Exception
628
     * @throws InvalidConfigException
629
     * @throws Throwable
630
     */
631 62
    private function getPragmaIndexList(string $tableName): array
632
    {
633 62
        return $this->db
634 62
            ->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')')
635 62
            ->queryAll();
636
    }
637
638
    /**
639
     * @throws Exception|InvalidConfigException|Throwable
640
     */
641 131
    private function getPragmaTableInfo(string $tableName): array
642
    {
643 131
        return $this->db->createCommand(
644 131
            'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
645 131
        )->queryAll();
646
    }
647
648
    /**
649
     * @throws Exception
650
     * @throws InvalidConfigException
651
     * @throws Throwable
652
     */
653 1
    protected function findViewNames(string $schema = ''): array
654
    {
655
        /** @psalm-var string[][] $views */
656 1
        $views = $this->db->createCommand(
657 1
            <<<SQL
658
            SELECT name as view FROM sqlite_master WHERE type = 'view' AND name NOT LIKE 'sqlite_%'
659 1
            SQL,
660 1
        )->queryAll();
661
662 1
        foreach ($views as $key => $view) {
663 1
            $views[$key] = $view['view'];
664
        }
665
666 1
        return $views;
667
    }
668
669
    /**
670
     * Returns the cache key for the specified table name.
671
     *
672
     * @param string $name the table name.
673
     *
674
     * @return array the cache key.
675
     */
676 185
    protected function getCacheKey(string $name): array
677
    {
678 185
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
679
    }
680
681
    /**
682
     * Returns the cache tag name.
683
     *
684
     * This allows {@see refresh()} to invalidate all cached table schemas.
685
     *
686
     * @return string the cache tag name.
687
     */
688 186
    protected function getCacheTag(): string
689
    {
690 186
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
691
    }
692
}
693