Completed
Pull Request — develop (#3348)
by Sergei
65:02
created

getDefaultTransactionIsolationLevel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
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
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
290 10160
     * of a field declaration to be used in statements like CREATE TABLE.
291
     *
292
     * @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
293
     *
294
     * @param string $collation name of the collation
295
     *
296
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
297
     *                 of a field declaration.
298
     */
299
    public function getCollationFieldDeclaration(string $collation) : string
300
    {
301
        return $this->getColumnCollationDeclarationSQL($collation);
302
    }
303
304
    /**
305
     * {@inheritDoc}
306
     *
307
     * MySql prefers "autoincrement" identity columns since sequences can only
308
     * be emulated with a table.
309
     */
310
    public function prefersIdentityColumns() : bool
311
    {
312
        return true;
313
    }
314
315 8006
    /**
316
     * {@inheritDoc}
317 8006
     *
318
     * MySql supports this through AUTO_INCREMENT columns.
319
     */
320
    public function supportsIdentityColumns() : bool
321
    {
322
        return true;
323
    }
324
325 9610
    /**
326
     * {@inheritDoc}
327 9610
     */
328
    public function supportsInlineColumnComments() : bool
329
    {
330
        return true;
331
    }
332
333 12651
    /**
334
     * {@inheritDoc}
335 12651
     */
336
    public function supportsColumnCollation() : bool
337
    {
338
        return true;
339
    }
340
341 10021
    /**
342
     * {@inheritDoc}
343 10021
     */
344
    public function getListTablesSQL() : string
345
    {
346
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
347
    }
348
349 9409
    /**
350
     * {@inheritDoc}
351 9409
     */
352
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
353
    {
354
        return 'SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ' .
355
               'COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, ' .
356
               'CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ' .
357 10641
               'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $this->getDatabaseNameSql($database) . ' ' .
358
               'AND TABLE_NAME = ' . $this->quoteStringLiteral($table) . ' ORDER BY ORDINAL_POSITION';
359 10641
    }
360
361 10641
    public function getListTableMetadataSQL(string $table, ?string $database = null) : string
362 10630
    {
363
        return sprintf(
364 7056
            <<<'SQL'
365
SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS
366
FROM information_schema.TABLES
367
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s
368
SQL
369
            ,
370 10641
            $database ? $this->quoteStringLiteral($database) : 'DATABASE()',
371 10641
            $this->quoteStringLiteral($table)
372
        );
373
    }
374 9219
375
    /**
376 9219
     * {@inheritDoc}
377
     */
378
    public function getCreateDatabaseSQL(string $database) : string
379
    {
380
        return 'CREATE DATABASE ' . $database;
381
    }
382
383 9219
    /**
384 9219
     * {@inheritDoc}
385
     */
386
    public function getDropDatabaseSQL(string $database) : string
387
    {
388
        return 'DROP DATABASE ' . $database;
389
    }
390
391 12460
    /**
392
     * {@inheritDoc}
393 12460
     */
394
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
395
    {
396
        $queryFields = $this->getColumnDeclarationListSQL($columns);
397
398
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
399 12460
            foreach ($options['uniqueConstraints'] as $name => $definition) {
400
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
401 12460
            }
402
        }
403
404
        // add all indexes
405
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
406
            foreach ($options['indexes'] as $index => $definition) {
407 12543
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
408
            }
409 12543
        }
410
411 12543
        // attach all primary keys
412
        if (isset($options['primary']) && ! empty($options['primary'])) {
413
            $keyColumns   = array_unique(array_values($options['primary']));
414
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
415
        }
416
417
        $query = 'CREATE ';
418 12543
419 11529
        if (! empty($options['temporary'])) {
420 11529
            $query .= 'TEMPORARY ';
421
        }
422
423
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
424
        $query .= $this->buildTableOptions($options);
425 12543
        $query .= $this->buildPartitionOptions($options);
426 12354
427 12354
        $sql    = [$query];
428
        $engine = 'INNODB';
429
430 12543
        if (isset($options['engine'])) {
431
            $engine = strtoupper(trim($options['engine']));
432 12543
        }
