Completed
Push — develop ( 7c38e8...152bc9 )
by Sergei
64:01 queued 11s
created

getDateArithmeticIntervalExpression()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 4
crap 2
1
<?php
2
3
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
6
use Doctrine\DBAL\Schema\Identifier;
7
use Doctrine\DBAL\Schema\Index;
8
use Doctrine\DBAL\Schema\Table;
9
use Doctrine\DBAL\Schema\TableDiff;
10
use Doctrine\DBAL\TransactionIsolationLevel;
11
use Doctrine\DBAL\Types\BlobType;
12
use Doctrine\DBAL\Types\TextType;
13
use InvalidArgumentException;
14
use function array_diff_key;
15
use function array_merge;
16
use function array_unique;
17
use function array_values;
18
use function count;
19
use function func_get_args;
20
use function implode;
21
use function in_array;
22
use function is_numeric;
23
use function is_string;
24
use function sprintf;
25
use function str_replace;
26
use function strtoupper;
27
use function trim;
28
29
/**
30
 * The MySqlPlatform provides the behavior, features and SQL dialect of the
31
 * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that
32
 * uses the InnoDB storage engine.
33
 *
34
 * @todo   Rename: MySQLPlatform
35
 */
36
class MySqlPlatform extends AbstractPlatform
37
{
38
    public const LENGTH_LIMIT_TINYTEXT   = 255;
39
    public const LENGTH_LIMIT_TEXT       = 65535;
40
    public const LENGTH_LIMIT_MEDIUMTEXT = 16777215;
41
42
    public const LENGTH_LIMIT_TINYBLOB   = 255;
43
    public const LENGTH_LIMIT_BLOB       = 65535;
44
    public const LENGTH_LIMIT_MEDIUMBLOB = 16777215;
45
46
    /**
47
     * {@inheritDoc}
48
     */
49
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
50 372
    {
51
        if ($limit !== null) {
52 372
            $query .= ' LIMIT ' . $limit;
53 222
54
            if ($offset > 0) {
55 222
                $query .= ' OFFSET ' . $offset;
56 222
            }
57
        } elseif ($offset > 0) {
58 162
            // 2^64-1 is the maximum of unsigned BIGINT, the biggest limit possible
59
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
60 81
        }
61
62
        return $query;
63 372
    }
64
65
    /**
66
     * {@inheritDoc}
67
     */
68
    public function getIdentifierQuoteCharacter()
69 1910
    {
70
        return '`';
71 1910
    }
72
73
    /**
74
     * {@inheritDoc}
75
     */
76
    public function getRegexpExpression()
77 69
    {
78
        return 'RLIKE';
79 69
    }
80
81
    /**
82
     * {@inheritDoc}
83
     */
84
    public function getLocateExpression($str, $substr, $startPos = false)
85 12
    {
86
        if ($startPos === false) {
87 12
            return 'LOCATE(' . $substr . ', ' . $str . ')';
88 12
        }
89
90
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
91 12
    }
92
93
    /**
94
     * {@inheritDoc}
95
     */
96
    public function getConcatExpression()
97 69
    {
98
        return sprintf('CONCAT(%s)', implode(', ', func_get_args()));
99 69
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
105 12
    {
106
        $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB';
107 12
108
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
109 12
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114
    public function getDateDiffExpression($date1, $date2)
115 36
    {
116
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
117 36
    }
118
119
    /**
120
     * {@inheritDoc}
121
     */
122
    public function getListDatabasesSQL()
123 93
    {
124
        return 'SHOW DATABASES';
125 93
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130
    public function getListTableConstraintsSQL($table)
131
    {
132
        return 'SHOW INDEX FROM ' . $table;
133
    }
134
135
    /**
136
     * {@inheritDoc}
137
     *
138
     * Two approaches to listing the table indexes. The information_schema is
139
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
140
     */
141
    public function getListTableIndexesSQL($table, $currentDatabase = null)
142 624
    {
143
        if ($currentDatabase) {
144 624
            $currentDatabase = $this->quoteStringLiteral($currentDatabase);
145 624
            $table           = $this->quoteStringLiteral($table);
146 624
147
            return 'SELECT NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, COLUMN_NAME AS Column_Name,' .
148
                   ' SUB_PART AS Sub_Part, INDEX_TYPE AS Index_Type' .
149
                   ' FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table .
150
                   ' AND TABLE_SCHEMA = ' . $currentDatabase .
151
                   ' ORDER BY SEQ_IN_INDEX ASC';
152 624
        }
153
154
        return 'SHOW INDEX FROM ' . $table;
155
    }
156
157
    /**
158
     * {@inheritDoc}
159
     */
160
    public function getListViewsSQL($database)
161 81
    {
162
        $database = $this->quoteStringLiteral($database);
163 81
164
        return 'SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ' . $database;
165 81
    }
166
167
    /**
168
     * {@inheritDoc}
169
     */
170
    public function getListTableForeignKeysSQL($table, $database = null)
171 645
    {
172
        $table = $this->quoteStringLiteral($table);
173 645
174
        if ($database !== null) {
175 645
            $database = $this->quoteStringLiteral($database);
176 576
        }
177
178
        $sql = 'SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ' .
179
               'k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ' .
180
               'FROM information_schema.key_column_usage k /*!50116 ' .
181
               'INNER JOIN information_schema.referential_constraints c ON ' .
182
               '  c.constraint_name = k.constraint_name AND ' .
183
               '  c.table_name = ' . $table . ' */ WHERE k.table_name = ' . $table;
184 645
185
        $databaseNameSql = $database ?? 'DATABASE()';
186 645
187
        $sql .= ' AND k.table_schema = ' . $databaseNameSql . ' /*!50116 AND c.constraint_schema = ' . $databaseNameSql . ' */';
188 645
        $sql .= ' AND k.`REFERENCED_COLUMN_NAME` is not NULL';
189 645
190
        return $sql;
191 645
    }
192
193
    /**
194
     * {@inheritDoc}
195
     */
196
    public function getCreateViewSQL($name, $sql)
197 12
    {
198
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
199 12
    }
200
201
    /**
202
     * {@inheritDoc}
203
     */
204
    public function getDropViewSQL($name)
205 12
    {
206
        return 'DROP VIEW ' . $name;
207 12
    }
208
209
    /**
210
     * {@inheritDoc}
211
     */
212
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
213 1992
    {
214
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
215 1992
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
216 1992
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
222 93
    {
223
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
224 93
    }
225
226
    /**
227
     * Gets the SQL snippet used to declare a CLOB column type.
228
     *     TINYTEXT   : 2 ^  8 - 1 = 255
229
     *     TEXT       : 2 ^ 16 - 1 = 65535
230
     *     MEDIUMTEXT : 2 ^ 24 - 1 = 16777215
231
     *     LONGTEXT   : 2 ^ 32 - 1 = 4294967295
232
     *
233
     * {@inheritDoc}
234
     */
235
    public function getClobTypeDeclarationSQL(array $field)
236 959
    {
237
        if (! empty($field['length']) && is_numeric($field['length'])) {
238 959
            $length = $field['length'];
239 104
240
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
241 104
                return 'TINYTEXT';
242 81
            }
243
244
            if ($length <= static::LENGTH_LIMIT_TEXT) {
245 104
                return 'TEXT';
246 104
            }
247
248
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
249 81
                return 'MEDIUMTEXT';
250 81
            }
251
        }
252
253
        return 'LONGTEXT';
254 936
    }
255
256
    /**
257
     * {@inheritDoc}
258
     */
259
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
260 361
    {
261
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) {
262 361
            return 'TIMESTAMP';
263 69
        }
264
265
        return 'DATETIME';
266 361
    }
267
268
    /**
269
     * {@inheritDoc}
270
     */
271
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
272 232
    {
273
        return 'DATE';
274 232
    }
275
276
    /**
277
     * {@inheritDoc}
278
     */
279
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
280 220
    {
281
        return 'TIME';
282 220
    }
283
284
    /**
285
     * {@inheritDoc}
286
     */
287
    public function getBooleanTypeDeclarationSQL(array $field)
288 249
    {
289
        return 'TINYINT(1)';
290 249
    }
291
292
    /**
293
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
294
     * of a field declaration to be used in statements like CREATE TABLE.
295
     *
296
     * @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
297
     *
298
     * @param string $collation name of the collation
299
     *
300
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
301
     *                 of a field declaration.
302
     */
303
    public function getCollationFieldDeclaration($collation)
304
    {
305
        return $this->getColumnCollationDeclarationSQL($collation);
306
    }
307
308
    /**
309
     * {@inheritDoc}
310
     *
311
     * MySql prefers "autoincrement" identity columns since sequences can only
312
     * be emulated with a table.
313
     */
314
    public function prefersIdentityColumns()
315 81
    {
316
        return true;
317 81
    }
318
319
    /**
320
     * {@inheritDoc}
321
     *
322
     * MySql supports this through AUTO_INCREMENT columns.
323
     */
324
    public function supportsIdentityColumns()
325 105
    {
326
        return true;
327 105
    }
328
329
    /**
330
     * {@inheritDoc}
331
     */
332
    public function supportsInlineColumnComments()
333 4241
    {
334
        return true;
335 4241
    }
336
337
    /**
338
     * {@inheritDoc}
339
     */
340
    public function supportsColumnCollation()
341 219
    {
342
        return true;
343 219
    }
344
345
    /**
346
     * {@inheritDoc}
347
     */
348
    public function getListTablesSQL()
349 906
    {
350
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
351 906
    }
352
353
    /**
354
     * {@inheritDoc}
355
     */
356
    public function getListTableColumnsSQL($table, $database = null)
357 720
    {
358
        $table = $this->quoteStringLiteral($table);
359 720
360
        if ($database) {
361 720
            $database = $this->quoteStringLiteral($database);
362 651
        } else {
363
            $database = 'DATABASE()';
364 69
        }
365
366
        return 'SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ' .
367
               'COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, ' .
368
               'CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ' .
369
               'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $database . ' AND TABLE_NAME = ' . $table .
370 720
               ' ORDER BY ORDINAL_POSITION ASC';
371
    }
372
373 414
    public function getListTableMetadataSQL(string $table, ?string $database = null) : string
374
    {
375 414
        return sprintf(
376
            <<<'SQL'
377 414
SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS
378
FROM information_schema.TABLES
379
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s
380
SQL
381
            ,
382 414
            $database ? $this->quoteStringLiteral($database) : 'DATABASE()',
383 414
            $this->quoteStringLiteral($table)
384
        );
385
    }
386
387
    /**
388
     * {@inheritDoc}
389
     */
390 93
    public function getCreateDatabaseSQL($name)
391
    {
392 93
        return 'CREATE DATABASE ' . $name;
393
    }
394
395
    /**
396
     * {@inheritDoc}
397
     */
398 93
    public function getDropDatabaseSQL($name)
399
    {
400 93
        return 'DROP DATABASE ' . $name;
401
    }
402
403
    /**
404
     * {@inheritDoc}
405
     */
406 2999
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
407
    {
408 2999
        $queryFields = $this->getColumnDeclarationListSQL($columns);
409
410 2999
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
411
            foreach ($options['uniqueConstraints'] as $name => $definition) {
412
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
413
            }
414
        }
415
416
        // add all indexes
417 2999
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
418 664
            foreach ($options['indexes'] as $index => $definition) {
419 664
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
420
            }
421
        }
422
423
        // attach all primary keys
424 2999
        if (isset($options['primary']) && ! empty($options['primary'])) {
425 1569
            $keyColumns   = array_unique(array_values($options['primary']));
426 1569
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
427
        }
428
429 2999
        $query = 'CREATE ';
430
431 2999
        if (! empty($options['temporary'])) {
432
            $query .= 'TEMPORARY ';
433
        }
434
435 2999
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
436 2999
        $query .= $this->buildTableOptions($options);
437 2999
        $query .= $this->buildPartitionOptions($options);
438
439 2999
        $sql    = [$query];
440 2999
        $engine = 'INNODB';
441
442 2999
        if (isset($options['engine'])) {
443 231
            $engine = strtoupper(trim($options['engine']));
444
        }
445
446
        // Propagate foreign key constraints only for InnoDB.
447 2999
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
448 1948
            foreach ((array) $options['foreignKeys'] as $definition) {
449 234
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
450
            }
451
        }
