Passed
Pull Request — 2.10.x (#3936)
by Asmir
05:07
created

MySqlPlatform::supportsNamedPrimaryConstraints()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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