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
|
350 |
|
public function __construct(private ConnectionInterface $db, SchemaCache $schemaCache) |
122
|
|
|
{ |
123
|
350 |
|
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
|
10 |
|
protected function findTableNames(string $schema = ''): array |
139
|
|
|
{ |
140
|
10 |
|
$tableNames = $this->db->createCommand( |
141
|
|
|
"SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name" |
142
|
10 |
|
)->queryColumn(); |
143
|
|
|
|
144
|
10 |
|
if (!$tableNames) { |
145
|
|
|
return []; |
146
|
|
|
} |
147
|
|
|
|
148
|
10 |
|
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
|
31 |
|
protected function loadTablePrimaryKey(string $tableName): ?Constraint |
186
|
|
|
{ |
187
|
31 |
|
$tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY); |
188
|
|
|
|
189
|
31 |
|
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
|
5 |
|
protected function loadTableForeignKeys(string $tableName): array |
202
|
|
|
{ |
203
|
5 |
|
$result = []; |
204
|
|
|
/** @psalm-var PragmaForeignKeyList */ |
205
|
5 |
|
$foreignKeysList = $this->getPragmaForeignKeyList($tableName); |
206
|
|
|
/** @psalm-var NormalizePragmaForeignKeyList */ |
207
|
5 |
|
$foreignKeysList = $this->normalizeRowKeyCase($foreignKeysList, true); |
208
|
|
|
/** @psalm-var NormalizePragmaForeignKeyList */ |
209
|
5 |
|
$foreignKeysList = ArrayHelper::index($foreignKeysList, null, 'table'); |
210
|
5 |
|
ArraySorter::multisort($foreignKeysList, 'seq', SORT_ASC, SORT_NUMERIC); |
211
|
|
|
|
212
|
|
|
/** @psalm-var NormalizePragmaForeignKeyList $foreignKeysList */ |
213
|
5 |
|
foreach ($foreignKeysList as $table => $foreignKey) { |
214
|
5 |
|
$fk = (new ForeignKeyConstraint()) |
215
|
5 |
|
->columnNames(ArrayHelper::getColumn($foreignKey, 'from')) |
216
|
5 |
|
->foreignTableName($table) |
217
|
5 |
|
->foreignColumnNames(ArrayHelper::getColumn($foreignKey, 'to')) |
218
|
5 |
|
->onDelete($foreignKey[0]['on_delete'] ?? null) |
219
|
5 |
|
->onUpdate($foreignKey[0]['on_update'] ?? null); |
220
|
|
|
|
221
|
5 |
|
$result[] = $fk; |
222
|
|
|
} |
223
|
|
|
|
224
|
5 |
|
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
|
11 |
|
protected function loadTableIndexes(string $tableName): array |
239
|
|
|
{ |
240
|
11 |
|
$tableIndexes = $this->loadTableConstraints($tableName, self::INDEXES); |
241
|
|
|
|
242
|
11 |
|
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
|
13 |
|
protected function loadTableUniques(string $tableName): array |
257
|
|
|
{ |
258
|
13 |
|
$tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES); |
259
|
|
|
|
260
|
13 |
|
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
|
13 |
|
protected function loadTableChecks(string $tableName): array |
273
|
|
|
{ |
274
|
13 |
|
$sql = $this->db->createCommand( |
275
|
|
|
'SELECT `sql` FROM `sqlite_master` WHERE name = :tableName', |
276
|
13 |
|
[':tableName' => $tableName], |
277
|
13 |
|
)->queryScalar(); |
278
|
|
|
|
279
|
13 |
|
$sql = ($sql === false || $sql === null) ? '' : (string) $sql; |
280
|
|
|
|
281
|
|
|
/** @var SqlToken[]|SqlToken[][]|SqlToken[][][] $code */ |
282
|
13 |
|
$code = (new SqlTokenizer($sql))->tokenize(); |
283
|
13 |
|
$pattern = (new SqlTokenizer('any CREATE any TABLE any()'))->tokenize(); |
284
|
13 |
|
$result = []; |
285
|
|
|
|
286
|
13 |
|
if ($code[0] instanceof SqlToken && $code[0]->matches($pattern, 0, $firstMatchIndex, $lastMatchIndex)) { |
|
|
|
|
287
|
13 |
|
$offset = 0; |
288
|
13 |
|
$createTableToken = $code[0][(int) $lastMatchIndex - 1]; |
289
|
13 |
|
$sqlTokenizerAnyCheck = new SqlTokenizer('any CHECK()'); |
290
|
|
|
|
291
|
|
|
while ( |
292
|
13 |
|
$createTableToken instanceof SqlToken && |
293
|
13 |
|
$createTableToken->matches($sqlTokenizerAnyCheck->tokenize(), (int) $offset, $firstMatchIndex, $offset) |
294
|
|
|
) { |
295
|
4 |
|
$name = null; |
296
|
4 |
|
$checkSql = (string) $createTableToken[(int) $offset - 1]; |
297
|
4 |
|
$pattern = (new SqlTokenizer('CONSTRAINT any'))->tokenize(); |
298
|
|
|
|
299
|
|
|
if ( |
300
|
4 |
|
isset($createTableToken[(int) $firstMatchIndex - 2]) |
301
|
4 |
|
&& $createTableToken->matches($pattern, (int) $firstMatchIndex - 2) |
302
|
|
|
) { |
303
|
|
|
$sqlToken = $createTableToken[(int) $firstMatchIndex - 1]; |
304
|
|
|
$name = $sqlToken?->getContent(); |
305
|
|
|
} |
306
|
|
|
|
307
|
4 |
|
$result[] = (new CheckConstraint())->name($name)->expression($checkSql); |
308
|
|
|
} |
309
|
|
|
} |
310
|
|
|
|
311
|
13 |
|
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(self::TYPE_BOOLEAN); |
480
|
76 |
|
} elseif ($type === 'bit') { |
481
|
|
|
if ($column->getSize() > 32) { |
482
|
|
|
$column->type(self::TYPE_BIGINT); |
483
|
|
|
} elseif ($column->getSize() === 32) { |
484
|
|
|
$column->type(self::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
|
31 |
|
private function loadTableColumnsInfo(string $tableName): array |
516
|
|
|
{ |
517
|
31 |
|
$tableColumns = $this->getPragmaTableInfo($tableName); |
518
|
|
|
/** @psalm-var PragmaTableInfo */ |
519
|
31 |
|
$tableColumns = $this->normalizeRowKeyCase($tableColumns, true); |
520
|
|
|
|
521
|
31 |
|
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
|
55 |
|
private function loadTableConstraints(string $tableName, string $returnType): Constraint|array|null |
537
|
|
|
{ |
538
|
55 |
|
$indexList = $this->getPragmaIndexList($tableName); |
539
|
|
|
/** @psalm-var PragmaIndexList $indexes */ |
540
|
55 |
|
$indexes = $this->normalizeRowKeyCase($indexList, true); |
541
|
55 |
|
$result = [ |
542
|
|
|
self::PRIMARY_KEY => null, |
543
|
55 |
|
self::INDEXES => [], |
544
|
55 |
|
self::UNIQUES => [], |
545
|
|
|
]; |
546
|
|
|
|
547
|
55 |
|
foreach ($indexes as $index) { |
548
|
|
|
/** @psalm-var Column $columns */ |
549
|
45 |
|
$columns = $this->getPragmaIndexInfo($index['name']); |
550
|
|
|
|
551
|
45 |
|
if ($index['origin'] === 'pk') { |
552
|
27 |
|
$result[self::PRIMARY_KEY] = (new Constraint()) |
553
|
27 |
|
->columnNames(ArrayHelper::getColumn($columns, 'name')); |
554
|
|
|
} |
555
|
|
|
|
556
|
45 |
|
if ($index['origin'] === 'u') { |
557
|
44 |
|
$result[self::UNIQUES][] = (new Constraint()) |
558
|
44 |
|
->name($index['name']) |
559
|
44 |
|
->columnNames(ArrayHelper::getColumn($columns, 'name')); |
560
|
|
|
} |
561
|
|
|
|
562
|
45 |
|
$result[self::INDEXES][] = (new IndexConstraint()) |
563
|
45 |
|
->primary($index['origin'] === 'pk') |
564
|
45 |
|
->unique((bool) $index['unique']) |
565
|
45 |
|
->name($index['name']) |
566
|
45 |
|
->columnNames(ArrayHelper::getColumn($columns, 'name')); |
567
|
|
|
} |
568
|
|
|
|
569
|
55 |
|
if (!isset($result[self::PRIMARY_KEY])) { |
570
|
|
|
/** |
571
|
|
|
* Additional check for PK in case of INTEGER PRIMARY KEY with ROWID. |
572
|
|
|
* |
573
|
|
|
* {@See https://www.sqlite.org/lang_createtable.html#primkeyconst} |
574
|
|
|
* |
575
|
|
|
* @psalm-var PragmaTableInfo |
576
|
|
|
*/ |
577
|
31 |
|
$tableColumns = $this->loadTableColumnsInfo($tableName); |
578
|
|
|
|
579
|
31 |
|
foreach ($tableColumns as $tableColumn) { |
580
|
31 |
|
if ($tableColumn['pk'] > 0) { |
581
|
21 |
|
$result[self::PRIMARY_KEY] = (new Constraint())->columnNames([$tableColumn['name']]); |
582
|
21 |
|
break; |
583
|
|
|
} |
584
|
|
|
} |
585
|
|
|
} |
586
|
|
|
|
587
|
55 |
|
foreach ($result as $type => $data) { |
588
|
55 |
|
$this->setTableMetadata($tableName, $type, $data); |
589
|
|
|
} |
590
|
|
|
|
591
|
55 |
|
return $result[$returnType]; |
592
|
|
|
} |
593
|
|
|
|
594
|
|
|
/** |
595
|
|
|
* Creates a column schema for the database. |
596
|
|
|
* |
597
|
|
|
* This method may be overridden by child classes to create a DBMS-specific column schema. |
598
|
|
|
* |
599
|
|
|
* @return ColumnSchema column schema instance. |
600
|
|
|
*/ |
601
|
80 |
|
private function createColumnSchema(): ColumnSchema |
602
|
|
|
{ |
603
|
80 |
|
return new ColumnSchema(); |
604
|
|
|
} |
605
|
|
|
|
606
|
|
|
/** |
607
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
608
|
|
|
*/ |
609
|
85 |
|
private function getPragmaForeignKeyList(string $tableName): array |
610
|
|
|
{ |
611
|
85 |
|
return $this->db->createCommand( |
612
|
85 |
|
'PRAGMA FOREIGN_KEY_LIST(' . $this->db->getQuoter()->quoteSimpleTableName(($tableName)) . ')' |
613
|
85 |
|
)->queryAll(); |
614
|
|
|
} |
615
|
|
|
|
616
|
|
|
/** |
617
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
618
|
|
|
*/ |
619
|
46 |
|
private function getPragmaIndexInfo(string $name): array |
620
|
|
|
{ |
621
|
46 |
|
$column = $this->db |
622
|
46 |
|
->createCommand('PRAGMA INDEX_INFO(' . (string) $this->db->getQuoter()->quoteValue($name) . ')') |
623
|
46 |
|
->queryAll(); |
624
|
|
|
/** @psalm-var Column */ |
625
|
46 |
|
$column = $this->normalizeRowKeyCase($column, true); |
626
|
46 |
|
ArraySorter::multisort($column, 'seqno', SORT_ASC, SORT_NUMERIC); |
627
|
|
|
|
628
|
46 |
|
return $column; |
629
|
|
|
} |
630
|
|
|
|
631
|
|
|
/** |
632
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
633
|
|
|
*/ |
634
|
56 |
|
private function getPragmaIndexList(string $tableName): array |
635
|
|
|
{ |
636
|
56 |
|
return $this->db |
637
|
56 |
|
->createCommand('PRAGMA INDEX_LIST(' . (string) $this->db->getQuoter()->quoteValue($tableName) . ')') |
638
|
56 |
|
->queryAll(); |
639
|
|
|
} |
640
|
|
|
|
641
|
|
|
/** |
642
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
643
|
|
|
*/ |
644
|
96 |
|
private function getPragmaTableInfo(string $tableName): array |
645
|
|
|
{ |
646
|
96 |
|
return $this->db->createCommand( |
647
|
96 |
|
'PRAGMA TABLE_INFO(' . $this->db->getQuoter()->quoteSimpleTableName($tableName) . ')' |
648
|
96 |
|
)->queryAll(); |
649
|
|
|
} |
650
|
|
|
|
651
|
|
|
/** |
652
|
|
|
* Returns the actual name of a given table name. |
653
|
|
|
* |
654
|
|
|
* This method will strip off curly brackets from the given table name and replace the percentage character '%' with |
655
|
|
|
* {@see ConnectionInterface::tablePrefix}. |
656
|
|
|
* |
657
|
|
|
* @param string $name the table name to be converted. |
658
|
|
|
* |
659
|
|
|
* @return string the real name of the given table name. |
660
|
|
|
*/ |
661
|
149 |
|
public function getRawTableName(string $name): string |
662
|
|
|
{ |
663
|
149 |
|
if (str_contains($name, '{{')) { |
664
|
23 |
|
$name = preg_replace('/{{(.*?)}}/', '\1', $name); |
665
|
|
|
|
666
|
23 |
|
return str_replace('%', $this->db->getTablePrefix(), $name); |
667
|
|
|
} |
668
|
|
|
|
669
|
149 |
|
return $name; |
670
|
|
|
} |
671
|
|
|
|
672
|
|
|
/** |
673
|
|
|
* Returns the cache key for the specified table name. |
674
|
|
|
* |
675
|
|
|
* @param string $name the table name. |
676
|
|
|
* |
677
|
|
|
* @return array the cache key. |
678
|
|
|
*/ |
679
|
149 |
|
protected function getCacheKey(string $name): array |
680
|
|
|
{ |
681
|
149 |
|
return array_merge([__CLASS__], $this->db->getCacheKey(), [$this->getRawTableName($name)]); |
682
|
|
|
} |
683
|
|
|
|
684
|
|
|
/** |
685
|
|
|
* Returns the cache tag name. |
686
|
|
|
* |
687
|
|
|
* This allows {@see refresh()} to invalidate all cached table schemas. |
688
|
|
|
* |
689
|
|
|
* @return string the cache tag name. |
690
|
|
|
*/ |
691
|
149 |
|
protected function getCacheTag(): string |
692
|
|
|
{ |
693
|
149 |
|
return md5(serialize(array_merge([__CLASS__], $this->db->getCacheKey()))); |
694
|
|
|
} |
695
|
|
|
|
696
|
|
|
/** |
697
|
|
|
* Changes row's array key case to lower. |
698
|
|
|
* |
699
|
|
|
* @param array $row row's array or an array of row's arrays. |
700
|
|
|
* @param bool $multiple whether multiple rows or a single row passed. |
701
|
|
|
* |
702
|
|
|
* @return array normalized row or rows. |
703
|
|
|
*/ |
704
|
61 |
|
protected function normalizeRowKeyCase(array $row, bool $multiple): array |
705
|
|
|
{ |
706
|
61 |
|
if ($multiple) { |
707
|
61 |
|
return array_map(static function (array $row) { |
708
|
61 |
|
return array_change_key_case($row, CASE_LOWER); |
709
|
|
|
}, $row); |
710
|
|
|
} |
711
|
|
|
|
712
|
|
|
return array_change_key_case($row, CASE_LOWER); |
713
|
|
|
} |
714
|
|
|
|
715
|
|
|
/** |
716
|
|
|
* @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint). |
717
|
|
|
*/ |
718
|
5 |
|
public function supportsSavepoint(): bool |
719
|
|
|
{ |
720
|
5 |
|
return $this->db->isSavepointEnabled(); |
721
|
|
|
} |
722
|
|
|
|
723
|
|
|
/** |
724
|
|
|
* @inheritDoc |
725
|
|
|
*/ |
726
|
|
|
public function getLastInsertID(?string $sequenceName = null): string |
727
|
|
|
{ |
728
|
|
|
return $this->db->getLastInsertID($sequenceName); |
729
|
|
|
} |
730
|
|
|
} |
731
|
|
|
|