Completed
Push — master ( 5a01c0...0070b9 )
by Carsten
32:47 queued 29:21
created

Schema::quoteTableName()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 9
nc 4
nop 1
crap 5
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\InvalidCallException;
12
use yii\base\InvalidConfigException;
13
use yii\base\NotSupportedException;
14
use yii\base\Object;
15
use yii\caching\Cache;
16
use yii\caching\CacheInterface;
17
use yii\caching\TagDependency;
18
19
/**
20
 * Schema is the base class for concrete DBMS-specific schema classes.
21
 *
22
 * Schema represents the database schema information that is DBMS specific.
23
 *
24
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
25
 * sequence object. This property is read-only.
26
 * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
27
 * @property string[] $schemaNames All schema names in the database, except system schemas. This property is
28
 * read-only.
29
 * @property string[] $tableNames All table names in the database. This property is read-only.
30
 * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an
31
 * instance of [[TableSchema]] or its child class. This property is read-only.
32
 * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
33
 * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]],
34
 * [[Transaction::REPEATABLE_READ]] and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific
35
 * syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is write-only.
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @author Sergey Makinen <[email protected]>
39
 * @since 2.0
40
 */
41
abstract class Schema extends Object
42
{
43
    // The following are the supported abstract column data types.
44
    const TYPE_PK = 'pk';
45
    const TYPE_UPK = 'upk';
46
    const TYPE_BIGPK = 'bigpk';
47
    const TYPE_UBIGPK = 'ubigpk';
48
    const TYPE_CHAR = 'char';
49
    const TYPE_STRING = 'string';
50
    const TYPE_TEXT = 'text';
51
    const TYPE_SMALLINT = 'smallint';
52
    const TYPE_INTEGER = 'integer';
53
    const TYPE_BIGINT = 'bigint';
54
    const TYPE_FLOAT = 'float';
55
    const TYPE_DOUBLE = 'double';
56
    const TYPE_DECIMAL = 'decimal';
57
    const TYPE_DATETIME = 'datetime';
58
    const TYPE_TIMESTAMP = 'timestamp';
59
    const TYPE_TIME = 'time';
60
    const TYPE_DATE = 'date';
61
    const TYPE_BINARY = 'binary';
62
    const TYPE_BOOLEAN = 'boolean';
63
    const TYPE_MONEY = 'money';
64
65
    /**
66
     * Schema cache version, to detect incompatibilities in cached values when the
67
     * data format of the cache changes.
68
     */
69
    const SCHEMA_CACHE_VERSION = 1;
70
71
    /**
72
     * @var Connection the database connection
73
     */
74
    public $db;
75
    /**
76
     * @var string the default schema name used for the current session.
77
     */
78
    public $defaultSchema;
79
    /**
80
     * @var array map of DB errors and corresponding exceptions
81
     * If left part is found in DB error message exception class from the right part is used.
82
     */
83
    public $exceptionMap = [
84
        'SQLSTATE[23' => 'yii\db\IntegrityException',
85
    ];
86
    /**
87
     * @var string column schema class
88
     * @since 2.0.11
89
     */
90
    public $columnSchemaClass = 'yii\db\ColumnSchema';
91
92
    /**
93
     * @var array list of ALL schema names in the database, except system schemas
94
     */
95
    private $_schemaNames;
96
    /**
97
     * @var array list of ALL table names in the database
98
     */
99
    private $_tableNames = [];
100
    /**
101
     * @var array list of loaded table metadata (table name => metadata type => metadata).
102
     */
103
    private $_tableMetadata = [];
104
    /**
105
     * @var QueryBuilder the query builder for this database
106
     */
107
    private $_builder;
108
109
110
    /**
111
     * Resolves the table name and schema name (if any).
112
     * @param string $name the table name
113
     * @return TableSchema [[TableSchema]] with resolved table, schema, etc. names.
114
     * @throws NotSupportedException if this method is not supported by the DBMS.
115
     * @since 2.0.13
116
     */
117
    protected function resolveTableName($name)
118
    {
119
        throw new NotSupportedException(get_class($this) . ' does not support resolving table names.');
120
    }
121
122
    /**
123
     * Returns all schema names in the database, including the default one but not system schemas.
124
     * This method should be overridden by child classes in order to support this feature
125
     * because the default implementation simply throws an exception.
126
     * @return array all schema names in the database, except system schemas.
127
     * @throws NotSupportedException if this method is not supported by the DBMS.
128
     * @since 2.0.4
129
     */
130
    protected function findSchemaNames()
131
    {
132
        throw new NotSupportedException(get_class($this) . ' does not support fetching all schema names.');
133
    }
134
135
    /**
136
     * Returns all table names in the database.
137
     * This method should be overridden by child classes in order to support this feature
138
     * because the default implementation simply throws an exception.
139
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
140
     * @return array all table names in the database. The names have NO schema name prefix.
141
     * @throws NotSupportedException if this method is not supported by the DBMS.
142
     */
143
    protected function findTableNames($schema = '')
144
    {
145
        throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
146
    }
147
148
    /**
149
     * Loads the metadata for the specified table.
150
     * @param string $name table name
151
     * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
152
     */
153
    abstract protected function loadTableSchema($name);
154
155
    /**
156
     * Creates a column schema for the database.
157
     * This method may be overridden by child classes to create a DBMS-specific column schema.
158
     * @return ColumnSchema column schema instance.
159
     * @throws InvalidConfigException if a column schema class cannot be created.
160
     */
161 629
    protected function createColumnSchema()
162
    {
163 629
        return Yii::createObject($this->columnSchemaClass);
164
    }
165
166
    /**
167
     * Obtains the metadata for the named table.
168
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
169
     * @param bool $refresh whether to reload the table schema even if it is found in the cache.
170
     * @return TableSchema|null table metadata. `null` if the named table does not exist.
171
     */
172 671
    public function getTableSchema($name, $refresh = false)
173
    {
174 671
        return $this->getTableMetadata($name, 'schema', $refresh);
175
    }
176
177
    /**
178
     * Returns the metadata for all tables in the database.
179
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
180
     * @param bool $refresh whether to fetch the latest available table schemas. If this is `false`,
181
     * cached data may be returned if available.
182
     * @return TableSchema[] the metadata for all tables in the database.
183
     * Each array element is an instance of [[TableSchema]] or its child class.
184
     */
185 10
    public function getTableSchemas($schema = '', $refresh = false)
186
    {
187 10
        return $this->getSchemaMetadata($schema, 'schema', $refresh);
188
    }
189
190
    /**
191
     * Returns all schema names in the database, except system schemas.
192
     * @param bool $refresh whether to fetch the latest available schema names. If this is false,
193
     * schema names fetched previously (if available) will be returned.
194
     * @return string[] all schema names in the database, except system schemas.
195
     * @since 2.0.4
196
     */
197 1
    public function getSchemaNames($refresh = false)
198
    {
199 1
        if ($this->_schemaNames === null || $refresh) {
200 1
            $this->_schemaNames = $this->findSchemaNames();
201
        }
202
203 1
        return $this->_schemaNames;
204
    }
205
206
    /**
207
     * Returns all table names in the database.
208
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
209
     * If not empty, the returned table names will be prefixed with the schema name.
210
     * @param bool $refresh whether to fetch the latest available table names. If this is false,
211
     * table names fetched previously (if available) will be returned.
212
     * @return string[] all table names in the database.
213
     */
214 16
    public function getTableNames($schema = '', $refresh = false)
215
    {
216 16
        if (!isset($this->_tableNames[$schema]) || $refresh) {
217 16
            $this->_tableNames[$schema] = $this->findTableNames($schema);
218
        }
219
220 16
        return $this->_tableNames[$schema];
221
    }
222
223
    /**
224
     * @return QueryBuilder the query builder for this connection.
225
     */
226 710
    public function getQueryBuilder()
227
    {
228 710
        if ($this->_builder === null) {
229 679
            $this->_builder = $this->createQueryBuilder();
230
        }
231
232 710
        return $this->_builder;
233
    }
234
235
    /**
236
     * Determines the PDO type for the given PHP data value.
237
     * @param mixed $data the data whose PDO type is to be determined
238
     * @return int the PDO type
239
     * @see http://www.php.net/manual/en/pdo.constants.php
240
     */
241 749
    public function getPdoType($data)
242
    {
243 749
        static $typeMap = [
244
            // php type => PDO type
245
            'boolean' => \PDO::PARAM_BOOL,
246
            'integer' => \PDO::PARAM_INT,
247
            'string' => \PDO::PARAM_STR,
248
            'resource' => \PDO::PARAM_LOB,
249
            'NULL' => \PDO::PARAM_NULL,
250
        ];
251 749
        $type = gettype($data);
252
253 749
        return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
254
    }
255
256
    /**
257
     * Refreshes the schema.
258
     * This method cleans up all cached table schemas so that they can be re-created later
259
     * to reflect the database schema change.
260
     */
261 22
    public function refresh()
262
    {
263
        /* @var $cache CacheInterface */
264 22
        $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
265 22
        if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
266 1
            TagDependency::invalidate($cache, $this->getCacheTag());
267
        }
268 22
        $this->_tableNames = [];
269 22
        $this->_tableMetadata = [];
270 22
    }
