Passed
Push — master ( 565bd9...e00335 )
by Def
19:37 queued 15:49
created

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

300
        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...
301 15
            $offset = 0;
302 15
            $createTableToken = $code[0][(int) $lastMatchIndex - 1];
303 15
            $sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()');
304
305
            while (
306 15
                $createTableToken instanceof SqlToken &&
307 15
                $createTableToken->matches($sqlTokenizerAnyCheck->tokenize(), (int) $offset, $firstMatchIndex, $offset)
308
            ) {
309 4
                $name = null;
310 4
                $checkSql = (string) $createTableToken[(int) $offset - 1];
311 4
                $pattern = (new SqlTokenizer('CONSTRAINT any'))->tokenize();
312
313
                if (
314 4
                    isset($createTableToken[(int) $firstMatchIndex - 2])
315 4
                    && $createTableToken->matches($pattern, (int) $firstMatchIndex - 2)
316
                ) {
317 1
                    $sqlToken = $createTableToken[(int) $firstMatchIndex - 1];
318 1
                    $name = $sqlToken?->getContent();
319
                }
320
321 4
                $result[] = (new CheckConstraint())->name($name)->expression($checkSql);
322
            }
323
        }
324
325 15
        return $result;
326
    }
327
328
    /**
329
     * Loads all default value constraints for the given table.
330
     *
331
     * @param string $tableName The table name.
332
     *
333
     * @throws NotSupportedException
334
     *
335
     * @return array Default value constraints for the given table.
336
     */
337 13
    protected function loadTableDefaultValues(string $tableName): array
338
    {
339 13
        throw new NotSupportedException('SQLite does not support default value constraints.');
340
    }
341
342
    /**
343
     * Collects the table column metadata.
344
     *
345
     * @param TableSchemaInterface $table The table metadata.
346
     *
347
     * @throws Exception
348
     * @throws InvalidConfigException
349
     * @throws Throwable
350
     *
351
     * @return bool Whether the table exists in the database.
352
     */
353 146
    protected function findColumns(TableSchemaInterface $table): bool
354
    {
355
        /** @psalm-var PragmaTableInfo $columns */
356 146
        $columns = $this->getPragmaTableInfo($table->getName());
357
358 146
        foreach ($columns as $info) {
359 103
            $column = $this->loadColumnSchema($info);
360 103
            $table->columns($column->getName(), $column);
361
362 103
            if ($column->isPrimaryKey()) {
363 70
                $table->primaryKey($column->getName());
364
            }
365
        }
366
367 146
        $column = count($table->getPrimaryKey()) === 1 ? $table->getColumn($table->getPrimaryKey()[0]) : null;
368
369 146
        if ($column !== null && !strncasecmp($column->getDbType(), 'int', 3)) {
370 69
            $table->sequenceName('');
371 69
            $column->autoIncrement(true);
372
        }
373
374 146
        return !empty($columns);
375
    }
376
377
    /**
378
     * Collects the foreign key column details for the given table.
379
     *
380
     * @param TableSchemaInterface $table The table metadata.
381
     *
382
     * @throws Exception
383
     * @throws InvalidConfigException
384
     * @throws Throwable
385
     */
386 103
    protected function findConstraints(TableSchemaInterface $table): void
387
    {
388
        /** @psalm-var PragmaForeignKeyList $foreignKeysList */
389 103
        $foreignKeysList = $this->getPragmaForeignKeyList($table->getName());
390
391 103
        foreach ($foreignKeysList as $foreignKey) {
392 5
            $id = (int) $foreignKey['id'];
393 5
            $fk = $table->getForeignKeys();
394
395 5
            if (!isset($fk[$id])) {
396 5
                $table->foreignKey($id, ([$foreignKey['table'], $foreignKey['from'] => $foreignKey['to']]));
397
            } else {
398
                /** composite FK */
399 5
                $table->compositeFK($id, $foreignKey['from'], $foreignKey['to']);
400
            }
401
        }
402
    }
403
404
    /**
405
     * Returns all unique indexes for the given table.
406
     *
407
     * Each array element is of the following structure:
408
     *
409
     * ```php
410
     * [
411
     *     'IndexName1' => ['col1' [, ...]],
412
     *     'IndexName2' => ['col2' [, ...]],
413
     * ]
414
     * ```
415
     *
416
     * @param TableSchemaInterface $table The table metadata.
417
     *
418
     * @throws Exception
419
     * @throws InvalidConfigException
420
     * @throws Throwable
421
     *
422
     * @return array All unique indexes for the given table.
423
     */
424 1
    public function findUniqueIndexes(TableSchemaInterface $table): array
