Passed
Push — master ( 7be875...4e97ca )
by Alexander
02:16
created

Schema::getColumnPhpType()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 17
nc 10
nop 1
dl 0
loc 28
ccs 9
cts 9
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Schema;
6
7
use Yiisoft\Db\Connection\Connection;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\IntegrityException;
10
use Yiisoft\Db\Exception\InvalidCallException;
11
use Yiisoft\Db\Exception\NotSupportedException;
12
use Yiisoft\Db\Query\QueryBuilder;
13
use Yiisoft\Cache\CacheInterface;
14
use Yiisoft\Cache\Dependency\TagDependency;
15
16
/**
17
 * Schema is the base class for concrete DBMS-specific schema classes.
18
 *
19
 * Schema represents the database schema information that is DBMS specific.
20
 *
21
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence
22
 * object. This property is read-only.
23
 * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
24
 * @property string[] $schemaNames All schema names in the database, except system schemas. This property is read-only.
25
 * @property string $serverVersion Server version as a string. This property is read-only.
26
 * @property string[] $tableNames All table names in the database. This property is read-only.
27
 * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an instance
28
 * of {@see TableSchema} or its child class. This property is read-only.
29
 * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction. This can be
30
 * one of {@see Transaction::READ_UNCOMMITTED}, {@see Transaction::READ_COMMITTED},
31
 * {@see Transaction::REPEATABLE_READ} and {@see Transaction::SERIALIZABLE} but also a string containing DBMS specific
32
 * syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is write-only.
33
 */
