-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathAbstractSchema.php
629 lines (557 loc) · 21.5 KB
/
AbstractSchema.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Schema;
use Psr\SimpleCache\InvalidArgumentException;
use Throwable;
use Yiisoft\Db\Cache\SchemaCache;
use Yiisoft\Db\Command\DataType;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Constraint\Constraint;
use Yiisoft\Db\Constraint\IndexConstraint;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Constant\GettypeResult;
use Yiisoft\Db\Schema\Column\BinaryColumnSchema;
use Yiisoft\Db\Schema\Column\BitColumnSchema;
use Yiisoft\Db\Schema\Column\BooleanColumnSchema;
use Yiisoft\Db\Schema\Column\ColumnSchemaInterface;
use Yiisoft\Db\Schema\Column\DoubleColumnSchema;
use Yiisoft\Db\Schema\Column\IntegerColumnSchema;
use Yiisoft\Db\Schema\Column\JsonColumnSchema;
use Yiisoft\Db\Schema\Column\StringColumnSchema;
use Yiisoft\Db\Schema\Column\BigIntColumnSchema;
use function gettype;
use function is_array;
/**
* Provides a set of methods for working with database schemas such as creating, modifying, and inspecting tables,
* columns, and other database objects.
*
* It's a powerful and flexible tool that allows you to perform a wide range of database operations in a
* database-agnostic way.
*/
abstract class AbstractSchema implements SchemaInterface
{
/**
* Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes.
*/
protected const SCHEMA_CACHE_VERSION = 1;
protected const CACHE_VERSION = 'cacheVersion';
/**
* @var string|null $defaultSchema The default schema name used for the current session.
*/
protected string|null $defaultSchema = null;
protected array $viewNames = [];
private array $schemaNames = [];
/** @psalm-var string[]|array */
private array $tableNames = [];
private array $tableMetadata = [];
public function __construct(protected ConnectionInterface $db, private SchemaCache $schemaCache)
{
}
/**
* @param string $name The table name.
*
* @return array The cache key for the specified table name.
*/
abstract protected function getCacheKey(string $name): array;
/**
* @return string The cache tag name.
*
* This allows {@see refresh()} to invalidate all cached table schemas.
*/
abstract protected function getCacheTag(): string;
/**
* Loads all check constraints for the given table.
*
* @param string $tableName The table name.
*
* @return array The check constraints for the given table.
*/
abstract protected function loadTableChecks(string $tableName): array;
/**
* Loads all default value constraints for the given table.
*
* @param string $tableName The table name.
*
* @return array The default value constraints for the given table.
*/
abstract protected function loadTableDefaultValues(string $tableName): array;
/**
* Loads all foreign keys for the given table.
*
* @param string $tableName The table name.
*
* @return array The foreign keys for the given table.
*/
abstract protected function loadTableForeignKeys(string $tableName): array;
/**
* Loads all indexes for the given table.
*
* @param string $tableName The table name.
*
* @return IndexConstraint[] The indexes for the given table.
*/
abstract protected function loadTableIndexes(string $tableName): array;
/**
* Loads a primary key for the given table.
*
* @param string $tableName The table name.
*
* @return Constraint|null The primary key for the given table. `null` if the table has no primary key.
*/
abstract protected function loadTablePrimaryKey(string $tableName): Constraint|null;
/**
* Loads all unique constraints for the given table.
*
* @param string $tableName The table name.
*
* @return array The unique constraints for the given table.
*/
abstract protected function loadTableUniques(string $tableName): array;
/**
* Loads the metadata for the specified table.
*
* @param string $name The table name.
*
* @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
*/
abstract protected function loadTableSchema(string $name): TableSchemaInterface|null;
public function getDefaultSchema(): string|null
{
return $this->defaultSchema;
}
public function getDataType(mixed $data): int
{
return match (gettype($data)) {
// php type => SQL data type
GettypeResult::BOOLEAN => DataType::BOOLEAN,
GettypeResult::INTEGER => DataType::INTEGER,
GettypeResult::RESOURCE => DataType::LOB,
GettypeResult::NULL => DataType::NULL,
default => DataType::STRING,
};
}
/**
* @throws InvalidArgumentException
* @throws NotSupportedException
*/
public function getSchemaChecks(string $schema = '', bool $refresh = false): array
{
return $this->getSchemaMetadata($schema, SchemaInterface::CHECKS, $refresh);
}
/**
* @throws InvalidArgumentException
* @throws NotSupportedException
*/
public function getSchemaDefaultValues(string $schema = '', bool $refresh = false): array
{
return $this->getSchemaMetadata($schema, SchemaInterface::DEFAULT_VALUES, $refresh);
}
/**
* @throws InvalidArgumentException
* @throws NotSupportedException
*/
public function getSchemaForeignKeys(string $schema = '', bool $refresh = false): array
{
return $this->getSchemaMetadata($schema, SchemaInterface::FOREIGN_KEYS, $refresh);
}
/**
* @throws InvalidArgumentException
* @throws NotSupportedException
*/
public function getSchemaIndexes(string $schema = '', bool $refresh = false): array
{
return $this->getSchemaMetadata($schema, SchemaInterface::INDEXES, $refresh);
}
/**
* @throws NotSupportedException If this method isn't supported by the underlying DBMS.
*/
public function getSchemaNames(bool $refresh = false): array
{
if (empty($this->schemaNames) || $refresh) {
$this->schemaNames = $this->findSchemaNames();
}
return $this->schemaNames;
}
/**
* @throws InvalidArgumentException
* @throws NotSupportedException
*/
public function getSchemaPrimaryKeys(string $schema = '', bool $refresh = false): array
{
/** @psalm-var list<Constraint> */
return $this->getSchemaMetadata($schema, SchemaInterface::PRIMARY_KEY, $refresh);
}
/**
* @throws NotSupportedException
* @throws InvalidArgumentException
*/
public function getSchemaUniques(string $schema = '', bool $refresh = false): array
{
return $this->getSchemaMetadata($schema, SchemaInterface::UNIQUES, $refresh);
}
/**
* @throws InvalidArgumentException
*/
public function getTableChecks(string $name, bool $refresh = false): array
{
/** @psalm-var mixed $tableChecks */
$tableChecks = $this->getTableMetadata($name, SchemaInterface::CHECKS, $refresh);
return is_array($tableChecks) ? $tableChecks : [];
}
/**
* @throws InvalidArgumentException
*/
public function getTableDefaultValues(string $name, bool $refresh = false): array
{
/** @psalm-var mixed $tableDefaultValues */
$tableDefaultValues = $this->getTableMetadata($name, SchemaInterface::DEFAULT_VALUES, $refresh);
return is_array($tableDefaultValues) ? $tableDefaultValues : [];
}
/**
* @throws InvalidArgumentException
*/
public function getTableForeignKeys(string $name, bool $refresh = false): array
{
/** @psalm-var mixed $tableForeignKeys */
$tableForeignKeys = $this->getTableMetadata($name, SchemaInterface::FOREIGN_KEYS, $refresh);
return is_array($tableForeignKeys) ? $tableForeignKeys : [];
}
/**
* @throws InvalidArgumentException
*/
public function getTableIndexes(string $name, bool $refresh = false): array
{
/** @var IndexConstraint[] */
return $this->getTableMetadata($name, SchemaInterface::INDEXES, $refresh);
}
/**
* @throws NotSupportedException If this method isn't supported by the underlying DBMS.
*/
public function getTableNames(string $schema = '', bool $refresh = false): array
{
if (!isset($this->tableNames[$schema]) || $refresh) {
$this->tableNames[$schema] = $this->findTableNames($schema);
}
return is_array($this->tableNames[$schema]) ? $this->tableNames[$schema] : [];
}
/**
* @throws InvalidArgumentException
*/
public function getTablePrimaryKey(string $name, bool $refresh = false): Constraint|null
{
/** @psalm-var mixed $tablePrimaryKey */
$tablePrimaryKey = $this->getTableMetadata($name, SchemaInterface::PRIMARY_KEY, $refresh);
return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
}
/**
* @throws InvalidArgumentException
*/
public function getTableSchema(string $name, bool $refresh = false): TableSchemaInterface|null
{
/** @psalm-var mixed $tableSchema */
$tableSchema = $this->getTableMetadata($name, SchemaInterface::SCHEMA, $refresh);
return $tableSchema instanceof TableSchemaInterface ? $tableSchema : null;
}
/**
* @throws NotSupportedException
* @throws InvalidArgumentException
*/
public function getTableSchemas(string $schema = '', bool $refresh = false): array
{
/** @psalm-var list<TableSchemaInterface> */
return $this->getSchemaMetadata($schema, SchemaInterface::SCHEMA, $refresh);
}
/**
* @throws InvalidArgumentException
*
* @return array The metadata for table unique constraints.
*/
public function getTableUniques(string $name, bool $refresh = false): array
{
/** @psalm-var mixed $tableUniques */
$tableUniques = $this->getTableMetadata($name, SchemaInterface::UNIQUES, $refresh);
return is_array($tableUniques) ? $tableUniques : [];
}
/**
* @throws InvalidArgumentException
*/
public function refresh(): void
{
if ($this->schemaCache->isEnabled()) {
$this->schemaCache->invalidate($this->getCacheTag());
}
$this->tableNames = [];
$this->tableMetadata = [];
}
/**
* @throws InvalidArgumentException
*/
public function refreshTableSchema(string $name): void
{
$rawName = $this->db->getQuoter()->getRawTableName($name);
unset($this->tableMetadata[$rawName]);
$this->tableNames = [];
if ($this->schemaCache->isEnabled()) {
$this->schemaCache->remove($this->getCacheKey($rawName));
}
}
public function enableCache(bool $value): void
{
$this->schemaCache->setEnabled($value);
}
/**
* Returns all schema names in the database, including the default one but not system schemas.
*
* This method should be overridden by child classes to support this feature because the default
* implementation simply throws an exception.
*
* @throws NotSupportedException If the DBMS doesn't support this method.
*
* @return array All schemas name in the database, except system schemas.
*/
protected function findSchemaNames(): array
{
throw new NotSupportedException(static::class . ' does not support fetching all schema names.');
}
/**
* Returns all table names in the database.
*
* This method should be overridden by child classes to support this feature because the default
* implementation simply throws an exception.
*
* @param string $schema The schema of the tables. Defaults to empty string, meaning the current or default schema.
*
* @throws NotSupportedException If the DBMS doesn't support this method.
*
* @return array All tables name in the database. The names have NO schema name prefix.
*/
protected function findTableNames(string $schema): array
{
throw new NotSupportedException(static::class . ' does not support fetching all table names.');
}
/**
* Creates a column schema for the database.
*
* This method may be overridden by child classes to create a DBMS-specific column schema.
*
* @param string $type The abstract data type.
* @param mixed ...$info The column information.
* @psalm-param array{unsigned?: bool} $info The set of parameters may be different for a specific DBMS.
*
* @return ColumnSchemaInterface
*/
protected function createColumnSchema(string $type, mixed ...$info): ColumnSchemaInterface
{
$isUnsigned = !empty($info['unsigned']);
$column = $this->createColumnSchemaFromType($type, $isUnsigned);
$column->unsigned($isUnsigned);
return $column;
}
protected function createColumnSchemaFromType(string $type, bool $isUnsigned = false): ColumnSchemaInterface
{
return match ($type) {
SchemaInterface::TYPE_BOOLEAN => new BooleanColumnSchema($type),
SchemaInterface::TYPE_BIT => new BitColumnSchema($type),
SchemaInterface::TYPE_TINYINT => new IntegerColumnSchema($type),
SchemaInterface::TYPE_SMALLINT => new IntegerColumnSchema($type),
SchemaInterface::TYPE_INTEGER => PHP_INT_SIZE !== 8 && $isUnsigned
? new BigIntColumnSchema($type)
: new IntegerColumnSchema($type),
SchemaInterface::TYPE_BIGINT => PHP_INT_SIZE !== 8 || $isUnsigned
? new BigIntColumnSchema($type)
: new IntegerColumnSchema($type),
SchemaInterface::TYPE_DECIMAL => new DoubleColumnSchema($type),
SchemaInterface::TYPE_FLOAT => new DoubleColumnSchema($type),
SchemaInterface::TYPE_DOUBLE => new DoubleColumnSchema($type),
SchemaInterface::TYPE_BINARY => new BinaryColumnSchema($type),
SchemaInterface::TYPE_JSON => new JsonColumnSchema($type),
default => new StringColumnSchema($type),
};
}
/**
* Returns the metadata of the given type for all tables in the given schema.
*
* @param string $schema The schema of the metadata. Defaults to empty string, meaning the current or default schema
* name.
* @param string $type The metadata type.
* @param bool $refresh Whether to fetch the latest available table metadata. If this is `false`, cached data may be
* returned if available.
*
* @throws InvalidArgumentException
* @throws NotSupportedException
*
* @return array The metadata of the given type for all tables in the given schema.
*
* @psalm-return list<Constraint|TableSchemaInterface|array>
*/
protected function getSchemaMetadata(string $schema, string $type, bool $refresh): array
{
$metadata = [];
/** @psalm-var string[] $tableNames */
$tableNames = $this->getTableNames($schema, $refresh);
foreach ($tableNames as $name) {
$name = $this->db->getQuoter()->quoteSimpleTableName($name);
if ($schema !== '') {
$name = $schema . '.' . $name;
}
$tableMetadata = $this->getTableTypeMetadata($type, $name, $refresh);
if ($tableMetadata !== null) {
$metadata[] = $tableMetadata;
}
}
return $metadata;
}
/**
* Returns the metadata of the given type for the given table.
*
* @param string $name The table name. The table name may contain a schema name if any.
* Don't quote the table name.
* @param string $type The metadata type.
* @param bool $refresh whether to reload the table metadata even if it's found in the cache.
*
* @throws InvalidArgumentException
*
* @return mixed The metadata of the given type for the given table.
*/
protected function getTableMetadata(string $name, string $type, bool $refresh = false): mixed
{
$rawName = $this->db->getQuoter()->getRawTableName($name);
if (!isset($this->tableMetadata[$rawName])) {
$this->loadTableMetadataFromCache($rawName);
}
if ($refresh || !isset($this->tableMetadata[$rawName][$type])) {
/** @psalm-suppress MixedArrayAssignment */
$this->tableMetadata[$rawName][$type] = $this->loadTableTypeMetadata($type, $rawName);
$this->saveTableMetadataToCache($rawName);
}
/** @psalm-suppress MixedArrayAccess */
return $this->tableMetadata[$rawName][$type];
}
/**
* This method returns the desired metadata type for the table name.
*/
protected function loadTableTypeMetadata(string $type, string $name): Constraint|array|TableSchemaInterface|null
{
return match ($type) {
SchemaInterface::SCHEMA => $this->loadTableSchema($name),
SchemaInterface::PRIMARY_KEY => $this->loadTablePrimaryKey($name),
SchemaInterface::UNIQUES => $this->loadTableUniques($name),
SchemaInterface::FOREIGN_KEYS => $this->loadTableForeignKeys($name),
SchemaInterface::INDEXES => $this->loadTableIndexes($name),
SchemaInterface::DEFAULT_VALUES => $this->loadTableDefaultValues($name),
SchemaInterface::CHECKS => $this->loadTableChecks($name),
default => null,
};
}
/**
* This method returns the desired metadata type for table name (with refresh if needed).
*
* @throws InvalidArgumentException
*/
protected function getTableTypeMetadata(
string $type,
string $name,
bool $refresh = false
): Constraint|array|null|TableSchemaInterface {
return match ($type) {
SchemaInterface::SCHEMA => $this->getTableSchema($name, $refresh),
SchemaInterface::PRIMARY_KEY => $this->getTablePrimaryKey($name, $refresh),
SchemaInterface::UNIQUES => $this->getTableUniques($name, $refresh),
SchemaInterface::FOREIGN_KEYS => $this->getTableForeignKeys($name, $refresh),
SchemaInterface::INDEXES => $this->getTableIndexes($name, $refresh),
SchemaInterface::DEFAULT_VALUES => $this->getTableDefaultValues($name, $refresh),
SchemaInterface::CHECKS => $this->getTableChecks($name, $refresh),
default => null,
};
}
/**
* Resolves the table name and schema name (if any).
*
* @param string $name The table name.
*
* @throws NotSupportedException If the DBMS doesn't support this method.
*
* @return TableSchemaInterface The with resolved table, schema, etc. names.
*
* @see TableSchemaInterface
*/
protected function resolveTableName(string $name): TableSchemaInterface
{
throw new NotSupportedException(static::class . ' does not support resolving table names.');
}
/**
* Sets the metadata of the given type for the given table.
*
* @param string $name The table name.
* @param string $type The metadata type.
* @param mixed $data The metadata to set.
*/
protected function setTableMetadata(string $name, string $type, mixed $data): void
{
/** @psalm-suppress MixedArrayAssignment */
$this->tableMetadata[$this->db->getQuoter()->getRawTableName($name)][$type] = $data;
}
/**
* Tries to load and populate table metadata from cache.
*
* @throws InvalidArgumentException
*/
private function loadTableMetadataFromCache(string $rawName): void
{
if (!$this->schemaCache->isEnabled() || $this->schemaCache->isExcluded($rawName)) {
$this->tableMetadata[$rawName] = [];
return;
}
$metadata = $this->schemaCache->get($this->getCacheKey($rawName));
if (
!is_array($metadata) ||
!isset($metadata[self::CACHE_VERSION]) ||
$metadata[self::CACHE_VERSION] !== static::SCHEMA_CACHE_VERSION
) {
$this->tableMetadata[$rawName] = [];
return;
}
unset($metadata[self::CACHE_VERSION]);
$this->tableMetadata[$rawName] = $metadata;
}
/**
* Saves table metadata to cache.
*
* @throws InvalidArgumentException
*/
private function saveTableMetadataToCache(string $rawName): void
{
if ($this->schemaCache->isEnabled() === false || $this->schemaCache->isExcluded($rawName) === true) {
return;
}
/** @psalm-var array<string, array<TableSchemaInterface|int>> $metadata */
$metadata = $this->tableMetadata[$rawName];
/** @psalm-var int */
$metadata[self::CACHE_VERSION] = static::SCHEMA_CACHE_VERSION;
$this->schemaCache->set($this->getCacheKey($rawName), $metadata, $this->getCacheTag());
}
/**
* Find the view names for the database.
*
* @param string $schema The schema of the views.
* Defaults to empty string, meaning the current or default schema.
*
* @return array The names of all views in the database.
*/
protected function findViewNames(string $schema = ''): array
{
return [];
}
/**
* @throws Throwable
*
* @return array The view names for the database.
*/
public function getViewNames(string $schema = '', bool $refresh = false): array
{
if (!isset($this->viewNames[$schema]) || $refresh) {
$this->viewNames[$schema] = $this->findViewNames($schema);
}
return (array) $this->viewNames[$schema];
}
}