Passed
Push — dev ( 10ff16...64f028 )
by Def
22:03 queued 18:18
created

Schema::getPragmaIndexInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 10
ccs 7
cts 7
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\Arrays\ArrayHelper;
9
use Yiisoft\Arrays\ArraySorter;
10
use Yiisoft\Db\Cache\SchemaCache;
11
use Yiisoft\Db\Connection\ConnectionInterface;
12
use Yiisoft\Db\Constraint\CheckConstraint;
13
use Yiisoft\Db\Constraint\Constraint;
14
use Yiisoft\Db\Constraint\ForeignKeyConstraint;
15
use Yiisoft\Db\Constraint\IndexConstraint;
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidArgumentException;
18
use Yiisoft\Db\Exception\InvalidConfigException;
19
use Yiisoft\Db\Exception\NotSupportedException;
20
use Yiisoft\Db\Expression\Expression;
21
use Yiisoft\Db\Schema\ColumnSchema;
22
use Yiisoft\Db\Schema\Schema as AbstractSchema;
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 345
    public function __construct(private ConnectionInterface $db, SchemaCache $schemaCache)
122
    {
123 345
        parent::__construct($schemaCache);
124
    }
125
126
    /**
127
     * Returns all table names in the database.
128
     *
129
     * This method should be overridden by child classes in order to support this feature because the default
130
     * implementation simply throws an exception.
131
     *
132
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
133
     *
134
     * @throws Exception|InvalidConfigException|Throwable
135
     *
136
     * @return array all table names in the database. The names have NO schema name prefix.
137
     */
138 5
    protected function findTableNames(string $schema = ''): array
139
    {
140 5
        $tableNames = $this->db->createCommand(
141
            "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name"
142 5
        )->queryColumn();
143
144 5
        if (!$tableNames) {
145
            return [];
146
        }
147
148 5
        return $tableNames;
149
    }
150
151
    /**
152
     * Loads the metadata for the specified table.
153
     *
154
     * @param string $name table name.
155
     *
156
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
157
     *
158
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
159
     */
160 84
    protected function loadTableSchema(string $name): ?TableSchema
161
    {
162 84
        $table = new TableSchema();
163
164 84
        $table->name($name);
165 84
        $table->fullName($name);
166
167 84
        if ($this->findColumns($table)) {
168 80
            $this->findConstraints($table);
169
170 80
            return $table;
171
        }
172
173 12
        return null;
174
    }
175
176
    /**
177
     * Loads a primary key for the given table.
178
     *
179
     * @param string $tableName table name.
180
     *
181
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
182
     *
183
     * @return Constraint|null primary key for the given table, `null` if the table has no primary key.
184
     */
185 30
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
186
    {
187 30
        $tablePrimaryKey = $this->loadTableConstraints($tableName, 'primaryKey');
188
189 30
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
190
    }
191
192
    /**
193
     * Loads all foreign keys for the given table.
194
     *
195
     * @param string $tableName table name.
196
     *
197
     * @throws Exception|InvalidConfigException|Throwable
198
     *
199
     * @return ForeignKeyConstraint[] foreign keys for the given table.
200
     */
201 4
    protected function loadTableForeignKeys(string $tableName): array
202
    {
203 4
        $result = [];
204
        /** @psalm-var PragmaForeignKeyList */
205 4
        $foreignKeysList = $this->getPragmaForeignKeyList($tableName);
206
        /** @psalm-var NormalizePragmaForeignKeyList */
207 4
        $foreignKeysList = $this->normalizeRowKeyCase($foreignKeysList, true);
208
        /** @psalm-var NormalizePragmaForeignKeyList */
209 4
        $foreignKeysList = ArrayHelper::index($foreignKeysList, null, 'table');
210 4
        ArraySorter::multisort($foreignKeysList, 'seq', SORT_ASC, SORT_NUMERIC);
211
212
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
213 4
        foreach ($foreignKeysList as $table => $foreignKey) {
214 4
            $fk = (new ForeignKeyConstraint())
215 4
                ->columnNames(ArrayHelper::getColumn($foreignKey, 'from'))
216 4
                ->foreignTableName($table)
217 4
                ->foreignColumnNames(ArrayHelper::getColumn($foreignKey, 'to'))
218 4
                ->onDelete($foreignKey[0]['on_delete'] ?? null)
219 4
                ->onUpdate($foreignKey[0]['on_update'] ?? null);
220
221 4
            $result[] = $fk;
222
        }
223
224 4
        return $result;
225
    }
