Passed
Push — 17667-sqlite-create-index-with... ( 21cdd8...b9d5ca )
by Alexander
84:30 queued 44:33
created

QueryBuilder::supportsFractionalSeconds()   B

Complexity

Conditions 8
Paths 48

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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