Passed
Push — scrutinizer-migrate-to-new-eng... ( 58afd6 )
by Alexander
18:11
created

QueryBuilder   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 386
Duplicated Lines 0 %

Test Coverage

Coverage 76.92%

Importance

Changes 0
Metric Value
eloc 137
dl 0
loc 386
ccs 100
cts 130
cp 0.7692
rs 6.4799
c 0
b 0
f 0
wmc 54

23 Methods

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