452
453 2999
        return $sql;
454
    }
455
456
    /**
457
     * {@inheritdoc}
458
     */
459 4310
    public function getDefaultValueDeclarationSQL($field)
460
    {
461
        // Unset the default value if the given field definition does not allow default values.
462 4310
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
463 780
            $field['default'] = null;
464
        }
465
466 4310
        return parent::getDefaultValueDeclarationSQL($field);
467
    }
468
469
    /**
470
     * Build SQL for table options
471
     *
472
     * @param mixed[] $options
473
     *
474
     * @return string
475
     */
476 2999
    private function buildTableOptions(array $options)
477
    {
478 2999
        if (isset($options['table_options'])) {
479
            return $options['table_options'];
480
        }
481
482 2999
        $tableOptions = [];
483
484
        // Charset
485 2999
        if (! isset($options['charset'])) {
486 2987
            $options['charset'] = 'utf8';
487
        }
488
489 2999
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
490
491
        // Collate
492 2999
        if (! isset($options['collate'])) {
493 2987
            $options['collate'] = $options['charset'] . '_unicode_ci';
494
        }
495
496 2999
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
497
498
        // Engine
499 2999
        if (! isset($options['engine'])) {
500 2768
            $options['engine'] = 'InnoDB';
501
        }
502
503 2999
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
504
505
        // Auto increment
506 2999
        if (isset($options['auto_increment'])) {
507
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
508
        }
509
510
        // Comment
511 2999
        if (isset($options['comment'])) {
512
            $comment = trim($options['comment'], " '");
513
514
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
515
        }
516
517
        // Row format
518 2999
        if (isset($options['row_format'])) {
519
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
520
        }
521
522 2999
        return implode(' ', $tableOptions);
523
    }
