MySqlPlatform.php 33.9 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\Connection;
23
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
24 25
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
26
use Doctrine\DBAL\Schema\TableDiff;
27 28
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\TextType;
29
use Doctrine\DBAL\Types\Type;
30

31 32
/**
 * The MySqlPlatform provides the behavior, features and SQL dialect of the
33 34
 * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that
 * uses the InnoDB storage engine.
35
 *
Benjamin Morel's avatar
Benjamin Morel committed
36
 * @since  2.0
37
 * @author Roman Borschel <roman@code-factory.org>
38
 * @author Benjamin Eberlei <kontakt@beberlei.de>
Benjamin Morel's avatar
Benjamin Morel committed
39
 * @todo   Rename: MySQLPlatform
40
 */
41
class MySqlPlatform extends AbstractPlatform
42
{
43 44 45 46 47 48 49 50
    const LENGTH_LIMIT_TINYTEXT   = 255;
    const LENGTH_LIMIT_TEXT       = 65535;
    const LENGTH_LIMIT_MEDIUMTEXT = 16777215;

    const LENGTH_LIMIT_TINYBLOB   = 255;
    const LENGTH_LIMIT_BLOB       = 65535;
    const LENGTH_LIMIT_MEDIUMBLOB = 16777215;

51 52 53
    /**
     * Adds MySQL-specific LIMIT clause to the query
     * 18446744073709551615 is 2^64-1 maximum of unsigned BIGINT the biggest limit possible
54 55 56 57 58 59
     *
     * @param string  $query
     * @param integer $limit
     * @param integer $offset
     *
     * @return string
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
        if ($limit !== null) {
            $query .= ' LIMIT ' . $limit;
            if ($offset !== null) {
                $query .= ' OFFSET ' . $offset;
            }
        } elseif ($offset !== null) {
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
        }

        return $query;
    }

romanb's avatar
romanb committed
75
    /**
76
     * {@inheritDoc}
romanb's avatar
romanb committed
77 78 79 80
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
81
    }
82

83
    /**
84
     * {@inheritDoc}
85 86 87 88 89 90 91
     */
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }

    /**
92
     * {@inheritDoc}
93 94 95 96 97 98
     */
    public function getGuidExpression()
    {
        return 'UUID()';
    }

99
    /**
100
     * {@inheritDoc}
101 102 103 104 105 106
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
107 108

        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
109 110
    }

111
    /**
112
     * {@inheritDoc}
113 114 115 116
     */
    public function getConcatExpression()
    {
        $args = func_get_args();
117

118 119
        return 'CONCAT(' . join(', ', (array) $args) . ')';
    }
120

121
    /**
122
     * {@inheritdoc}
123
     */
124
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
125
    {
126
        $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB';
127

128
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
129 130
    }

131 132 133
    /**
     * {@inheritDoc}
     */
134
    public function getDateDiffExpression($date1, $date2)
135
    {
136
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
137
    }
138

Benjamin Morel's avatar
Benjamin Morel committed
139 140 141
    /**
     * {@inheritDoc}
     */
142
    public function getListDatabasesSQL()
143 144 145 146
    {
        return 'SHOW DATABASES';
    }

Benjamin Morel's avatar
Benjamin Morel committed
147 148 149
    /**
     * {@inheritDoc}
     */
150
    public function getListTableConstraintsSQL($table)
151
    {
152
        return 'SHOW INDEX FROM ' . $table;
153 154
    }

155
    /**
156 157
     * {@inheritDoc}
     *
158
     * Two approaches to listing the table indexes. The information_schema is
Pascal Borreli's avatar
Pascal Borreli committed
159
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
160 161
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
162
    {
163
        if ($currentDatabase) {
164 165 166
            $currentDatabase = $this->quoteStringLiteral($currentDatabase);
            $table = $this->quoteStringLiteral($table);

167 168 169
            return "SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ".
                   "SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ".
                   "CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, " .
170
                   "NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment " .
171
                   "FROM information_schema.STATISTICS WHERE TABLE_NAME = " . $table . " AND TABLE_SCHEMA = " . $currentDatabase;
172
        }
173 174

        return 'SHOW INDEX FROM ' . $table;
175 176
    }

Benjamin Morel's avatar
Benjamin Morel committed
177 178 179
    /**
     * {@inheritDoc}
     */