433
434
        // Propagate foreign key constraints only for InnoDB.
435
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
436 12543
            foreach ((array) $options['foreignKeys'] as $definition) {
437 12543
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
438 12543
            }
439
        }
440 12543
441 12543
        return $sql;
442
    }
443 12543
444 10317
    /**
445
     * {@inheritdoc}
446
     */
447
    public function getDefaultValueDeclarationSQL(array $field) : string
448 12543
    {
449 12336
        // Unset the default value if the given field definition does not allow default values.
450 11436
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
451
            $field['default'] = null;
452
        }
453
454 12543
        return parent::getDefaultValueDeclarationSQL($field);
455
    }
456
457
    /**
458
     * Build SQL for table options
459
     *
460 12657
     * @param mixed[] $options
461
     */
462
    private function buildTableOptions(array $options) : string
463 12657
    {
464 12405
        if (isset($options['table_options'])) {
465
            return $options['table_options'];
466
        }
467 12657
468
        $tableOptions = [];
469
470
        // Charset
471
        if (! isset($options['charset'])) {
472
            $options['charset'] = 'utf8';
473
        }
474
475
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
476
477 12543
        // Collate
478
        if (! isset($options['collate'])) {
479 12543
            $options['collate'] = $options['charset'] . '_unicode_ci';
480
        }
481
482
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
483 12543
484
        // Engine
485
        if (! isset($options['engine'])) {
486 12543
            $options['engine'] = 'InnoDB';
487 12543
        }
488
489
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
490 12543
491
        // Auto increment
492
        if (isset($options['auto_increment'])) {
493 12543
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
494 12543
        }
495
496
        // Comment
497 12543
        if (isset($options['comment'])) {
498
            $comment = trim($options['comment'], " '");
499
500 12543
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
501 12525
        }
502
503
        // Row format
504 12543
        if (isset($options['row_format'])) {
505
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
506
        }
507 12543
508
        return implode(' ', $tableOptions);
509
    }
510
511
    /**
512 12543
     * Build SQL for partition options.
513
     *
514
     * @param mixed[] $options
515
     */
516
    private function buildPartitionOptions(array $options) : string
517
    {
518
        return isset($options['partition_options'])
519 12543
            ? ' ' . $options['partition_options']
520
            : '';
521
    }
522
523 12543
    /**
524
     * {@inheritDoc}
525
     */
526
    public function getAlterTableSQL(TableDiff $diff) : array
527
    {
528
        $columnSql  = [];
529
        $queryParts = [];
530
        $newName    = $diff->getNewName();
531
532
        if ($newName !== false) {
533 12543
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
534
        }
535 12543
536
        foreach ($diff->addedColumns as $column) {
537 12543
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
538
                continue;
539
            }
540
541
            $columnArray            = $column->toArray();
542
            $columnArray['comment'] = $this->getColumnComment($column);
543 10907
            $queryParts[]           = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
544
        }
545 10907
546 10907
        foreach ($diff->removedColumns as $column) {
547 10907
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
548
                continue;
549 10907
            }
550 6537
551
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
552
        }
553 10907
554 10725
        foreach ($diff->changedColumns as $columnDiff) {
555
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
556
                continue;
557
            }
558 10725
559 10725
            $column      = $columnDiff->column;
560 10725
            $columnArray = $column->toArray();
561
562
            // Don't propagate default value changes for unsupported column types.
563 10907
            if ($columnDiff->hasChanged('default') &&
564 9432
                count($columnDiff->changedProperties) === 1 &&
565
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
566
            ) {
567
                continue;
568 9432
            }
569
570
            $columnArray['comment'] = $this->getColumnComment($column);
571 10907
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
572 10036
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
573
        }
574
575
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
576 10036
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
577 10036
                continue;
578
            }
579
580 10036
            $oldColumnName          = new Identifier($oldColumnName);
581 10036
            $columnArray            = $column->toArray();
582 10036
            $columnArray['comment'] = $this->getColumnComment($column);
583
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
584 8633
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
585
        }