524
525
    /**
526
     * Build SQL for partition options.
527
     *
528
     * @param mixed[] $options
529
     *
530
     * @return string
531
     */
532 2999
    private function buildPartitionOptions(array $options)
533
    {
534 2999
        return isset($options['partition_options'])
535
            ? ' ' . $options['partition_options']
536 2999
            : '';
537
    }
538
539
    /**
540
     * {@inheritDoc}
541
     */
542 2041
    public function getAlterTableSQL(TableDiff $diff)
543
    {
544 2041
        $columnSql  = [];
545 2041
        $queryParts = [];
546 2041
        if ($diff->newName !== false) {
547 138
            $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
548
        }
549
550 2041
        foreach ($diff->addedColumns as $column) {
551 426
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
552
                continue;
553
            }
554
555 426
            $columnArray            = $column->toArray();
556 426
            $columnArray['comment'] = $this->getColumnComment($column);
557 426
            $queryParts[]           = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
558
        }
559
560 2041
        foreach ($diff->removedColumns as $column) {
561 219
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
562
                continue;
563
            }
564
565 219
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
566
        }
567
568 2041
        foreach ($diff->changedColumns as $columnDiff) {
569 681
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
570
                continue;
571
            }
572
573
            $column      = $columnDiff->column;
574 681
            $columnArray = $column->toArray();