271
272
    /**
273
     * Refreshes the particular table schema.
274
     * This method cleans up cached table schema so that it can be re-created later
275
     * to reflect the database schema change.
276
     * @param string $name table name.
277
     * @since 2.0.6
278
     */
279 109
    public function refreshTableSchema($name)
280
    {
281 109
        unset($this->_tableMetadata[$name]);
282 109
        $this->_tableNames = [];
283
        /* @var $cache CacheInterface */
284 109
        $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
285 109
        if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
286 4
            $cache->delete($this->getCacheKey($name));
287
        }
288 109
    }
289
290
    /**
291
     * Creates a query builder for the database.
292
     * This method may be overridden by child classes to create a DBMS-specific query builder.
293
     * @return QueryBuilder query builder instance
294
     */
295
    public function createQueryBuilder()
296
    {
297
        return new QueryBuilder($this->db);
298
    }
299
300
    /**
301
     * Create a column schema builder instance giving the type and value precision.
302
     *
303
     * This method may be overridden by child classes to create a DBMS-specific column schema builder.
304
     *
305
     * @param string $type type of the column. See [[ColumnSchemaBuilder::$type]].
306
     * @param int|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]].
307
     * @return ColumnSchemaBuilder column schema builder instance
308
     * @since 2.0.6
309
     */