180
    public function getListViewsSQL($database)
181
    {
182 183 184
        $database = $this->quoteStringLiteral($database);

        return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = " . $database;
185 186
    }

Benjamin Morel's avatar
Benjamin Morel committed
187 188 189
    /**
     * {@inheritDoc}
     */
190
    public function getListTableForeignKeysSQL($table, $database = null)
191
    {
192 193 194 195 196 197
        $table = $this->quoteStringLiteral($table);

        if (null !== $database) {
            $database = $this->quoteStringLiteral($database);
        }

198 199 200
        $sql = "SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ".
               "k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ".
               "FROM information_schema.key_column_usage k /*!50116 ".
201
               "INNER JOIN information_schema.referential_constraints c ON ".
202
               "  c.constraint_name = k.constraint_name AND ".
203
               "  c.table_name = $table */ WHERE k.table_name = $table";
204

Steve Müller's avatar
Steve Müller committed
205
        $databaseNameSql = null === $database ? 'DATABASE()' : $database;
206

207
        $sql .= " AND k.table_schema = $databaseNameSql /*!50116 AND c.constraint_schema = $databaseNameSql */";
208
        $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL";
209 210 211 212

        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
213 214 215
    /**
     * {@inheritDoc}
     */
216
    public function getCreateViewSQL($name, $sql)
217 218 219 220
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
221 222 223
    /**
     * {@inheritDoc}
     */
224
    public function getDropViewSQL($name)
225 226 227 228
    {
        return 'DROP VIEW '. $name;
    }

229
    /**
230
     * {@inheritDoc}
231
     */
232
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
233 234
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
235
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
236
    }
237

Steve Müller's avatar
Steve Müller committed
238 239 240 241 242 243 244 245
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
    }

246
    /**
247 248 249 250 251 252 253 254 255
     * Gets the SQL snippet used to declare a CLOB column type.
     *     TINYTEXT   : 2 ^  8 - 1 = 255
     *     TEXT       : 2 ^ 16 - 1 = 65535
     *     MEDIUMTEXT : 2 ^ 24 - 1 = 16777215
     *     LONGTEXT   : 2 ^ 32 - 1 = 4294967295
     *
     * @param array $field
     *
     * @return string
256
     */
257
    public function getClobTypeDeclarationSQL(array $field)
258
    {
259
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
260
            $length = $field['length'];
261

262
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
263
                return 'TINYTEXT';
264 265
            }

266
            if ($length <= static::LENGTH_LIMIT_TEXT) {
267
                return 'TEXT';
268 269
            }

270
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
271 272 273
                return 'MEDIUMTEXT';
            }
        }
274

275 276
        return 'LONGTEXT';
    }
277

278
    /**
279
     * {@inheritDoc}
280
     */
281
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
282
    {
283
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
284 285
            return 'TIMESTAMP';
        }
286 287

        return 'DATETIME';
288
    }
289

290
    /**
291
     * {@inheritDoc}
292
     */
293
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
294 295 296
    {
        return 'DATE';
    }
297

298
    /**
299
     * {@inheritDoc}
300
     */
301
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
302 303
    {
        return 'TIME';
304
    }
305

306
    /**
307
     * {@inheritDoc}
308
     */
309
    public function getBooleanTypeDeclarationSQL(array $field)
310 311 312 313
    {
        return 'TINYINT(1)';
    }

314 315 316 317
    /**
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
     * of a field declaration to be used in statements like CREATE TABLE.
     *
318 319
     * @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
     *
320
     * @param string $collation name of the collation
321
     *
322 323 324 325 326
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
     *                 of a field declaration.
     */
    public function getCollationFieldDeclaration($collation)
    {
327
        return $this->getColumnCollationDeclarationSQL($collation);
328
    }
