Completed
Push — query-alias ( e06046...9802bc )
by Carsten
40:39
created

QueryBuilder   C

Complexity

Total Complexity 58

Size/Duplication

Total Lines 409
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 59.09%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 58
c 3
b 1
f 0
lcom 2
cbo 8
dl 0
loc 409
ccs 91
cts 154
cp 0.5909
rs 6.3005

18 Methods

Rating   Name   Duplication   Size   Complexity  
C batchInsert() 0 42 11
A checkIntegrity() 0 4 1
A truncateTable() 0 4 1
A dropIndex() 0 4 1
A dropColumn() 0 4 1
A renameColumn() 0 4 1
A addForeignKey() 0 4 1
A dropForeignKey() 0 4 1
A renameTable() 0 4 1
A alterColumn() 0 4 1
A addPrimaryKey() 0 4 1
A dropPrimaryKey() 0 4 1
A buildLimit() 0 16 4
A buildSubqueryInCondition() 0 7 2
C buildCompositeInCondition() 0 23 10
B resetSequence() 0 25 6
C build() 0 49 9
B buildUnion() 0 19 5

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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\sqlite;
9
10
use yii\db\Connection;
11
use yii\db\Exception;
12
use yii\base\InvalidParamException;
13
use yii\base\NotSupportedException;
14
use yii\db\Expression;
15
use yii\db\Query;
16
17
/**
18
 * QueryBuilder is the query builder for SQLite 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 => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
30
        Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
31
        Schema::TYPE_STRING => 'varchar(255)',
32
        Schema::TYPE_TEXT => 'text',
33
        Schema::TYPE_SMALLINT => 'smallint',
34
        Schema::TYPE_INTEGER => 'integer',
35
        Schema::TYPE_BIGINT => 'bigint',
36
        Schema::TYPE_FLOAT => 'float',
37
        Schema::TYPE_DOUBLE => 'double',
38
        Schema::TYPE_DECIMAL => 'decimal(10,0)',
39
        Schema::TYPE_DATETIME => 'datetime',
40
        Schema::TYPE_TIMESTAMP => 'timestamp',
41
        Schema::TYPE_TIME => 'time',
42
        Schema::TYPE_DATE => 'date',
43
        Schema::TYPE_BINARY => 'blob',
44
        Schema::TYPE_BOOLEAN => 'boolean',
45
        Schema::TYPE_MONEY => 'decimal(19,4)',
46
    ];
47
48
49
    /**
50
     * Generates a batch INSERT SQL statement.
51
     * For example,
52
     *
53
     * ```php
54
     * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
55
     *     ['Tom', 30],
56
     *     ['Jane', 20],
57
     *     ['Linda', 25],
58
     * ])->execute();
59
     * ```
60
     *
61
     * Note that the values in each row must match the corresponding column names.
62
     *
63
     * @param string $table the table that new rows will be inserted into.
64
     * @param array $columns the column names
65
     * @param array $rows the rows to be batch inserted into the table
66
     * @return string the batch INSERT SQL statement
67
     */
68 1
    public function batchInsert($table, $columns, $rows)
69
    {
70
        // SQLite supports batch insert natively since 3.7.11
71
        // http://www.sqlite.org/releaselog/3_7_11.html
72 1
        $this->db->open(); // ensure pdo is not null
73 1
        if (version_compare($this->db->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '3.7.11', '>=')) {
74 1
            return parent::batchInsert($table, $columns, $rows);
75
        }
76
77
        $schema = $this->db->getSchema();
78
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
79
            $columnSchemas = $tableSchema->columns;
80
        } else {
81
            $columnSchemas = [];
82
        }
83
84
        $values = [];
85
        foreach ($rows as $row) {
86
            $vs = [];
87
            foreach ($row as $i => $value) {
88
                if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
89
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
90
                }
91
                if (is_string($value)) {
92
                    $value = $schema->quoteValue($value);
93
                } elseif ($value === false) {
94
                    $value = 0;
95
                } elseif ($value === null) {
96
                    $value = 'NULL';
97
                }
98
                $vs[] = $value;
99
            }
100
            $values[] = implode(', ', $vs);
101
        }
102
103
        foreach ($columns as $i => $name) {
104
            $columns[$i] = $schema->quoteColumnName($name);
105
        }
106
107
        return 'INSERT INTO ' . $schema->quoteTableName($table)
108
        . ' (' . implode(', ', $columns) . ') SELECT ' . implode(' UNION SELECT ', $values);
109
    }
110
111
    /**
112
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
113
     * The sequence will be reset such that the primary key of the next new row inserted
114
     * will have the specified value or 1.
115
     * @param string $tableName the name of the table whose primary key sequence will be reset
116
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
117
     * the next new row's primary key will have a value 1.
118
     * @return string the SQL statement for resetting sequence
119
     * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
120
     */
121
    public function resetSequence($tableName, $value = null)