34
abstract class Schema
35
{
36
    public const TYPE_PK = 'pk';
37
    public const TYPE_UPK = 'upk';
38
    public const TYPE_BIGPK = 'bigpk';
39
    public const TYPE_UBIGPK = 'ubigpk';
40
    public const TYPE_CHAR = 'char';
41
    public const TYPE_STRING = 'string';
42
    public const TYPE_TEXT = 'text';
43
    public const TYPE_TINYINT = 'tinyint';
44
    public const TYPE_SMALLINT = 'smallint';
45
    public const TYPE_INTEGER = 'integer';
46
    public const TYPE_BIGINT = 'bigint';
47
    public const TYPE_FLOAT = 'float';
48
    public const TYPE_DOUBLE = 'double';
49
    public const TYPE_DECIMAL = 'decimal';
50
    public const TYPE_DATETIME = 'datetime';
51
    public const TYPE_TIMESTAMP = 'timestamp';
52
    public const TYPE_TIME = 'time';
53
    public const TYPE_DATE = 'date';
54
    public const TYPE_BINARY = 'binary';
55
    public const TYPE_BOOLEAN = 'boolean';
56
    public const TYPE_MONEY = 'money';
57
    public const TYPE_JSON = 'json';
58
59
    /**
60
     * Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes.
61
     */
62
    protected const SCHEMA_CACHE_VERSION = 1;
63
64
    /**
65
     * @var string|null the default schema name used for the current session.
66
     */
67
    protected ?string $defaultSchema = null;
68
69
    /**
70
     * @var array map of DB errors and corresponding exceptions. If left part is found in DB error message exception
71
     * class from the right part is used.
72
     */
73
    protected array $exceptionMap = [
74
        'SQLSTATE[23' => IntegrityException::class,
75
    ];
76
77
    /**
78
     * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in
79
     * case starting and ending characters are different.
80
     */
81
    protected string $tableQuoteCharacter = "'";
82
83
    /**
84
     * @var string|string[] character used to quote column names. An array of 2 characters can be used in case starting
85
     * and ending characters are different.
86
     */
87
    protected string $columnQuoteCharacter = '"';
88
89
    private array $schemaNames = [];
90
    private array $tableNames = [];
91
    private array $tableMetadata = [];
92
    private ?QueryBuilder $builder = null;
93
    private ?string $serverVersion = null;
94
    private CacheInterface $cache;
95
    private ?Connection $db = null;
96
97 900
    public function __construct(Connection $db)
98
    {
99 900
        $this->db = $db;
100 900
        $this->cache = $this->db->getSchemaCache();
101 900
    }
102
103
    /**
104
     * Resolves the table name and schema name (if any).
105
     *
106
     * @param string $name the table name.
107
     *
108
     * @return void with resolved table, schema, etc. names.
109
     *
110
     * @throws NotSupportedException if this method is not supported by the DBMS.
111
     *
112
     * {@see \Yiisoft\Db\Schema\TableSchema}
113
     */
114
    protected function resolveTableName(string $name): TableSchema
115
    {
116
        throw new NotSupportedException(get_class($this) . ' does not support resolving table names.');
117
    }
118
119
    /**
120
     * Returns all schema names in the database, including the default one but not system schemas.
121
     *
122
     * This method should be overridden by child classes in order to support this feature because the default
123
     * implementation simply throws an exception.
124
     *
125
     * @return void all schema names in the database, except system schemas.
126
     *
127
     * @throws NotSupportedException if this method is not supported by the DBMS.
128
     */
129
    protected function findSchemaNames()
130
    {
131
        throw new NotSupportedException(get_class($this) . ' does not support fetching all schema names.');
132
    }
133
134
    /**
135
     * Returns all table names in the database.
136
     *
137
     * This method should be overridden by child classes in order to support this feature because the default
138
     * implementation simply throws an exception.
139
     *
140
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
141
     *
142
     * @return void all table names in the database. The names have NO schema name prefix.
143
     *
144
     * @throws NotSupportedException if this method is not supported by the DBMS.
145
     */
146
    protected function findTableNames(string $schema = ''): array
147
    {
148
        throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
149
    }
150
151
    /**
152
     * Loads the metadata for the specified table.
153
     *
154
     * @param string $name table name.
155
     *
156
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
157
     */
158
    abstract protected function loadTableSchema(string $name): ?TableSchema;
159
160
    /**
161
     * Creates a column schema for the database.
162
     *
163
     * This method may be overridden by child classes to create a DBMS-specific column schema.
164
     *
165
     * @return ColumnSchema column schema instance.
166
     */
167 75
    protected function createColumnSchema(): ColumnSchema
168
    {
169 75
        return new ColumnSchema();
170
    }
171
172
    /**
173
     * Obtains the metadata for the named table.
174
     *
175
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
176
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
177
     *
178
     * @return TableSchema|null table metadata. `null` if the named table does not exist.
179
     */
180 263
    public function getTableSchema(string $name, bool $refresh = false): ?TableSchema
181
    {
182 263
        return $this->getTableMetadata($name, 'schema', $refresh);
183
    }
184
185
    /**
186
     * Returns the metadata for all tables in the database.
187
     *
188
     * @param string $schema  the schema of the tables. Defaults to empty string, meaning the current or default schema
189
     * name.
190
     * @param bool $refresh whether to fetch the latest available table schemas. If this is `false`, cached data may be
191
     * returned if available.
192
     *
193
     * @return TableSchema[] the metadata for all tables in the database. Each array element is an instance of
194
     * {@see TableSchema} or its child class.
195
     */
196 9
    public function getTableSchemas(string $schema = '', bool $refresh = false): array
197
    {
198 9
        return $this->getSchemaMetadata($schema, 'schema', $refresh);
199
    }
200
201
    /**
202
     * Returns all schema names in the database, except system schemas.
203
     *
204
     * @param bool $refresh whether to fetch the latest available schema names. If this is false, schema names fetched
205
     * previously (if available) will be returned.
206
     *
207
     * @return string[] all schema names in the database, except system schemas.
208
     */
209 2
    public function getSchemaNames(bool $refresh = false): array
210
    {
211 2
        if (empty($this->schemaNames) || $refresh) {
212 2
            $this->schemaNames = $this->findSchemaNames();
213
        }
214
215 2
        return $this->schemaNames;
216
    }
217
218
    /**
219
     * Returns all table names in the database.
220
     *
221
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema
222
     * name.
223
     * If not empty, the returned table names will be prefixed with the schema name.
224
     * @param bool $refresh whether to fetch the latest available table names. If this is false, table names fetched
225
     * previously (if available) will be returned.
226
     *
227
     * @return string[] all table names in the database.
228
     */
229 15
    public function getTableNames(string $schema = '', bool $refresh = false): array
230
    {
231 15
        if (!isset($this->tableNames[$schema]) || $refresh) {
232 15
            $this->tableNames[$schema] = $this->findTableNames($schema);
233
        }
234
235 15
        return $this->tableNames[$schema];
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->tableNames[$schema] returns the type string which is incompatible with the type-hinted return array.
Loading history...
236
    }
237
238
    /**
239
     * @return QueryBuilder the query builder for this connection.
240
     */
241 179
    public function getQueryBuilder(): QueryBuilder
242
    {
243 179
        if ($this->builder === null) {
244 179
            $this->builder = $this->createQueryBuilder();
245
        }
246
247 179
        return $this->builder;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->builder could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Query\QueryBuilder. Consider adding an additional type-check to rule them out.
Loading history...
248
    }
249
250
    /**
251
     * Determines the PDO type for the given PHP data value.
252
     *
253
     * @param mixed $data the data whose PDO type is to be determined
254
     *
255
     * @return int the PDO type
256
     *
257
     * {@see http://www.php.net/manual/en/pdo.constants.php}
258
     */
259 308
    public function getPdoType($data): int
260
    {
261 308
        static $typeMap = [
262
            // php type => PDO type
263
            'boolean'  => \PDO::PARAM_BOOL,
264
            'integer'  => \PDO::PARAM_INT,
265
            'string'   => \PDO::PARAM_STR,
266
            'resource' => \PDO::PARAM_LOB,
267
            'NULL'     => \PDO::PARAM_NULL,
268
        ];
269 308
        $type = gettype($data);
270
271 308
        return $typeMap[$type] ?? \PDO::PARAM_STR;
272
    }
273
274
    /**
275
     * Refreshes the schema.
276
     *
277
     * This method cleans up all cached table schemas so that they can be re-created later to reflect the database
278
     * schema change.
279
     */
280
    public function refresh(): void
281
    {
282
        /* @var $cache CacheInterface */
283
        $cache = \is_string($this->db->getSchemaCache()) ? $this->cache : $this->db->getSchemaCache();
0 ignored issues
show
introduced by
The condition is_string($this->db->getSchemaCache()) is always false.
Loading history...
Bug introduced by
The method getSchemaCache() does not exist on null. ( Ignorable by Annotation )

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

283
        $cache = \is_string($this->db->/** @scrutinizer ignore-call */ getSchemaCache()) ? $this->cache : $this->db->getSchemaCache();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
284
285
        if ($this->db->isSchemaCacheEnabled() && $cache instanceof CacheInterface) {
286
            TagDependency::invalidate($cache, $this->getCacheTag());
287
        }
288
289
        $this->tableNames = [];
290
        $this->tableMetadata = [];
291
    }
292
293
    /**
294
     * Refreshes the particular table schema.
295
     *
296
     * This method cleans up cached table schema so that it can be re-created later to reflect the database schema
297
     * change.
298
     *
299
     * @param string $name table name.
300
     */
301 65
    public function refreshTableSchema(string $name): void
302
    {
303 65
        $rawName = $this->getRawTableName($name);
304
305 65
        unset($this->tableMetadata[$rawName]);
306
307 65
        $this->tableNames = [];
308
309 65
        if ($this->db->isSchemaCacheEnabled() && $this->cache instanceof CacheInterface) {
310 65
            $this->cache->delete($this->getCacheKey($rawName));
0 ignored issues
show
Bug introduced by
$this->getCacheKey($rawName) of type array<integer,null|string> is incompatible with the type string expected by parameter $key of Psr\SimpleCache\CacheInterface::delete(). ( Ignorable by Annotation )

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

310
            $this->cache->delete(/** @scrutinizer ignore-type */ $this->getCacheKey($rawName));
Loading history...
311
        }
312 65
    }
313
314
    /**
315
     * Creates a query builder for the database.
316
     *
317
     * This method may be overridden by child classes to create a DBMS-specific query builder.
318
     *
319
     * @return QueryBuilder query builder instance.
320
     */
321
    public function createQueryBuilder()
322
    {
323
        return new QueryBuilder($this->db);
0 ignored issues
show
Bug introduced by
It seems like $this->db can also be of type null; however, parameter $db of Yiisoft\Db\Query\QueryBuilder::__construct() does only seem to accept Yiisoft\Db\Connection\Connection, maybe add an additional type check? ( Ignorable by Annotation )

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

323
        return new QueryBuilder(/** @scrutinizer ignore-type */ $this->db);
Loading history...
324
    }
325
326
    /**
327
     * Create a column schema builder instance giving the type and value precision.
328
     *
329
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
330
     *
331
     * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}.
332
     * @param int|string|array $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}.
333
     *
334
     * @return ColumnSchemaBuilder column schema builder instance
335
     */
336 4
    public function createColumnSchemaBuilder(string $type, $length = null)
337
    {
338 4
        return new ColumnSchemaBuilder($type, $length);
339
    }
340
341
    /**
342
     * Returns all unique indexes for the given table.
343
     *
344
     * Each array element is of the following structure:
345
     *
346
     * ```php
347
     * [
348
     *  'IndexName1' => ['col1' [, ...]],
349
     *  'IndexName2' => ['col2' [, ...]],
350
     * ]
351
     * ```
352
     *
353
     * This method should be overridden by child classes in order to support this feature because the default
354
     * implementation simply throws an exception
355
     *
356
     * @param TableSchema $table the table metadata
357
     *
358
     * @throws NotSupportedException if this method is called
359
     *
360
     * @return array all unique indexes for the given table.
361
     */
362
    public function findUniqueIndexes($table): array
363
    {
364
        throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
365
    }
366
367
    /**
368
     * Returns the ID of the last inserted row or sequence value.
369
     *
370
     * @param string $sequenceName name of the sequence object (required by some DBMS)
371
     *
372
     * @throws InvalidCallException if the DB connection is not active
373
     *
374
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
375
     *
376
     * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
377
     */
378 3
    public function getLastInsertID(string $sequenceName = ''): string
379
    {
380 3
        if ($this->db->isActive()) {
381 3
            return $this->db->getPDO()->lastInsertId(
382 3
                $sequenceName === '' ? null : $this->quoteTableName($sequenceName)
383
            );
384
        }
385
386
        throw new InvalidCallException('DB Connection is not active.');
387
    }
388
389
    /**
390
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
391
     */
392 6
    public function supportsSavepoint(): bool
393
    {
394 6
        return $this->db->isSavepointEnabled();
395
    }
396
397
    /**
398
     * Creates a new savepoint.
399
     *
400
     * @param string $name the savepoint name
401
     */
402 3
    public function createSavepoint(string $name): void
403
    {
404 3
        $this->db->createCommand("SAVEPOINT $name")->execute();
405 3
    }
406
407
    /**
408
     * Releases an existing savepoint.
409
     *
410
     * @param string $name the savepoint name
411
     */
412
    public function releaseSavepoint(string $name): void
413
    {
414
        $this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
415
    }
416
417
    /**
418
     * Rolls back to a previously created savepoint.
419
     *
420
     * @param string $name the savepoint name
421
     */
422 3
    public function rollBackSavepoint(string $name): void
423
    {
424 3
        $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
425 3
    }
426
427
    /**
428
     * Sets the isolation level of the current transaction.
429
     *
430
     * @param string $level The transaction isolation level to use for this transaction.
431
     *
432
     * This can be one of {@see Transaction::READ_UNCOMMITTED}, {@see Transaction::READ_COMMITTED},
433
     * {@see Transaction::REPEATABLE_READ} and {@see Transaction::SERIALIZABLE} but also a string containing DBMS
434
     * specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
435
     *
436
     * {@see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels}
437
     */
438 6
    public function setTransactionIsolationLevel(string $level): void
439
    {
440 6
        $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
441 6
    }
442
443
    /**
444
     * Executes the INSERT command, returning primary key values.
445
     *
446
     * @param string $table the table that new rows will be inserted into.
447
     * @param array $columns the column data (name => value) to be inserted into the table.
448
     *
449
     * @return array|false primary key values or false if the command fails.
450
     */
451
    public function insert(string $table, array $columns)
452
    {
453
        $command = $this->db->createCommand()->insert($table, $columns);
454
455
        if (!$command->execute()) {
456
            return false;
457
        }
458
459
        $tableSchema = $this->getTableSchema($table);
460
        $result = [];
461
462
        foreach ($tableSchema->getPrimaryKey() as $name) {
463
            if ($tableSchema->getColumn($name)->isAutoIncrement()) {
464
                $result[$name] = $this->getLastInsertID($tableSchema->getSequenceName());
0 ignored issues
show
Bug introduced by
It seems like $tableSchema->getSequenceName() can also be of type null; however, parameter $sequenceName of Yiisoft\Db\Schema\Schema::getLastInsertID() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

464
                $result[$name] = $this->getLastInsertID(/** @scrutinizer ignore-type */ $tableSchema->getSequenceName());
Loading history...
465
                break;
466
            }
467
468
            $result[$name] = $columns[$name] ?? $tableSchema->getColumn($name)->getDefaultValue();
469
        }
470
471
        return $result;
472
    }
473
474
    /**
475
     * Quotes a string value for use in a query.
476
     *
477
     * Note that if the parameter is not a string, it will be returned without change.
478
     *
479
     * @param string|int $str string to be quoted.
480
     *
481
     * @return string|int the properly quoted string.
482
     *
483
     * {@see http://www.php.net/manual/en/function.PDO-quote.php}
484
     */
485 376
    public function quoteValue($str)
486
    {
487 376
        if (!is_string($str)) {
488 3
            return $str;
489
        }
490
491 376
        if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
492 376
            return $value;
493
        }
494
495
        /** the driver doesn't support quote (e.g. oci) */
496
        return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
497
    }