586
587 10000
        if (isset($diff->addedIndexes['primary'])) {
588 10000
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
589 10000
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
590
            unset($diff->addedIndexes['primary']);
591
        } elseif (isset($diff->changedIndexes['primary'])) {
592 10907
            // Necessary in case the new primary key includes a new auto_increment column
593 9348
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
594
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
595
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
596
                    $queryParts[] = 'DROP PRIMARY KEY';
597 9348
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
598 9348
                    unset($diff->changedIndexes['primary']);
599 9348
                    break;
600 9348
                }
601 9348
            }
602
        }
603
604 10907
        $sql      = [];
605 10379
        $tableSql = [];
606 10379
607 10379
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
608 10872
            if (count($queryParts) > 0) {
609
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
610 10735
            }
611 10735
            $sql = array_merge(
612 9219
                $this->getPreAlterTableIndexForeignKeySQL($diff),
613 9219
                $sql,
614 9219
                $this->getPostAlterTableIndexForeignKeySQL($diff)
615 9219
            );
616 9245
        }
617
618
        return array_merge($sql, $tableSql, $columnSql);
619
    }
620
621 10907
    /**
622 10907
     * {@inheritDoc}
623
     */
624 10907
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
625 10907
    {
626 10829
        $sql   = [];
627
        $table = $diff->getName($this)->getQuotedName($this);
628 10907
629 10907
        foreach ($diff->changedIndexes as $changedIndex) {
630 10907
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
631 10907
        }
632
633
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
634
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
635 10907
636
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
637
                if ($remIndex->getColumns() === $addIndex->getColumns()) {
638
                    $indexClause = 'INDEX ' . $addIndex->getName();
639
640
                    if ($addIndex->isPrimary()) {
641 10907
                        $indexClause = 'PRIMARY KEY';
642
                    } elseif ($addIndex->isUnique()) {
643 10907
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
644 10907
                    }
645
646 10907
                    $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
647 9631
                    $query .= 'ADD ' . $indexClause;
648
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
649
650 10907
                    $sql[] = $query;
651 10262
652
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
653 10262
654 7581
                    break;
655 7581
                }
656
            }
657 7581
        }
658
659 7581
        $engine = 'INNODB';
660 7581
661
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
662
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
663 7581
        }
664 7581
665 7581
        // Suppress foreign key constraint propagation on non-supporting engines.
666
        if ($engine !== 'INNODB') {
667 7581
            $diff->addedForeignKeys   = [];
668
            $diff->changedForeignKeys = [];
669 7581
            $diff->removedForeignKeys = [];
670
        }
671 7593
672
        $sql = array_merge(
673
            $sql,
674
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
675
            parent::getPreAlterTableIndexForeignKeySQL($diff),
676 10907
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
677
        );
678 10907
679 10275
        return $sql;
680
    }
681
682
    /**
683 10907
     * @return string[]
684 7206
     */
685 7206
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index) : array
686 7206
    {
687
        $sql = [];
688
689 10907
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
690 10907
            return $sql;
691 10907
        }
692 10907
693 10907
        $tableName = $diff->getName($this)->getQuotedName($this);
694
695
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
696 10907
        foreach ($index->getColumns() as $columnName) {
697
            if (! $diff->fromTable->hasColumn($columnName)) {
698
                continue;
699
            }
700
701
            $column = $diff->fromTable->getColumn($columnName);
702 10294
703
            if (! $column->getAutoincrement()) {
704 10294
                continue;
705
            }
706 10294
707 10262
            $column->setAutoincrement(false);
708
709
            $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
710 10231
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
711
712
            // original autoincrement information might be needed later on by other parts of the table alteration
713 10231
            $column->setAutoincrement(true);
714 10231
        }
715 7306
716
        return $sql;
717
    }
718 10231
719
    /**
720 10231
     * @param TableDiff $diff The table diff to gather the SQL for.
721 10225
     *
722
     * @return string[]
723
     */
724 10212
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff) : array
725
    {
726 10212
        $sql   = [];
727 10212
        $table = $diff->getName($this)->getQuotedName($this);
728
729
        foreach ($diff->changedIndexes as $changedIndex) {
730 10212
            // Changed primary key
731
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
732
                continue;
733 10231
            }
734
735
            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
736
                $column = $diff->fromTable->getColumn($columnName);
737
738
                // Check if an autoincrement column was dropped from the primary key.
739
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) {
740
                    continue;
741 10907
                }