575 681
576
            // Don't propagate default value changes for unsupported column types.
577
            if ($columnDiff->hasChanged('default') &&
578 681
                count($columnDiff->changedProperties) === 1 &&
579 681
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
580 681
            ) {
581
                continue;
582 54
            }
583
584
            $columnArray['comment'] = $this->getColumnComment($column);
585 627
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
586 627
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
587 627
        }
588
589
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
590 2041
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
591 288
                continue;
592
            }
593
594
            $oldColumnName          = new Identifier($oldColumnName);
595 288
            $columnArray            = $column->toArray();
596 288
            $columnArray['comment'] = $this->getColumnComment($column);
597 288
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
598 288
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
599 288
        }
600
601
        if (isset($diff->addedIndexes['primary'])) {
602 2041
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
603 254
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
604 254
            unset($diff->addedIndexes['primary']);
605 254
        } elseif (isset($diff->changedIndexes['primary'])) {
606
            // Necessary in case the new primary key includes a new auto_increment column
607
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
608 2041
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
609 2041
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
610
                    $queryParts[] = 'DROP PRIMARY KEY';
611 2041
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
612 2041
                    unset($diff->changedIndexes['primary']);
613 1112
                    break;
614
                }
615 2041
            }
616 2041
        }
617 2041
618 2041
        $sql      = [];
