MySqlPlatform.php 33.7 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Platforms;
4

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
7
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
8 9
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
10
use Doctrine\DBAL\Schema\TableDiff;
11
use Doctrine\DBAL\TransactionIsolationLevel;
12 13
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\TextType;
14
use InvalidArgumentException;
15

16 17 18 19 20 21 22 23 24 25 26 27 28 29
use function array_diff_key;
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function func_get_args;
use function implode;
use function in_array;
use function is_numeric;
use function is_string;
use function sprintf;
use function str_replace;
use function strtoupper;
use function trim;
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
 * @todo   Rename: MySQLPlatform
37
 */
38
class MySqlPlatform extends AbstractPlatform
39
{
40 41 42
    public const LENGTH_LIMIT_TINYTEXT   = 255;
    public const LENGTH_LIMIT_TEXT       = 65535;
    public const LENGTH_LIMIT_MEDIUMTEXT = 16777215;
43

44 45 46
    public const LENGTH_LIMIT_TINYBLOB   = 255;
    public const LENGTH_LIMIT_BLOB       = 65535;
    public const LENGTH_LIMIT_MEDIUMBLOB = 16777215;
47

48
    /**
49
     * {@inheritDoc}
50 51 52 53 54
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
        if ($limit !== null) {
            $query .= ' LIMIT ' . $limit;
55 56

            if ($offset > 0) {
57 58
                $query .= ' OFFSET ' . $offset;
            }
59 60
        } elseif ($offset > 0) {
            // 2^64-1 is the maximum of unsigned BIGINT, the biggest limit possible
61 62 63 64 65 66
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
        }

        return $query;
    }

romanb's avatar
romanb committed
67
    /**
68
     * {@inheritDoc}
romanb's avatar
romanb committed
69 70 71 72
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
73
    }
74

75
    /**
76
     * {@inheritDoc}
77 78 79 80 81 82
     */
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }

83
    /**
84
     * {@inheritDoc}
85 86 87
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
88
        if ($startPos === false) {
89 90
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
91

92
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
93 94
    }

95
    /**
96
     * {@inheritDoc}
97 98 99
     */
    public function getConcatExpression()
    {
100
        return sprintf('CONCAT(%s)', implode(', ', func_get_args()));
101
    }
102

103
    /**
104
     * {@inheritdoc}
105
     */
106
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
107
    {
108
        $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB';
109

110
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
111 112
    }

113 114 115
    /**
     * {@inheritDoc}
     */
116
    public function getDateDiffExpression($date1, $date2)
117
    {
118
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
119
    }
120

121 122 123 124 125
    public function getCurrentDatabaseExpression(): string
    {
        return 'DATABASE()';
    }

Benjamin Morel's avatar
Benjamin Morel committed
126 127 128
    /**
     * {@inheritDoc}
     */
129
    public function getListDatabasesSQL()
130 131 132 133
    {
        return 'SHOW DATABASES';
    }

Benjamin Morel's avatar
Benjamin Morel committed
134 135 136
    /**
     * {@inheritDoc}
     */
137
    public function getListTableConstraintsSQL($table)
138
    {
139
        return 'SHOW INDEX FROM ' . $table;
140 141
    }

142
    /**
143 144
     * {@inheritDoc}
     *
145
     * Two approaches to listing the table indexes. The information_schema is
Pascal Borreli's avatar
Pascal Borreli committed
146
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
147
     */
148
    public function getListTableIndexesSQL($table, $database = null)
149
    {
150
        if ($database !== null) {
151 152
            $database = $this->quoteStringLiteral($database);
            $table    = $this->quoteStringLiteral($table);
153

154 155 156
            return 'SELECT NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, COLUMN_NAME AS Column_Name,' .
                   ' SUB_PART AS Sub_Part, INDEX_TYPE AS Index_Type' .
                   ' FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table .
157
                   ' AND TABLE_SCHEMA = ' . $database .
158
                   ' ORDER BY SEQ_IN_INDEX ASC';
159
        }
160 161

        return 'SHOW INDEX FROM ' . $table;
162 163
    }