742
743 10907
                // The autoincrement attribute needs to be removed from the dropped column
744 10907
                // before we can drop and recreate the primary key.
745
                $column->setAutoincrement(false);
746 10907
747
                $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
748 9631
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
749 9580
750
                // Restore the autoincrement attribute as it might be needed later on
751
                // by other parts of the table alteration.
752 7476
                $column->setAutoincrement(true);
753 7476
            }
754
        }
755
756 7476
        return $sql;
757 7420
    }
758
759
    /**
760
     * @param TableDiff $diff The table diff to gather the SQL for.
761
     *
762 7456
     * @return string[]
763
     */
764 7456
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
765 7456
    {
766
        $sql       = [];
767
        $tableName = $diff->getName($this)->getQuotedName($this);
768
769 7476
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
770
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
771
                continue;
772
            }
773 10907
774
            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
775
        }
776
777
        return $sql;
778
    }
779
780
    /**
781 9597
     * Returns the remaining foreign key constraints that require one of the renamed indexes.
782
     *
783 9597
     * "Remaining" here refers to the diff between the foreign keys currently defined in the associated
784 9597
     * table and the foreign keys to be removed.
785
     *
786 9597
     * @param TableDiff $diff The table diff to evaluate.
787 7744
     *
788
     * @return ForeignKeyConstraint[]
789
     */
790
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff) : array
791 7744
    {
792
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
793
            return [];
794 9597
        }
795
796
        $foreignKeys = [];
797
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
798
        $remainingForeignKeys = array_diff_key(
799
            $diff->fromTable->getForeignKeys(),
800
            $diff->removedForeignKeys
801
        );
802
803
        foreach ($remainingForeignKeys as $foreignKey) {
804
            foreach ($diff->renamedIndexes as $index) {
805
                if ($foreignKey->intersectsIndexColumns($index)) {
806
                    $foreignKeys[] = $foreignKey;
807 9597
808
                    break;
809 9597
                }
810 9577
            }
811
        }
812
813 8028
        return $foreignKeys;
814
    }
815 8028
816 8028
    /**
817 8028
     * {@inheritdoc}
818
     */
819
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
820 8028
    {
821 7744
        return array_merge(
822 7744
            parent::getPostAlterTableIndexForeignKeySQL($diff),
823 7744
            $this->getPostAlterTableRenameIndexForeignKeySQL($diff)
824
        );
825 7744
    }
826
827
    /**
828
     * @param TableDiff $diff The table diff to gather the SQL for.
829
     *
830 8028
     * @return string[]
831
     */
832
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
833
    {
834
        $sql     = [];
835
        $newName = $diff->getNewName();
836 10907
837
        if ($newName !== false) {
838 10907
            $tableName = $newName->getQuotedName($this);
839 10907
        } else {
840 10907
            $tableName = $diff->getName($this)->getQuotedName($this);
841
        }
842
843
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
844
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
845
                continue;
846
            }
847
848
            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
849 9597
        }
850
851 9597
        return $sql;
852 9597
    }
853
854 9597
    /**
855 6533
     * {@inheritDoc}
856
     */
857 9589
    protected function getCreateIndexSQLFlags(Index $index) : string
858
    {
859
        $type = '';
860 9597
        if ($index->isUnique()) {
861 7744
            $type .= 'UNIQUE ';
862
        } elseif ($index->hasFlag('fulltext')) {
863
            $type .= 'FULLTEXT ';
864
        } elseif ($index->hasFlag('spatial')) {
865 7744
            $type .= 'SPATIAL ';
866
        }
867
868 9597
        return $type;
869
    }
870
871
    /**
872
     * {@inheritDoc}
873
     */
874 11599
    public function getIntegerTypeDeclarationSQL(array $columnDef) : string
875
    {
876 11599
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
877 11599
    }
878 11387
879 11561
    /**
880 10305
     * {@inheritDoc}
881 11550
     */