498
499
    /**
500
     * Quotes a table name for use in a query.
501
     *
502
     * If the table name contains schema prefix, the prefix will also be properly quoted. If the table name is already
503
     * quoted or contains '(' or '{{', then this method will do nothing.
504
     *
505
     * @param string $name table name.
506
     *
507
     * @return string the properly quoted table name.
508
     *
509
     * {@see quoteSimpleTableName()}
510
     */
511 446
    public function quoteTableName(string $name): string
512
    {
513 446
        if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
514 55
            return $name;
515
        }
516
517 430
        if (strpos($name, '.') === false) {
518 426
            return $this->quoteSimpleTableName($name);
519
        }
520
521 10
        $parts = explode('.', $name);
522
523 10
        foreach ($parts as $i => $part) {
524 10
            $parts[$i] = $this->quoteSimpleTableName($part);
525
        }
526
527 10
        return implode('.', $parts);
528
    }
529
530
    /**
531
     * Quotes a column name for use in a query.
532
     *
533
     * If the column name contains prefix, the prefix will also be properly quoted. If the column name is already quoted
534
     * or contains '(', '[[' or '{{', then this method will do nothing.
535
     *
536
     * @param string $name column name.
537
     *
538
     * @return string the properly quoted column name.
539
     *
540
     * {@see quoteSimpleColumnName()}
541
     */
