Passed
Push — master ( 74eca0...e40c7e )
by Def
04:05
created

Schema::getRawTableName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use Throwable;
8
use Yiisoft\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
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
136 10
           ->createCommand(
137
               "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name"
138
           )
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 86
    protected function loadTableSchema(string $name): ?TableSchemaInterface
152
    {
153 86
        $table = new TableSchema();
154
155 86
        $table->name($name);
156 86
        $table->fullName($name);
157
158 86
        if ($this->findColumns($table)) {
159 82
            $this->findConstraints($table);
160
161 82
            return $table;
162
        }
163
164 12
        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 31
    protected function loadTablePrimaryKey(string $tableName): ?Constraint
177
    {
178 31
        $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY);
179
180 31
        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 5
    protected function loadTableForeignKeys(string $tableName): array
193
    {
194 5
        $result = [];
195
        /** @psalm-var PragmaForeignKeyList */
196 5
        $foreignKeysList = $this->getPragmaForeignKeyList($tableName);
197
        /** @psalm-var NormalizePragmaForeignKeyList */
198 5
        $foreignKeysList = $this->normalizeRowKeyCase($foreignKeysList, true);
199
        /** @psalm-var NormalizePragmaForeignKeyList */
200 5
        $foreignKeysList = ArrayHelper::index($foreignKeysList, null, 'table');
201 5
        ArraySorter::multisort($foreignKeysList, 'seq', SORT_ASC, SORT_NUMERIC);
202
203
        /** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */
204 5
        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 5
        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 11
    protected function loadTableIndexes(string $tableName): array
230
    {
231 11
        $tableIndexes = $this->loadTableConstraints($tableName, self::INDEXES);
232
233 11
        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 13
    protected function loadTableUniques(string $tableName): array
248
    {
249 13
        $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES);
250
251 13
        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 13
    protected function loadTableChecks(string $tableName): array
264
    {
265 13
        $sql = $this->db->createCommand(
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
266
            'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName',
267 13
            [':tableName' => $tableName],
268 13
        )->queryScalar();
269
270 13
        $sql = ($sql === false || $sql === null) ? '' : (string) $sql;
271
272
        /** @var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */
273 13
        $code = (new SqlTokenizer($sql))->tokenize();
274 13
        $pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize();
275 13
        $result = [];
276
277 13
        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 13
            $offset = 0;
279 13
            $createTableToken = $code[0][(int) $lastMatchIndex - 1];
280 13
            $sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()');
281
282
            while (
283 13
                $createTableToken instanceof SqlToken &&
284 13
                $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
                    $sqlToken = $createTableToken[(int) $firstMatchIndex - 1];
295
                    $name = $sqlToken?->getContent();
296
                }
297
298 4
                $result[] = (new CheckConstraint())->name($name)->expression($checkSql);
299
            }
300
        }
301
302 13
        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 12
    protected function loadTableDefaultValues(string $tableName): array
315
    {
316 12
        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 3
    public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder
332
    {
333 3
        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 86
    protected function findColumns(TableSchemaInterface $table): bool
346
    {
347
        /** @psalm-var PragmaTableInfo */
348 86
        $columns = $this->getPragmaTableInfo($table->getName());
349
350 86
        foreach ($columns as $info) {
351 82
            $column = $this->loadColumnSchema($info);
352 82
            $table->columns($column->getName(), $column);
353
354 82
            if ($column->isPrimaryKey()) {
355 57
                $table->primaryKey($column->getName());
356
            }
357
        }
358
359 86
        $column = count($table->getPrimaryKey()) === 1 ? $table->getColumn($table->getPrimaryKey()[0]) : null;
360
361 86
        if ($column !== null && !strncasecmp($column->getDbType(), 'int', 3)) {
362 57
            $table->sequenceName('');
363 57
            $column->autoIncrement(true);
364
        }
365
366 86
        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 82
    protected function findConstraints(TableSchemaInterface $table): void
377
    {
378
        /** @psalm-var PragmaForeignKeyList */
379 82
        $foreignKeysList = $this->getPragmaForeignKeyList($table->getName());
380
381 82
        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 */
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 */
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
     * Loads the column information into a {@see ColumnSchemaInterface} object.
436
     *
437
     * @param array $info column information.
438
     *
439
     * @return ColumnSchemaInterface the column schema object.
440
     *
441
     * @psalm-param array{cid:string, name:string, type:string, notnull:string, dflt_value:string|null, pk:string} $info
442
     */
443 82
    protected function loadColumnSchema(array $info): ColumnSchemaInterface
444
    {
445 82
        $column = $this->createColumnSchema();
446 82
        $column->name($info['name']);
447 82
        $column->allowNull(!$info['notnull']);
448 82
        $column->primaryKey($info['pk'] != '0');
449 82
        $column->dbType(strtolower($info['type']));
450 82
        $column->unsigned(str_contains($column->getDbType(), 'unsigned'));
451 82
        $column->type(self::TYPE_STRING);
452
453 82
        if (preg_match('/^(\w+)(?:\(([^)]+)\))?/', $column->getDbType(), $matches)) {
454 82
            $type = strtolower($matches[1]);
455
456 82
            if (isset($this->typeMap[$type])) {
457 82
                $column->type($this->typeMap[$type]);
458
            }
459
460 82
            if (!empty($matches[2])) {
461 77
                $values = explode(',', $matches[2]);
462 77
                $column->precision((int) $values[0]);
463 77
                $column->size((int) $values[0]);
464
465 77
                if (isset($values[1])) {
466 27
                    $column->scale((int) $values[1]);
467
                }
468
469 77
                if ($column->getSize() === 1 && ($type === 'tinyint' || $type === 'bit')) {
470 22
                    $column->type(self::TYPE_BOOLEAN);
471 77
                } elseif ($type === 'bit') {
472
                    if ($column->getSize() > 32) {
473
                        $column->type(self::TYPE_BIGINT);
474
                    } elseif ($column->getSize() === 32) {
475
                        $column->type(self::TYPE_INTEGER);
476
                    }
477
                }
478
            }
479
        }
480
481 82
        $column->phpType($this->getColumnPhpType($column));
482
483 82
        if (!$column->isPrimaryKey()) {
484 80
            if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
485 78
                $column->defaultValue(null);
486 64
            } elseif ($column->getType() === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
487 22
                $column->defaultValue(new Expression('CURRENT_TIMESTAMP'));
488
            } else {
489 64
                $value = trim($info['dflt_value'], "'\"");
490 64
                $column->defaultValue($column->phpTypecast($value));
491
            }
492
        }
493
494 82
        return $column;
495
    }
496
497
    /**
498
     * Returns table columns info.
499
     *
500
     * @param string $tableName table name.
501
     *
502
     * @throws Exception|InvalidConfigException|Throwable
503
     *
504
     * @return array
505
     */
506 31
    private function loadTableColumnsInfo(string $tableName): array
507
    {
508 31
        $tableColumns = $this->getPragmaTableInfo($tableName);
509
        /** @psalm-var PragmaTableInfo */
510 31
        $tableColumns = $this->normalizeRowKeyCase($tableColumns, true);
511
512 31
        return ArrayHelper::index($tableColumns, 'cid');
513
    }
514
515
    /**
516
     * Loads multiple types of constraints and returns the specified ones.
517
     *
518
     * @param string $tableName table name.
519
     * @param string $returnType return type: (primaryKey, indexes, uniques).
520
     *
521
     * @throws Exception|InvalidConfigException|Throwable
522
     *
523
     * @return array|Constraint|null
524
     *
525
     * @psalm-return (Constraint|IndexConstraint)[]|Constraint|null
526
     */
527 55
    private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null
528
    {
529 55
        $indexList = $this->getPragmaIndexList($tableName);
530
        /** @psalm-var PragmaIndexList $indexes */
531 55
        $indexes = $this->normalizeRowKeyCase($indexList, true);
532 55
        $result = [
533
            self::PRIMARY_KEY => null,
534 55
            self::INDEXES => [],
535 55
            self::UNIQUES => [],
536
        ];
537
538 55
        foreach ($indexes as $index) {
539
            /** @psalm-var Column $columns */
540 45
            $columns = $this->getPragmaIndexInfo($index['name']);
541
542 45
            if ($index['origin'] === 'pk') {
543 27
                $result[self::PRIMARY_KEY] = (new Constraint())
544 27
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
545
            }
546
547 45
            if ($index['origin'] === 'u') {
548 44
                $result[self::UNIQUES][] = (new Constraint())
549 44
                    ->name($index['name'])
550 44
                    ->columnNames(ArrayHelper::getColumn($columns, 'name'));
551
            }
552
553 45
            $result[self::INDEXES][] = (new IndexConstraint())
554 45
                ->primary($index['origin'] === 'pk')
555 45
                ->unique((bool) $index['unique'])
556 45
                ->name($index['name'])
557 45
                ->columnNames(ArrayHelper::getColumn($columns, 'name'));
558
        }
559
560 55
        if (!isset($result[self::PRIMARY_KEY])) {
561
            /**
562
             * Additional check for PK in case of INTEGER PRIMARY KEY with ROWID.
563
             *
564
             * {@See https://www.sqlite.org/lang_createtable.html#primkeyconst}
565
             *
566
             * @psalm-var PragmaTableInfo
567
             */
568 31
            $tableColumns = $this->loadTableColumnsInfo($tableName);
569
570 31
            foreach ($tableColumns as $tableColumn) {
571 31
                if ($tableColumn['pk'] > 0) {
572 21
                    $result[self::PRIMARY_KEY] = (new Constraint())->columnNames([$tableColumn['name']]);
573 21
                    break;
574
                }
575
            }
576
        }
577
578 55
        foreach ($result as $type => $data) {
579 55
            $this->setTableMetadata($tableName, $type, $data);
580
        }
581
582 55
        return $result[$returnType];
583
    }
584
585
    /**
586
     * Creates a column schema for the database.
587
     *
588
     * This method may be overridden by child classes to create a DBMS-specific column schema.
589
     *
590
     * @return ColumnSchemaInterface column schema instance.
591
     */
592 82
    private function createColumnSchema(): ColumnSchemaInterface
593
    {
594 82
        return new ColumnSchema();
595
    }
596
597
    /**
598
     * @throws Exception|InvalidConfigException|Throwable
599
     */
600 87
    private function getPragmaForeignKeyList(string $tableName): array
601
    {
602 87
        return $this->db->createCommand(
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
603 87
            'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName(($tableName)) . ')'
604 87
        )->queryAll();
605
    }
606
607
    /**
608
     * @throws Exception|InvalidConfigException|Throwable
609
     */
610 46
    private function getPragmaIndexInfo(string $name): array
611
    {
612 46
        $column = $this->db
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
613 46
            ->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')')
614 46
            ->queryAll();
615
        /** @psalm-var Column */
616 46
        $column = $this->normalizeRowKeyCase($column, true);
617 46
        ArraySorter::multisort($column, 'seqno', SORT_ASC, SORT_NUMERIC);
618
619 46
        return $column;
620
    }
621
622
    /**
623
     * @throws Exception|InvalidConfigException|Throwable
624
     */
625 56
    private function getPragmaIndexList(string $tableName): array
626
    {
627 56
        return $this->db
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
628 56
            ->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')')
629 56
            ->queryAll();
630
    }
631
632
    /**
633
     * @throws Exception|InvalidConfigException|Throwable
634
     */
635 98
    private function getPragmaTableInfo(string $tableName): array
636
    {
637 98
        return $this->db->createCommand(
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
638 98
            'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')'
639 98
        )->queryAll();
640
    }
641
642
    /**
643
     * Returns the cache key for the specified table name.
644
     *
645
     * @param string $name the table name.
646
     *
647
     * @return array the cache key.
648
     */
649 151
    protected function getCacheKey(string $name): array
650
    {
651 151
        return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
652
    }
653
654
    /**
655
     * Returns the cache tag name.
656
     *
657
     * This allows {@see refresh()} to invalidate all cached table schemas.
658
     *
659
     * @return string the cache tag name.
660
     */
661 151
    protected function getCacheTag(): string
662
    {
663 151
        return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey())));
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
664
    }
665
666
    /**
667
     * Changes row's array key case to lower.
668
     *
669
     * @param array $row row's array or an array of row's arrays.
670
     * @param bool $multiple whether multiple rows or a single row passed.
671
     *
672
     * @return array normalized row or rows.
673
     */
674 61
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
675
    {
676 61
        if ($multiple) {
677 61
            return array_map(static function (array $row) {
678 61
                return array_change_key_case($row, CASE_LOWER);
679
            }, $row);
680
        }
681
682
        return array_change_key_case($row, CASE_LOWER);
683
    }
684
685
    /**
686
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
687
     */
688 5
    public function supportsSavepoint(): bool
689
    {
690 5
        return $this->db->isSavepointEnabled();
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
691
    }
692
693
    /**
694
     * @inheritDoc
695
     */
696
    public function getLastInsertID(?string $sequenceName = null): string
697
    {
698
        return $this->db->getLastInsertID($sequenceName);
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist on Yiisoft\Db\Sqlite\Schema. Did you maybe forget to declare it?
Loading history...
699
    }
700
}
701