Completed
Pull Request — 2.1 (#12704)
by Robert
08:59
created

Schema::insert()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

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