226
227
    /**
228
     * Loads all indexes for the given table.
229
     *
230
     * @param string $tableName table name.
231
     *
232
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
233
     *
234
     * @return array indexes for the given table.
235
     *
236
     * @psalm-return array|IndexConstraint[]
237
     */
238 10
    protected function loadTableIndexes(string $tableName): array
239
    {
240 10
        $tableIndexes = $this->loadTableConstraints($tableName, 'indexes');
241
242 10
        return is_array($tableIndexes) ? $tableIndexes : [];
243
    }
244
245
    /**
246
     * Loads all unique constraints for the given table.
247
     *
248
     * @param string $tableName table name.
249
     *
250
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
251
     *
252
     * @return array unique constraints for the given table.
253
     *
254
     * @psalm-return array|Constraint[]
255
     */
256 12
    protected function loadTableUniques(string $tableName): array
257
    {
258 12
        $tableUniques = $this->loadTableConstraints($tableName, 'uniques');
259
260 12
        return is_array($tableUniques) ? $tableUniques : [];
261
    }
262
263
    /**
264
     * Loads all check constraints for the given table.
265
     *
266
     * @param string $tableName table name.
267
     *
268
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
269
     *
270
     * @return CheckConstraint[] check constraints for the given table.
271
     */
272 12
    protected function loadTableChecks(string $tableName): array
273
    {
274 12
        $sql = $this->db->createCommand(
275
            'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName',
276 12
            [':tableName' => $tableName],
277 12
        )->queryScalar();
278
279 12
        $sql = ($sql === false || $sql === null) ? '' : (string) $sql;
280
281
        /** @var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */
282 12
        $code = (new SqlTokenizer($sql))->tokenize();
283 12
        $pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize();
284 12
        $result = [];
285
286 12
        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...
287 12
            $offset = 0;
288 12
            $createTableToken = $code[0][(int) $lastMatchIndex - 1];
289 12
            $sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()');
290
291
            while (
292 12
                $createTableToken instanceof SqlToken &&
293 12
                $createTableToken->matches($sqlTokenizerAnyCheck->tokenize(), (int) $offset, $firstMatchIndex, $offset)
294
            ) {
295 3
                $name = null;
296 3
                $checkSql = (string) $createTableToken[(int) $offset - 1];
297 3
                $pattern = (new SqlTokenizer('CONSTRAINT any'))->tokenize();
298
299
                if (
300 3
                    isset($createTableToken[(int) $firstMatchIndex - 2])
301 3
                    && $createTableToken->matches($pattern, (int) $firstMatchIndex - 2)
302
                ) {
303
                    $sqlToken = $createTableToken[(int) $firstMatchIndex - 1];
304
                    $name = $sqlToken?->getContent();
305
                }
306
307 3
                $result[] = (new CheckConstraint())->name($name)->expression($checkSql);
308
            }
309
        }
310
311 12
        return $result;
312
    }
313
314
    /**
315
     * Loads all default value constraints for the given table.
316
     *
317
     * @param string $tableName table name.
318
     *
319
     * @throws NotSupportedException
320
     *
321
     * @return array default value constraints for the given table.
322
     */
323 12
    protected function loadTableDefaultValues(string $tableName): array
324
    {
325 12
        throw new NotSupportedException('SQLite does not support default value constraints.');
326
    }
327
328
    /**
329
     * Create a column schema builder instance giving the type and value precision.
330
     *
331
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
332
     *
333
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
334
     * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
335
     *
336
     * @return ColumnSchemaBuilder column schema builder instance.
337
     *
338
     * @psalm-param array<array-key, string>|int|null|string $length
339
     */
340 3
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
341
    {
342 3
        return new ColumnSchemaBuilder($type, $length);
343
    }
