Completed
Pull Request — master (#2412)
by Benoît
20:29
created

MySqlPlatform::supportsColumnLengthIndexes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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