425
    {
426
        /** @psalm-var PragmaIndexList $indexList */
427 1
        $indexList = $this->getPragmaIndexList($table->getName());
428 1
        $uniqueIndexes = [];
429
430 1
        foreach ($indexList as $index) {
431 1
            $indexName = $index['name'];
432
            /** @psalm-var PragmaIndexInfo $indexInfo */
433 1
            $indexInfo = $this->getPragmaIndexInfo($index['name']);
434
435 1
            if ($index['unique']) {
436 1
                $uniqueIndexes[$indexName] = [];
437 1
                foreach ($indexInfo as $row) {
438 1
                    $uniqueIndexes[$indexName][] = $row['name'];
439
                }
440
            }
441
        }
442
443 1
        return $uniqueIndexes;
444
    }
445
446
    /**
447
     * @throws NotSupportedException
448
     */
449 1
    public function getSchemaDefaultValues(string $schema = '', bool $refresh = false): array
450
    {
451 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
452
    }
453
454
    /**
455
     * Loads the column information into a {@see ColumnSchemaInterface} object.
456
     *
457
     * @param array $info The column information.
458
     *
459
     * @return ColumnSchemaInterface The column schema object.
460
     *
461
     * @psalm-param array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string} $info
462
     */
463 103
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
464
    {
465 103
        $column = $this->createColumnSchema();
466 103
        $column->name($info['name']);
467 103
        $column->allowNull(!$info['notnull']);
468 103
        $column->primaryKey($info['pk'] != '0');
469 103
        $column->dbType(strtolower($info['type']));
470 103
        $column->unsigned(str_contains($column->getDbType(), 'unsigned'));
471 103
        $column->type(self::TYPE_STRING);
472
473 103
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
474 103
            $type = strtolower($matches[1]);
475
476 103
            if (isset($this->typeMap[$type])) {
477 103
                $column->type($this->typeMap[$type]);
478
            }
479
480 103
            if (!empty($matches[2])) {
481 91
                $values = explode(',', $matches[2]);
482 91
                $column->precision((int) $values[0]);
483 91
                $column->size((int) $values[0]);
484
485 91
                if (isset($values[1])) {
486 30
                    $column->scale((int) $values[1]);
487
                }
488
489 91
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
490 24
                    $column->type(self::TYPE_BOOLEAN);
491 91
                } elseif ($type === 'bit') {
492 4
                    if ($column->getSize() > 32) {
493 4
                        $column->type(self::TYPE_BIGINT);
494 4
                    } elseif ($column->getSize() === 32) {
495 4
                        $column->type(self::TYPE_INTEGER);
496
                    }
497
                }
498
            }
499
        }
500
501 103
        $column->phpType($this->getColumnPhpType($column));
502
503 103
        if (!$column->isPrimaryKey()) {
504 101
            if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
505 98
                $column->defaultValue(null);
506 73
            } elseif ($column->getType() === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
507 23
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP'));
508
            } else {
509 73
                $value = trim($info['dflt_value'], "'\"");
510 73
                $column->defaultValue($column->phpTypecast($value));
511
            }
512
        }
513
514 103
        return $column;
515
    }
516
517
    /**
518
     * Returns table columns info.
519
     *
520
     * @param string $tableName The table name.
521
     *
522
     * @throws Exception
523
     * @throws InvalidConfigException
524
     * @throws Throwable
525
     *
526
     * @return array The table columns info.
527
     */
528 54
    private function loadTableColumnsInfo(string $tableName): array
529
    {
530 54
        $tableColumns = $this->getPragmaTableInfo($tableName);
531
        /** @psalm-var PragmaTableInfo $tableColumns */
532 54
        $tableColumns = $this->normalizeRowKeyCase($tableColumns, true);
533
534 54
        return ArrayHelper::index($tableColumns, 'cid');
535
    }
536
537
    /**
538
     * Loads multiple types of constraints and returns the specified ones.
539
     *
540
     * @param string $tableName The table name.
541
     * @param string $returnType Return type: (primaryKey, indexes, uniques).
542
     *
543
     * @throws Exception
544
     * @throws InvalidConfigException
545
     * @throws Throwable
546
     *
547
     * @psalm-return Constraint[]|IndexConstraint[]|Constraint|null
548
     */
549 78
    private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null
