Completed
Push — develop ( fa42c1...0ef7d4 )
by Sergei
22:52
created

MySqlPlatform::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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