Passed
Branch dev (914540)
by Wilmer
06:24
created

SchemaPDOSqlite::findConstraints()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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