Completed
Push — master ( 1a9812...b70610 )
by Sergei
19s queued 14s
created

getPreAlterTableIndexForeignKeySQL()   B

Complexity

Conditions 10
Paths 48

Size

Total Lines 56
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 10.0027

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 56
ccs 32
cts 33
cp 0.9697
rs 7.6666
c 0
b 0
f 0
cc 10
nc 48
nop 1
crap 10.0027

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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