882 10280
    public function getBigIntTypeDeclarationSQL(array $columnDef) : string
883
    {
884
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
885 11599
    }
886
887
    /**
888
     * {@inheritDoc}
889
     */
890
    public function getSmallIntTypeDeclarationSQL(array $columnDef) : string
891 12563
    {
892
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
893 12563
    }
894
895
    /**
896
     * {@inheritdoc}
897
     */
898
    public function getFloatDeclarationSQL(array $fieldDeclaration) : string
899 6973
    {
900
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($fieldDeclaration);
901 6973
    }
902
903
    /**
904
     * {@inheritdoc}
905
     */
906
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
907 7929
    {
908
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
909 7929
    }
910
911
    /**
912
     * Get unsigned declaration for a column.
913
     *
914
     * @param mixed[] $columnDef
915 9674
     */
916
    private function getUnsignedDeclaration(array $columnDef) : string
917 9674
    {
918
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
919
    }
920
921
    /**
922
     * {@inheritDoc}
923 9719
     */
924
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string
925 9719
    {
926
        $autoinc = '';
927
        if (! empty($columnDef['autoincrement'])) {
928
            $autoinc = ' AUTO_INCREMENT';
929
        }
930
931
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
932
    }
933
934
    /**
935 12635
     * {@inheritDoc}
936
     */
937 12635
    public function getColumnCharsetDeclarationSQL(string $charset) : string
938
    {
939
        return 'CHARACTER SET ' . $charset;
940
    }
941
942
    /**
943 12563
     * {@inheritDoc}
944
     */
945 12563
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
946 12563
    {
947 11127
        $query = '';
948
        if ($foreignKey->hasOption('match')) {
949
            $query .= ' MATCH ' . $foreignKey->getOption('match');
950 12563
        }
951
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
952
953
        return $query;
954
    }
955
956 10074
    /**
957
     * {@inheritDoc}
958 10074
     */
959
    public function getDropIndexSQL($index, $table = null) : string
960
    {
961
        if ($index instanceof Index) {
962
            $indexName = $index->getQuotedName($this);
963
        } elseif (is_string($index)) {
964 11466
            $indexName = $index;
965
        } else {
966 11466
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
967 11466
        }
968
969
        if ($table instanceof Table) {
970 11466
            $table = $table->getQuotedName($this);
971
        } elseif (! is_string($table)) {
972 11466
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
973
        }
974
975
        if ($index instanceof Index && $index->isPrimary()) {
976
            // mysql primary keys are always named "PRIMARY",
977
            // so we cannot use them in statements because of them being keyword.
978 10288
            return $this->getDropPrimaryKeySQL($table);
979
        }
980 10288
981 10268
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
982 9424
    }
983 9424
984
    protected function getDropPrimaryKeySQL(string $table) : string
985
    {
986
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
987
    }
988 10288
989 8189
    /**
990 10288
     * {@inheritDoc}
991
     */
992
    public function getSetTransactionIsolationSQL(int $level) : string
993
    {
994 10288
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
995
    }
996
997 10237
    /**
998
     * {@inheritDoc}
999
     */
1000 10250
    public function getName() : string
1001
    {
1002
        return 'mysql';
1003
    }
1004
1005
    /**
1006
     * {@inheritDoc}
1007
     */
1008 10237
    public function getReadLockSQL() : string
1009
    {
1010 10237
        return 'LOCK IN SHARE MODE';
1011
    }
1012
1013
    /**
1014
     * {@inheritDoc}
1015
     */
1016 7806
    protected function initializeDoctrineTypeMappings() : void