329

330
    /**
331 332
     * {@inheritDoc}
     *
333 334 335 336 337 338 339
     * MySql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
     */
    public function prefersIdentityColumns()
    {
        return true;
    }
340

romanb's avatar
romanb committed
341
    /**
342
     * {@inheritDoc}
romanb's avatar
romanb committed
343
     *
344
     * MySql supports this through AUTO_INCREMENT columns.
romanb's avatar
romanb committed
345 346 347 348
     */
    public function supportsIdentityColumns()
    {
        return true;
349 350
    }

351 352 353
    /**
     * {@inheritDoc}
     */
354 355 356
    public function supportsInlineColumnComments()
    {
        return true;
romanb's avatar
romanb committed
357
    }
358

Benjamin Morel's avatar
Benjamin Morel committed
359 360 361
    /**
     * {@inheritDoc}
     */
362 363 364 365 366
    public function supportsColumnCollation()
    {
        return true;
    }

367 368 369
    /**
     * {@inheritDoc}
     */
370
    public function getListTablesSQL()
371
    {
372
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
373
    }
374

Benjamin Morel's avatar
Benjamin Morel committed
375 376 377
    /**
     * {@inheritDoc}
     */
378
    public function getListTableColumnsSQL($table, $database = null)
379
    {
380 381
        $table = $this->quoteStringLiteral($table);

382
        if ($database) {
383
            $database = $this->quoteStringLiteral($database);
384 385
        } else {
            $database = 'DATABASE()';
386
        }
387

388 389 390
        return "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ".
               "COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, " .
               "CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ".
391
               "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = " . $database . " AND TABLE_NAME = " . $table;
392 393
    }

394
    /**
395
     * {@inheritDoc}
396
     */
397
    public function getCreateDatabaseSQL($name)
398
    {
399
        return 'CREATE DATABASE ' . $name;
400
    }
401

402
    /**
403
     * {@inheritDoc}
404
     */
405
    public function getDropDatabaseSQL($name)
406
    {
407
        return 'DROP DATABASE ' . $name;
408
    }
409

410
    /**
411
     * {@inheritDoc}
412
     */
413
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
414
    {
415
        $queryFields = $this->getColumnDeclarationListSQL($columns);
416

417
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
418
            foreach ($options['uniqueConstraints'] as $index => $definition) {
419
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($index, $definition);
420
            }
421 422 423 424
        }

        // add all indexes
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Steve Müller's avatar
Steve Müller committed
425
            foreach ($options['indexes'] as $index => $definition) {
426
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
427 428 429 430 431
            }
        }

        // attach all primary keys
        if (isset($options['primary']) && ! empty($options['primary'])) {
432
            $keyColumns = array_unique(array_values($options['primary']));
433 434 435 436
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

        $query = 'CREATE ';
437

438 439 440
        if (!empty($options['temporary'])) {
            $query .= 'TEMPORARY ';
        }
441

442
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
443 444
        $query .= $this->buildTableOptions($options);
        $query .= $this->buildPartitionOptions($options);
445

446 447
        $sql[]  = $query;
        $engine = 'INNODB';
448

449 450 451 452 453 454
        if (isset($options['engine'])) {
            $engine = strtoupper(trim($options['engine']));
        }

        // Propagate foreign key constraints only for InnoDB.
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
455 456 457 458
            foreach ((array) $options['foreignKeys'] as $definition) {
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }
459

460 461 462
        return $sql;
    }

463 464 465 466 467 468
    /**
     * Tells whether a field type supports declaration of a default value.
     *
     * MySQL (as of 5.7.19) does not support default values for Blob and Text
     * columns while MariaDB 10.2.1 does.
     */
469
    protected function isDefaultValueSupportedForType(Type $field) : bool
470
    {
471
        return ! $field instanceof TextType && ! $field instanceof BlobType;
472 473
    }