Benjamin Morel's avatar
Benjamin Morel committed
164 165 166
    /**
     * {@inheritDoc}
     */
167
    public function getListViewsSQL($database)
168
    {
169 170
        $database = $this->quoteStringLiteral($database);

171
        return 'SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ' . $database;
172 173
    }

Benjamin Morel's avatar
Benjamin Morel committed
174
    /**
175 176 177 178
     * @param string      $table
     * @param string|null $database
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
179
     */
180
    public function getListTableForeignKeysSQL($table, $database = null)
181
    {
182 183
        $table = $this->quoteStringLiteral($table);

184
        if ($database !== null) {
185 186 187
            $database = $this->quoteStringLiteral($database);
        }

188 189 190 191 192
        $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 ' .
               'INNER JOIN information_schema.referential_constraints c ON ' .
               '  c.constraint_name = k.constraint_name AND ' .
193
               '  c.table_name = ' . $table . ' */ WHERE k.table_name = ' . $table;
194

195
        $databaseNameSql = $database ?? 'DATABASE()';
196

Sergei Morozov's avatar
Sergei Morozov committed
197 198 199
        return $sql . ' AND k.table_schema = ' . $databaseNameSql
            . ' /*!50116 AND c.constraint_schema = ' . $databaseNameSql . ' */'
            . ' AND k.`REFERENCED_COLUMN_NAME` is not NULL';
200 201
    }

Benjamin Morel's avatar
Benjamin Morel committed
202 203 204
    /**
     * {@inheritDoc}
     */
205
    public function getCreateViewSQL($name, $sql)
206 207 208 209
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
210 211 212
    /**
     * {@inheritDoc}
     */
213
    public function getDropViewSQL($name)
214
    {
215
        return 'DROP VIEW ' . $name;
216 217
    }

218
    /**
219
     * {@inheritDoc}
220
     */
221
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
222
    {
223 224
        return $fixed ? ($length > 0 ? 'CHAR(' . $length . ')' : 'CHAR(255)')
                : ($length > 0 ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
225
    }
226

Steve Müller's avatar
Steve Müller committed
227 228 229 230 231
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
232 233 234
        return $fixed
            ? 'BINARY(' . ($length > 0 ? $length : 255) . ')'
            : 'VARBINARY(' . ($length > 0 ? $length : 255) . ')';
Steve Müller's avatar
Steve Müller committed
235 236
    }

237
    /**
238 239 240 241 242 243
     * 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
     *
244
     * {@inheritDoc}
245
     */
246
    public function getClobTypeDeclarationSQL(array $column)
247
    {
248 249
        if (! empty($column['length']) && is_numeric($column['length'])) {
            $length = $column['length'];
250

251
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
252
                return 'TINYTEXT';
253 254
            }

255
            if ($length <= static::LENGTH_LIMIT_TEXT) {
256
                return 'TEXT';
257 258
            }

259
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
260 261 262
                return 'MEDIUMTEXT';
            }
        }
263

264 265
        return 'LONGTEXT';
    }
266

267
    /**
268
     * {@inheritDoc}
269
     */
270
    public function getDateTimeTypeDeclarationSQL(array $column)
271
    {
272
        if (isset($column['version']) && $column['version'] === true) {
273 274
            return 'TIMESTAMP';
        }
275 276

        return 'DATETIME';
277
    }
278

279
    /**
280
     * {@inheritDoc}
281
     */
282
    public function getDateTypeDeclarationSQL(array $column)
283 284 285
    {
        return 'DATE';
    }
286

287
    /**
288
     * {@inheritDoc}
289
     */
290
    public function getTimeTypeDeclarationSQL(array $column)
291 292
    {
        return 'TIME';
293
    }
294

295
    /**
296
     * {@inheritDoc}
297
     */
298
    public function getBooleanTypeDeclarationSQL(array $column)
299 300 301 302
    {
        return 'TINYINT(1)';
    }

303
    /**
304 305
     * {@inheritDoc}
     *
306 307 308 309 310 311 312
     * MySql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
     */
    public function prefersIdentityColumns()
    {
        return true;
    }
