Completed
Push — master ( 5a01c0...0070b9 )
by Carsten
32:47 queued 29:21
created

QueryBuilder::resetSequence()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.3906

Importance

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