Passed
Push — fix-master ( d14f05 )
by Alexander
77:57 queued 70:24
created

QueryBuilder::resetSequence()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.3906

Importance

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