619
        $tableSql = [];
620
621
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
622 2041
            if (count($queryParts) > 0) {
623
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
624
            }
625
            $sql = array_merge(
626
                $this->getPreAlterTableIndexForeignKeySQL($diff),
627
                $sql,
628 2041
                $this->getPostAlterTableIndexForeignKeySQL($diff)
629
            );
630 2041
        }
631 2041
632
        return array_merge($sql, $tableSql, $columnSql);
633 2041
    }
634 392
635
    /**
636
     * {@inheritDoc}
637 2041
     */
638 243
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
639
    {
640 243
        $sql   = [];
641 69
        $table = $diff->getName($this)->getQuotedName($this);
642 69
643
        foreach ($diff->changedIndexes as $changedIndex) {
644 69
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
645
        }
646 69
647 69
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
648
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
649
650 69
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
651 69
                if ($remIndex->getColumns() === $addIndex->getColumns()) {
652 69
                    $indexClause = 'INDEX ' . $addIndex->getName();
653
654 69
                    if ($addIndex->isPrimary()) {
655
                        $indexClause = 'PRIMARY KEY';
656 69
                    } elseif ($addIndex->isUnique()) {
657
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
658 243
                    }
659
660
                    $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
661
                    $query .= 'ADD ' . $indexClause;
662
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
663 2041
664
                    $sql[] = $query;
665 2041
666 93
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
667
668
                    break;
669
                }
670 2041
            }
671 69
        }
672 69
673 69
        $engine = 'INNODB';
674
675
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
676 2041
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
677 2041
        }
678 2041
679 2041
        // Suppress foreign key constraint propagation on non-supporting engines.
680 2041
        if ($engine !== 'INNODB') {
681
            $diff->addedForeignKeys   = [];
682
            $diff->changedForeignKeys = [];
683 2041
            $diff->removedForeignKeys = [];
684
        }
685
686
        $sql = array_merge(
687
            $sql,
688
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
689 623
            parent::getPreAlterTableIndexForeignKeySQL($diff),
690
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
691 623
        );
692
693 623
        return $sql;
694 243
    }
695
696
    /**
697 380
     * @return string[]
698
     */
699
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index)
700 380
    {
701 380
        $sql = [];
702 69
703
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
704
            return $sql;
705 380
        }
706
707 380
        $tableName = $diff->getName($this)->getQuotedName($this);
708 311
709
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
710
        foreach ($index->getColumns() as $columnName) {
711 219
            if (! $diff->fromTable->hasColumn($columnName)) {
712
                continue;
713 219
            }
714 219
715
            $column = $diff->fromTable->getColumn($columnName);
716
717 219
            if ($column->getAutoincrement() !== true) {
718
                continue;
719
            }
720 380
721
            $column->setAutoincrement(false);
722
723
            $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
724
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
725
726
            // original autoincrement information might be needed later on by other parts of the table alteration
727
            $column->setAutoincrement(true);
728 2041
        }
729
730 2041
        return $sql;
731 2041
    }