313

romanb's avatar
romanb committed
314
    /**
315
     * {@inheritDoc}
romanb's avatar
romanb committed
316
     *
317
     * MySql supports this through AUTO_INCREMENT columns.
romanb's avatar
romanb committed
318 319 320 321
     */
    public function supportsIdentityColumns()
    {
        return true;
322 323
    }

324 325 326
    /**
     * {@inheritDoc}
     */
327 328 329
    public function supportsInlineColumnComments()
    {
        return true;
romanb's avatar
romanb committed
330
    }
331

Benjamin Morel's avatar
Benjamin Morel committed
332 333 334
    /**
     * {@inheritDoc}
     */
335 336 337 338 339
    public function supportsColumnCollation()
    {
        return true;
    }

340 341 342
    /**
     * {@inheritDoc}
     */
343
    public function getListTablesSQL()
344
    {
345
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
346
    }
347

Benjamin Morel's avatar
Benjamin Morel committed
348 349 350
    /**
     * {@inheritDoc}
     */
351
    public function getListTableColumnsSQL($table, $database = null)
352
    {
353 354
        $table = $this->quoteStringLiteral($table);

355
        if ($database !== null) {
356
            $database = $this->quoteStringLiteral($database);
357 358
        } else {
            $database = 'DATABASE()';
359
        }
360

361 362 363
        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 ' .
364 365
               'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $database . ' AND TABLE_NAME = ' . $table .
               ' ORDER BY ORDINAL_POSITION ASC';
366 367
    }

368
    public function getListTableMetadataSQL(string $table, ?string $database = null): string
369 370 371 372 373 374 375 376
    {
        return sprintf(
            <<<'SQL'
SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS
FROM information_schema.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s
SQL
            ,
377
            $database !== null ? $this->quoteStringLiteral($database) : 'DATABASE()',
378 379 380 381
            $this->quoteStringLiteral($table)
        );
    }

382
    /**
383
     * {@inheritDoc}
384
     */
385
    public function getCreateDatabaseSQL($name)
386
    {
387
        return 'CREATE DATABASE ' . $name;
388
    }
389

390
    /**
391
     * {@inheritDoc}
392
     */
393
    public function getDropDatabaseSQL($name)
394
    {
395
        return 'DROP DATABASE ' . $name;
396
    }
397

398
    /**
399
     * {@inheritDoc}
400
     */
401
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
402
    {
403
        $queryFields = $this->getColumnDeclarationListSQL($columns);
404

405
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
406
            foreach ($options['uniqueConstraints'] as $index => $definition) {
407
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($index, $definition);
408
            }
409 410 411 412
        }

        // add all indexes
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Steve Müller's avatar
Steve Müller committed
413
            foreach ($options['indexes'] as $index => $definition) {
414
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
415 416 417 418 419
            }
        }

        // attach all primary keys
        if (isset($options['primary']) && ! empty($options['primary'])) {
420
            $keyColumns   = array_unique(array_values($options['primary']));
421 422 423 424
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

        $query = 'CREATE ';
425

426
        if (! empty($options['temporary'])) {
427 428
            $query .= 'TEMPORARY ';
        }
429

430
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
431 432
        $query .= $this->buildTableOptions($options);
        $query .= $this->buildPartitionOptions($options);
433

434
        $sql    = [$query];
435
        $engine = 'INNODB';
436

437 438 439 440 441 442
        if (isset($options['engine'])) {
            $engine = strtoupper(trim($options['engine']));
        }

        // Propagate foreign key constraints only for InnoDB.
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
443 444 445 446
            foreach ((array) $options['foreignKeys'] as $definition) {
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }
447

448 449 450
        return $sql;
    }

451 452 453
    /**
     * {@inheritdoc}
     */
454
    public function getDefaultValueDeclarationSQL($column)
455
    {
456 457 458
        // Unset the default value if the given column definition does not allow default values.
        if ($column['type'] instanceof TextType || $column['type'] instanceof BlobType) {
            $column['default'] = null;
459 460
        }

461
        return parent::getDefaultValueDeclarationSQL($column);
462 463
    }

