Passed
Pull Request — master (#736)
by
unknown
11:37
created

AbstractSchema::getDateTimeFormat()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 1
nop 1
dl 0
loc 12
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Schema;
6
7
use Psr\SimpleCache\InvalidArgumentException;
8
use Throwable;
9
use Yiisoft\Db\Cache\SchemaCache;
10
use Yiisoft\Db\Command\DataType;
11
use Yiisoft\Db\Connection\ConnectionInterface;
12
use Yiisoft\Db\Constraint\Constraint;
13
use Yiisoft\Db\Exception\NotSupportedException;
14
15
use function array_change_key_case;
16
use function array_map;
17
use function gettype;
18
use function is_array;
19
use function preg_match;
20
use function preg_replace;
21
use function str_contains;
22
use function str_replace;
23
24
/**
25
 * Provides a set of methods for working with database schemas such as creating, modifying, and inspecting tables,
26
 * columns, and other database objects.
27
 *
28
 * It's a powerful and flexible tool that allows you to perform a wide range of database operations in a
29
 * database-agnostic way.
30
 */
31
abstract class AbstractSchema implements SchemaInterface
32
{
33
    /**
34
     * Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes.
35
     */
36
    protected const SCHEMA_CACHE_VERSION = 1;
37
    protected const CACHE_VERSION = 'cacheVersion';
38
    /**
39
     * @var string|null $defaultSchema The default schema name used for the current session.
40
     */
41
    protected string|null $defaultSchema = null;
42
    protected array $viewNames = [];
43
    private array $schemaNames = [];
44
    /** @psalm-var string[]|array */
45
    private array $tableNames = [];
46
    private array $tableMetadata = [];
47
48
    public function __construct(protected ConnectionInterface $db, private SchemaCache $schemaCache)
49
    {
50
    }
51
52
    /**
53
     * @param string $name The table name.
54
     *
55
     * @return array The cache key for the specified table name.
56
     */
57
    abstract protected function getCacheKey(string $name): array;
58
59
    /**
60
     * @return string The cache tag name.
61
     *
62
     * This allows {@see refresh()} to invalidate all cached table schemas.
63
     */
64
    abstract protected function getCacheTag(): string;
65
66
    /**
67
     * Loads all check constraints for the given table.
68
     *
69
     * @param string $tableName The table name.
70
     *
71
     * @return array The check constraints for the given table.
72
     */
73
    abstract protected function loadTableChecks(string $tableName): array;
74
75
    /**
76
     * Loads all default value constraints for the given table.
77
     *
78
     * @param string $tableName The table name.
79
     *
80
     * @return array The default value constraints for the given table.
81
     */
82
    abstract protected function loadTableDefaultValues(string $tableName): array;
83
84
    /**
85
     * Loads all foreign keys for the given table.
86
     *
87
     * @param string $tableName The table name.
88
     *
89
     * @return array The foreign keys for the given table.
90
     */
91
    abstract protected function loadTableForeignKeys(string $tableName): array;
92
93
    /**
94
     * Loads all indexes for the given table.
95
     *
96
     * @param string $tableName The table name.
97
     *
98
     * @return array The indexes for the given table.
99
     */
100
    abstract protected function loadTableIndexes(string $tableName): array;
101
102
    /**
103
     * Loads a primary key for the given table.
104
     *
105
     * @param string $tableName The table name.
106
     *
107
     * @return Constraint|null The primary key for the given table. `null` if the table has no primary key.
108
     */
109
    abstract protected function loadTablePrimaryKey(string $tableName): Constraint|null;
110
111
    /**
112
     * Loads all unique constraints for the given table.
113
     *
114
     * @param string $tableName The table name.
115
     *
116
     * @return array The unique constraints for the given table.
117
     */
118
    abstract protected function loadTableUniques(string $tableName): array;
119
120
    /**
121
     * Loads the metadata for the specified table.
122
     *
123
     * @param string $name The table name.
124
     *
125
     * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist.
126
     */
127
    abstract protected function loadTableSchema(string $name): TableSchemaInterface|null;
128
129
    public function getDefaultSchema(): string|null
130
    {
131
        return $this->defaultSchema;
132
    }
133
134
    public function getDataType(mixed $data): int
135
    {
136
        /** @psalm-var array<string, int> $typeMap */
137
        $typeMap = [
138
            // php type => SQL data type
139
            SchemaInterface::PHP_TYPE_BOOLEAN => DataType::BOOLEAN,
140
            SchemaInterface::PHP_TYPE_INTEGER => DataType::INTEGER,
141
            SchemaInterface::PHP_TYPE_STRING => DataType::STRING,
142
            SchemaInterface::PHP_TYPE_RESOURCE => DataType::LOB,
143
            SchemaInterface::PHP_TYPE_NULL => DataType::NULL,
144
        ];
145
146
        $type = gettype($data);
147
148
        return $typeMap[$type] ?? DataType::STRING;
149
    }
150
151
    public function getRawTableName(string $name): string
152
    {
153
        if (str_contains($name, '{{')) {
154
            $name = preg_replace('/{{(.*?)}}/', '\1', $name);
155
156
            return str_replace('%', $this->db->getTablePrefix(), $name);
157
        }
158
159
        return $name;
160
    }
161
162
    /**
163
     * @throws InvalidArgumentException
164
     * @throws NotSupportedException
165
     */
166
    public function getSchemaChecks(string $schema = '', bool $refresh = false): array
167
    {
168
        return $this->getSchemaMetadata($schema, SchemaInterface::CHECKS, $refresh);
169
    }
170
171
    /**
172
     * @throws InvalidArgumentException
173
     * @throws NotSupportedException
174
     */
175
    public function getSchemaDefaultValues(string $schema = '', bool $refresh = false): array
176
    {
177
        return $this->getSchemaMetadata($schema, SchemaInterface::DEFAULT_VALUES, $refresh);
178
    }
179
180
    /**
181
     * @throws InvalidArgumentException
182
     * @throws NotSupportedException
183
     */
184
    public function getSchemaForeignKeys(string $schema = '', bool $refresh = false): array
185
    {
186
        return $this->getSchemaMetadata($schema, SchemaInterface::FOREIGN_KEYS, $refresh);
187
    }
188
189
    /**
190
     * @throws InvalidArgumentException
191
     * @throws NotSupportedException
192
     */
193
    public function getSchemaIndexes(string $schema = '', bool $refresh = false): array
194
    {
195
        return $this->getSchemaMetadata($schema, SchemaInterface::INDEXES, $refresh);
196
    }
197
198
    /**
199
     * @throws NotSupportedException If this method isn't supported by the underlying DBMS.
200
     */
201
    public function getSchemaNames(bool $refresh = false): array
202
    {
203
        if (empty($this->schemaNames) || $refresh) {
204
            $this->schemaNames = $this->findSchemaNames();
205
        }
206
207
        return $this->schemaNames;
208
    }
209
210
    /**
211
     * @throws InvalidArgumentException
212
     * @throws NotSupportedException
213
     */
214
    public function getSchemaPrimaryKeys(string $schema = '', bool $refresh = false): array
215
    {
216
        /** @psalm-var list<Constraint> */
217
        return $this->getSchemaMetadata($schema, SchemaInterface::PRIMARY_KEY, $refresh);
218
    }
219
220
    /**
221
     * @throws NotSupportedException
222
     * @throws InvalidArgumentException
223
     */
224
    public function getSchemaUniques(string $schema = '', bool $refresh = false): array
225
    {
226
        return $this->getSchemaMetadata($schema, SchemaInterface::UNIQUES, $refresh);
227
    }
228
229
    /**
230
     * @throws InvalidArgumentException
231
     */
232
    public function getTableChecks(string $name, bool $refresh = false): array
233
    {
234
        /** @psalm-var mixed $tableChecks */
235
        $tableChecks = $this->getTableMetadata($name, SchemaInterface::CHECKS, $refresh);
236
        return is_array($tableChecks) ? $tableChecks : [];
237
    }
238
239
    /**
240
     * @throws InvalidArgumentException
241
     */
242
    public function getTableDefaultValues(string $name, bool $refresh = false): array
243
    {
244
        /** @psalm-var mixed $tableDefaultValues */
245
        $tableDefaultValues = $this->getTableMetadata($name, SchemaInterface::DEFAULT_VALUES, $refresh);
246
        return is_array($tableDefaultValues) ? $tableDefaultValues : [];
247
    }
248
249
    /**
250
     * @throws InvalidArgumentException
251
     */
252
    public function getTableForeignKeys(string $name, bool $refresh = false): array
253
    {
254
        /** @psalm-var mixed $tableForeignKeys */
255
        $tableForeignKeys = $this->getTableMetadata($name, SchemaInterface::FOREIGN_KEYS, $refresh);
256
        return is_array($tableForeignKeys) ? $tableForeignKeys : [];
257
    }
258
259
    /**
260
     * @throws InvalidArgumentException
261
     */
262
    public function getTableIndexes(string $name, bool $refresh = false): array
263
    {
264
        /** @psalm-var mixed $tableIndexes */
265
        $tableIndexes = $this->getTableMetadata($name, SchemaInterface::INDEXES, $refresh);
266
        return is_array($tableIndexes) ? $tableIndexes : [];
267
    }
268
269
    /**
270
     * @throws NotSupportedException If this method isn't supported by the underlying DBMS.
271
     */
272
    public function getTableNames(string $schema = '', bool $refresh = false): array
273
    {
274
        if (!isset($this->tableNames[$schema]) || $refresh) {
275
            $this->tableNames[$schema] = $this->findTableNames($schema);
276
        }
277
278
        return is_array($this->tableNames[$schema]) ? $this->tableNames[$schema] : [];
279
    }
280
281
    /**
282
     * @throws InvalidArgumentException
283
     */
284
    public function getTablePrimaryKey(string $name, bool $refresh = false): Constraint|null
285
    {
286
        /** @psalm-var mixed $tablePrimaryKey */
287
        $tablePrimaryKey = $this->getTableMetadata($name, SchemaInterface::PRIMARY_KEY, $refresh);
288
        return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null;
289
    }
290
291
    /**
292
     * @throws InvalidArgumentException
293
     */
294
    public function getTableSchema(string $name, bool $refresh = false): TableSchemaInterface|null
295
    {
296
        /** @psalm-var mixed $tableSchema */
297
        $tableSchema = $this->getTableMetadata($name, SchemaInterface::SCHEMA, $refresh);
298
        return $tableSchema instanceof TableSchemaInterface ? $tableSchema : null;
299
    }
300
301
    /**
302
     * @throws NotSupportedException
303
     * @throws InvalidArgumentException
304
     */
305
    public function getTableSchemas(string $schema = '', bool $refresh = false): array
306
    {
307
        /** @psalm-var list<TableSchemaInterface> */
308
        return $this->getSchemaMetadata($schema, SchemaInterface::SCHEMA, $refresh);
309
    }
310
311
    /**
312
     * @throws InvalidArgumentException
313
     *
314
     * @return array The metadata for table unique constraints.
315
     */
316
    public function getTableUniques(string $name, bool $refresh = false): array
317
    {
318
        /** @psalm-var mixed $tableUniques */
319
        $tableUniques = $this->getTableMetadata($name, SchemaInterface::UNIQUES, $refresh);
320
        return is_array($tableUniques) ? $tableUniques : [];
321
    }
322
323
    public function isReadQuery(string $sql): bool
324
    {
325
        $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
326
327
        return preg_match($pattern, $sql) > 0;
328
    }
329
330
    /**
331
     * @throws InvalidArgumentException
332
     */
333
    public function refresh(): void
334
    {
335
        if ($this->schemaCache->isEnabled()) {
336
            $this->schemaCache->invalidate($this->getCacheTag());
337
        }
338
339
        $this->tableNames = [];
340
        $this->tableMetadata = [];
341
    }
342
343
    /**
344
     * @throws InvalidArgumentException
345
     */
346
    public function refreshTableSchema(string $name): void
347
    {
348
        $rawName = $this->getRawTableName($name);
349
350
        unset($this->tableMetadata[$rawName]);
351
352
        $this->tableNames = [];
353
354
        if ($this->schemaCache->isEnabled()) {
355
            $this->schemaCache->remove($this->getCacheKey($rawName));
356
        }
357
    }
358
359
    public function enableCache(bool $value): void
360
    {
361
        $this->schemaCache->setEnabled($value);
362
    }
363
364
    /**
365
     * Returns all schema names in the database, including the default one but not system schemas.
366
     *
367
     * This method should be overridden by child classes to support this feature because the default
368
     * implementation simply throws an exception.
369
     *
370
     * @throws NotSupportedException If the DBMS doesn't support this method.
371
     *
372
     * @return array All schemas name in the database, except system schemas.
373
     */
374
    protected function findSchemaNames(): array
375
    {
376
        throw new NotSupportedException(static::class . ' does not support fetching all schema names.');
377
    }
378
379
    /**
380
     * Returns all table names in the database.
381
     *
382
     * This method should be overridden by child classes to support this feature because the default
383
     * implementation simply throws an exception.
384
     *
385
     * @param string $schema The schema of the tables. Defaults to empty string, meaning the current or default schema.
386
     *
387
     * @throws NotSupportedException If the DBMS doesn't support this method.
388
     *
389
     * @return array All tables name in the database. The names have NO schema name prefix.
390
     */
391
    protected function findTableNames(string $schema): array
0 ignored issues
show
Unused Code introduced by
The parameter $schema is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

391
    protected function findTableNames(/** @scrutinizer ignore-unused */ string $schema): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
392
    {
393
        throw new NotSupportedException(static::class . ' does not support fetching all table names.');
394
    }
395
396
    /**
397
     * Extracts the PHP type from an abstract DB type.
398
     *
399
     * @param ColumnSchemaInterface $column The column schema information.
400
     *
401
     * @return string The PHP type name.
402
     */
403
    protected function getColumnPhpType(ColumnSchemaInterface $column): string
404
    {
405
        return match ($column->getType()) {
406
            // abstract type => php type
407
            SchemaInterface::TYPE_TINYINT => SchemaInterface::PHP_TYPE_INTEGER,
408
            SchemaInterface::TYPE_SMALLINT => SchemaInterface::PHP_TYPE_INTEGER,
409
            SchemaInterface::TYPE_INTEGER => PHP_INT_SIZE === 4 && $column->isUnsigned()
410
                ? SchemaInterface::PHP_TYPE_STRING
411
                : SchemaInterface::PHP_TYPE_INTEGER,
412
            SchemaInterface::TYPE_BIGINT => PHP_INT_SIZE === 8 && !$column->isUnsigned()
413
                ? SchemaInterface::PHP_TYPE_INTEGER
414
                : SchemaInterface::PHP_TYPE_STRING,
415
            SchemaInterface::TYPE_BOOLEAN => SchemaInterface::PHP_TYPE_BOOLEAN,
416
            SchemaInterface::TYPE_DECIMAL => SchemaInterface::PHP_TYPE_DOUBLE,
417
            SchemaInterface::TYPE_FLOAT => SchemaInterface::PHP_TYPE_DOUBLE,
418
            SchemaInterface::TYPE_DOUBLE => SchemaInterface::PHP_TYPE_DOUBLE,
419
            SchemaInterface::TYPE_BINARY => SchemaInterface::PHP_TYPE_RESOURCE,
420
            SchemaInterface::TYPE_JSON => SchemaInterface::PHP_TYPE_ARRAY,
421
            SchemaInterface::TYPE_DATETIME => SchemaInterface::PHP_TYPE_DATE_TIME,
422
            SchemaInterface::TYPE_TIMESTAMP => SchemaInterface::PHP_TYPE_DATE_TIME,
423
            SchemaInterface::TYPE_DATE => SchemaInterface::PHP_TYPE_DATE_TIME,
424
            SchemaInterface::TYPE_TIME => SchemaInterface::PHP_TYPE_DATE_TIME,
425
426
            default => SchemaInterface::PHP_TYPE_STRING,
427
        };
428
    }
429
430
    /**
431
     * Returns the metadata of the given type for all tables in the given schema.
432
     *
433
     * @param string $schema The schema of the metadata. Defaults to empty string, meaning the current or default schema
434
     * name.
435
     * @param string $type The metadata type.
436
     * @param bool $refresh Whether to fetch the latest available table metadata. If this is `false`, cached data may be
437
     * returned if available.
438
     *
439
     * @throws InvalidArgumentException
440
     * @throws NotSupportedException
441
     *
442
     * @return array The metadata of the given type for all tables in the given schema.
443
     *
444
     * @psalm-return list<Constraint|TableSchemaInterface|array>
445
     */
446
    protected function getSchemaMetadata(string $schema, string $type, bool $refresh): array
447
    {
448
        $metadata = [];
449
        /** @psalm-var string[] $tableNames */
450
        $tableNames = $this->getTableNames($schema, $refresh);
451
452
        foreach ($tableNames as $name) {
453
            $name = $this->db->getQuoter()->quoteSimpleTableName($name);
454
455
            if ($schema !== '') {
456
                $name = $schema . '.' . $name;
457
            }
458
459
            $tableMetadata = $this->getTableTypeMetadata($type, $name, $refresh);
460
461
            if ($tableMetadata !== null) {
462
                $metadata[] = $tableMetadata;
463
            }
464
        }
465
466
        return $metadata;
467
    }
468
469
    /**
470
     * Returns the metadata of the given type for the given table.
471
     *
472
     * @param string $name The table name. The table name may contain a schema name if any.
473
     * Don't quote the table name.
474
     * @param string $type The metadata type.
475
     * @param bool $refresh whether to reload the table metadata even if it's found in the cache.
476
     *
477
     * @throws InvalidArgumentException
478
     *
479
     * @return mixed The metadata of the given type for the given table.
480
     */
481
    protected function getTableMetadata(string $name, string $type, bool $refresh = false): mixed
482
    {
483
        $rawName = $this->getRawTableName($name);
484
485
        if (!isset($this->tableMetadata[$rawName])) {
486
            $this->loadTableMetadataFromCache($rawName);
487
        }
488
489
        if ($refresh || !isset($this->tableMetadata[$rawName][$type])) {
490
            /** @psalm-suppress MixedArrayAssignment */
491
            $this->tableMetadata[$rawName][$type] = $this->loadTableTypeMetadata($type, $rawName);
492
            $this->saveTableMetadataToCache($rawName);
493
        }
494
495
        /** @psalm-suppress MixedArrayAccess */
496
        return $this->tableMetadata[$rawName][$type];
497
    }
498
499
    /**
500
     * This method returns the desired metadata type for the table name.
501
     */
502
    protected function loadTableTypeMetadata(string $type, string $name): Constraint|array|TableSchemaInterface|null
503
    {
504
        return match ($type) {
505
            SchemaInterface::SCHEMA => $this->loadTableSchema($name),
506
            SchemaInterface::PRIMARY_KEY => $this->loadTablePrimaryKey($name),
507
            SchemaInterface::UNIQUES => $this->loadTableUniques($name),
508
            SchemaInterface::FOREIGN_KEYS => $this->loadTableForeignKeys($name),
509
            SchemaInterface::INDEXES => $this->loadTableIndexes($name),
510
            SchemaInterface::DEFAULT_VALUES => $this->loadTableDefaultValues($name),
511
            SchemaInterface::CHECKS => $this->loadTableChecks($name),
512
            default => null,
513
        };
514
    }
515
516
    /**
517
     * This method returns the desired metadata type for table name (with refresh if needed).
518
     *
519
     * @throws InvalidArgumentException
520
     */
521
    protected function getTableTypeMetadata(
522
        string $type,
523
        string $name,
524
        bool $refresh = false
525
    ): Constraint|array|null|TableSchemaInterface {
526
        return match ($type) {
527
            SchemaInterface::SCHEMA => $this->getTableSchema($name, $refresh),
528
            SchemaInterface::PRIMARY_KEY => $this->getTablePrimaryKey($name, $refresh),
529
            SchemaInterface::UNIQUES => $this->getTableUniques($name, $refresh),
530
            SchemaInterface::FOREIGN_KEYS => $this->getTableForeignKeys($name, $refresh),
531
            SchemaInterface::INDEXES => $this->getTableIndexes($name, $refresh),
532
            SchemaInterface::DEFAULT_VALUES => $this->getTableDefaultValues($name, $refresh),
533
            SchemaInterface::CHECKS => $this->getTableChecks($name, $refresh),
534
            default => null,
535
        };
536
    }
537
538
    /**
539
     * Change row's array key case to lower.
540
     *
541
     * @param array $row Thew row's array or an array of row arrays.
542
     * @param bool $multiple Whether many rows or a single row passed.
543
     *
544
     * @return array The normalized row or rows.
545
     */
546
    protected function normalizeRowKeyCase(array $row, bool $multiple): array
547
    {
548
        if ($multiple) {
549
            return array_map(static fn (array $row) => array_change_key_case($row), $row);
550
        }
551
552
        return array_change_key_case($row);
553
    }
554
555
    /**
556
     * Resolves the table name and schema name (if any).
557
     *
558
     * @param string $name The table name.
559
     *
560
     * @throws NotSupportedException If the DBMS doesn't support this method.
561
     *
562
     * @return TableSchemaInterface The with resolved table, schema, etc. names.
563
     *
564
     * @see TableSchemaInterface
565
     */
566
    protected function resolveTableName(string $name): TableSchemaInterface
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

566
    protected function resolveTableName(/** @scrutinizer ignore-unused */ string $name): TableSchemaInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
567
    {
568
        throw new NotSupportedException(static::class . ' does not support resolving table names.');
569
    }
570
571
    /**
572
     * Sets the metadata of the given type for the given table.
573
     *
574
     * @param string $name The table name.
575
     * @param string $type The metadata type.
576
     * @param mixed $data The metadata to set.
577
     */
578
    protected function setTableMetadata(string $name, string $type, mixed $data): void
579
    {
580
        /** @psalm-suppress MixedArrayAssignment  */
581
        $this->tableMetadata[$this->getRawTableName($name)][$type] = $data;
582
    }
583
584
    /**
585
     * Tries to load and populate table metadata from cache.
586
     *
587
     * @throws InvalidArgumentException
588
     */
589
    private function loadTableMetadataFromCache(string $rawName): void
590
    {
591
        if (!$this->schemaCache->isEnabled() || $this->schemaCache->isExcluded($rawName)) {
592
            $this->tableMetadata[$rawName] = [];
593
            return;
594
        }
595
596
        $metadata = $this->schemaCache->get($this->getCacheKey($rawName));
597
598
        if (
599
            !is_array($metadata) ||
600
            !isset($metadata[self::CACHE_VERSION]) ||
601
            $metadata[self::CACHE_VERSION] !== static::SCHEMA_CACHE_VERSION
602
        ) {
603
            $this->tableMetadata[$rawName] = [];
604
            return;
605
        }
606
607
        unset($metadata[self::CACHE_VERSION]);
608
        $this->tableMetadata[$rawName] = $metadata;
609
    }
610
611
    /**
612
     * Saves table metadata to cache.
613
     *
614
     * @throws InvalidArgumentException
615
     */
616
    private function saveTableMetadataToCache(string $rawName): void
617
    {
618
        if ($this->schemaCache->isEnabled() === false || $this->schemaCache->isExcluded($rawName) === true) {
619
            return;
620
        }
621
622
        /** @psalm-var array<string, array<TableSchemaInterface|int>> $metadata */
623
        $metadata = $this->tableMetadata[$rawName];
624
        /** @psalm-var int */
625
        $metadata[self::CACHE_VERSION] = static::SCHEMA_CACHE_VERSION;
626
627
        $this->schemaCache->set($this->getCacheKey($rawName), $metadata, $this->getCacheTag());
628
    }
629
630
    /**
631
     * Find the view names for the database.
632
     *
633
     * @param string $schema The schema of the views.
634
     * Defaults to empty string, meaning the current or default schema.
635
     *
636
     * @return array The names of all views in the database.
637
     */
638
    protected function findViewNames(string $schema = ''): array
0 ignored issues
show
Unused Code introduced by
The parameter $schema is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

638
    protected function findViewNames(/** @scrutinizer ignore-unused */ string $schema = ''): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
639
    {
640
        return [];
641
    }
642
643
    /**
644
     * @throws Throwable
645
     *
646
     * @return array The view names for the database.
647
     */
648
    public function getViewNames(string $schema = '', bool $refresh = false): array
649
    {
650
        if (!isset($this->viewNames[$schema]) || $refresh) {
651
            $this->viewNames[$schema] = $this->findViewNames($schema);
652
        }
653
654
        return (array) $this->viewNames[$schema];
655
    }
656
657
    protected function getDateTimeFormat(ColumnSchemaInterface $column): string|null
658
    {
659
        return match ($column->getType()) {
660
            self::TYPE_TIMESTAMP,
661
            self::TYPE_DATETIME => 'Y-m-d H:i:s'
662
                . $this->getMillisecondsFormat($column)
663
                . ($column->hasTimezone() ? 'P' : ''),
664
            self::TYPE_DATE => 'Y-m-d',
665
            self::TYPE_TIME => 'H:i:s'
666
                . $this->getMillisecondsFormat($column)
667
                . ($column->hasTimezone() ? 'P' : ''),
668
            default => null,
669
        };
670
    }
671
672
    protected function getMillisecondsFormat(ColumnSchemaInterface $column): string
673
    {
674
        $precision = $column->getPrecision();
675
676
        return match (true) {
677
            $precision > 3 => '.u',
678
            $precision > 0 => '.v',
679
            default => '',
680
        };
681
    }
682
}
683