344
345
    /**
346
     * Collects the table column metadata.
347
     *
348
     * @param TableSchema $table the table metadata.
349
     *
350
     * @throws Exception|InvalidConfigException|Throwable
351
     *
352
     * @return bool whether the table exists in the database.
353
     */
354 84
    protected function findColumns(TableSchema $table): bool
355
    {
356
        /** @psalm-var PragmaTableInfo */
357 84
        $columns = $this->getPragmaTableInfo($table->getName());
358
359 84
        foreach ($columns as $info) {
360 80
            $column = $this->loadColumnSchema($info);
361 80
            $table->columns($column->getName(), $column);
362
363 80
            if ($column->isPrimaryKey()) {
364 56
                $table->primaryKey($column->getName());
365
            }
366
        }
367
368 84
        $column = count($table->getPrimaryKey()) === 1 ? $table->getColumn($table->getPrimaryKey()[0]) : null;
369
370 84
        if ($column !== null && !strncasecmp($column->getDbType(), 'int', 3)) {
371 56
            $table->sequenceName('');
372 56
            $column->autoIncrement(true);
373
        }
374
375 84
        return !empty($columns);
376
    }
377
378
    /**
379
     * Collects the foreign key column details for the given table.
380
     *
381
     * @param TableSchema $table the table metadata.
382
     *
383
     * @throws Exception|InvalidConfigException|Throwable
384
     */
385 80
    protected function findConstraints(TableSchema $table): void
386
    {
387
        /** @psalm-var PragmaForeignKeyList */
388 80
        $foreignKeysList = $this->getPragmaForeignKeyList($table->getName());
389
390 80
        foreach ($foreignKeysList as $foreignKey) {
391 5
            $id = (int) $foreignKey['id'];
392 5
            $fk = $table->getForeignKeys();
393
394 5
            if (!isset($fk[$id])) {
395 5
                $table->foreignKey($id, ([$foreignKey['table'], $foreignKey['from'] => $foreignKey['to']]));
396
            } else {
397
                /** composite FK */
398 5
                $table->compositeFK($id, $foreignKey['from'], $foreignKey['to']);
399
            }
400
        }
401
    }
402
403
    /**
404
     * Returns all unique indexes for the given table.
405
     *
406
     * Each array element is of the following structure:
407
     *
408
     * ```php
409
     * [
410
     *     'IndexName1' => ['col1' [, ...]],
411
     *     'IndexName2' => ['col2' [, ...]],
412
     * ]
413
     * ```
414
     *
415
     * @param TableSchema $table the table metadata.
416
     *
417
     * @throws Exception|InvalidConfigException|Throwable
418
     *
419
     * @return array all unique indexes for the given table.
420
     */
421 1
    public function findUniqueIndexes(TableSchema $table): array
422
    {
423
        /** @psalm-var PragmaIndexList */
424 1
        $indexList = $this->getPragmaIndexList($table->getName());
425 1
        $uniqueIndexes = [];
426
427 1
        foreach ($indexList as $index) {
428 1
            $indexName = $index['name'];
429
            /** @psalm-var PragmaIndexInfo */
430 1
            $indexInfo = $this->getPragmaIndexInfo($index['name']);
431
432 1
            if ($index['unique']) {
433 1
                $uniqueIndexes[$indexName] = [];
434 1
                foreach ($indexInfo as $row) {
435 1
                    $uniqueIndexes[$indexName][] = $row['name'];
436
                }
437
            }
438
        }
439
440 1
        return $uniqueIndexes;
441
    }
442
443
    /**
444
     * Loads the column information into a {@see ColumnSchema} object.
445
     *
446
     * @param array $info column information.
447
     *
448
     * @return ColumnSchema the column schema object.
449
     *
450
     * @psalm-param array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string} $info
451
     */
452 80
    protected function loadColumnSchema(array $info): ColumnSchema