122
    {
123
        $db = $this->db;
124
        $table = $db->getTableSchema($tableName);
125
        if ($table !== null && $table->sequenceName !== null) {
126
            if ($value === null) {
127
                $key = reset($table->primaryKey);
128
                $tableName = $db->quoteTableName($tableName);
129
                $value = $this->db->useMaster(function (Connection $db) use ($key, $tableName) {
130
                    return $db->createCommand("SELECT MAX('$key') FROM $tableName")->queryScalar();
131
                });
132
            } else {
133
                $value = (int) $value - 1;
134
            }
135
            try {
136
                $db->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
137
            } catch (Exception $e) {
138
                // it's possible that sqlite_sequence does not exist
139
            }
140
        } elseif ($table === null) {
141
            throw new InvalidParamException("Table not found: $tableName");
142
        } else {
143
            throw new InvalidParamException("There is not sequence associated with table '$tableName'.'");
144
        }
145
    }
146
147
    /**
148
     * Enables or disables integrity check.
149
     * @param boolean $check whether to turn on or off the integrity check.
150
     * @param string $schema the schema of the tables. Meaningless for SQLite.
151
     * @param string $table the table name. Meaningless for SQLite.
152
     * @return string the SQL statement for checking integrity
153
     * @throws NotSupportedException this is not supported by SQLite
154
     */
155
    public function checkIntegrity($check = true, $schema = '', $table = '')
156
    {
157
        return 'PRAGMA foreign_keys='.(int) $check;
158
    }
159
160
    /**
161
     * Builds a SQL statement for truncating a DB table.
162
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
163
     * @return string the SQL statement for truncating a DB table.
164
     */
165 1
    public function truncateTable($table)
166
    {
167 1
        return 'DELETE FROM ' . $this->db->quoteTableName($table);
168
    }
169
170
    /**
171
     * Builds a SQL statement for dropping an index.
172
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
173
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
174
     * @return string the SQL statement for dropping an index.
175
     */
176
    public function dropIndex($name, $table)
177
    {
178
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
179
    }
180
181
    /**
182
     * Builds a SQL statement for dropping a DB column.
183
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
184
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
185
     * @return string the SQL statement for dropping a DB column.
186
     * @throws NotSupportedException this is not supported by SQLite
187
     */
188
    public function dropColumn($table, $column)
189
    {
190
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
191
    }
192
193
    /**
194
     * Builds a SQL statement for renaming a column.
195
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
196
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
197
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
198
     * @return string the SQL statement for renaming a DB column.
199
     * @throws NotSupportedException this is not supported by SQLite
200
     */
201
    public function renameColumn($table, $oldName, $newName)
202
    {
203
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
204
    }
205
206
    /**
207
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
208
     * The method will properly quote the table and column names.
209
     * @param string $name the name of the foreign key constraint.
210
     * @param string $table the table that the foreign key constraint will be added to.
211
     * @param string|array $columns the name of the column to that the constraint will be added on.
212
     * If there are multiple columns, separate them with commas or use an array to represent them.
213
     * @param string $refTable the table that the foreign key references to.
214
     * @param string|array $refColumns the name of the column that the foreign key references to.
215
     * If there are multiple columns, separate them with commas or use an array to represent them.
216
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
217
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
218
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
219
     * @throws NotSupportedException this is not supported by SQLite
220
     */
221
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
222
    {
223
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
224
    }
225
226
    /**
227
     * Builds a SQL statement for dropping a foreign key constraint.
228
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
229
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
230
     * @return string the SQL statement for dropping a foreign key constraint.
231
     * @throws NotSupportedException this is not supported by SQLite
232
     */
233
    public function dropForeignKey($name, $table)
234
    {
235
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
236
    }
237
238
    /**
239
     * Builds a SQL statement for renaming a DB table.
240
     *
241
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
242
     * @param string $newName the new table name. The name will be properly quoted by the method.
243
     * @return string the SQL statement for renaming a DB table.
244
     */
245 2
    public function renameTable($table, $newName)
246
    {
247 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
248
    }
249
250
    /**
251
     * Builds a SQL statement for changing the definition of a column.
252
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
253
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
254
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
255
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
256
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
257
     * will become 'varchar(255) not null'.
258
     * @return string the SQL statement for changing the definition of a column.
259
     * @throws NotSupportedException this is not supported by SQLite
260
     */
261
    public function alterColumn($table, $column, $type)
262
    {
263
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
264
    }
265
266
    /**
267
     * Builds a SQL statement for adding a primary key constraint to an existing table.
268
     * @param string $name the name of the primary key constraint.
269
     * @param string $table the table that the primary key constraint will be added to.
270
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
271
     * @return string the SQL statement for adding a primary key constraint to an existing table.
272
     * @throws NotSupportedException this is not supported by SQLite
273
     */
274 1
    public function addPrimaryKey($name, $table, $columns)
275
    {
276 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
277
    }
278
279
    /**
280
     * Builds a SQL statement for removing a primary key constraint to an existing table.
281
     * @param string $name the name of the primary key constraint to be removed.
282
     * @param string $table the table that the primary key constraint will be removed from.
283
     * @return string the SQL statement for removing a primary key constraint from an existing table.
284
     * @throws NotSupportedException this is not supported by SQLite
285
     */
