Completed
Pull Request — master (#3772)
by Christoph
51:54
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 8989
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
51
    {
52 8989
        if ($limit !== null) {
53 8891
            $query .= ' LIMIT ' . $limit;
54
55 8891
            if ($offset > 0) {
56 8891
                $query .= ' OFFSET ' . $offset;
57
            }
58 8971
        } elseif ($offset > 0) {
59
            // 2^64-1 is the maximum of unsigned BIGINT, the biggest limit possible
60 8962
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
61
        }
62
63 8989
        return $query;
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69 10148
    public function getIdentifierQuoteCharacter() : string
70
    {
71 10148
        return '`';
72
    }
73
74
    /**
75
     * {@inheritDoc}
76
     */
77 6817
    public function getRegexpExpression() : string
78
    {
79 6817
        return 'RLIKE';
80
    }
81
82
    /**
83
     * {@inheritDoc}
84
     */
85 6259
    public function getLocateExpression(string $string, string $substring, ?string $start = null) : string
86
    {
87 6259
        if ($start === null) {
88 6259
            return sprintf('LOCATE(%s, %s)', $substring, $string);
89
        }
90
91 6259
        return sprintf('LOCATE(%s, %s, %s)', $substring, $string, $start);
92
    }
93
94
    /**
95
     * {@inheritDoc}
96
     */
97 6817
    public function getConcatExpression(string ...$string) : string
98
    {
99 6817
        return sprintf('CONCAT(%s)', implode(', ', $string));
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105 6675
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
106
    {
107 6675
        $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB';
108
109 6675
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
110
    }
111
112
    /**
113
     * {@inheritDoc}
114
     */
115 5778
    public function getDateDiffExpression(string $date1, string $date2) : string
116
    {
117 5778
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
118
    }
119
120
    /**
121
     * {@inheritDoc}
122
     */
123 6339
    public function getCurrentDatabaseExpression() : string
124
    {
125 6339
        return 'DATABASE()';
126
    }
127
128
    /**
129
     * {@inheritDoc}
130
     */
131 8079
    public function getListDatabasesSQL() : string
132
    {
133 8079
        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 8477
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
151
    {
152 8477
        if ($currentDatabase) {
153 8477
            $currentDatabase = $this->quoteStringLiteral($currentDatabase);
154 8477
            $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 8477
                   ' FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table .
159 8477
                   ' AND TABLE_SCHEMA = ' . $currentDatabase .
160 8477
                   ' ORDER BY SEQ_IN_INDEX ASC';
161
        }
162
163
        return 'SHOW INDEX FROM ' . $table;
164
    }
165
166
    /**
167
     * {@inheritDoc}
168
     */
169 7667
    public function getListViewsSQL(string $database) : string
170
    {
171 7667
        return 'SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ' . $this->quoteStringLiteral($database);
172
    }
173
174
    /**
175
     * {@inheritDoc}
176
     */
177 8466
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
178
    {
179 8466
        $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 8466
               '  c.table_name = ' . $table . ' */ WHERE k.table_name = ' . $table;
187
188 8466
        $databaseNameSql = $this->getDatabaseNameSql($database);
189
190 8466
        $sql .= ' AND k.table_schema = ' . $databaseNameSql . ' /*!50116 AND c.constraint_schema = ' . $databaseNameSql . ' */';
191 8466
        $sql .= ' AND k.`REFERENCED_COLUMN_NAME` is not NULL';
192
193 8466
        return $sql;
194
    }
195
196
    /**
197
     * {@inheritDoc}
198
     */
199 4948
    public function getCreateViewSQL(string $name, string $sql) : string
200
    {
201 4948
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
202
    }
203
204
    /**
205
     * {@inheritDoc}
206
     */
207 4948
    public function getDropViewSQL(string $name) : string
208
    {
209 4948
        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 9733
    public function getClobTypeDeclarationSQL(array $field) : string
222
    {
223 9733
        if (! empty($field['length']) && is_numeric($field['length'])) {
224 8139
            $length = $field['length'];
225
226 8139
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
227 8136
                return 'TINYTEXT';
228
            }
229
230 8139
            if ($length <= static::LENGTH_LIMIT_TEXT) {
231 8139
                return 'TEXT';
232
            }
233
234 8136
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
235 8136
                return 'MEDIUMTEXT';
236
            }
237
        }
238
239 9730
        return 'LONGTEXT';
240
    }
241
242
    /**
243
     * {@inheritDoc}
244
     */
245 9600
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
246
    {
247 9600
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) {
248 6656
            return 'TIMESTAMP';
249
        }
250
251 9600
        return 'DATETIME';
252
    }
253
254
    /**
255
     * {@inheritDoc}
256
     */
257 5199
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
258
    {
259 5199
        return 'DATE';
260
    }
261
262
    /**
263
     * {@inheritDoc}
264
     */
265 5123
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
266
    {
267 5123
        return 'TIME';
268
    }
269
270
    /**
271
     * {@inheritDoc}
272
     */
273 7963
    public function getBooleanTypeDeclarationSQL(array $columnDef) : string
274
    {
275 7963
        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 6907
    public function prefersIdentityColumns() : bool
285
    {
286 6907
        return true;
287
    }
288
289
    /**
290
     * {@inheritDoc}
291
     *
292
     * MySql supports this through AUTO_INCREMENT columns.
293
     */
294 4944
    public function supportsIdentityColumns() : bool
295
    {
296 4944
        return true;
297
    }
298
299
    /**
300
     * {@inheritDoc}
301
     */
302 10091
    public function supportsInlineColumnComments() : bool
303
    {
304 10091
        return true;
305
    }
306
307
    /**
308
     * {@inheritDoc}
309
     */
310 6081
    public function supportsColumnCollation() : bool
311
    {
312 6081
        return true;
313
    }
314
315
    /**
316
     * {@inheritDoc}
317
     */
318 5876
    public function getListTablesSQL() : string
319
    {
320 5876
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
321
    }
322
323
    /**
324
     * {@inheritDoc}
325
     */
326 8437
    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 8437
               'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $this->getDatabaseNameSql($database) . ' ' .
332 8437
               'AND TABLE_NAME = ' . $this->quoteStringLiteral($table) . ' ORDER BY ORDINAL_POSITION';
333
    }
334
335 5739
    public function getListTableMetadataSQL(string $table, ?string $database = null) : string
336
    {
337 5739
        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 5739
            $database ? $this->quoteStringLiteral($database) : 'DATABASE()',
345 5739
            $this->quoteStringLiteral($table)
346
        );
347
    }
348
349
    /**
350
     * {@inheritDoc}
351
     */
352 9780
    public function getCreateDatabaseSQL(string $database) : string
353
    {
354 9780
        return 'CREATE DATABASE ' . $database;
355
    }
356
357
    /**
358
     * {@inheritDoc}
359
     */
360 9780
    public function getDropDatabaseSQL(string $database) : string
361
    {
362 9780
        return 'DROP DATABASE ' . $database;
363
    }
364
365
    /**
366
     * {@inheritDoc}
367
     */
368 9929
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
369
    {
370 9929
        $queryFields = $this->getColumnDeclarationListSQL($columns);
371
372 9929
        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 9929
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
380 9137
            foreach ($options['indexes'] as $index => $definition) {
381 9137
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
382
            }
383
        }
384
385
        // attach all primary keys
386 9929
        if (isset($options['primary']) && ! empty($options['primary'])) {
387 9603
            $keyColumns   = array_unique(array_values($options['primary']));
388 9603
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
389
        }
390
391 9929
        $query = 'CREATE ';
392
393 9929
        if (! empty($options['temporary'])) {
394
            $query .= 'TEMPORARY ';
395
        }
396
397 9929
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
398 9929
        $query .= $this->buildTableOptions($options);
399 9929
        $query .= $this->buildPartitionOptions($options);
400
401 9929
        $sql    = [$query];
402 9929
        $engine = 'INNODB';
403
404 9929
        if (isset($options['engine'])) {
405 8300
            $engine = strtoupper(trim($options['engine']));
406
        }
407
408
        // Propagate foreign key constraints only for InnoDB.
409 9929
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
410 9576
            foreach ((array) $options['foreignKeys'] as $definition) {
411 8965
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
412
            }
413
        }
