Completed
Pull Request — master (#3365)
by Benjamin
21:11
created

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