453
    {
454 80
        $column = $this->createColumnSchema();
455 80
        $column->name($info['name']);
456 80
        $column->allowNull(!$info['notnull']);
457 80
        $column->primaryKey($info['pk'] !== '0');
458 80
        $column->dbType(strtolower($info['type']));
459 80
        $column->unsigned(str_contains($column->getDbType(), 'unsigned'));
460 80
        $column->type(self::TYPE_STRING);
461
462 80
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
463 80
            $type = strtolower($matches[1]);
464
465 80
            if (isset($this->typeMap[$type])) {
466 80
                $column->type($this->typeMap[$type]);
467
            }
468
469 80
            if (!empty($matches[2])) {
470 76
                $values = explode(',', $matches[2]);
471 76
                $column->precision((int) $values[0]);
472 76
                $column->size((int) $values[0]);
473
474 76
                if (isset($values[1])) {
475 26
                    $column->scale((int) $values[1]);
476
                }
477
478 76
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
479 21
                    $column->type('boolean');
480 76
                } elseif ($type === 'bit') {
481
                    if ($column->getSize() > 32) {
482
                        $column->type('bigint');
483
                    } elseif ($column->getSize() === 32) {
484
                        $column->type('integer');
485
                    }
486
                }
487
            }
488
        }
489
490 80
        $column->phpType($this->getColumnPhpType($column));
491
492 80
        if (!$column->isPrimaryKey()) {
493 78
            if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
494 76
                $column->defaultValue(null);
495 62
            } elseif ($column->getType() === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
496 21
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP'));
497
            } else {
498 62
                $value = trim($info['dflt_value'], "'\"");
499 62
                $column->defaultValue($column->phpTypecast($value));
500
            }
501
        }
502
503 80
        return $column;
504
    }
505
506
    /**
507
     * Returns table columns info.
508
     *
509
     * @param string $tableName table name.
510
     *
511
     * @throws Exception|InvalidConfigException|Throwable
512
     *
513
     * @return array
514
     */
515 28
    private function loadTableColumnsInfo(string $tableName): array
516
    {
517 28
        $tableColumns = $this->getPragmaTableInfo($tableName);
518
        /** @psalm-var PragmaTableInfo */
519 28
        $tableColumns = $this->normalizeRowKeyCase($tableColumns, true);
520
521 28
        return ArrayHelper::index($tableColumns, 'cid');
522
    }
523
524
    /**
525
     * Loads multiple types of constraints and returns the specified ones.
526
     *
527
     * @param string $tableName table name.
528
     * @param string $returnType return type: (primaryKey, indexes, uniques).
529
     *
530
     * @throws Exception|InvalidConfigException|Throwable
531
     *
532
     * @return array|Constraint|null
533
     *
534
     * @psalm-return (Constraint|IndexConstraint)[]|Constraint|null
535
     */
536 52
    private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null
537
    {
538 52
        $indexList = $this->getPragmaIndexList($tableName);
539
        /** @psalm-var PragmaIndexList $indexes */
540 52
        $indexes = $this->normalizeRowKeyCase($indexList, true);
541 52
        $result = ['primaryKey' => null, 'indexes' => [], 'uniques' => []];
542
543 52
        foreach ($indexes as $index) {
544
            /** @psalm-var Column $columns */
545 42
            $columns = $this->getPragmaIndexInfo($index['name']);
546
547 42
            $result['indexes'][] = (new IndexConstraint())
548 42
                ->primary($index['origin'] === 'pk')
549 42
                ->unique((bool) $index['unique'])
550 42
                ->name($index['name'])
551 42
                ->columnNames(ArrayHelper::getColumn($columns, 'name'));
552
553 42
            if ($index['origin'] === 'u') {
554 41
                $result['uniques'][] = (new Constraint())
555 41
                    ->name($index['name'])
556 41
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
557
            }
558
559 42
            if ($index['origin'] === 'pk') {
560 24
                $result['primaryKey'] = (new Constraint())
561 24
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
562
            }
563
        }
564
565 52
        if (!isset($result['primaryKey'])) {
566
            /**
567
             * Additional check for PK in case of INTEGER PRIMARY KEY with ROWID.
568
             *
569
             * {@See https://www.sqlite.org/lang_createtable.html#primkeyconst}
570
             *
571
             * @psalm-var PragmaTableInfo
572
             */
573 28
            $tableColumns = $this->loadTableColumnsInfo($tableName);
574
575 28
            foreach ($tableColumns as $tableColumn) {
576 28
                if ($tableColumn['pk'] > 0) {
577 18
                    $result['primaryKey'] = (new Constraint())->columnNames([$tableColumn['name']]);
578 18
                    break;
579
                }
580
            }
581
        }
582
583 52
        foreach ($result as $type => $data) {
584 52
            $this->setTableMetadata($tableName, $type, $data);
585
        }
586
587 52
        return $result[$returnType];
588
    }
