Completed
Push — master ( fab53b...ab36cb )
by Dmitry
106:39 queued 103:10
created

QueryBuilder::renameColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 2
cp 0
cc 1
eloc 2
nc 1
nop 3
crap 2
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_UPK => 'integer UNSIGNED PRIMARY KEY AUTOINCREMENT NOT NULL',
31
        Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
32
        Schema::TYPE_UBIGPK => 'integer UNSIGNED PRIMARY KEY AUTOINCREMENT NOT NULL',
33
        Schema::TYPE_CHAR => 'char(1)',
34
        Schema::TYPE_STRING => 'varchar(255)',
35
        Schema::TYPE_TEXT => 'text',
36
        Schema::TYPE_SMALLINT => 'smallint',
37
        Schema::TYPE_INTEGER => 'integer',
38
        Schema::TYPE_BIGINT => 'bigint',
39
        Schema::TYPE_FLOAT => 'float',
40
        Schema::TYPE_DOUBLE => 'double',
41
        Schema::TYPE_DECIMAL => 'decimal(10,0)',
42
        Schema::TYPE_DATETIME => 'datetime',
43
        Schema::TYPE_TIMESTAMP => 'timestamp',
44
        Schema::TYPE_TIME => 'time',
45
        Schema::TYPE_DATE => 'date',
46
        Schema::TYPE_BINARY => 'blob',
47
        Schema::TYPE_BOOLEAN => 'boolean',
48
        Schema::TYPE_MONEY => 'decimal(19,4)',
49
    ];
50
51
52
    /**
53
     * Generates a batch INSERT SQL statement.
54
     * For example,
55
     *
56
     * ```php
57
     * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
58
     *     ['Tom', 30],
59
     *     ['Jane', 20],
60
     *     ['Linda', 25],
61
     * ])->execute();
62
     * ```
63
     *
64
     * Note that the values in each row must match the corresponding column names.
65
     *
66
     * @param string $table the table that new rows will be inserted into.
67
     * @param array $columns the column names
68
     * @param array $rows the rows to be batch inserted into the table
69
     * @return string the batch INSERT SQL statement
70
     */
71 9
    public function batchInsert($table, $columns, $rows)
72
    {
73 9
        if (empty($rows)) {
74 2
            return '';
75
        }
76
77
        // SQLite supports batch insert natively since 3.7.11
78
        // http://www.sqlite.org/releaselog/3_7_11.html
79 8
        $this->db->open(); // ensure pdo is not null
80 8
        if (version_compare($this->db->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '3.7.11', '>=')) {
81 8
            return parent::batchInsert($table, $columns, $rows);
82
        }
83
84
        $schema = $this->db->getSchema();
85
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
86
            $columnSchemas = $tableSchema->columns;
87
        } else {
88
            $columnSchemas = [];
89
        }
90
91
        $values = [];
92
        foreach ($rows as $row) {
93
            $vs = [];
94
            foreach ($row as $i => $value) {
95
                if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
96
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
97
                }
98
                if (is_string($value)) {
99
                    $value = $schema->quoteValue($value);
100
                } elseif ($value === false) {
101
                    $value = 0;
102
                } elseif ($value === null) {
103
                    $value = 'NULL';
104
                }
105
                $vs[] = $value;
106
            }
107
            $values[] = implode(', ', $vs);
108
        }
109
110
        foreach ($columns as $i => $name) {
111
            $columns[$i] = $schema->quoteColumnName($name);
112
        }
113
114
        return 'INSERT INTO ' . $schema->quoteTableName($table)
115
        . ' (' . implode(', ', $columns) . ') SELECT ' . implode(' UNION SELECT ', $values);
116
    }
117
118
    /**
119
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
120
     * The sequence will be reset such that the primary key of the next new row inserted
121
     * will have the specified value or 1.
122
     * @param string $tableName the name of the table whose primary key sequence will be reset
123
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
124
     * the next new row's primary key will have a value 1.
125
     * @return string the SQL statement for resetting sequence
126
     * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
127
     */
128 3
    public function resetSequence($tableName, $value = null)
129
    {
130 3
        $db = $this->db;
131 3
        $table = $db->getTableSchema($tableName);
132 3
        if ($table !== null && $table->sequenceName !== null) {
133 3
            if ($value === null) {
134 1
                $key = reset($table->primaryKey);
135 1
                $tableName = $db->quoteTableName($tableName);
136 1
                $value = $this->db->useMaster(function (Connection $db) use ($key, $tableName) {
137 1
                    return $db->createCommand("SELECT MAX($key) FROM $tableName")->queryScalar();
138 1
                });
139 1
            } else {
140 3
                $value = (int) $value - 1;
141
            }
142
            try {
143 3
                return "UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'";
144
            } catch (Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\yii\db\Exception $e) { } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
145
                // it's possible that sqlite_sequence does not exist
146
            }
147
        } elseif ($table === null) {
148
            throw new InvalidParamException("Table not found: $tableName");
149
        } else {
150
            throw new InvalidParamException("There is not sequence associated with table '$tableName'.'");
151
        }