542 562
    public function quoteColumnName(string $name): string
543
    {
544 562
        if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
545 39
            return $name;
546
        }
547
548 553
        if (($pos = strrpos($name, '.')) !== false) {
549 23
            $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
550 23
            $name = substr($name, $pos + 1);
551
        } else {
552 550
            $prefix = '';
553
        }
554
555 553
        if (strpos($name, '{{') !== false) {
556 3
            return $name;
557
        }
558
559 553
        return $prefix . $this->quoteSimpleColumnName($name);
560
    }
561
562
    /**
563
     * Quotes a simple table name for use in a query.
564
     *
565
     * A simple table name should contain the table name only without any schema prefix. If the table name is already
566
     * quoted, this method will do nothing.
567
     *
568
     * @param string $name table name.
569
     *
570
     * @return string the properly quoted table name.
571
     */
572 456
    public function quoteSimpleTableName(string $name): string
573
    {
574 456
        if (is_string($this->tableQuoteCharacter)) {
0 ignored issues
show
introduced by
The condition is_string($this->tableQuoteCharacter) is always true.
Loading history...
575 456
            $startingCharacter = $endingCharacter = $this->tableQuoteCharacter;
576
        } else {
577
            [$startingCharacter, $endingCharacter] = $this->tableQuoteCharacter;
578
        }
579
580 456
        return strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
581
    }