589
590
    /**
591
     * Creates a column schema for the database.
592
     *
593
     * This method may be overridden by child classes to create a DBMS-specific column schema.
594
     *
595
     * @return ColumnSchema column schema instance.
596
     */
597 80
    private function createColumnSchema(): ColumnSchema
598
    {
599 80
        return new ColumnSchema();
600
    }
601
602
    /**
603
     * @throws Exception|InvalidConfigException|Throwable
604
     */
605 84
    private function getPragmaForeignKeyList(string $tableName): array
606
    {
607 84
        return $this->db->createCommand(
608 84
            'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName(($tableName)) . ')'
609 84
        )->queryAll();
610
    }
611
612
    /**
613
     * @throws Exception|InvalidConfigException|Throwable
614
     */
615 43
    private function getPragmaIndexInfo(string $name): array
616
    {
617 43
        $column = $this->db
618 43
            ->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')')
619 43
            ->queryAll();
620
        /** @psalm-var Column */
621 43
        $column = $this->normalizeRowKeyCase($column, true);
622 43
        ArraySorter::multisort($column, 'seqno', SORT_ASC, SORT_NUMERIC);
623
624 43
        return $column;
625
    }
626
627
    /**
628
     * @throws Exception|InvalidConfigException|Throwable
629
     */
630 53
    private function getPragmaIndexList(string $tableName): array
631
    {
632 53
        return $this->db
633 53
            ->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')')
634 53
            ->queryAll();
635
    }
636
637
    /**
638
     * @throws Exception|InvalidConfigException|Throwable
639
     */
640 93
    private function getPragmaTableInfo(string $tableName): array
641
    {
642 93
        return $this->db->createCommand(
643 93
            'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
644 93
        )->queryAll();
645
    }
646
647
    /**
648
     * Returns the actual name of a given table name.
649
     *
650
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
651
     * {@see ConnectionInterface::tablePrefix}.
652
     *
653
     * @param string $name the table name to be converted.
654
     *
655
     * @return string the real name of the given table name.
656
     */
657 144
    public function getRawTableName(string $name): string
658
    {
659 144
        if (str_contains($name, '{{')) {
660 23
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
661
662 23
            return str_replace('%', $this->db->getTablePrefix(), $name);
663
        }
664
665 144
        return $name;
666
    }
667
668
    /**
669
     * Returns the cache key for the specified table name.
670
     *
671
     * @param string $name the table name.
672
     *
673
     * @return array the cache key.
674
     */
675 144
    protected function getCacheKey(string $name): array
676
    {
677 144
        return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
678
    }
679
680
    /**
681
     * Returns the cache tag name.
682
     *
683
     * This allows {@see refresh()} to invalidate all cached table schemas.
684
     *
685
     * @return string the cache tag name.
686
     */
687 144
    protected function getCacheTag(): string
688
    {
689 144
        return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey())));
690
    }
691
692
    /**
693
     * Changes row's array key case to lower.
694
     *
695
     * @param array $row row's array or an array of row's arrays.
696
     * @param bool $multiple whether multiple rows or a single row passed.
697
     *
698
     * @return array normalized row or rows.
699
     */
700 57
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
701
    {
702 57
        if ($multiple) {
703 57
            return array_map(static function (array $row) {
704 57
                return array_change_key_case($row, CASE_LOWER);
705
            }, $row);
706
        }
707
708
        return array_change_key_case($row, CASE_LOWER);
709
    }
710
711
    /**
712
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
713
     */
714 5
    public function supportsSavepoint(): bool
715
    {
716 5
        return $this->db->isSavepointEnabled();
717
    }
718
719
    /**
720
     * @inheritDoc
721
     */
722
    public function getLastInsertID(?string $sequenceName = null): string
723
    {
724
        return $this->db->getLastInsertID($sequenceName);
725
    }
726
}
727