310 3
    public function createColumnSchemaBuilder($type, $length = null)
311
    {
312 3
        return new ColumnSchemaBuilder($type, $length);
313
    }
314
315
    /**
316
     * Returns all unique indexes for the given table.
317
     * Each array element is of the following structure:
318
     *
319
     * ```php
320
     * [
321
     *  'IndexName1' => ['col1' [, ...]],
322
     *  'IndexName2' => ['col2' [, ...]],
323
     * ]
324
     * ```
325
     *
326
     * This method should be overridden by child classes in order to support this feature
327
     * because the default implementation simply throws an exception
328
     * @param TableSchema $table the table metadata
329
     * @return array all unique indexes for the given table.
330
     * @throws NotSupportedException if this method is called
331
     */
332
    public function findUniqueIndexes($table)
333
    {
334
        throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
335
    }
336
337
    /**
338
     * Returns the ID of the last inserted row or sequence value.
339
     * @param string $sequenceName name of the sequence object (required by some DBMS)
340
     * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
341
     * @throws InvalidCallException if the DB connection is not active
342
     * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
343
     */
344 65
    public function getLastInsertID($sequenceName = '')
345
    {
346 65
        if ($this->db->isActive) {
347 65
            return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
348
        }
349
350
        throw new InvalidCallException('DB Connection is not active.');
351
    }
352
353
    /**
354
     * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
355
     */
356 4
    public function supportsSavepoint()
357
    {
358 4
        return $this->db->enableSavepoint;
359
    }
360
361
    /**
362
     * Creates a new savepoint.
363
     * @param string $name the savepoint name
364
     */
365 4
    public function createSavepoint($name)
366
    {
367 4
        $this->db->createCommand("SAVEPOINT $name")->execute();
368 4
    }
369
370
    /**
371
     * Releases an existing savepoint.
372
     * @param string $name the savepoint name
373
     */
374
    public function releaseSavepoint($name)
375
    {
376
        $this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
377
    }
378
379
    /**
380
     * Rolls back to a previously created savepoint.
381
     * @param string $name the savepoint name
382
     */