464 465 466
    /**
     * Build SQL for table options
     *
467
     * @param mixed[] $options
468 469 470 471 472 473 474
     *
     * @return string
     */
    private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
475
        }
476

477
        $tableOptions = [];
478 479

        // Charset
480
        if (! isset($options['charset'])) {
481
            $options['charset'] = 'utf8';
482 483
        }

484 485 486
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);

        // Collate
487
        if (! isset($options['collate'])) {
488
            $options['collate'] = $options['charset'] . '_unicode_ci';
489
        }
490

491
        $tableOptions[] = $this->getColumnCollationDeclarationSQL($options['collate']);
492

493
        // Engine
494
        if (! isset($options['engine'])) {
495
            $options['engine'] = 'InnoDB';
496
        }
497

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

500 501 502
        // Auto increment
        if (isset($options['auto_increment'])) {
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
503
        }
504

505 506
        // Comment
        if (isset($options['comment'])) {
507
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($options['comment']));
508 509 510 511 512 513 514 515 516 517 518 519 520
        }

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

        return implode(' ', $tableOptions);
    }

    /**
     * Build SQL for partition options.
     *
521
     * @param mixed[] $options
522 523 524 525 526
     *
     * @return string
     */
    private function buildPartitionOptions(array $options)
    {
527
        return isset($options['partition_options'])
528
            ? ' ' . $options['partition_options']
529
            : '';
530
    }
531

532
    /**
533
     * {@inheritDoc}
534
     */
535
    public function getAlterTableSQL(TableDiff $diff)
536
    {
537
        $columnSql  = [];
538
        $queryParts = [];
Sergei Morozov's avatar
Sergei Morozov committed
539 540 541 542
        $newName    = $diff->getNewName();

        if ($newName !== false) {
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
543 544
        }

545
        foreach ($diff->addedColumns as $column) {
546 547
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
548 549
            }

Sergei Morozov's avatar
Sergei Morozov committed
550 551 552 553 554
            $columnArray = array_merge($column->toArray(), [
                'comment' => $this->getColumnComment($column),
            ]);

            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
555 556
        }

557
        foreach ($diff->removedColumns as $column) {
558 559
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
560 561
            }

562
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
563 564
        }

565
        foreach ($diff->changedColumns as $columnDiff) {
566 567
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
568 569
            }

570
            $column      = $columnDiff->column;
571
            $columnArray = $column->toArray();
572 573

            // Don't propagate default value changes for unsupported column types.
574 575
            if (
                $columnDiff->hasChanged('default') &&
576 577 578 579 580 581
                count($columnDiff->changedProperties) === 1 &&
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
            ) {
                continue;
            }

582
            $columnArray['comment'] = $this->getColumnComment($column);
583
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
584
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
585 586
        }

587
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
588 589
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
590 591
            }

592 593
            $oldColumnName          = new Identifier($oldColumnName);
            $columnArray            = $column->toArray();
594
            $columnArray['comment'] = $this->getColumnComment($column);
595
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
596
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
597 598
        }

599
        if (isset($diff->addedIndexes['primary'])) {
600
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
601 602
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
            unset($diff->addedIndexes['primary']);
603 604 605 606 607 608 609 610 611 612 613
        } elseif (isset($diff->changedIndexes['primary'])) {
            // Necessary in case the new primary key includes a new auto_increment column
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
                    $queryParts[] = 'DROP PRIMARY KEY';
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
                    unset($diff->changedIndexes['primary']);
                    break;
                }
            }
614 615
        }

616
        $sql      = [];
617
        $tableSql = [];
618

619
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
620
            if (count($queryParts) > 0) {
Sergei Morozov's avatar
Sergei Morozov committed
621 622
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' '
                    . implode(', ', $queryParts);
623
            }
Grégoire Paris's avatar
Grégoire Paris committed
624

625 626 627 628 629
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
630
        }
631 632

        return array_merge($sql, $tableSql, $columnSql);
633
    }
634