474 475 476 477 478
    /**
     * {@inheritdoc}
     */
    public function getDefaultValueDeclarationSQL($field)
    {
479
        // Unset the default value if the given field type does not allow default values.
480
        if (! $this->isDefaultValueSupportedForType($field['type'])) {
481 482 483 484 485 486
            $field['default'] = null;
        }

        return parent::getDefaultValueDeclarationSQL($field);
    }

487 488 489 490 491 492 493 494 495 496 497
    /**
     * Build SQL for table options
     *
     * @param array $options
     *
     * @return string
     */
    private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
498
        }
499

500
        $tableOptions = [];
501 502

        // Charset
503 504
        if ( ! isset($options['charset'])) {
            $options['charset'] = 'utf8';
505 506
        }

507 508 509
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);

        // Collate
510
        if ( ! isset($options['collate'])) {
511
            $options['collate'] = 'utf8_unicode_ci';
512
        }
513

514
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
515

516
        // Engine
517 518
        if ( ! isset($options['engine'])) {
            $options['engine'] = 'InnoDB';
519
        }
520

521
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
522

523 524 525
        // Auto increment
        if (isset($options['auto_increment'])) {
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
526
        }
527

528 529 530 531
        // Comment
        if (isset($options['comment'])) {
            $comment = trim($options['comment'], " '");

532
            $tableOptions[] = sprintf("COMMENT = %s ", $this->quoteStringLiteral($comment));
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        }

        // Row format
        if (isset($options['row_format'])) {
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
        }

        return implode(' ', $tableOptions);
    }

    /**
     * Build SQL for partition options.
     *
     * @param array $options
     *
     * @return string
     */
    private function buildPartitionOptions(array $options)
    {
        return (isset($options['partition_options']))
553
            ? ' ' . $options['partition_options']
554
            : '';
555
    }
556

557
    /**
558
     * {@inheritDoc}
559
     */
560
    public function getAlterTableSQL(TableDiff $diff)
561
    {
562 563
        $columnSql = [];
        $queryParts = [];
564
        if ($diff->newName !== false) {
565
            $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
566 567
        }

568
        foreach ($diff->addedColumns as $column) {
569 570
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
571 572
            }

573 574 575
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
576 577
        }

578
        foreach ($diff->removedColumns as $column) {
579 580
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
581 582
            }

583
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
584 585
        }

586
        foreach ($diff->changedColumns as $columnDiff) {
587 588
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
589 590
            }

591
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
592
            $column = $columnDiff->column;
593
            $columnArray = $column->toArray();
594 595 596 597

            // Don't propagate default value changes for unsupported column types.
            if ($columnDiff->hasChanged('default') &&
                count($columnDiff->changedProperties) === 1 &&
598
                ! $this->isDefaultValueSupportedForType($columnArray['type'])
599 600 601 602
            ) {
                continue;
            }

603
            $columnArray['comment'] = $this->getColumnComment($column);
604
            $queryParts[] =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
605
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
606 607
        }

608
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
609 610
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
611 612
            }

613
            $oldColumnName = new Identifier($oldColumnName);
614 615
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
616
            $queryParts[] =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
617
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
618 619
        }

620 621 622 623 624 625
        if (isset($diff->addedIndexes['primary'])) {
            $keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
            unset($diff->addedIndexes['primary']);
        }

626 627
        $sql = [];
        $tableSql = [];
628

629
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
630
            if (count($queryParts) > 0) {
631
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(", ", $queryParts);
632 633 634 635 636 637
            }
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
638
        }
639 640

        return array_merge($sql, $tableSql, $columnSql);
641
    }
642