383 4
    public function rollBackSavepoint($name)
384
    {
385 4
        $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
386 4
    }
387
388
    /**
389
     * Sets the isolation level of the current transaction.
390
     * @param string $level The transaction isolation level to use for this transaction.
391
     * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
392
     * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
393
     * after `SET TRANSACTION ISOLATION LEVEL`.
394
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
395
     */
396 6
    public function setTransactionIsolationLevel($level)
397
    {
398 6
        $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
399 6
    }
400
401
    /**
402
     * Executes the INSERT command, returning primary key values.
403
     * @param string $table the table that new rows will be inserted into.
404
     * @param array $columns the column data (name => value) to be inserted into the table.
405
     * @return array|false primary key values or false if the command fails
406
     * @since 2.0.4
407
     */
408 69
    public function insert($table, $columns)
409
    {
410 69
        $command = $this->db->createCommand()->insert($table, $columns);
411 69
        if (!$command->execute()) {
412
            return false;
413
        }
414 69
        $tableSchema = $this->getTableSchema($table);
415 69
        $result = [];
416 69
        foreach ($tableSchema->primaryKey as $name) {
417 66
            if ($tableSchema->columns[$name]->autoIncrement) {
418 62
                $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
419 62
                break;
420
            }
421
422 6
            $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
423
        }
424 69
        return $result;
425
    }
426
427
    /**
428
     * Quotes a string value for use in a query.
429
     * Note that if the parameter is not a string, it will be returned without change.
430
     * @param string $str string to be quoted
431
     * @return string the properly quoted string
432
     * @see http://www.php.net/manual/en/function.PDO-quote.php
433
     */
434 720
    public function quoteValue($str)
435
    {
436 720
        if (!is_string($str)) {
437 4
            return $str;
438
        }
439
440 720
        if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
441 720
            return $value;
442
        }
443
444
        // the driver doesn't support quote (e.g. oci)
445
        return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
446
    }
447
448
    /**
449
     * Quotes a table name for use in a query.
450
     * If the table name contains schema prefix, the prefix will also be properly quoted.
451
     * If the table name is already quoted or contains '(' or '{{',
452
     * then this method will do nothing.
453
     * @param string $name table name
454
     * @return string the properly quoted table name
455
     * @see quoteSimpleTableName()
456
     */
457 881
    public function quoteTableName($name)
458
    {
459 881
        if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
460 245
            return $name;
461
        }
462 877
        if (strpos($name, '.') === false) {
463 877
            return $this->quoteSimpleTableName($name);
464
        }
465 5
        $parts = explode('.', $name);
466 5
        foreach ($parts as $i => $part) {
467 5
            $parts[$i] = $this->quoteSimpleTableName($part);
468
        }
469
470 5
        return implode('.', $parts);
471
    }
472
473
    /**
474
     * Quotes a column name for use in a query.
475
     * If the column name contains prefix, the prefix will also be properly quoted.
476
     * If the column name is already quoted or contains '(', '[[' or '{{',
477
     * then this method will do nothing.
478
     * @param string $name column name
479
     * @return string the properly quoted column name
480
     * @see quoteSimpleColumnName()
481
     */
482 932
    public function quoteColumnName($name)
483
    {
484 932
        if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
485 96
            return $name;
486
        }
487 926
        if (($pos = strrpos($name, '.')) !== false) {
488 140
            $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
489 140
            $name = substr($name, $pos + 1);
490
        } else {
491 926
            $prefix = '';
492
        }
493 926
        if (strpos($name, '{{') !== false) {
494 4
            return $name;
495
        }
496 926
        return $prefix . $this->quoteSimpleColumnName($name);
497
    }
498
499
    /**
500
     * Quotes a simple table name for use in a query.
501
     * A simple table name should contain the table name only without any schema prefix.
502
     * If the table name is already quoted, this method will do nothing.
503
     * @param string $name table name
504
     * @return string the properly quoted table name
505
     */
506
    public function quoteSimpleTableName($name)
507
    {
508
        return strpos($name, "'") !== false ? $name : "'" . $name . "'";
509
    }
510
511
    /**
512
     * Quotes a simple column name for use in a query.
513
     * A simple column name should contain the column name only without any prefix.
514
     * If the column name is already quoted or is the asterisk character '*', this method will do nothing.
515
     * @param string $name column name
516
     * @return string the properly quoted column name
517
     */