582
583
    /**
584
     * Quotes a simple column name for use in a query.
585
     *
586
     * A simple column name should contain the column name only without any prefix. If the column name is already quoted
587
     * or is the asterisk character '*', this method will do nothing.
588
     *
589
     * @param string $name column name.
590
     *
591
     * @return string the properly quoted column name.
592
     */
593 553
    public function quoteSimpleColumnName(string $name): string
594
    {
595 553
        if (is_string($this->tableQuoteCharacter)) {
0 ignored issues
show
introduced by
The condition is_string($this->tableQuoteCharacter) is always true.
Loading history...
596 553
            $startingCharacter = $endingCharacter = $this->columnQuoteCharacter;
597
        } else {
598
            [$startingCharacter, $endingCharacter] = $this->columnQuoteCharacter;
599
        }
600
601 553
        return $name === '*' || strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name
602 553
            . $endingCharacter;
603
    }
604
605
    /**
606
     * Unquotes a simple table name.
607
     *
608
     * A simple table name should contain the table name only without any schema prefix. If the table name is not
609
     * quoted, this method will do nothing.
610
     *
611
     * @param string $name table name.
612
     *
613
     * @return string unquoted table name.
614
     */
615 2
    public function unquoteSimpleTableName(string $name): string
616
    {
617 2
        if (\is_string($this->tableQuoteCharacter)) {
0 ignored issues
show
introduced by
The condition is_string($this->tableQuoteCharacter) is always true.
Loading history...
618 2
            $startingCharacter = $this->tableQuoteCharacter;
619
        } else {
620
            $startingCharacter = $this->tableQuoteCharacter[0];
621
        }
622
623 2
        return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
624
    }