414
415 9929
        return $sql;
416
    }
417
418
    /**
419
     * {@inheritdoc}
420
     */
421 10100
    public function getDefaultValueDeclarationSQL(array $field) : string
422
    {
423
        // Unset the default value if the given field definition does not allow default values.
424 10100
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
425 9712
            $field['default'] = null;
426
        }
427
428 10100
        return parent::getDefaultValueDeclarationSQL($field);
429
    }
430
431
    /**
432
     * Build SQL for table options
433
     *
434
     * @param mixed[] $options
435
     */
436 9929
    private function buildTableOptions(array $options) : string
437
    {
438 9929
        if (isset($options['table_options'])) {
439
            return $options['table_options'];
440
        }
441
442 9929
        $tableOptions = [];
443
444
        // Charset
445 9929
        if (! isset($options['charset'])) {
446 9929
            $options['charset'] = 'utf8';
447
        }
448
449 9929
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
450
451
        // Collate
452 9929
        if (! isset($options['collate'])) {
453 9929
            $options['collate'] = $options['charset'] . '_unicode_ci';
454
        }
455
456 9929
        $tableOptions[] = $this->getColumnCollationDeclarationSQL($options['collate']);
457
458
        // Engine
459 9929
        if (! isset($options['engine'])) {
460 9902
            $options['engine'] = 'InnoDB';
461
        }
462
463 9929
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
464
465
        // Auto increment
466 9929
        if (isset($options['auto_increment'])) {
467
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
468
        }
469
470
        // Comment
471 9929
        if (isset($options['comment'])) {
472 4592
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($options['comment']));
473
        }