643
    /**
644
     * {@inheritDoc}
645 646 647
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
648
        $sql = [];
649
        $table = $diff->getName($this)->getQuotedName($this);
650

651 652 653
        foreach ($diff->changedIndexes as $changedIndex) {
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
        }
andig's avatar
andig committed
654

655 656
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
657 658 659 660

            foreach ($diff->addedIndexes as $addKey => $addIndex) {
                if ($remIndex->getColumns() == $addIndex->getColumns()) {

661 662 663 664 665 666
                    $indexClause = 'INDEX ' . $addIndex->getName();

                    if ($addIndex->isPrimary()) {
                        $indexClause = 'PRIMARY KEY';
                    } elseif ($addIndex->isUnique()) {
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
667 668 669
                    }

                    $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
670
                    $query .= 'ADD ' . $indexClause;
671
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')';
672 673 674 675 676 677 678 679 680 681 682

                    $sql[] = $query;

                    unset($diff->removedIndexes[$remKey]);
                    unset($diff->addedIndexes[$addKey]);

                    break;
                }
            }
        }

683 684 685 686 687 688 689 690
        $engine = 'INNODB';

        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
        }

        // Suppress foreign key constraint propagation on non-supporting engines.
        if ('INNODB' !== $engine) {
691 692 693
            $diff->addedForeignKeys   = [];
            $diff->changedForeignKeys = [];
            $diff->removedForeignKeys = [];
694 695
        }

696 697
        $sql = array_merge(
            $sql,
698
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
699 700 701 702 703 704 705
            parent::getPreAlterTableIndexForeignKeySQL($diff),
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
        );

        return $sql;
    }

706 707 708 709 710 711 712 713
    /**
     * @param TableDiff $diff
     * @param Index     $index
     *
     * @return string[]
     */
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index)
    {
714
        $sql = [];
715 716 717 718 719 720 721 722 723

        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
            return $sql;
        }

        $tableName = $diff->getName($this)->getQuotedName($this);

        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
        foreach ($index->getColumns() as $columnName) {
724 725 726
            if (! $diff->fromTable->hasColumn($columnName)) {
                continue;
            }
727

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
            $column = $diff->fromTable->getColumn($columnName);

            if ($column->getAutoincrement() === true) {
                $column->setAutoincrement(false);

                $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());

                // original autoincrement information might be needed later on by other parts of the table alteration
                $column->setAutoincrement(true);
            }
        }

        return $sql;
    }

744 745 746 747 748 749 750
    /**
     * @param TableDiff $diff The table diff to gather the SQL for.
     *
     * @return array
     */
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff)
    {
751
        $sql = [];
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        $table = $diff->getName($this)->getQuotedName($this);

        foreach ($diff->changedIndexes as $changedIndex) {
            // Changed primary key
            if ($changedIndex->isPrimary() && $diff->fromTable instanceof Table) {
                foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
                    $column = $diff->fromTable->getColumn($columnName);

                    // Check if an autoincrement column was dropped from the primary key.
                    if ($column->getAutoincrement() && ! in_array($columnName, $changedIndex->getColumns())) {
                        // The autoincrement attribute needs to be removed from the dropped column
                        // before we can drop and recreate the primary key.
                        $column->setAutoincrement(false);

                        $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
                            $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());

                        // Restore the autoincrement attribute as it might be needed later on
                        // by other parts of the table alteration.
                        $column->setAutoincrement(true);
                    }
                }
            }
        }

        return $sql;
    }

780 781 782 783 784 785 786
    /**
     * @param TableDiff $diff The table diff to gather the SQL for.
     *
     * @return array
     */
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
    {
787
        $sql = [];
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
        $tableName = $diff->getName($this)->getQuotedName($this);

        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
            if (! in_array($foreignKey, $diff->changedForeignKeys, true)) {
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
            }
        }

        return $sql;
    }

    /**
     * Returns the remaining foreign key constraints that require one of the renamed indexes.
     *
     * "Remaining" here refers to the diff between the foreign keys currently defined in the associated
     * table and the foreign keys to be removed.
     *
     * @param TableDiff $diff The table diff to evaluate.
     *
     * @return array
     */
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff)
    {
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
812
            return [];
813 814
        }