625
626
    /**
627
     * Unquotes a simple column name.
628
     *
629
     * A simple column name should contain the column name only without any prefix. If the column name is not quoted or
630
     * is the asterisk character '*', this method will do nothing.
631
     *
632
     * @param string $name column name.
633
     *
634
     * @return string unquoted column name.
635
     */
636
    public function unquoteSimpleColumnName(string $name): string
637
    {
638
        if (\is_string($this->columnQuoteCharacter)) {
0 ignored issues
show
introduced by
The condition is_string($this->columnQuoteCharacter) is always true.
Loading history...
639
            $startingCharacter = $this->columnQuoteCharacter;
640
        } else {
641
            $startingCharacter = $this->columnQuoteCharacter[0];
642
        }
643
644
        return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
645
    }
646
647
    /**
648
     * Returns the actual name of a given table name.
649
     *
650
     * This method will strip off curly brackets from the given table name and replace the percentage character '%' with
651
     * {@see Connection::tablePrefix}.
652
     *
653
     * @param string $name the table name to be converted.
654
     *
655
     * @return string the real name of the given table name.
656
     */
657 443
    public function getRawTableName(string $name): string
658
    {
659 443
        if (strpos($name, '{{') !== false) {
660 69
            $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
661
662 69
            return str_replace('%', $this->db->getTablePrefix(), $name);
663
        }
664
665 443
        return $name;
666
    }
667
668
    /**
669
     * Extracts the PHP type from abstract DB type.
670
     *
671
     * @param ColumnSchema $column the column schema information.
672
     *
673
     * @return string PHP type name.
674
     */
675 246
    protected function getColumnPhpType(ColumnSchema $column): string
676
    {
677 246
        static $typeMap = [
678
            // abstract type => php type
679
            self::TYPE_TINYINT  => 'integer',
680
            self::TYPE_SMALLINT => 'integer',
681
            self::TYPE_INTEGER  => 'integer',
682
            self::TYPE_BIGINT   => 'integer',
683
            self::TYPE_BOOLEAN  => 'boolean',
684
            self::TYPE_FLOAT    => 'double',
685
            self::TYPE_DOUBLE   => 'double',
686
            self::TYPE_BINARY   => 'resource',
687
            self::TYPE_JSON     => 'array',
688
        ];
689
690 246
        if (isset($typeMap[$column->getType()])) {
691 238
            if ($column->getType() === 'bigint') {
692 36
                return PHP_INT_SIZE === 8 && !$column->isUnsigned() ? 'integer' : 'string';
693
            }
694
695 238
            if ($column->getType() === 'integer') {
696 238
                return PHP_INT_SIZE === 4 && $column->isUnsigned() ? 'string' : 'integer';
697
            }
698
699 150
            return $typeMap[$column->getType()];
700
        }
701
702 230
        return 'string';
703
    }
