Completed
Push — master ( 2914db...46bf3c )
by Carsten
13:36
created

QueryBuilder::addCommentOnTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 1
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
    public function createIndex($name, $table, $columns, $unique = false)
92
    {
93
        return 'ALTER TABLE '
94
        . $this->db->quoteTableName($table)
95
        . ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
96
        . $this->db->quoteTableName($name)
97
        . ' (' . $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
    public function dropForeignKey($name, $table)
107
    {
108
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
109
            . ' 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
    public function dropPrimaryKey($name, $table)
119
    {
120
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' DROP PRIMARY KEY';
121
    }
122
123
    /**
124
     * @inheritDoc
125
     */
126
    public function dropUnique($name, $table)
127
    {
128
        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 1
    public function resetSequence($tableName, $value = null)
160
    {
161 1
        $table = $this->db->getTableSchema($tableName);
162
        if ($table !== null && $table->sequenceName !== null) {
163
            $tableName = $this->db->quoteTableName($tableName);
164
            if ($value === null) {
165
                $key = reset($table->primaryKey);
166
                $value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
167
            } else {
168
                $value = (int) $value;
169
            }
170
171
            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
    public function checkIntegrity($check = true, $schema = '', $table = '')
187
    {
188
        return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
189
    }
190
191
    /**
192
     * @inheritdoc
193
     */
194 100
    public function buildLimit($limit, $offset)
195
    {
196 100
        $sql = '';
197 100
        if ($this->hasLimit($limit)) {
198
            $sql = 'LIMIT ' . $limit;
199
            if ($this->hasOffset($offset)) {
200
                $sql .= ' OFFSET ' . $offset;
201
            }
202 100
        } 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
            $sql = "LIMIT $offset, 18446744073709551615"; // 2^64-1
207
        }
208
209 100
        return $sql;
210
    }
211
212
    /**
213
     * @inheritdoc
214
     */
215 100
    protected function hasLimit($limit)
216
    {
217
        // In MySQL limit argument must be nonnegative integer constant
218 100
        return ctype_digit((string) $limit);
219
    }
220
221
    /**
222
     * @inheritdoc
223
     */
224 100
    protected function hasOffset($offset)
225
    {
226
        // In MySQL offset argument must be nonnegative integer constant
227 100
        $offset = (string) $offset;
228 100
        return ctype_digit($offset) && $offset !== '0';
229
    }
230
231
    /**
232
     * @inheritdoc
233
     */
234
    public function insert($table, $columns, &$params)
235
    {
236
        $schema = $this->db->getSchema();
237
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
238
            $columnSchemas = $tableSchema->columns;
239
        } else {
240
            $columnSchemas = [];
241
        }
242
        $names = [];
243
        $placeholders = [];
244
        $values = ' DEFAULT VALUES';
245
        if ($columns instanceof \yii\db\Query) {
246
            list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
247
        } else {
248
            foreach ($columns as $name => $value) {
249
                $names[] = $schema->quoteColumnName($name);
250
                if ($value instanceof Expression) {
251
                    $placeholders[] = $value->expression;
252
                    foreach ($value->params as $n => $v) {
253
                        $params[$n] = $v;
254
                    }
255
                } elseif ($value instanceof \yii\db\Query) {
256
                    list($sql, $params) = $this->build($value, $params);
257
                    $placeholders[] = "($sql)";
258
                } else {
259
                    $phName = self::PARAM_PREFIX . count($params);
260
                    $placeholders[] = $phName;
261
                    $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
262
                }
263
            }
264
            if (empty($names) && $tableSchema !== null) {
265
                $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : [reset($tableSchema->columns)->name];
266
                foreach ($columns as $name) {
267
                    $names[] = $schema->quoteColumnName($name);
268
                    $placeholders[] = 'DEFAULT';
269
                }
270
            }
271
        }
272
273
        return 'INSERT INTO ' . $schema->quoteTableName($table)
274
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
275
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
276
    }
277
278
    /**
279
     * @inheritdoc
280
     * @since 2.0.8
281
     */
282 1
    public function addCommentOnColumn($table, $column, $comment)
283
    {
284 1
        $definition = $this->getColumnDefinition($table, $column);
285
        $definition = trim(preg_replace("/COMMENT '(.*?)'/i", '', $definition));
286
287
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
288
            . ' CHANGE ' . $this->db->quoteColumnName($column)
289
            . ' ' . $this->db->quoteColumnName($column)
290
            . (empty($definition) ? '' : ' ' . $definition)
291
            . ' 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
    public function dropCommentFromColumn($table, $column)
308
    {
309
        return $this->addCommentOnColumn($table, $column, '');
310
    }
311
312
    /**
313
     * @inheritdoc
314
     * @since 2.0.8
315
     */
316
    public function dropCommentFromTable($table)
317
    {
318
        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 1
    private function getColumnDefinition($table, $column)
331
    {
332 1
        $quotedTable = $this->db->quoteTableName($table);
333 1
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
334
        if ($row === false) {
335
            throw new Exception("Unable to find column '$column' in table '$table'.");
336
        }
337
        if (isset($row['Create Table'])) {
338
            $sql = $row['Create Table'];
339
        } else {
340
            $row = array_values($row);
341
            $sql = $row[1];
342
        }
343
        if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
344
            foreach ($matches[1] as $i => $c) {
345
                if ($c === $column) {
346
                    return $matches[2][$i];
347
                }
348
            }
349
        }
350
        return null;
351
    }
352
}
353