152
    }
153
154
    /**
155
     * Enables or disables integrity check.
156
     * @param bool $check whether to turn on or off the integrity check.
157
     * @param string $schema the schema of the tables. Meaningless for SQLite.
158
     * @param string $table the table name. Meaningless for SQLite.
159
     * @return string the SQL statement for checking integrity
160
     * @throws NotSupportedException this is not supported by SQLite
161
     */
162 2
    public function checkIntegrity($check = true, $schema = '', $table = '')
163
    {
164 2
        return 'PRAGMA foreign_keys='.(int) $check;
165
    }
166
167
    /**
168
     * Builds a SQL statement for truncating a DB table.
169
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
170
     * @return string the SQL statement for truncating a DB table.
171
     */
172 1
    public function truncateTable($table)
173
    {
174 1
        return 'DELETE FROM ' . $this->db->quoteTableName($table);
175
    }
176
177
    /**
178
     * Builds a SQL statement for dropping an index.
179
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
180
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
181
     * @return string the SQL statement for dropping an index.
182
     */
183
    public function dropIndex($name, $table)
184
    {
185
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
186
    }
187
188
    /**
189
     * Builds a SQL statement for dropping a DB column.
190
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
191
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
192
     * @return string the SQL statement for dropping a DB column.
193
     * @throws NotSupportedException this is not supported by SQLite
194
     */
195
    public function dropColumn($table, $column)
196
    {
197
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
198
    }
199
200
    /**
201
     * Builds a SQL statement for renaming a column.
202
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
203
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
204
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
205
     * @return string the SQL statement for renaming a DB column.
206
     * @throws NotSupportedException this is not supported by SQLite
207
     */
208
    public function renameColumn($table, $oldName, $newName)
209
    {
210
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
211
    }
212
213
    /**
214
     * Builds a SQL statement for adding a foreign key constraint to an existing table.
215
     * The method will properly quote the table and column names.
216
     * @param string $name the name of the foreign key constraint.
217
     * @param string $table the table that the foreign key constraint will be added to.
218
     * @param string|array $columns the name of the column to that the constraint will be added on.
219
     * If there are multiple columns, separate them with commas or use an array to represent them.
220
     * @param string $refTable the table that the foreign key references to.
221
     * @param string|array $refColumns the name of the column that the foreign key references to.
222
     * If there are multiple columns, separate them with commas or use an array to represent them.
223
     * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
224
     * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
225
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
226
     * @throws NotSupportedException this is not supported by SQLite
227
     */
228
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
229
    {
230
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
231
    }
232
233
    /**
234
     * Builds a SQL statement for dropping a foreign key constraint.
235
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
236
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
237
     * @return string the SQL statement for dropping a foreign key constraint.
238
     * @throws NotSupportedException this is not supported by SQLite
239
     */
240
    public function dropForeignKey($name, $table)
241
    {
242
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
243
    }
244
245
    /**
246
     * Builds a SQL statement for renaming a DB table.
247
     *
248
     * @param string $table the table to be renamed. The name will be properly quoted by the method.
249
     * @param string $newName the new table name. The name will be properly quoted by the method.
250
     * @return string the SQL statement for renaming a DB table.
251
     */
252 2
    public function renameTable($table, $newName)
253
    {
254 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
255
    }
256
257
    /**
258
     * Builds a SQL statement for changing the definition of a column.
259
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
260
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
261
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
262
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
263
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
264
     * will become 'varchar(255) not null'.
265
     * @return string the SQL statement for changing the definition of a column.
266
     * @throws NotSupportedException this is not supported by SQLite
267
     */
268
    public function alterColumn($table, $column, $type)
269
    {
270
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
271
    }
272
273
    /**
274
     * Builds a SQL statement for adding a primary key constraint to an existing table.
275
     * @param string $name the name of the primary key constraint.
276
     * @param string $table the table that the primary key constraint will be added to.
277
     * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
278
     * @return string the SQL statement for adding a primary key constraint to an existing table.
279
     * @throws NotSupportedException this is not supported by SQLite
280
     */
281
    public function addPrimaryKey($name, $table, $columns)
282
    {
283
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
284
    }
285
286
    /**
287
     * Builds a SQL statement for removing a primary key constraint to an existing table.
288
     * @param string $name the name of the primary key constraint to be removed.
289
     * @param string $table the table that the primary key constraint will be removed from.
290
     * @return string the SQL statement for removing a primary key constraint from an existing table.
291
     * @throws NotSupportedException this is not supported by SQLite
292
     */
293
    public function dropPrimaryKey($name, $table)
294
    {
295
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
296
    }
297
298
    /**
299
     * @inheritdoc
300
     * @throws NotSupportedException
301
     * @since 2.0.8
302
     */
303
    public function addCommentOnColumn($table, $column, $comment)
304
    {
305
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
306
    }
307
308
    /**
309
     * @inheritdoc
310
     * @throws NotSupportedException
311
     * @since 2.0.8
312
     */