815
        $foreignKeys = [];
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        /** @var \Doctrine\DBAL\Schema\ForeignKeyConstraint[] $remainingForeignKeys */
        $remainingForeignKeys = array_diff_key(
            $diff->fromTable->getForeignKeys(),
            $diff->removedForeignKeys
        );

        foreach ($remainingForeignKeys as $foreignKey) {
            foreach ($diff->renamedIndexes as $index) {
                if ($foreignKey->intersectsIndexColumns($index)) {
                    $foreignKeys[] = $foreignKey;

                    break;
                }
            }
        }

        return $foreignKeys;
    }

    /**
     * {@inheritdoc}
     */
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        return array_merge(
            parent::getPostAlterTableIndexForeignKeySQL($diff),
            $this->getPostAlterTableRenameIndexForeignKeySQL($diff)
        );
    }

    /**
     * @param TableDiff $diff The table diff to gather the SQL for.
     *
     * @return array
     */
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
    {
853
        $sql = [];
854 855 856 857 858 859 860 861 862
        $tableName = (false !== $diff->newName)
            ? $diff->getNewName()->getQuotedName($this)
            : $diff->getName($this)->getQuotedName($this);

        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
            if (! in_array($foreignKey, $diff->changedForeignKeys, true)) {
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
            }
        }
863 864 865 866

        return $sql;
    }

867
    /**
868
     * {@inheritDoc}
869 870 871 872 873 874
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
Steve Müller's avatar
Steve Müller committed
875
        } elseif ($index->hasFlag('fulltext')) {
876
            $type .= 'FULLTEXT ';
877 878
        } elseif ($index->hasFlag('spatial')) {
            $type .= 'SPATIAL ';
879 880 881 882 883
        }

        return $type;
    }

884
    /**
885
     * {@inheritDoc}
886
     */
887
    public function getIntegerTypeDeclarationSQL(array $field)
888
    {
889
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
890 891
    }

892 893 894
    /**
     * {@inheritDoc}
     */
895
    public function getBigIntTypeDeclarationSQL(array $field)
896
    {
897
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
898 899
    }

900 901 902
    /**
     * {@inheritDoc}
     */
903
    public function getSmallIntTypeDeclarationSQL(array $field)
904
    {
905
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
906 907
    }

908 909 910 911 912
    /**
     * {@inheritdoc}
     */
    public function getFloatDeclarationSQL(array $field)
    {
913
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($field);
914 915
    }

916 917 918 919 920
    /**
     * {@inheritdoc}
     */
    public function getDecimalTypeDeclarationSQL(array $columnDef)
    {
Steve Müller's avatar
Steve Müller committed
921
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
922 923 924 925 926 927 928 929 930 931 932
    }

    /**
     * Get unsigned declaration for a column.
     *
     * @param array $columnDef
     *
     * @return string
     */
    private function getUnsignedDeclaration(array $columnDef)
    {
933
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
934 935
    }

936 937 938
    /**
     * {@inheritDoc}
     */
939
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
940
    {
941
        $autoinc = '';
942
        if ( ! empty($columnDef['autoincrement'])) {
943 944 945
            $autoinc = ' AUTO_INCREMENT';
        }

946
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
947
    }
948

949
    /**
950
     * {@inheritDoc}
951
     */
952
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
953 954
    {
        $query = '';
955 956
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
957
        }
958
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
959

960 961
        return $query;
    }
962

963
    /**
964
     * {@inheritDoc}
965
     */
966
    public function getDropIndexSQL($index, $table=null)
967
    {
968
        if ($index instanceof Index) {
969
            $indexName = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
970
        } elseif (is_string($index)) {
971 972
            $indexName = $index;
        } else {
973
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
974
        }
975

976
        if ($table instanceof Table) {
977
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
978
        } elseif (!is_string($table)) {
979
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
980
        }
981

982
        if ($index instanceof Index && $index->isPrimary()) {
983
            // mysql primary keys are always named "PRIMARY",
984 985 986
            // so we cannot use them in statements because of them being keyword.
            return $this->getDropPrimaryKeySQL($table);
        }
987

988 989
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
    }
990

991
    /**
992 993 994
     * @param string $table
     *
     * @return string
995 996 997 998
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
999
    }
1000

1001 1002 1003
    /**
     * {@inheritDoc}
     */