635
    /**
636
     * {@inheritDoc}
637 638 639
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
640
        $sql   = [];
641
        $table = $diff->getName($this)->getQuotedName($this);
642

643 644 645
        foreach ($diff->changedIndexes as $changedIndex) {
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
        }
andig's avatar
andig committed
646

647 648
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
649 650

            foreach ($diff->addedIndexes as $addKey => $addIndex) {
Grégoire Paris's avatar
Grégoire Paris committed
651 652 653
                if ($remIndex->getColumns() !== $addIndex->getColumns()) {
                    continue;
                }
654

Grégoire Paris's avatar
Grégoire Paris committed
655
                $indexClause = 'INDEX ' . $addIndex->getName();
656

Grégoire Paris's avatar
Grégoire Paris committed
657 658 659 660 661
                if ($addIndex->isPrimary()) {
                    $indexClause = 'PRIMARY KEY';
                } elseif ($addIndex->isUnique()) {
                    $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
                }
662

Grégoire Paris's avatar
Grégoire Paris committed
663 664 665
                $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
                $query .= 'ADD ' . $indexClause;
                $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
666

Grégoire Paris's avatar
Grégoire Paris committed
667
                $sql[] = $query;
668

Grégoire Paris's avatar
Grégoire Paris committed
669 670 671
                unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);

                break;
672 673 674
            }
        }

675 676 677 678 679 680 681
        $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.
682
        if ($engine !== 'INNODB') {
683 684 685
            $diff->addedForeignKeys   = [];
            $diff->changedForeignKeys = [];
            $diff->removedForeignKeys = [];
686 687
        }

688 689
        $sql = array_merge(
            $sql,
690
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
691 692 693 694 695 696 697
            parent::getPreAlterTableIndexForeignKeySQL($diff),
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
        );

        return $sql;
    }

698 699
    /**
     * @return string[]
700 701
     *
     * @throws DBALException
702 703 704
     */
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index)
    {
705
        $sql = [];
706 707 708 709 710 711 712 713 714

        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) {
715 716 717
            if (! $diff->fromTable->hasColumn($columnName)) {
                continue;
            }
718

719 720
            $column = $diff->fromTable->getColumn($columnName);

721 722 723
            if ($column->getAutoincrement() !== true) {
                continue;
            }
724

725
            $column->setAutoincrement(false);
726

727 728 729 730 731
            $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);
732 733 734 735 736
        }

        return $sql;
    }

737 738 739
    /**
     * @param TableDiff $diff The table diff to gather the SQL for.
     *
740
     * @return string[]
741 742
     *
     * @throws DBALException
743 744 745
     */
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff)
    {
746
        $sql   = [];
747 748 749 750
        $table = $diff->getName($this)->getQuotedName($this);

        foreach ($diff->changedIndexes as $changedIndex) {
            // Changed primary key
751 752 753 754 755 756 757 758
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
                continue;
            }

            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
                $column = $diff->fromTable->getColumn($columnName);

                // Check if an autoincrement column was dropped from the primary key.
759
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns(), true)) {
760
                    continue;
761
                }
762 763 764 765 766 767 768 769 770 771 772

                // 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);
773 774 775 776 777 778
            }
        }

        return $sql;
    }

779 780 781
    /**
     * @param TableDiff $diff The table diff to gather the SQL for.
     *
782
     * @return string[]
783 784 785
     */
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
    {
786
        $sql       = [];
787 788 789
        $tableName = $diff->getName($this)->getQuotedName($this);

        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
790 791
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
                continue;
792
            }
793 794

            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
795 796 797 798 799 800 801 802 803 804 805 806 807
        }

        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.
     *
808
     * @return ForeignKeyConstraint[]
809 810 811 812
     */
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff)
    {
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
813
            return [];
814 815
        }

816
        $foreignKeys = [];
817
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
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
        $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.
     *
850
     * @return string[]
851 852 853
     */
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
    {
Sergei Morozov's avatar
Sergei Morozov committed
854 855 856 857 858 859 860 861
        $sql     = [];
        $newName = $diff->getNewName();

        if ($newName !== false) {
            $tableName = $newName->getQuotedName($this);
        } else {
            $tableName = $diff->getName($this)->getQuotedName($this);
        }
862 863

        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
864 865
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
                continue;
866
            }