474
475
        // Row format
476 9929
        if (isset($options['row_format'])) {
477
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
478
        }
479
480 9929
        return implode(' ', $tableOptions);
481
    }
482
483
    /**
484
     * Build SQL for partition options.
485
     *
486
     * @param mixed[] $options
487
     */
488 9929
    private function buildPartitionOptions(array $options) : string
489
    {
490 9929
        return isset($options['partition_options'])
491
            ? ' ' . $options['partition_options']
492 9929
            : '';
493
    }
494
495
    /**
496
     * {@inheritDoc}
497
     */
498 8886
    public function getAlterTableSQL(TableDiff $diff) : array
499
    {
500 8886
        $columnSql  = [];
501 8886
        $queryParts = [];
502 8886
        $newName    = $diff->getNewName();
503
504 8886
        if ($newName !== null) {
505 5699
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
506
        }
507
508 8886
        foreach ($diff->addedColumns as $column) {
509 8583
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
510
                continue;
511
            }
512
513 8583
            $columnArray            = $column->toArray();
514 8583
            $columnArray['comment'] = $this->getColumnComment($column);
515 8583
            $queryParts[]           = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
516
        }
517
518 8886
        foreach ($diff->removedColumns as $column) {
519 7458
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
520
                continue;
521
            }
522
523 7458
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
524
        }
525
526 8886
        foreach ($diff->changedColumns as $columnDiff) {
527 7873
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
528
                continue;
529
            }
530
531 7873
            $column      = $columnDiff->column;
532 7873
            $columnArray = $column->toArray();
533
534
            // Don't propagate default value changes for unsupported column types.
535 7873
            if ($columnDiff->hasChanged('default') &&
536 7873
                count($columnDiff->changedProperties) === 1 &&
537 7873
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
538
            ) {
539 6182
                continue;
540
            }
541
542 7849
            $columnArray['comment'] = $this->getColumnComment($column);
543 7849
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
544 7849
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
545
        }
546
547 8886
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
548 7395
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
549
                continue;
550
            }
551
552 7395
            $oldColumnName          = new Identifier($oldColumnName);
553 7395
            $columnArray            = $column->toArray();
554 7395
            $columnArray['comment'] = $this->getColumnComment($column);
555 7395
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
556 7395
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
557
        }