704
705
    /**
706
     * Converts a DB exception to a more concrete one if possible.
707
     *
708
     * @param \Exception $e
709
     * @param string $rawSql SQL that produced exception.
710
     *
711
     * @return Exception
712
     */
713 28
    public function convertException(\Exception $e, string $rawSql): Exception
714
    {
715 28
        if ($e instanceof Exception) {
716
            return $e;
717
        }
718
719
        $exceptionClass = Exception::class;
720
721 28
        foreach ($this->exceptionMap as $error => $class) {
722 28
            if (strpos($e->getMessage(), $error) !== false) {
723 7
                $exceptionClass = $class;
724
            }
725
        }
726
727 28
        $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
728 28
        $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
729
730 28
        return new $exceptionClass($message, $errorInfo, $e->getCode(), $e);
731
    }
732
733
    /**
734
     * Returns a value indicating whether a SQL statement is for read purpose.
735
     *
736
     * @param string $sql the SQL statement.
737
     *
738
     * @return bool whether a SQL statement is for read purpose.
739
     */
740 9
    public function isReadQuery($sql): bool
741
    {
742 9
        $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
743
744 9
        return preg_match($pattern, $sql) > 0;
745
    }
746
747
    /**
748
     * Returns a server version as a string comparable by {@see \version_compare()}.
749
     *
750
     * @return string server version as a string.
751
     */
752 116
    public function getServerVersion(): string
753
    {
754 116
        if ($this->serverVersion === null) {
755 116
            $this->serverVersion = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
756
        }
757
758 116
        return $this->serverVersion;
759
    }
760
761
    /**
762
     * Returns the cache key for the specified table name.
763
     *
764
     * @param string $name the table name.
765
     *
766
     * @return mixed the cache key.
767
     */
768 443
    protected function getCacheKey($name)
769
    {
770
        return [
771 443
            __CLASS__,
772 443
            $this->db->getDsn(),
773 443
            $this->db->getUsername(),
774 443
            $this->getRawTableName($name),
775
        ];
776
    }
777
778
    /**
779
     * Returns the cache tag name.
780
     *
781
     * This allows {@see refresh()} to invalidate all cached table schemas.
782
     *
783
     * @return string the cache tag name.
784
     */
785 395
    protected function getCacheTag(): string
786
    {
787 395
        return md5(serialize([
788 395
            __CLASS__,
789 395
            $this->db->getDsn(),
790 395
            $this->db->getUsername(),
791
        ]));
792
    }
793
794
    /**
795
     * Returns the metadata of the given type for the given table.
796
     *
797
     * If there's no metadata in the cache, this method will call a `'loadTable' . ucfirst($type)` named method with the
798
     * table name to obtain the metadata.
799
     *
800
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
801
     * @param string $type metadata type.
802
     * @param bool $refresh whether to reload the table metadata even if it is found in the cache.
803
     *
804
     * @return mixed metadata.
805
     */
806 443
    protected function getTableMetadata(string $name, string $type, bool $refresh)
807
    {
808 443
        if ($this->db->isSchemaCacheEnabled() && !\in_array($name, $this->db->getSchemaCacheExclude(), true)) {
809 443
            $schemaCache = $this->cache;
810
        }
811
812 443
        $rawName = $this->getRawTableName($name);
813
814 443
        if (!isset($this->tableMetadata[$rawName])) {
815 443
            $this->loadTableMetadataFromCache($schemaCache, $rawName);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $schemaCache does not seem to be defined for all execution paths leading up to this point.
Loading history...
816
        }
817
818 443
        if ($refresh || !\array_key_exists($type, $this->tableMetadata[$rawName])) {
819 443
            $this->tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
820 395
            $this->saveTableMetadataToCache($schemaCache, $rawName);
821
        }
822
823 395
        return $this->tableMetadata[$rawName][$type];
824
    }
825
826
    /**
827
     * Returns the metadata of the given type for all tables in the given schema.
828
     *
829
     * This method will call a `'getTable' . ucfirst($type)` named method with the table name and the refresh flag to
830
     * obtain the metadata.
831
     *
832
     * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema
833
     * name.
834
     * @param string $type metadata type.
835
     * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`, cached data may be
836
     * returned if available.
837
     *
838
     * @return array array of metadata.
839
     */
