Failed Conditions
Pull Request — develop (#3348)
by Sergei
125:02 queued 59:58
created

MySqlPlatform::getDatabaseNameSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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