558
559 8886
        if (isset($diff->addedIndexes['primary'])) {
560 8356
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
561 8356
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
562 8356
            unset($diff->addedIndexes['primary']);
563 8826
        } elseif (isset($diff->changedIndexes['primary'])) {
564
            // Necessary in case the new primary key includes a new auto_increment column
565 8608
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
566 8608
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
567 5739
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
568 5739
                    $queryParts[] = 'DROP PRIMARY KEY';
569 5739
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
570 5739
                    unset($diff->changedIndexes['primary']);
571 5739
                    break;
572
                }
573
            }
574
        }
575
576 8886
        $sql      = [];
577 8886
        $tableSql = [];
578
579 8886
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
580 8886
            if (count($queryParts) > 0) {
581 8769
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
582
            }
583 8886
            $sql = array_merge(
584 8886
                $this->getPreAlterTableIndexForeignKeySQL($diff),
585 8886
                $sql,
586 8886
                $this->getPostAlterTableIndexForeignKeySQL($diff)
587
            );
588
        }
589
590 8886
        return array_merge($sql, $tableSql, $columnSql);
591
    }
592
593
    /**
594
     * {@inheritDoc}
595
     */
596 8886
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
597
    {
598 8886
        $sql   = [];
599 8886
        $table = $diff->getName($this)->getQuotedName($this);
600
601 8886
        foreach ($diff->changedIndexes as $changedIndex) {
602 7839
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
603
        }
604
605 8886
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
606 8271
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
607
608 8271
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
609 6633
                if ($remIndex->getColumns() === $addIndex->getColumns()) {
610 6633
                    $indexClause = 'INDEX ' . $addIndex->getName();
611
612 6633
                    if ($addIndex->isPrimary()) {
613
                        $indexClause = 'PRIMARY KEY';
614 6633
                    } elseif ($addIndex->isUnique()) {
615 6633
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
616
                    }
617
618 6633
                    $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
619 6633
                    $query .= 'ADD ' . $indexClause;
620 6633
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
621
622 6633
                    $sql[] = $query;
623
624 6633
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
625
626 6633
                    break;
627
                }
628
            }
629
        }
630
631 8886
        $engine = 'INNODB';
632
633 8886
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
634 8155
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
635
        }
636
637
        // Suppress foreign key constraint propagation on non-supporting engines.
638 8886
        if ($engine !== 'INNODB') {
639 6288
            $diff->addedForeignKeys   = [];
640 6288
            $diff->changedForeignKeys = [];
641 6288
            $diff->removedForeignKeys = [];
642
        }
643
644 8886
        $sql = array_merge(
645 8886
            $sql,
646 8886
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
647 8886
            parent::getPreAlterTableIndexForeignKeySQL($diff),
648 8886
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
649
        );
650
651 8886
        return $sql;
652
    }
653
654
    /**
655
     * @return string[]
656
     */
657 8319
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index) : array
658
    {
659 8319
        $sql = [];
660
661 8319
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
662 8271
            return $sql;
663
        }
664
665 8229
        $tableName = $diff->getName($this)->getQuotedName($this);
666
667
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
668 8229
        foreach ($index->getColumns() as $columnName) {
669 8229
            if (! $diff->fromTable->hasColumn($columnName)) {
670 6380
                continue;
671
            }
672
673 8229
            $column = $diff->fromTable->getColumn($columnName);
674
675 8229
            if (! $column->getAutoincrement()) {
676 8220
                continue;
677
            }
678
679 8198
            $column->setAutoincrement(false);
680
681 8198
            $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
682 8198
                $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 8198
            $column->setAutoincrement(true);
686
        }
687
688 8229
        return $sql;
689
    }
690
691
    /**
692
     * @param TableDiff $diff The table diff to gather the SQL for.
693
     *
694
     * @return string[]
695
     */
696 8886
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff) : array
697
    {
698 8886
        $sql   = [];
699 8886
        $table = $diff->getName($this)->getQuotedName($this);
700
701 8886
        foreach ($diff->changedIndexes as $changedIndex) {
702
            // Changed primary key
703 7839
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
704 7750
                continue;
705
            }
706
707 6548
            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
708 6548
                $column = $diff->fromTable->getColumn($columnName);
709
710
                // Check if an autoincrement column was dropped from the primary key.
711 6548
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) {
712 6493
                    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 6518
                $column->setAutoincrement(false);
718
719 6518
                $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
720 6518
                    $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 6518
                $column->setAutoincrement(true);
725
            }