732
733 2041
    /**
734
     * @param TableDiff $diff The table diff to gather the SQL for.
735 392
     *
736 93
     * @return string[]
737
     */
738
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff)
739 299
    {
740 299
        $sql   = [];
741
        $table = $diff->getName($this)->getQuotedName($this);
742
743 299
        foreach ($diff->changedIndexes as $changedIndex) {
744 230
            // Changed primary key
745
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
746
                continue;
747
            }
748
749 69
            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
750
                $column = $diff->fromTable->getColumn($columnName);
751 69
752 69
                // Check if an autoincrement column was dropped from the primary key.
753
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) {
754
                    continue;
755
                }
756 299
757
                // The autoincrement attribute needs to be removed from the dropped column
758
                // before we can drop and recreate the primary key.
759
                $column->setAutoincrement(false);
760 2041
761
                $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
762
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
763
764
                // Restore the autoincrement attribute as it might be needed later on
765
                // by other parts of the table alteration.
766
                $column->setAutoincrement(true);
767
            }
768 1405
        }
769
770 1405
        return $sql;
771 1405
    }
772
773 1405
    /**
774 56
     * @param TableDiff $diff The table diff to gather the SQL for.
775
     *
776
     * @return string[]
777
     */
778 56
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
779
    {
780
        $sql       = [];
781 1405
        $tableName = $diff->getName($this)->getQuotedName($this);
782
783
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
784
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
785
                continue;
786
            }
787
788
            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
789
        }
790
791
        return $sql;
792
    }
793
794 1405
    /**
795
     * Returns the remaining foreign key constraints that require one of the renamed indexes.
796 1405
     *
797 1165
     * "Remaining" here refers to the diff between the foreign keys currently defined in the associated
798
     * table and the foreign keys to be removed.
799
     *
800 250
     * @param TableDiff $diff The table diff to evaluate.
801
     *
802 250
     * @return ForeignKeyConstraint[]
803 250
     */
804 250
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff)
805
    {
806
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
807 250
            return [];
808 56
        }
809 56
810 56
        $foreignKeys = [];
811
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
812 56
        $remainingForeignKeys = array_diff_key(
813
            $diff->fromTable->getForeignKeys(),
814
            $diff->removedForeignKeys
815
        );
816
817 250
        foreach ($remainingForeignKeys as $foreignKey) {
818
            foreach ($diff->renamedIndexes as $index) {
819
                if ($foreignKey->intersectsIndexColumns($index)) {
820
                    $foreignKeys[] = $foreignKey;
821
822
                    break;
823 2041
                }
824
            }
825 2041
        }
826 2041
827 2041
        return $foreignKeys;
828
    }
829
830
    /**
831
     * {@inheritdoc}
832
     */
833
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
834
    {
835
        return array_merge(
836 1405
            parent::getPostAlterTableIndexForeignKeySQL($diff),
837
            $this->getPostAlterTableRenameIndexForeignKeySQL($diff)
838 1405
        );
839 1405
    }
840 92
841 1405
    /**
842
     * @param TableDiff $diff The table diff to gather the SQL for.
843 1405
     *
844 56
     * @return string[]
845
     */
846
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
847
    {
848 56
        $sql       = [];
849
        $tableName = $diff->newName !== false
850
            ? $diff->getNewName()->getQuotedName($this)
851 1405
            : $diff->getName($this)->getQuotedName($this);
852
853
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
854
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
855
                continue;
856
            }
857 1251
858
            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
859 1251
        }
860 1251
861 267
        return $sql;
862 1020
    }
863 81
864 939
    /**
865 81
     * {@inheritDoc}
866
     */
867
    protected function getCreateIndexSQLFlags(Index $index)
868 1251
    {
869
        $type = '';
870
        if ($index->isUnique()) {
871
            $type .= 'UNIQUE ';
872
        } elseif ($index->hasFlag('fulltext')) {
873
            $type .= 'FULLTEXT ';
874 3039
        } elseif ($index->hasFlag('spatial')) {
875
            $type .= 'SPATIAL ';
876 3039
        }
877
878
        return $type;
879
    }
