Passed
Pull Request — develop (#3453)
by Evgeniy
19:01
created

MySqlPlatform::getReadLockSQL()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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