726
        }
727
728 8886
        return $sql;
729
    }
730
731
    /**
732
     * @param TableDiff $diff The table diff to gather the SQL for.
733
     *
734
     * @return string[]
735
     */
736 8049
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
737
    {
738 8049
        $sql       = [];
739 8049
        $tableName = $diff->getName($this)->getQuotedName($this);
740
741 8049
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
742 6228
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
743
                continue;
744
            }
745
746 6228
            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
747
        }
748
749 8049
        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 8049
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff) : array
763
    {
764 8049
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
765 8019
            return [];
766
        }
767
768 6517
        $foreignKeys = [];
769
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
770 6517
        $remainingForeignKeys = array_diff_key(
771 6517
            $diff->fromTable->getForeignKeys(),
772 6517
            $diff->removedForeignKeys
773
        );
774
775 6517
        foreach ($remainingForeignKeys as $foreignKey) {
776 6228
            foreach ($diff->renamedIndexes as $index) {
777 6228
                if ($foreignKey->intersectsIndexColumns($index)) {
778 6228
                    $foreignKeys[] = $foreignKey;
779
780 6228
                    break;
781
                }
782
            }
783
        }
784
785 6517
        return $foreignKeys;
786
    }
787
788
    /**
789
     * {@inheritdoc}
790
     */
791 8886
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
792
    {
793 8886
        return array_merge(
794 8886
            parent::getPostAlterTableIndexForeignKeySQL($diff),
795 8886
            $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 8049
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
805
    {
806 8049
        $sql     = [];
807 8049
        $newName = $diff->getNewName();
808
809 8049
        if ($newName !== null) {
810 5693
            $tableName = $newName->getQuotedName($this);
811
        } else {
812 8037
            $tableName = $diff->getName($this)->getQuotedName($this);
813
        }
814
815 8049
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
816 6228
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
817
                continue;
818
            }
819
820 6228
            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
821
        }
822
823 8049
        return $sql;
824
    }
825
826
    /**
827
     * {@inheritDoc}
828
     */
829 9252
    protected function getCreateIndexSQLFlags(Index $index) : string
830
    {
831 9252
        $type = '';
832 9252
        if ($index->isUnique()) {
833 9053
            $type .= 'UNIQUE ';
834 9185
        } elseif ($index->hasFlag('fulltext')) {
835 8282
            $type .= 'FULLTEXT ';
836 9166
        } elseif ($index->hasFlag('spatial')) {
837 8259
            $type .= 'SPATIAL ';
838
        }
839
840 9252
        return $type;
841
    }
842
843
    /**
844
     * {@inheritDoc}
845
     */
846 9959
    public function getIntegerTypeDeclarationSQL(array $columnDef) : string
847
    {
848 9959
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
849
    }
850
851
    /**
852
     * {@inheritDoc}
853
     */
854 4281
    public function getBigIntTypeDeclarationSQL(array $columnDef) : string
855
    {
856 4281
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
857
    }
858
859
    /**
860
     * {@inheritDoc}
861
     */
862 4844
    public function getSmallIntTypeDeclarationSQL(array $columnDef) : string
863
    {
864 4844
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
865
    }
866
867
    /**
868
     * {@inheritdoc}
869
     */
870 7372
    public function getFloatDeclarationSQL(array $fieldDeclaration) : string
871
    {
872 7372
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($fieldDeclaration);
873
    }
874
875
    /**
876
     * {@inheritdoc}
877
     */
878 7435
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
879
    {
880 7435
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
881
    }
882
883
    /**
884
     * Get unsigned declaration for a column.
885
     *
886
     * @param mixed[] $columnDef
887
     */
888 10067
    private function getUnsignedDeclaration(array $columnDef) : string
889
    {
890 10067
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
891
    }
892
893
    /**
894
     * {@inheritDoc}
895
     */
896 9959
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string
897
    {
898 9959
        $autoinc = '';
899 9959
        if (! empty($columnDef['autoincrement'])) {
900 8930
            $autoinc = ' AUTO_INCREMENT';
901
        }
902
903 9959
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
904
    }
