Completed
Pull Request — develop (#3348)
by Sergei
62:37
created

MySqlPlatform::getDatabaseNameSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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