286
    public function dropPrimaryKey($name, $table)
287
    {
288
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
289
    }
290
291
    /**
292
     * @inheritdoc
293
     */
294 185
    public function buildLimit($limit, $offset)
295
    {
296 185
        $sql = '';
297 185
        if ($this->hasLimit($limit)) {
298 15
            $sql = 'LIMIT ' . $limit;
299 15
            if ($this->hasOffset($offset)) {
300 1
                $sql .= ' OFFSET ' . $offset;
301 1
            }
302 185
        } elseif ($this->hasOffset($offset)) {
303
            // limit is not optional in SQLite
304
            // http://www.sqlite.org/syntaxdiagrams.html#select-stmt
305 2
            $sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
306 2
        }
307
308 185
        return $sql;
309
    }
310
311
    /**
312
     * @inheritdoc
313
     * @throws NotSupportedException if `$columns` is an array
314
     */
315 2
    protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
316
    {
317 2
        if (is_array($columns)) {
318
            throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
319
        }
320 2
        return parent::buildSubqueryInCondition($operator, $columns, $values, $params);
321
    }
322
323
    /**
324
     * Builds SQL for IN condition
325
     *
326
     * @param string $operator
327
     * @param array $columns
328
     * @param array $values
329
     * @param array $params
330
     * @return string SQL
331
     */
332 3
    protected function buildCompositeInCondition($operator, $columns, $values, &$params)
333
    {
334 3
        $quotedColumns = [];
335 3
        foreach ($columns as $i => $column) {
336 3
            $quotedColumns[$i] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
337 3
        }
338 3
        $vss = [];
339 3
        foreach ($values as $value) {
340 3
            $vs = [];
341 3
            foreach ($columns as $i => $column) {
342 3
                if (isset($value[$column])) {
343 3
                    $phName = self::PARAM_PREFIX . count($params);
344 3
                    $params[$phName] = $value[$column];
345 3
                    $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' = ' : ' != ') . $phName;
346 3
                } else {
347
                    $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' IS' : ' IS NOT') . ' NULL';
348
                }
349 3
            }
350 3
            $vss[] = '(' . implode($operator === 'IN' ? ' AND ' : ' OR ', $vs) . ')';
351 3
        }
352
353 3
        return '(' . implode($operator === 'IN' ? ' OR ' : ' AND ', $vss) . ')';
354
    }
355
356
    /**
357
     * @inheritdoc
358
     */
359 185
    public function build($query, $params = [])
360
    {
361 185
        $query = $query->prepare($this);
362
363 185
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
364
365
        $clauses = [
366 185
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
367 185
            $this->buildFrom($query->from, $params),
368 185
            $this->buildJoin($query->join, $params),
369 185
            $this->buildWhere($query->where, $params),
370 185
            $this->buildGroupBy($query->groupBy),
371 185
            $this->buildHaving($query->having, $params),
372 185
        ];
373
374 185
        $sql = implode($this->separator, array_filter($clauses));
375 185
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
376
377 185
        if (!empty($query->orderBy)) {
378 44
            foreach ($query->orderBy as $expression) {
379 44
                if ($expression instanceof Expression) {
380 1
                    $params = array_merge($params, $expression->params);
381 1
                }
382 44
            }
383 44
        }
384 185
        if (!empty($query->groupBy)) {
385 3
            foreach ($query->groupBy as $expression) {
386 3
                if ($expression instanceof Expression) {
387 1
                    $params = array_merge($params, $expression->params);
388 1
                }
389 3
            }
390 3
        }
391
392 185
        $union = $this->buildUnion($query->union, $params);
393 185
        if ($union !== '') {
394 2
            $sql = "$sql{$this->separator}$union";
395 2
        }
396
397
        // replace aliases with table names
398 185
        $sql = preg_replace_callback(
399 185
            '/\\{\\{@([\w\-\. ]+)\\}\\}/',
400 185
            function ($matches) use ($query) {
401 2
                return '{{' . $query->getAlias($matches[1]) . '}}';
402 185
            },
403
            $sql
404 185
        );
405
406 185
        return [$sql, $params];
407
    }
408
409
    /**
410
     * @inheritdoc
411
     */
412 185
    public function buildUnion($unions, &$params)
413
    {
414 185
        if (empty($unions)) {
415 185
            return '';
416
        }
417
418 2
        $result = '';
419
420 2
        foreach ($unions as $i => $union) {
421 2
            $query = $union['query'];
422 2
            if ($query instanceof Query) {
423 2
                list($unions[$i]['query'], $params) = $this->build($query, $params);
424 2
            }
425
426 2
            $result .= ' UNION ' . ($union['all'] ? 'ALL ' : '') . ' ' . $unions[$i]['query'];
427 2
        }
428
429 2
        return trim($result);
430
    }
431
}
432