518 304
    public function quoteSimpleColumnName($name)
519
    {
520 304
        return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
521
    }
522
523
    /**
524
     * Returns the actual name of a given table name.
525
     * This method will strip off curly brackets from the given table name
526
     * and replace the percentage character '%' with [[Connection::tablePrefix]].
527
     * @param string $name the table name to be converted
528
     * @return string the real name of the given table name
529
     */
530 831
    public function getRawTableName($name)
531
    {
532 831
        if (strpos($name, '{{') !== false) {
533 203
            $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
534
535 203
            return str_replace('%', $this->db->tablePrefix, $name);
536
        }
537
538 632
        return $name;
539
    }
540
541
    /**
542
     * Extracts the PHP type from abstract DB type.
543
     * @param ColumnSchema $column the column schema information
544
     * @return string PHP type name
545
     */
546 629
    protected function getColumnPhpType($column)
547
    {
548 629
        static $typeMap = [
549
            // abstract type => php type
550
            'smallint' => 'integer',
551
            'integer' => 'integer',
552
            'bigint' => 'integer',
553
            'boolean' => 'boolean',
554
            'float' => 'double',
555
            'double' => 'double',
556
            'binary' => 'resource',
557
        ];
558 629
        if (isset($typeMap[$column->type])) {
559 622
            if ($column->type === 'bigint') {
560 29
                return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
561 622
            } elseif ($column->type === 'integer') {
562 622
                return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
563
            }
564
565 234
            return $typeMap[$column->type];
566
        }
567
568 602
        return 'string';
569
    }
570
571
    /**
572
     * Converts a DB exception to a more concrete one if possible.
573
     *
574
     * @param \Exception $e
575
     * @param string $rawSql SQL that produced exception
576
     * @return Exception
577
     */
578 30
    public function convertException(\Exception $e, $rawSql)
579
    {
580 30
        if ($e instanceof Exception) {
581
            return $e;
582
        }
583
584 30
        $exceptionClass = '\yii\db\Exception';
585 30
        foreach ($this->exceptionMap as $error => $class) {
586 30
            if (strpos($e->getMessage(), $error) !== false) {
587 30
                $exceptionClass = $class;
588
            }
589
        }
590 30
        $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
591 30
        $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
592 30
        return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
593
    }
594
595
    /**
596
     * Returns a value indicating whether a SQL statement is for read purpose.
597
     * @param string $sql the SQL statement
598
     * @return bool whether a SQL statement is for read purpose.
599
     */
600 9
    public function isReadQuery($sql)
601
    {
602 9
        $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
603 9
        return preg_match($pattern, $sql) > 0;
604
    }
605
606
    /**
607
     * Returns the cache key for the specified table name.
608
     * @param string $name the table name
609
     * @return mixed the cache key
610
     */
611 7
    protected function getCacheKey($name)
612
    {
613
        return [
614 7
            __CLASS__,
615 7
            $this->db->dsn,
616 7
            $this->db->username,
617 7
            $name,
618
        ];
619
    }
620
621
    /**
622
     * Returns the cache tag name.
623
     * This allows [[refresh()]] to invalidate all cached table schemas.
624
     * @return string the cache tag name
625
     */
626 7
    protected function getCacheTag()
627
    {
628 7
        return md5(serialize([
629 7
            __CLASS__,
630 7
            $this->db->dsn,
631 7
            $this->db->username,
632
        ]));
633
    }
634
635
    /**
636
     * Returns the metadata of the given type for the given table.
637
     * If there's no metadata in the cache, this method will call
638
     * a `'loadTable' . ucfirst($type)` named method with the table name to obtain the metadata.
639
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
640
     * @param string $type metadata type.
641
     * @param bool $refresh whether to reload the table metadata even if it is found in the cache.
642
     * @return mixed metadata.
643
     * @since 2.0.13
644
     */
645 851
    protected function getTableMetadata($name, $type, $refresh)
646
    {
647 851
        $cache = null;
648 851
        if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
649 7
            $schemaCache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
650 7
            if ($schemaCache instanceof Cache) {
651 7
                $cache = $schemaCache;
652
            }
653
        }