905
906
    /**
907
     * {@inheritDoc}
908
     */
909 7988
    public function getColumnCharsetDeclarationSQL(string $charset) : string
910
    {
911 7988
        return 'CHARACTER SET ' . $charset;
912
    }
913
914
    /**
915
     * {@inheritDoc}
916
     */
917 9938
    public function getColumnCollationDeclarationSQL(string $collation) : string
918
    {
919 9938
        return 'COLLATE ' . $this->quoteSingleIdentifier($collation);
920
    }
921
922
    /**
923
     * {@inheritDoc}
924
     */
925 9010
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
926
    {
927 9010
        $query = '';
928 9010
        if ($foreignKey->hasOption('match')) {
929
            $query .= ' MATCH ' . $foreignKey->getOption('match');
930
        }
931 9010
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
932
933 9010
        return $query;
934
    }
935
936
    /**
937
     * {@inheritDoc}
938
     */
939 8300
    public function getDropIndexSQL($index, $table = null) : string
940
    {
941 8300
        if ($index instanceof Index) {
942 8270
            $indexName = $index->getQuotedName($this);
943 7333
        } elseif (is_string($index)) {
944 7333
            $indexName = $index;
945
        } else {
946
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
947
        }
948
949 8300
        if ($table instanceof Table) {
950 5013
            $table = $table->getQuotedName($this);
951 8300
        } elseif (! is_string($table)) {
952
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
953
        }
954
955 8300
        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 8238
            return $this->getDropPrimaryKeySQL($table);
959
        }
960
961 8243
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
962
    }
963
964 8238
    protected function getDropPrimaryKeySQL(string $table) : string
965
    {
966 8238
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
967
    }
968
969
    /**
970
     * {@inheritDoc}
971
     */
972 6794
    public function getSetTransactionIsolationSQL(int $level) : string
973
    {
974 6794
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
975
    }
976
977
    /**
978
     * {@inheritDoc}
979
     */
980 9526
    public function getName() : string
981
    {
982 9526
        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 8780
    protected function initializeDoctrineTypeMappings() : void
997
    {
998 8780
        $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 8780
    }
1031
1032
    /**
1033
     * {@inheritDoc}
1034
     */
1035 4307
    protected function getReservedKeywordsClass() : string
1036
    {
1037 4307
        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 4307
    public function getDropTemporaryTableSQL($table) : string
1047
    {
1048 4307
        if ($table instanceof Table) {
1049
            $table = $table->getQuotedName($this);
1050 4307
        } elseif (! is_string($table)) {
1051
            throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1052
        }
1053
1054 4307
        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 8603
    public function getBlobTypeDeclarationSQL(array $field) : string
1067
    {
1068 8603
        if (! empty($field['length']) && is_numeric($field['length'])) {
1069 5286
            $length = $field['length'];
1070
1071 5286
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1072 5286
                return 'TINYBLOB';
1073
            }
1074
1075 5286
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1076 5286
                return 'BLOB';
1077
            }
1078
1079 5286
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1080 5286
                return 'MEDIUMBLOB';
1081
            }
1082
        }
1083
1084 8603
        return 'LONGBLOB';
1085
    }
1086
1087
    /**
1088
     * {@inheritdoc}
1089
     */
1090 8666
    public function quoteStringLiteral(string $str) : string
1091
    {
1092 8666
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1093
1094 8666
        return parent::quoteStringLiteral($str);
1095
    }
1096
1097
    /**
1098
     * {@inheritdoc}
1099
     */
1100 2487
    public function getDefaultTransactionIsolationLevel() : int
1101
    {
1102 2487
        return TransactionIsolationLevel::REPEATABLE_READ;
1103
    }
1104
1105
    /**
1106
     * {@inheritdoc}
1107
     */
1108 9965
    public function supportsColumnLengthIndexes() : bool
1109
    {
1110 9965
        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 8484
    private function getDatabaseNameSql(?string $database) : string
1119
    {
1120 8484
        if ($database === null) {
1121 6237
            return 'DATABASE()';
1122
        }
1123
1124 8456
        return $this->quoteStringLiteral($database);
1125
    }
1126
}
1127