550
    {
551 78
        $indexList = $this->getPragmaIndexList($tableName);
552
        /** @psalm-var PragmaIndexList $indexes */
553 78
        $indexes = $this->normalizeRowKeyCase($indexList, true);
554 78
        $result = [
555 78
            self::PRIMARY_KEY => null,
556 78
            self::INDEXES => [],
557 78
            self::UNIQUES => [],
558 78
        ];
559
560 78
        foreach ($indexes as $index) {
561
            /** @psalm-var Column $columns */
562 59
            $columns = $this->getPragmaIndexInfo($index['name']);
563
564 59
            if ($index['origin'] === 'pk') {
565 24
                $result[self::PRIMARY_KEY] = (new Constraint())
566 24
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
567
            }
568
569 59
            if ($index['origin'] === 'u') {
570 54
                $result[self::UNIQUES][] = (new Constraint())
571 54
                    ->name($index['name'])
572 54
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
573
            }
574
575 59
            $result[self::INDEXES][] = (new IndexConstraint())
576 59
                ->primary($index['origin'] === 'pk')
577 59
                ->unique((bool) $index['unique'])
578 59
                ->name($index['name'])
579 59
                ->columnNames(ArrayHelper::getColumn($columns, 'name'));
580
        }
581
582 78
        if (!isset($result[self::PRIMARY_KEY])) {
583
            /**
584
             * Additional check for PK in case of INTEGER PRIMARY KEY with ROWID.
585
             *
586
             * @link https://www.sqlite.org/lang_createtable.html#primkeyconst
587
             *
588
             * @psalm-var PragmaTableInfo $tableColumns
589
             */
590 54
            $tableColumns = $this->loadTableColumnsInfo($tableName);
591
592 54
            foreach ($tableColumns as $tableColumn) {
593 54
                if ($tableColumn['pk'] > 0) {
594 34
                    $result[self::PRIMARY_KEY] = (new Constraint())->columnNames([$tableColumn['name']]);
595 34
                    break;
596
                }
597
            }
598
        }
599
600 78
        foreach ($result as $type => $data) {
601 78
            $this->setTableMetadata($tableName, $type, $data);
602
        }
603
604 78
        return $result[$returnType];
605
    }
606
607
    /**
608
     * Creates a column schema for the database.
609
     *
610
     * This method may be overridden by child classes to create a DBMS-specific column schema.
611
     */
612 103
    private function createColumnSchema(): ColumnSchemaInterface
613
    {
614 103
        return new ColumnSchema();
615
    }
616
617
    /**
618
     * @throws Exception
619
     * @throws InvalidConfigException
620
     * @throws Throwable
621
     */
622 112
    private function getPragmaForeignKeyList(string $tableName): array
623
    {
624 112
        return $this->db->createCommand(
625 112
            'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName(($tableName)) . ')'
626 112
        )->queryAll();
627
    }
628
629
    /**
630
     * @throws Exception
631
     * @throws InvalidConfigException
632
     * @throws Throwable
633
     */
634 60
    private function getPragmaIndexInfo(string $name): array
635
    {
636 60
        $column = $this->db
637 60
            ->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')')
638 60
            ->queryAll();
639
        /** @psalm-var Column $column */
640 60
        $column = $this->normalizeRowKeyCase($column, true);
641 60
        ArrayHelper::multisort($column, 'seqno');
642
643 60
        return $column;
644
    }
645
646
    /**
647
     * @throws Exception
648
     * @throws InvalidConfigException
649
     * @throws Throwable
650
     */
651 79
    private function getPragmaIndexList(string $tableName): array
652
    {
653 79
        return $this->db
654 79
            ->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')')
655 79
            ->queryAll();
656
    }
657
658
    /**
659
     * @throws Exception
660
     * @throws InvalidConfigException
661
     * @throws Throwable
662
     */
663 155
    private function getPragmaTableInfo(string $tableName): array
664
    {
665 155
        return $this->db->createCommand(
666 155
            'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
667 155
        )->queryAll();
668
    }
669
670
    /**
671
     * @throws Exception
672
     * @throws InvalidConfigException
673
     * @throws Throwable
674
     */
675 1
    protected function findViewNames(string $schema = ''): array
676
    {
677
        /** @psalm-var string[][] $views */
678 1
        $views = $this->db->createCommand(
679 1
            <<<SQL
680
            SELECT name as view FROM sqlite_master WHERE type = 'view' AND name NOT LIKE 'sqlite_%'
681 1
            SQL,
682 1
        )->queryAll();
683
684 1
        foreach ($views as $key => $view) {
685 1
            $views[$key] = $view['view'];
686
        }
687
688 1
        return $views;
689
    }
690
691
    /**
692
     * Returns the cache key for the specified table name.
693
     *
694
     * @param string $name the table name.
695
     *
696
     * @return array The cache key.
697
     */
698 212
    protected function getCacheKey(string $name): array
699
    {
700 212
        return array_merge([self::class], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
701
    }
702
703
    /**
704
     * Returns the cache tag name.
705
     *
706
     * This allows {@see refresh()} to invalidate all cached table schemas.
707
     *
708
     * @return string The cache tag name.
709
     */
710 213
    protected function getCacheTag(): string
711
    {
712 213
        return md5(serialize(array_merge([self::class], $this->db->getCacheKey())));
713
    }
714
}
715