880
881
    /**
882 180
     * {@inheritDoc}
883
     */
884 180
    public function getIntegerTypeDeclarationSQL(array $field)
885
    {
886
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
887
    }
888
889
    /**
890 12
     * {@inheritDoc}
891
     */
892 12
    public function getBigIntTypeDeclarationSQL(array $field)
893
    {
894
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
895
    }
896
897
    /**
898 606
     * {@inheritDoc}
899
     */
900 606
    public function getSmallIntTypeDeclarationSQL(array $field)
901
    {
902
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
903
    }
904
905
    /**
906 654
     * {@inheritdoc}
907
     */
908 654
    public function getFloatDeclarationSQL(array $field)
909
    {
910
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($field);
911
    }
912
913
    /**
914
     * {@inheritdoc}
915
     */
916
    public function getDecimalTypeDeclarationSQL(array $columnDef)
917
    {
918 3891
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
919
    }
920 3891
921
    /**
922
     * Get unsigned declaration for a column.
923
     *
924
     * @param mixed[] $columnDef
925
     *
926 3039
     * @return string
927
     */
928 3039
    private function getUnsignedDeclaration(array $columnDef)
929 3039
    {
930 471
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
931
    }
932
933 3039
    /**
934
     * {@inheritDoc}
935
     */
936
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
937
    {
938
        $autoinc = '';
939 615
        if (! empty($columnDef['autoincrement'])) {
940
            $autoinc = ' AUTO_INCREMENT';
941 615
        }
942 615
943
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
944
    }
945 615
946
    /**
947 615
     * {@inheritDoc}
948
     */
949
    public function getColumnCharsetDeclarationSQL($charset)
950
    {
951
        return 'CHARACTER SET ' . $charset;
952
    }
953 806
954
    /**
955 806
     * {@inheritDoc}
956 554
     */
957 262
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
958 262
    {
959
        $query = '';
960
        if ($foreignKey->hasOption('match')) {
961
            $query .= ' MATCH ' . $foreignKey->getOption('match');
962
        }
963 806
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
964 12
965 794
        return $query;
966
    }
967
968
    /**
969 806
     * {@inheritDoc}
970
     */
971
    public function getDropIndexSQL($index, $table = null)
972 449
    {
973
        if ($index instanceof Index) {
974
            $indexName = $index->getQuotedName($this);
975 357
        } elseif (is_string($index)) {
976
            $indexName = $index;
977
        } else {
978
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
979
        }
980
981
        if ($table instanceof Table) {
982
            $table = $table->getQuotedName($this);
983 449
        } elseif (! is_string($table)) {
984
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
985 449
        }
986
987
        if ($index instanceof Index && $index->isPrimary()) {
988
            // mysql primary keys are always named "PRIMARY",
989
            // so we cannot use them in statements because of them being keyword.
990
            return $this->getDropPrimaryKeySQL($table);
991 69
        }
992
993 69
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
994
    }
995
996
    /**
997
     * @param string $table
998
     *
999 1200
     * @return string
1000
     */
1001 1200
    protected function getDropPrimaryKeySQL($table)
1002
    {
1003
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
1004
    }
1005
1006
    /**
1007
     * {@inheritDoc}
1008
     */
1009
    public function getSetTransactionIsolationSQL($level)
1010
    {
1011
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
1012
    }
1013
1014
    /**
1015 415
     * {@inheritDoc}
1016
     */
1017 415
    public function getName()
1018
    {
1019
        return 'mysql';
1020
    }
1021
1022
    /**
1023
     * {@inheritDoc}
1024
     */
1025
    public function getReadLockSQL()
1026
    {
1027
        return 'LOCK IN SHARE MODE';
1028
    }
1029
1030
    /**
1031
     * {@inheritDoc}
1032
     */
1033
    protected function initializeDoctrineTypeMappings()