867 868

            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
869
        }
870 871 872 873

        return $sql;
    }

874
    /**
875
     * {@inheritDoc}
876 877 878 879 880 881
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
Steve Müller's avatar
Steve Müller committed
882
        } elseif ($index->hasFlag('fulltext')) {
883
            $type .= 'FULLTEXT ';
884 885
        } elseif ($index->hasFlag('spatial')) {
            $type .= 'SPATIAL ';
886 887 888 889 890
        }

        return $type;
    }

891
    /**
892
     * {@inheritDoc}
893
     */
894
    public function getIntegerTypeDeclarationSQL(array $column)
895
    {
896
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($column);
897 898
    }

899 900 901
    /**
     * {@inheritDoc}
     */
902
    public function getBigIntTypeDeclarationSQL(array $column)
903
    {
904
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($column);
905 906
    }

907 908 909
    /**
     * {@inheritDoc}
     */
910
    public function getSmallIntTypeDeclarationSQL(array $column)
911
    {
912
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($column);
913 914
    }

915 916 917
    /**
     * {@inheritdoc}
     */
918
    public function getFloatDeclarationSQL(array $column)
919
    {
920
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($column);
921 922
    }

923 924 925
    /**
     * {@inheritdoc}
     */
926
    public function getDecimalTypeDeclarationSQL(array $column)
927
    {
928
        return parent::getDecimalTypeDeclarationSQL($column) . $this->getUnsignedDeclaration($column);
929 930 931 932 933
    }

    /**
     * Get unsigned declaration for a column.
     *
934
     * @param mixed[] $columnDef
935 936 937 938 939
     *
     * @return string
     */
    private function getUnsignedDeclaration(array $columnDef)
    {
940
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
941 942
    }

943 944 945
    /**
     * {@inheritDoc}
     */
946
    protected function _getCommonIntegerTypeDeclarationSQL(array $column)
947
    {
948
        $autoinc = '';
949
        if (! empty($column['autoincrement'])) {
950 951 952
            $autoinc = ' AUTO_INCREMENT';
        }

953
        return $this->getUnsignedDeclaration($column) . $autoinc;
954
    }
955

956 957 958 959 960 961 962 963
    /**
     * {@inheritDoc}
     */
    public function getColumnCharsetDeclarationSQL($charset)
    {
        return 'CHARACTER SET ' . $charset;
    }

964 965 966 967 968 969 970 971
    /**
     * {@inheritDoc}
     */
    public function getColumnCollationDeclarationSQL($collation)
    {
        return 'COLLATE ' . $this->quoteSingleIdentifier($collation);
    }

972
    /**
973
     * {@inheritDoc}
974
     */
975
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
976 977
    {
        $query = '';
978 979
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
980
        }
Grégoire Paris's avatar
Grégoire Paris committed
981

982
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
983

984 985
        return $query;
    }
986

987
    /**
988
     * {@inheritDoc}
989
     */
990
    public function getDropIndexSQL($index, $table = null)
991
    {
992
        if ($index instanceof Index) {
993
            $indexName = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
994
        } elseif (is_string($index)) {
995 996
            $indexName = $index;
        } else {
997 998 999
            throw new InvalidArgumentException(
                __METHOD__ . '() expects $index parameter to be string or ' . Index::class . '.'
            );
1000
        }
1001

1002
        if ($table instanceof Table) {
1003
            $table = $table->getQuotedName($this);
1004
        } elseif (! is_string($table)) {
1005 1006 1007
            throw new InvalidArgumentException(
                __METHOD__ . '() expects $table parameter to be string or ' . Table::class . '.'
            );
1008
        }
1009

1010
        if ($index instanceof Index && $index->isPrimary()) {
1011
            // mysql primary keys are always named "PRIMARY",
1012 1013 1014
            // so we cannot use them in statements because of them being keyword.
            return $this->getDropPrimaryKeySQL($table);
        }
1015

1016 1017
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
    }
1018

