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

MySqlPlatform::supportsColumnLengthIndexes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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