1004
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
1005
    {
1006
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
1007
    }
1008 1009

    /**
1010
     * {@inheritDoc}
1011 1012 1013 1014 1015
     */
    public function getName()
    {
        return 'mysql';
    }
1016

1017 1018 1019
    /**
     * {@inheritDoc}
     */
1020 1021 1022 1023
    public function getReadLockSQL()
    {
        return 'LOCK IN SHARE MODE';
    }
1024

1025 1026 1027
    /**
     * {@inheritDoc}
     */
1028 1029
    protected function initializeDoctrineTypeMappings()
    {
1030
        $this->doctrineTypeMapping = [
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            'tinyint'       => 'boolean',
            'smallint'      => 'smallint',
            'mediumint'     => 'integer',
            'int'           => 'integer',
            'integer'       => 'integer',
            'bigint'        => 'bigint',
            'tinytext'      => 'text',
            'mediumtext'    => 'text',
            'longtext'      => 'text',
            'text'          => 'text',
            'varchar'       => 'string',
            'string'        => 'string',
            'char'          => 'string',
            'date'          => 'date',
            'datetime'      => 'datetime',
            'timestamp'     => 'datetime',
            'time'          => 'time',
1048 1049 1050
            'float'         => 'float',
            'double'        => 'float',
            'real'          => 'float',
1051 1052 1053
            'decimal'       => 'decimal',
            'numeric'       => 'decimal',
            'year'          => 'date',
1054 1055 1056 1057
            'longblob'      => 'blob',
            'blob'          => 'blob',
            'mediumblob'    => 'blob',
            'tinyblob'      => 'blob',
Steve Müller's avatar
Steve Müller committed
1058 1059
            'binary'        => 'binary',
            'varbinary'     => 'binary',
1060
            'set'           => 'simple_array',
1061
        ];
1062
    }
1063

1064 1065 1066
    /**
     * {@inheritDoc}
     */
1067 1068 1069 1070
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1071

Steve Müller's avatar
Steve Müller committed
1072 1073 1074 1075 1076 1077 1078 1079
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 65535;
    }

1080 1081 1082
    /**
     * {@inheritDoc}
     */
1083 1084
    protected function getReservedKeywordsClass()
    {
1085
        return Keywords\MySQLKeywords::class;
1086
    }
1087 1088

    /**
1089
     * {@inheritDoc}
1090 1091 1092 1093 1094 1095
     *
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
     * if DROP TEMPORARY TABLE is executed.
     */
    public function getDropTemporaryTableSQL($table)
    {
1096
        if ($table instanceof Table) {
1097
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
1098
        } elseif (!is_string($table)) {
Leo's avatar
Leo committed
1099
            throw new \InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1100 1101 1102 1103
        }

        return 'DROP TEMPORARY TABLE ' . $table;
    }
1104 1105

    /**
1106 1107 1108 1109 1110 1111 1112 1113 1114
     * Gets the SQL Snippet used to declare a BLOB column type.
     *     TINYBLOB   : 2 ^  8 - 1 = 255
     *     BLOB       : 2 ^ 16 - 1 = 65535
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
     *
     * @param array $field
     *
     * @return string
1115 1116 1117
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
1118 1119 1120
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
            $length = $field['length'];

1121
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1122 1123 1124
                return 'TINYBLOB';
            }

1125
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1126 1127 1128
                return 'BLOB';
            }

1129
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1130 1131 1132 1133
                return 'MEDIUMBLOB';
            }
        }

1134 1135
        return 'LONGBLOB';
    }
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145

    /**
     * {@inheritdoc}
     */
    public function quoteStringLiteral($str)
    {
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.

        return parent::quoteStringLiteral($str);
    }
1146 1147 1148 1149 1150 1151 1152 1153

    /**
     * {@inheritdoc}
     */
    public function getDefaultTransactionIsolationLevel()
    {
        return Connection::TRANSACTION_REPEATABLE_READ;
    }
1154
}