313
    public function addCommentOnTable($table, $comment)
314
    {
315
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
316
    }
317
318
    /**
319
     * @inheritdoc
320
     * @throws NotSupportedException
321
     * @since 2.0.8
322
     */
323
    public function dropCommentFromColumn($table, $column)
324
    {
325
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
326
    }
327
328
    /**
329
     * @inheritdoc
330
     * @throws NotSupportedException
331
     * @since 2.0.8
332
     */
333
    public function dropCommentFromTable($table)
334
    {
335
        throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
336
    }
337
338
    /**
339
     * @inheritdoc
340
     */
341 240
    public function buildLimit($limit, $offset)
342
    {
343 240
        $sql = '';
344 240
        if ($this->hasLimit($limit)) {
345 19
            $sql = 'LIMIT ' . $limit;
346 19
            if ($this->hasOffset($offset)) {
347 1
                $sql .= ' OFFSET ' . $offset;
348 1
            }
349 240
        } elseif ($this->hasOffset($offset)) {
350
            // limit is not optional in SQLite
351
            // http://www.sqlite.org/syntaxdiagrams.html#select-stmt
352 2
            $sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
353 2
        }
354
355 240
        return $sql;
356
    }
357
358
    /**
359
     * @inheritdoc
360
     * @throws NotSupportedException if `$columns` is an array
361
     */
362 2
    protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
363
    {
364 2
        if (is_array($columns)) {
365
            throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
366
        }
367 2
        return parent::buildSubqueryInCondition($operator, $columns, $values, $params);
368
    }
369
370
    /**
371
     * Builds SQL for IN condition
372
     *
373
     * @param string $operator
374
     * @param array $columns
375
     * @param array $values
376
     * @param array $params
377
     * @return string SQL
378
     */
379 5
    protected function buildCompositeInCondition($operator, $columns, $values, &$params)
380
    {
381 5
        $quotedColumns = [];
382 5
        foreach ($columns as $i => $column) {
383 5
            $quotedColumns[$i] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
384 5
        }
385 5
        $vss = [];
386 5
        foreach ($values as $value) {
387 5
            $vs = [];
388 5
            foreach ($columns as $i => $column) {
389 5
                if (isset($value[$column])) {
390 5
                    $phName = self::PARAM_PREFIX . count($params);
391 5
                    $params[$phName] = $value[$column];
392 5
                    $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' = ' : ' != ') . $phName;
393 5
                } else {
394
                    $vs[] = $quotedColumns[$i] . ($operator === 'IN' ? ' IS' : ' IS NOT') . ' NULL';
395
                }
396 5
            }
397 5
            $vss[] = '(' . implode($operator === 'IN' ? ' AND ' : ' OR ', $vs) . ')';
398 5
        }
399
400 5
        return '(' . implode($operator === 'IN' ? ' OR ' : ' AND ', $vss) . ')';
401
    }
402
403
    /**
404
     * @inheritdoc
405
     */
406 240
    public function build($query, $params = [])
407
    {
408 240
        $query = $query->prepare($this);
409
410 240
        $params = empty($params) ? $query->params : array_merge($params, $query->params);
411
412
        $clauses = [
413 240
            $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
414 240
            $this->buildFrom($query->from, $params),
415 240
            $this->buildJoin($query->join, $params),
416 240
            $this->buildWhere($query->where, $params),
417 240
            $this->buildGroupBy($query->groupBy),
418 240
            $this->buildHaving($query->having, $params),
419 240
        ];
420
421 240
        $sql = implode($this->separator, array_filter($clauses));
422 240
        $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
423
424 240
        if (!empty($query->orderBy)) {
425 58
            foreach ($query->orderBy as $expression) {
426 58
                if ($expression instanceof Expression) {
427 1
                    $params = array_merge($params, $expression->params);
428 1
                }
429 58
            }
430 58
        }
431 240
        if (!empty($query->groupBy)) {
432 3
            foreach ($query->groupBy as $expression) {
433 3
                if ($expression instanceof Expression) {
434 1
                    $params = array_merge($params, $expression->params);
435 1
                }
436 3
            }
437 3
        }
438
439 240
        $union = $this->buildUnion($query->union, $params);
440 240
        if ($union !== '') {
441 2
            $sql = "$sql{$this->separator}$union";
442 2
        }
443
444 240
        return [$sql, $params];
445
    }
446
447
    /**
448
     * @inheritdoc
449
     */
450 240
    public function buildUnion($unions, &$params)
451
    {
452 240
        if (empty($unions)) {
453 240
            return '';
454
        }
455
456 2
        $result = '';
457
458 2
        foreach ($unions as $i => $union) {
459 2
            $query = $union['query'];
460 2
            if ($query instanceof Query) {
461 2
                list($unions[$i]['query'], $params) = $this->build($query, $params);
462 2
            }
463
464 2
            $result .= ' UNION ' . ($union['all'] ? 'ALL ' : '') . ' ' . $unions[$i]['query'];
465 2
        }
466
467 2
        return trim($result);
468
    }
469
}
470