1019
    /**
1020 1021 1022
     * @param string $table
     *
     * @return string
1023 1024 1025 1026
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
1027
    }
1028

1029 1030 1031
    /**
     * {@inheritDoc}
     */
1032
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
1033
    {
1034
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
1035
    }
1036 1037

    /**
1038
     * {@inheritDoc}
1039 1040 1041 1042 1043
     */
    public function getName()
    {
        return 'mysql';
    }
1044

1045 1046 1047
    /**
     * {@inheritDoc}
     */
1048 1049 1050 1051
    public function getReadLockSQL()
    {
        return 'LOCK IN SHARE MODE';
    }
1052

1053 1054 1055
    /**
     * {@inheritDoc}
     */
1056 1057
    protected function initializeDoctrineTypeMappings()
    {
1058
        $this->doctrineTypeMapping = [
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
            'bigint'     => 'bigint',
            'binary'     => 'binary',
            'blob'       => 'blob',
            'char'       => 'string',
            'date'       => 'date',
            'datetime'   => 'datetime',
            'decimal'    => 'decimal',
            'double'     => 'float',
            'float'      => 'float',
            'int'        => 'integer',
            'integer'    => 'integer',
            'longblob'   => 'blob',
            'longtext'   => 'text',
            'mediumblob' => 'blob',
            'mediumint'  => 'integer',
            'mediumtext' => 'text',
            'numeric'    => 'decimal',
            'real'       => 'float',
            'set'        => 'simple_array',
            'smallint'   => 'smallint',
            'string'     => 'string',
            'text'       => 'text',
            'time'       => 'time',
            'timestamp'  => 'datetime',
            'tinyblob'   => 'blob',
            'tinyint'    => 'boolean',
            'tinytext'   => 'text',
            'varbinary'  => 'binary',
            'varchar'    => 'string',
            'year'       => 'date',
1089
        ];
1090
    }
1091

1092 1093 1094
    /**
     * {@inheritDoc}
     */
1095 1096 1097 1098
    public function getVarcharMaxLength()
    {
        return 65535;
    }
1099

Steve Müller's avatar
Steve Müller committed
1100 1101 1102 1103 1104 1105 1106 1107
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 65535;
    }

1108 1109 1110
    /**
     * {@inheritDoc}
     */
1111 1112
    protected function getReservedKeywordsClass()
    {
1113
        return Keywords\MySQLKeywords::class;
1114
    }
1115 1116

    /**
1117
     * {@inheritDoc}
1118 1119 1120 1121 1122 1123
     *
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
     * if DROP TEMPORARY TABLE is executed.
     */
    public function getDropTemporaryTableSQL($table)
    {
1124
        if ($table instanceof Table) {
1125
            $table = $table->getQuotedName($this);
1126
        } elseif (! is_string($table)) {
1127 1128 1129
            throw new InvalidArgumentException(
                __METHOD__ . '() expects $table parameter to be string or ' . Table::class . '.'
            );
1130 1131 1132 1133
        }

        return 'DROP TEMPORARY TABLE ' . $table;
    }
1134 1135

    /**
1136 1137 1138 1139 1140 1141
     * 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
     *
1142
     * {@inheritDoc}
1143
     */
1144
    public function getBlobTypeDeclarationSQL(array $column)
1145
    {
1146 1147
        if (! empty($column['length']) && is_numeric($column['length'])) {
            $length = $column['length'];
1148

1149
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1150 1151 1152
                return 'TINYBLOB';
            }

1153
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1154 1155 1156
                return 'BLOB';
            }

1157
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1158 1159 1160 1161
                return 'MEDIUMBLOB';
            }
        }

1162 1163
        return 'LONGBLOB';
    }
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

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

        return parent::quoteStringLiteral($str);
    }
1174 1175 1176 1177 1178 1179

    /**
     * {@inheritdoc}
     */
    public function getDefaultTransactionIsolationLevel()
    {
1180
        return TransactionIsolationLevel::REPEATABLE_READ;
1181
    }
1182

1183
    public function supportsColumnLengthIndexes(): bool
1184 1185 1186
    {
        return true;
    }
1187
}