1034
    {
1035
        $this->doctrineTypeMapping = [
1036
            'bigint'     => 'bigint',
1037
            'binary'     => 'binary',
1038
            'blob'       => 'blob',
1039
            'char'       => 'string',
1040
            'date'       => 'date',
1041
            'datetime'   => 'datetime',
1042
            'decimal'    => 'decimal',
1043
            'double'     => 'float',
1044
            'float'      => 'float',
1045
            'int'        => 'integer',
1046
            'integer'    => 'integer',
1047
            'longblob'   => 'blob',
1048
            'longtext'   => 'text',
1049 415
            'mediumblob' => 'blob',
1050
            'mediumint'  => 'integer',
1051
            'mediumtext' => 'text',
1052
            'numeric'    => 'decimal',
1053
            'real'       => 'float',
1054 1992
            'set'        => 'simple_array',
1055
            'smallint'   => 'smallint',
1056 1992
            'string'     => 'string',
1057
            'text'       => 'text',
1058
            'time'       => 'time',
1059
            'timestamp'  => 'datetime',
1060
            'tinyblob'   => 'blob',
1061
            'tinyint'    => 'boolean',
1062 69
            'tinytext'   => 'text',
1063
            'varbinary'  => 'binary',
1064 69
            'varchar'    => 'string',
1065
            'year'       => 'date',
1066
        ];
1067
    }
1068
1069
    /**
1070 1526
     * {@inheritDoc}
1071
     */
1072 1526
    public function getVarcharMaxLength()
1073
    {
1074
        return 65535;
1075
    }
1076
1077
    /**
1078
     * {@inheritdoc}
1079
     */
1080
    public function getBinaryMaxLength()
1081 24
    {
1082
        return 65535;
1083 24
    }
1084
1085 24
    /**
1086
     * {@inheritDoc}
1087
     */
1088
    protected function getReservedKeywordsClass()
1089 24
    {
1090
        return Keywords\MySQLKeywords::class;
1091
    }
1092
1093
    /**
1094
     * {@inheritDoc}
1095
     *
1096
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
1097
     * if DROP TEMPORARY TABLE is executed.
1098
     */
1099
    public function getDropTemporaryTableSQL($table)
1100
    {
1101 231
        if ($table instanceof Table) {
1102
            $table = $table->getQuotedName($this);
1103 231
        } elseif (! is_string($table)) {
1104 93
            throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1105
        }
1106 93
1107 81
        return 'DROP TEMPORARY TABLE ' . $table;
1108
    }
1109
1110 93
    /**
1111 81
     * Gets the SQL Snippet used to declare a BLOB column type.
1112
     *     TINYBLOB   : 2 ^  8 - 1 = 255
1113
     *     BLOB       : 2 ^ 16 - 1 = 65535
1114 93
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
1115 81
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
1116
     *
1117
     * {@inheritDoc}
1118
     */
1119 231
    public function getBlobTypeDeclarationSQL(array $field)
1120
    {
1121
        if (! empty($field['length']) && is_numeric($field['length'])) {
1122
            $length = $field['length'];
1123
1124
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1125 2355
                return 'TINYBLOB';
1126
            }
1127 2355
1128
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1129 2355
                return 'BLOB';
1130
            }
1131
1132
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1133
                return 'MEDIUMBLOB';
1134
            }
1135 23
        }
1136
1137 23
        return 'LONGBLOB';
1138
    }
1139
1140
    /**
1141
     * {@inheritdoc}
1142
     */
1143 3101
    public function quoteStringLiteral($str)
1144
    {
1145 3101
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1146
1147
        return parent::quoteStringLiteral($str);
1148
    }
1149
1150
    /**
1151
     * {@inheritdoc}
1152
     */
1153
    public function getDefaultTransactionIsolationLevel()
1154
    {
1155
        return TransactionIsolationLevel::REPEATABLE_READ;
1156
    }
1157
1158
    /**
1159
     * {@inheritdoc}
1160
     */
1161
    public function supportsColumnLengthIndexes() : bool
1162
    {
1163
        return true;
1164
    }
1165
}
1166