840 9
    protected function getSchemaMetadata(string $schema, string $type, bool $refresh): array
841
    {
842 9
        $metadata = [];
843 9
        $methodName = 'getTable' . ucfirst($type);
844
845 9
        foreach ($this->getTableNames($schema, $refresh) as $name) {
846 9
            if ($schema !== '') {
847
                $name = $schema . '.' . $name;
848
            }
849 9
            $tableMetadata = $this->$methodName($name, $refresh);
850 9
            if ($tableMetadata !== null) {
851 9
                $metadata[] = $tableMetadata;
852
            }
853
        }
854
855 9
        return $metadata;
856
    }
857
858
    /**
859
     * Sets the metadata of the given type for the given table.
860
     *
861
     * @param string $name table name.
862
     * @param string $type metadata type.
863
     * @param mixed  $data metadata.
864
     */
865 162
    protected function setTableMetadata(string $name, string $type, $data): void
866
    {
867 162
        $this->tableMetadata[$this->getRawTableName($name)][$type] = $data;
868 162
    }
869
870
    /**
871
     * Changes row's array key case to lower if PDO's one is set to uppercase.
872
     *
873
     * @param array $row row's array or an array of row's arrays.
874
     * @param bool $multiple whether multiple rows or a single row passed.
875
     *
876
     * @return array normalized row or rows.
877
     */
878 186
    protected function normalizePdoRowKeyCase(array $row, bool $multiple): array
879
    {
880 186
        if ($this->db->getSlavePdo()->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
881 146
            return $row;
882
        }
883
884 40
        if ($multiple) {
885 40
            return \array_map(function (array $row) {
886 39
                return \array_change_key_case($row, CASE_LOWER);
887 40
            }, $row);
888
        }
889
890
        return \array_change_key_case($row, CASE_LOWER);
891
    }
892
893
    /**
894
     * Tries to load and populate table metadata from cache.
895
     *
896
     * @param CacheInterface|null $cache
897
     * @param string $name
898
     */
899 443
    private function loadTableMetadataFromCache(?CacheInterface $cache, string $name): void
900
    {
901 443
        if ($cache === null) {
902
            $this->tableMetadata[$name] = [];
903
904
            return;
905
        }
906
907 443
        $metadata = $cache->get($this->getCacheKey($name));
0 ignored issues
show
Bug introduced by
$this->getCacheKey($name) of type array<integer,null|string> is incompatible with the type string expected by parameter $key of Psr\SimpleCache\CacheInterface::get(). ( Ignorable by Annotation )

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

907
        $metadata = $cache->get(/** @scrutinizer ignore-type */ $this->getCacheKey($name));
Loading history...
908
909 443
        if (!\is_array($metadata) || !isset($metadata['cacheVersion']) || $metadata['cacheVersion'] !== static::SCHEMA_CACHE_VERSION) {
910 443
            $this->tableMetadata[$name] = [];
911
912 443
            return;
913
        }
914
915
        unset($metadata['cacheVersion']);
916
        $this->tableMetadata[$name] = $metadata;
917
    }
918
919
    /**
920
     * Saves table metadata to cache.
921
     *
922
     * @param CacheInterface|null $cache
923
     * @param string $name
924
     */
925 395
    private function saveTableMetadataToCache(?CacheInterface $cache, string $name): void
926
    {
927 395
        if ($cache === null) {
928
            return;
929
        }
930
931 395
        $metadata = $this->tableMetadata[$name];
932
933 395
        $metadata['cacheVersion'] = static::SCHEMA_CACHE_VERSION;
934
935 395
        $cache->set(
936 395
            $this->getCacheKey($name),
937
            $metadata,
938 395
            $this->db->getSchemaCacheDuration(),
939 395
            new TagDependency(['tags' => $this->getCacheTag()])
940
        );
941 395
    }
942
943 445
    public function getDb(): ?Connection
944
    {
945 445
        return $this->db;
946
    }
947
948
    public function getDefaultSchema(): ?string
949
    {
950
        return $this->defaultSchema;
951
    }
952
}
953