Passed
Push — bizley-patch-2 ( f0e2a9 )
by Paweł
10:22
created

QueryBuilder::defaultTimeTypeMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 0
dl 0
loc 17
ccs 5
cts 5
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\mysql;
9
10
use yii\base\InvalidArgumentException;
11
use yii\base\NotSupportedException;
12
use yii\caching\CacheInterface;
13
use yii\caching\DbCache;
14
use yii\db\Exception;
15
use yii\db\Expression;
16
use yii\db\Query;
17
18
/**
19
 * QueryBuilder is the query builder for MySQL databases.
20
 *
21
 * @author Qiang Xue <[email protected]>
22
 * @since 2.0
23
 */
24
class QueryBuilder extends \yii\db\QueryBuilder
25
{
26
    /**
27
     * @var array mapping from abstract column types (keys) to physical column types (values).
28
     */
29
    public $typeMap = [
30
        Schema::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
31
        Schema::TYPE_UPK => 'int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
32
        Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY',
33
        Schema::TYPE_UBIGPK => 'bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
34
        Schema::TYPE_CHAR => 'char(1)',
35
        Schema::TYPE_STRING => 'varchar(255)',
36
        Schema::TYPE_TEXT => 'text',
37
        Schema::TYPE_TINYINT => 'tinyint(3)',
38
        Schema::TYPE_SMALLINT => 'smallint(6)',
39
        Schema::TYPE_INTEGER => 'int(11)',
40
        Schema::TYPE_BIGINT => 'bigint(20)',
41
        Schema::TYPE_FLOAT => 'float',
42
        Schema::TYPE_DOUBLE => 'double',
43
        Schema::TYPE_DECIMAL => 'decimal(10,0)',
44
        Schema::TYPE_DATE => 'date',
45
        Schema::TYPE_BINARY => 'blob',
46
        Schema::TYPE_BOOLEAN => 'tinyint(1)',
47
        Schema::TYPE_MONEY => 'decimal(19,4)',
48
        Schema::TYPE_JSON => 'json'
49
    ];
50
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 592
    public function init()
56
    {
57 592
        parent::init();
58
59 592
        $this->typeMap = array_merge($this->typeMap, $this->defaultTimeTypeMap());
60 592
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 592
    protected function defaultExpressionBuilders()
66
    {
67 592
        return array_merge(parent::defaultExpressionBuilders(), [
68 592
            'yii\db\JsonExpression' => 'yii\db\mysql\JsonExpressionBuilder',
69
        ]);
70
    }
71
72
    /**
73
     * Builds a SQL statement for renaming a column.
74
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
75
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
76
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
77
     * @return string the SQL statement for renaming a DB column.
78
     * @throws Exception
79
     */
80
    public function renameColumn($table, $oldName, $newName)
81
    {
82
        $quotedTable = $this->db->quoteTableName($table);
83
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
84
        if ($row === false) {
85
            throw new Exception("Unable to find column '$oldName' in table '$table'.");
86
        }
87
        if (isset($row['Create Table'])) {
88
            $sql = $row['Create Table'];
89
        } else {
90
            $row = array_values($row);
91
            $sql = $row[1];
92
        }
93
        if (preg_match_all('/^\s*[`"](.*?)[`"]\s+(.*?),?$/m', $sql, $matches)) {
94
            foreach ($matches[1] as $i => $c) {
95
                if ($c === $oldName) {
96
                    return "ALTER TABLE $quotedTable CHANGE "
97
                        . $this->db->quoteColumnName($oldName) . ' '
98
                        . $this->db->quoteColumnName($newName) . ' '
99
                        . $matches[2][$i];
100
                }
101
            }
102
        }
103
        // try to give back a SQL anyway
104
        return "ALTER TABLE $quotedTable CHANGE "
105
            . $this->db->quoteColumnName($oldName) . ' '
106
            . $this->db->quoteColumnName($newName);
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     * @see https://bugs.mysql.com/bug.php?id=48875
112
     */
113 12
    public function createIndex($name, $table, $columns, $unique = false)
114
    {
115
        return 'ALTER TABLE '
116 12
        . $this->db->quoteTableName($table)
117 12
        . ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
118 12
        . $this->db->quoteTableName($name)
119 12
        . ' (' . $this->buildColumns($columns) . ')';
120
    }
121
122
    /**
123
     * Builds a SQL statement for dropping a foreign key constraint.
124
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
125
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
126
     * @return string the SQL statement for dropping a foreign key constraint.
127
     */
128 4
    public function dropForeignKey($name, $table)
129
    {
130 4
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
131 4
            . ' DROP FOREIGN KEY ' . $this->db->quoteColumnName($name);
132
    }
133
134
    /**
135
     * Builds a SQL statement for removing a primary key constraint to an existing table.
136
     * @param string $name the name of the primary key constraint to be removed.
137
     * @param string $table the table that the primary key constraint will be removed from.
138
     * @return string the SQL statement for removing a primary key constraint from an existing table.
139
     */
140 2
    public function dropPrimaryKey($name, $table)
141
    {
142 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148 2
    public function dropUnique($name, $table)
149
    {
150 2
        return $this->dropIndex($name, $table);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     * @throws NotSupportedException this is not supported by MySQL.
156
     */
157
    public function addCheck($name, $table, $expression)
158
    {
159
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     * @throws NotSupportedException this is not supported by MySQL.
165
     */
166
    public function dropCheck($name, $table)
167
    {
168
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
169
    }
170
171
    /**
172
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
173
     * The sequence will be reset such that the primary key of the next new row inserted
174
     * will have the specified value or 1.
175
     * @param string $tableName the name of the table whose primary key sequence will be reset
176
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
177
     * the next new row's primary key will have a value 1.
178
     * @return string the SQL statement for resetting sequence
179
     * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
180
     */
181 16
    public function resetSequence($tableName, $value = null)
182
    {
183 16
        $table = $this->db->getTableSchema($tableName);
184 16
        if ($table !== null && $table->sequenceName !== null) {
185 16
            $tableName = $this->db->quoteTableName($tableName);
186 16
            if ($value === null) {
187 1
                $key = reset($table->primaryKey);
188 1
                $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
189
            } else {
190 16
                $value = (int) $value;
191
            }
192
193 16
            return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
194
        } elseif ($table === null) {
195
            throw new InvalidArgumentException("Table not found: $tableName");
196
        }
197
198
        throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
199
    }
200
201
    /**
202
     * Builds a SQL statement for enabling or disabling integrity check.
203
     * @param bool $check whether to turn on or off the integrity check.
204
     * @param string $schema the schema of the tables. Meaningless for MySQL.
205
     * @param string $table the table name. Meaningless for MySQL.
206
     * @return string the SQL statement for checking integrity
207
     */
208 4
    public function checkIntegrity($check = true, $schema = '', $table = '')
209
    {
210 4
        return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216 473
    public function buildLimit($limit, $offset)
217
    {
218 473
        $sql = '';
219 473
        if ($this->hasLimit($limit)) {
220 34
            $sql = 'LIMIT ' . $limit;
221 34
            if ($this->hasOffset($offset)) {
222 34
                $sql .= ' OFFSET ' . $offset;
223
            }
224 464
        } elseif ($this->hasOffset($offset)) {
225
            // limit is not optional in MySQL
226
            // https://stackoverflow.com/questions/255517/mysql-offset-infinite-rows/271650#271650
227
            // https://dev.mysql.com/doc/refman/5.7/en/select.html#idm46193796386608
228 2
            $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
229
        }
230
231 473
        return $sql;
232
    }
233
234
    /**
235
     * {@inheritdoc}
236
     */
237 473
    protected function hasLimit($limit)
238
    {
239
        // In MySQL limit argument must be nonnegative integer constant
240 473
        return ctype_digit((string) $limit);
241
    }
242
243
    /**
244
     * {@inheritdoc}
245
     */
246 473
    protected function hasOffset($offset)
247
    {
248
        // In MySQL offset argument must be nonnegative integer constant
249 473
        $offset = (string) $offset;
250 473
        return ctype_digit($offset) && $offset !== '0';
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     */
256 212
    protected function prepareInsertValues($table, $columns, $params = [])
257
    {
258 212
        list($names, $placeholders, $values, $params) = parent::prepareInsertValues($table, $columns, $params);
259 209
        if (!$columns instanceof Query && empty($names)) {
260 2
            $tableSchema = $this->db->getSchema()->getTableSchema($table);
261 2
            if ($tableSchema !== null) {
262 2
                if (!empty($tableSchema->primaryKey)) {
263 2
                    $columns = $tableSchema->primaryKey;
264 2
                    $defaultValue = 'NULL';
265
                } else {
266 1
                    $columns = [reset($tableSchema->columns)->name];
267 1
                    $defaultValue = 'DEFAULT';
268
                }
269
                
270 2
                foreach ($columns as $name) {
271 2
                    $names[] = $this->db->quoteColumnName($name);
272 2
                    $placeholders[] = $defaultValue;
273
                }
274
            }
275
        }
276 209
        return [$names, $placeholders, $values, $params];
277
    }
278
279
    /**
280
     * {@inheritdoc}
281
     * @see https://downloads.mysql.com/docs/refman-5.1-en.pdf
282
     */
283 41
    public function upsert($table, $insertColumns, $updateColumns, &$params)
284
    {
285 41
        $insertSql = $this->insert($table, $insertColumns, $params);
286 41
        list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
287 41
        if (empty($uniqueNames)) {
288 3
            return $insertSql;
289
        }
290 38
        if ($updateNames === []) {
291
            // there are no columns to update
292 1
            $updateColumns = false;
293
        }
294
295 38
        if ($updateColumns === true) {
296 27
            $updateColumns = [];
297 27
            foreach ($updateNames as $name) {
298 27
                $updateColumns[$name] = new Expression('VALUES(' . $this->db->quoteColumnName($name) . ')');
299
            }
300 11
        } elseif ($updateColumns === false) {
301 5
            $name = $this->db->quoteColumnName(reset($uniqueNames));
302 5
            $updateColumns = [$name => new Expression($this->db->quoteTableName($table) . '.' . $name)];
303
        }
304 38
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
305 38
        return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
306
    }
307
308
    /**
309
     * {@inheritdoc}
310
     * @since 2.0.8
311
     */
312 2
    public function addCommentOnColumn($table, $column, $comment)
313
    {
314
        // Strip existing comment which may include escaped quotes
315 2
        $definition = trim(preg_replace("/COMMENT '(?:''|[^'])*'/i", '',
316 2
            $this->getColumnDefinition($table, $column)));
317
318 2
        $checkRegex = '/CHECK *(\(([^()]|(?-2))*\))/';
319 2
        $check = preg_match($checkRegex, $definition, $checkMatches);
320 2
        if ($check === 1) {
321
            $definition = preg_replace($checkRegex, '', $definition);
322
        }
323 2
        $alterSql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
324 2
            . ' CHANGE ' . $this->db->quoteColumnName($column)
325 2
            . ' ' . $this->db->quoteColumnName($column)
326 2
            . (empty($definition) ? '' : ' ' . $definition)
327 2
            . ' COMMENT ' . $this->db->quoteValue($comment);
328 2
        if ($check === 1) {
329
            $alterSql .= ' ' . $checkMatches[0];
330
        }
331 2
        return $alterSql;
332
    }
333
334
    /**
335
     * {@inheritdoc}
336
     * @since 2.0.8
337
     */
338 1
    public function addCommentOnTable($table, $comment)
339
    {
340 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
341
    }
342
343
    /**
344
     * {@inheritdoc}
345
     * @since 2.0.8
346
     */
347 2
    public function dropCommentFromColumn($table, $column)
348
    {
349 2
        return $this->addCommentOnColumn($table, $column, '');
350
    }
351
352
    /**
353
     * {@inheritdoc}
354
     * @since 2.0.8
355
     */
356 1
    public function dropCommentFromTable($table)
357
    {
358 1
        return $this->addCommentOnTable($table, '');
359
    }
360
361
362
    /**
363
     * Gets column definition.
364
     *
365
     * @param string $table table name
366
     * @param string $column column name
367
     * @return string|null the column definition
368
     * @throws Exception in case when table does not contain column
369
     */
370 2
    private function getColumnDefinition($table, $column)
371
    {
372 2
        $quotedTable = $this->db->quoteTableName($table);
373 2
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
374 2
        if ($row === false) {
375
            throw new Exception("Unable to find column '$column' in table '$table'.");
376
        }
377 2
        if (isset($row['Create Table'])) {
378 2
            $sql = $row['Create Table'];
379
        } else {
380
            $row = array_values($row);
381
            $sql = $row[1];
382
        }
383 2
        if (preg_match_all('/^\s*[`"](.*?)[`"]\s+(.*?),?$/m', $sql, $matches)) {
384 2
            foreach ($matches[1] as $i => $c) {
385 2
                if ($c === $column) {
386 2
                    return $matches[2][$i];
387
                }
388
            }
389
        }
390
391
        return null;
392
    }
393
394
    /**
395
     * Checks the ability to use fractional seconds.
396
     *
397
     * @return bool
398
     * @see https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
399
     */
400 592
    private function supportsFractionalSeconds()
401
    {
402
        // use cache to prevent opening MySQL connection
403
        // https://github.com/yiisoft/yii2/issues/13749#issuecomment-481657224
404 592
        $key = [__METHOD__, $this->db->dsn];
405 592
        $cache = null;
406 592
        $schemaCache = (\Yii::$app && is_string($this->db->schemaCache)) ? \Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
407
        // If the `$schemaCache` is an instance of `DbCache` we don't use it to avoid a loop
408 592
        if ($this->db->enableSchemaCache && $schemaCache instanceof CacheInterface && !($schemaCache instanceof DbCache)) {
409 2
            $cache = $schemaCache;
410
        }
411 592
        $version = $cache ? $cache->get($key) : null;
412 592
        if (!$version) {
413 592
            $version = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
414 592
            if ($cache) {
415 2
                $cache->set($key, $version, $this->db->schemaCacheDuration);
416
            }
417
        }
418
419 592
        return version_compare($version, '5.6.4', '>=');
0 ignored issues
show
Bug Best Practice introduced by
The expression return version_compare($version, '5.6.4', '>=') also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
420
    }
421
422
    /**
423
     * Returns the map for default time type.
424
     * If the version of MySQL is lower than 5.6.4, then the types will be without fractional seconds,
425
     * otherwise with fractional seconds.
426
     *
427
     * @return array
428
     */
429 592
    private function defaultTimeTypeMap()
430
    {
431
        $map = [
432 592
            Schema::TYPE_DATETIME => 'datetime',
433
            Schema::TYPE_TIMESTAMP => 'timestamp',
434
            Schema::TYPE_TIME => 'time',
435
        ];
436
437 592
        if ($this->supportsFractionalSeconds()) {
438
            $map = [
439 592
                Schema::TYPE_DATETIME => 'datetime(0)',
440
                Schema::TYPE_TIMESTAMP => 'timestamp(0)',
441
                Schema::TYPE_TIME => 'time(0)',
442
            ];
443
        }
444
445 592
        return $map;
446
    }
447
}
448