1017
    {
1018 7806
        $this->doctrineTypeMapping = [
1019
            'bigint'     => 'bigint',
1020
            'binary'     => 'binary',
1021
            'blob'       => 'blob',
1022
            'char'       => 'string',
1023
            'date'       => 'date',
1024 12146
            'datetime'   => 'datetime',
1025
            'decimal'    => 'decimal',
1026 12146
            'double'     => 'float',
1027
            'float'      => 'float',
1028
            'int'        => 'integer',
1029
            'integer'    => 'integer',
1030
            'longblob'   => 'blob',
1031
            'longtext'   => 'text',
1032
            'mediumblob' => 'blob',
1033
            'mediumint'  => 'integer',
1034
            'mediumtext' => 'text',
1035
            'numeric'    => 'decimal',
1036
            'real'       => 'float',
1037
            'set'        => 'simple_array',
1038
            'smallint'   => 'smallint',
1039
            'string'     => 'string',
1040 10833
            'text'       => 'text',
1041
            'time'       => 'time',
1042 10833
            'timestamp'  => 'datetime',
1043
            'tinyblob'   => 'blob',
1044
            'tinyint'    => 'boolean',
1045
            'tinytext'   => 'text',
1046
            'varbinary'  => 'binary',
1047
            'varchar'    => 'string',
1048
            'year'       => 'date',
1049
        ];
1050
    }
1051
1052
    /**
1053
     * {@inheritDoc}
1054
     */
1055
    public function getVarcharMaxLength() : int
1056
    {
1057
        return 65535;
1058
    }
1059
1060
    /**
1061
     * {@inheritdoc}
1062
     */
1063
    public function getBinaryMaxLength() : int
1064
    {
1065
        return 65535;
1066
    }
1067
1068
    /**
1069
     * {@inheritDoc}
1070
     */
1071
    protected function getReservedKeywordsClass() : string
1072
    {
1073
        return Keywords\MySQLKeywords::class;
1074 10833
    }
1075
1076
    /**
1077
     * {@inheritDoc}
1078
     *
1079 12360
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
1080
     * if DROP TEMPORARY TABLE is executed.
1081 12360
     */
1082
    public function getDropTemporaryTableSQL($table) : string
1083
    {
1084
        if ($table instanceof Table) {
1085
            $table = $table->getQuotedName($this);
1086
        } elseif (! is_string($table)) {
1087 6081
            throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1088
        }
1089 6081
1090
        return 'DROP TEMPORARY TABLE ' . $table;
1091
    }
1092
1093
    /**
1094
     * Gets the SQL Snippet used to declare a BLOB column type.
1095 6354
     *     TINYBLOB   : 2 ^  8 - 1 = 255
1096
     *     BLOB       : 2 ^ 16 - 1 = 65535
1097 6354
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
1098
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
1099
     *
1100
     * {@inheritDoc}
1101
     */
1102
    public function getBlobTypeDeclarationSQL(array $field) : string
1103
    {
1104
        if (! empty($field['length']) && is_numeric($field['length'])) {
1105
            $length = $field['length'];
1106 7013
1107
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1108 7013
                return 'TINYBLOB';
1109
            }
1110 7013
1111
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1112
                return 'BLOB';
1113
            }
1114 7013
1115
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1116
                return 'MEDIUMBLOB';
1117
            }
1118
        }
1119
1120
        return 'LONGBLOB';
1121
    }
1122
1123
    /**
1124
     * {@inheritdoc}
1125
     */
1126 12384
    public function quoteStringLiteral(string $str) : string
1127
    {
1128 12384
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1129 10094
1130
        return parent::quoteStringLiteral($str);
1131 10094
    }
1132 10094
1133
    /**
1134
     * {@inheritdoc}
1135 10094
     */
1136 10094
    public function getDefaultTransactionIsolationLevel() : int
1137
    {
1138
        return TransactionIsolationLevel::REPEATABLE_READ;
1139 10094
    }
1140 10094
1141
    /**
1142
     * {@inheritdoc}
1143
     */
1144 12384
    public function supportsColumnLengthIndexes() : bool
1145
    {
1146
        return true;
1147
    }
1148
1149
    /**
1150 10775
     * Returns an SQL expression representing the given database name or current database name
1151
     *
1152 10775
     * @param string|null $database Database name
1153
     */
1154 10775
    private function getDatabaseNameSql(?string $database) : string
1155
    {
1156
        if ($database === null) {
1157
            return 'DATABASE()';
1158
        }
1159
1160 2827
        return $this->quoteStringLiteral($database);
1161
    }
1162
}
1163