Completed
Push — master ( ff6cbd...ce4534 )
by Sergei
13:19 queued 13:15
created

MySqlPlatform::getListTableMetadataSQL()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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