Passed
Pull Request — master (#19881)
by Alexander
10:25
created

QueryBuilder   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 403
Duplicated Lines 0 %

Test Coverage

Coverage 82.05%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 157
c 1
b 0
f 0
dl 0
loc 403
ccs 128
cts 156
cp 0.8205
rs 3.36
wmc 63

21 Methods

Rating   Name   Duplication   Size   Complexity  
A dropCommentFromColumn() 0 3 1
A getColumnDefinition() 0 22 6
A addCommentOnTable() 0 3 1
A dropCommentFromTable() 0 3 1
B supportsFractionalSeconds() 0 20 9
A init() 0 5 1
A defaultExpressionBuilders() 0 4 1
A renameColumn() 0 27 6
A dropPrimaryKey() 0 3 1
A dropForeignKey() 0 4 1
A dropUnique() 0 3 1
A createIndex() 0 7 2
A hasLimit() 0 4 1
A defaultTimeTypeMap() 0 17 2
A resetSequence() 0 18 5
A upsert() 0 23 6
A addCommentOnColumn() 0 19 4
A hasOffset() 0 5 2
A prepareInsertValues() 0 21 6
A checkIntegrity() 0 3 2
A buildLimit() 0 16 4

How to fix   Complexity   

Complex Class

Complex classes like QueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use QueryBuilder, and based on these observations, apply Extract Interface, too.

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