Completed
Push — master ( 217999...8c0bf7 )
by Sergei
27s queued 12s
created

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