654 851
        if ($refresh || !isset($this->_tableMetadata[$name])) {
655 831
            $this->loadTableMetadataFromCache($cache, $name);
656
        }
657 851
        if (!array_key_exists($type, $this->_tableMetadata[$name])) {
658 831
            $this->_tableMetadata[$name][$type] = $this->{'loadTable' . ucfirst($type)}($this->getRawTableName($name));
659
        }
660 803
        $this->saveTableMetadataToCache($cache, $name);
661 803
        return $this->_tableMetadata[$name][$type];
662
    }
663
664
    /**
665
     * Returns the metadata of the given type for all tables in the given schema.
666
     * This method will call a `'getTable' . ucfirst($type)` named method with the table name
667
     * and the refresh flag to obtain the metadata.
668
     * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema name.
669
     * @param string $type metadata type.
670
     * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`,
671
     * cached data may be returned if available.
672
     * @return array array of metadata.
673
     * @since 2.0.13
674
     */
675 10
    protected function getSchemaMetadata($schema, $type, $refresh)
676
    {
677 10
        $metadata = [];
678 10
        $methodName = 'getTable' . ucfirst($type);
679 10
        foreach ($this->getTableNames($schema, $refresh) as $name) {
680 10
            if ($schema !== '') {
681
                $name = $schema . '.' . $name;
682
            }
683 10
            $tableMetadata = $this->$methodName($name, $refresh);
684 10
            if ($tableMetadata !== null) {
685 10
                $metadata[] = $tableMetadata;
686
            }
687
        }
688 10
        return $metadata;
689
    }
690
691
    /**
692
     * Sets the metadata of the given type for the given table.
693
     * @param string $name table name.
694
     * @param string $type metadata type.
695
     * @param mixed $data metadata.
696
     * @since 2.0.13
697
     */
698 107
    protected function setTableMetadata($name, $type, $data)
699
    {
700 107
        $this->_tableMetadata[$name][$type] = $data;
701 107
    }
702
703
    /**
704
     * Changes row's array key case to lower if PDO's one is set to uppercase.
705
     * @param array $row row's array or an array of row's arrays.
706
     * @param bool $multiple whether multiple rows or a single row passed.
707
     * @return array normalized row or rows.
708
     * @since 2.0.13
709
     */
710 130
    protected function normalizePdoRowKeyCase(array $row, $multiple)
711
    {
712 130
        if ($this->db->getSlavePdo()->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
713 90
            return $row;
714
        }
715
716 40
        if ($multiple) {
717 40
            return array_map(function (array $row) {
718 36
                return array_change_key_case($row, CASE_LOWER);
719 40
            }, $row);
720
        }
721
722
        return array_change_key_case($row, CASE_LOWER);
723
    }
724
725
    /**
726
     * Tries to load and populate table metadata from cache.
727
     * @param Cache|null $cache
728
     * @param string $name
729
     */
730 831
    private function loadTableMetadataFromCache($cache, $name)
731
    {
732 831
        if ($cache === null) {
733 824
            $this->_tableMetadata[$name] = [];
734 824
            return;
735
        }
736
737 7
        $metadata = $cache->get($this->getCacheKey($name));
738 7
        if (!is_array($metadata) || !isset($metadata['cacheVersion']) || $metadata['cacheVersion'] !== static::SCHEMA_CACHE_VERSION) {
739 7
            $this->_tableMetadata[$name] = [];
740 7
            return;
741
        }
742
743 4
        unset($metadata['cacheVersion']);
744 4
        $this->_tableMetadata[$name] = $metadata;
745 4
    }
746
747
    /**
748
     * Saves table metadata to cache.
749
     * @param Cache|null $cache
750
     * @param string $name
751
     */
752 803
    private function saveTableMetadataToCache($cache, $name)
753
    {
754 803
        if ($cache === null) {
755 796
            return;
756
        }
757
758 7
        $metadata = $this->_tableMetadata[$name];
759 7
        $metadata['cacheVersion'] = static::SCHEMA_CACHE_VERSION;
760 7
        $cache->set(
761 7
            $this->getCacheKey($name),
762 7
            $metadata,
763 7
            $this->db->schemaCacheDuration,
764 7
            new TagDependency(['tags' => $this->getCacheTag()])
765
        );
766 7
    }
767
}
768