Completed
Pull Request — 2.10.x (#3936)
by Asmir
65:42
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
            $queryFields .= ', ' . $this->getPrimaryKeyAsConstraintSQL($options['primary'], $options['primary_index']);
447 9648
        }
448
449 9648
        $query = 'CREATE ';
450 9648
451
        if (! empty($options['temporary'])) {
452 9648
            $query .= 'TEMPORARY ';
453 8508
        }
454
455
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
456
        $query .= $this->buildTableOptions($options);
457 9648
        $query .= $this->buildPartitionOptions($options);
458 9280
459 9100
        $sql    = [$query];
460
        $engine = 'INNODB';
461
462
        if (isset($options['engine'])) {
463 9648
            $engine = strtoupper(trim($options['engine']));
464
        }
465
466
        // Propagate foreign key constraints only for InnoDB.
467
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
468
            foreach ((array) $options['foreignKeys'] as $definition) {
469 9762
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
470
            }
471
        }
472 9762
473 9438
        return $sql;
474
    }
475
476 9762
    /**
477
     * {@inheritdoc}
478
     */
479
    public function getDefaultValueDeclarationSQL($field)
480
    {
481
        // Unset the default value if the given field definition does not allow default values.
482
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
483
            $field['default'] = null;
484
        }
485
486 9648
        return parent::getDefaultValueDeclarationSQL($field);
487
    }
488 9648
489
    /**
490
     * Build SQL for table options
491
     *
492 9648
     * @param mixed[] $options
493
     *
494
     * @return string
495 9648
     */
496 9648
    private function buildTableOptions(array $options)
497
    {
498
        if (isset($options['table_options'])) {
499 9648
            return $options['table_options'];
500
        }
501
502 9648
        $tableOptions = [];
503 9648
504
        // Charset
505
        if (! isset($options['charset'])) {
506 9648
            $options['charset'] = 'utf8';
507
        }
508
509 9648
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
510 9630
511
        // Collate
512
        if (! isset($options['collate'])) {
513 9648
            $options['collate'] = $options['charset'] . '_unicode_ci';
514
        }
515
516 9648
        $tableOptions[] = $this->getColumnCollationDeclarationSQL($options['collate']);
517
518
        // Engine
519
        if (! isset($options['engine'])) {
520
            $options['engine'] = 'InnoDB';
521 9648
        }
522 4430
523
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
524
525
        // Auto increment
526 9648
        if (isset($options['auto_increment'])) {
527
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
528
        }
529
530 9648
        // Comment
531
        if (isset($options['comment'])) {
532
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($options['comment']));
533
        }
534
535
        // Row format
536
        if (isset($options['row_format'])) {
537
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
538
        }
539
540 9648
        return implode(' ', $tableOptions);
541
    }
542 9648
543
    /**
544 9648
     * Build SQL for partition options.
545
     *
546
     * @param mixed[] $options
547
     *
548
     * @return string
549
     */
550 9023
    private function buildPartitionOptions(array $options)
551
    {
552 9023
        return isset($options['partition_options'])
553 9023
            ? ' ' . $options['partition_options']
554 9023
            : '';
555
    }
556 9023
557 5854
    /**
558
     * {@inheritDoc}
559
     */
560 9023
    public function getAlterTableSQL(TableDiff $diff)
561 8758
    {
562
        $columnSql  = [];
563
        $queryParts = [];
564
        $newName    = $diff->getNewName();
565 8758
566 8758
        if ($newName !== false) {
567 8758
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
568
        }
569
570 9023
        foreach ($diff->addedColumns as $column) {
571 7650
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
572
                continue;
573
            }
574
575 7650
            $columnArray            = $column->toArray();
576
            $columnArray['comment'] = $this->getColumnComment($column);
577
            $queryParts[]           = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
578 9023
        }
579 8010
580
        foreach ($diff->removedColumns as $column) {
581
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
582
                continue;
583 8010
            }
584 8010
585
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
586
        }
587 8010
588 8010
        foreach ($diff->changedColumns as $columnDiff) {
589 8010
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
590
                continue;
591 6173
            }
592
593
            $column      = $columnDiff->column;
594 7990
            $columnArray = $column->toArray();
595 7990
596 7990
            // Don't propagate default value changes for unsupported column types.
597
            if ($columnDiff->hasChanged('default') &&
598
                count($columnDiff->changedProperties) === 1 &&
599 9023
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
600 7586
            ) {
601
                continue;
602
            }
603
604 7586
            $columnArray['comment'] = $this->getColumnComment($column);
605 7586
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
606 7586
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
607 7586
        }
608 7586
609
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
610
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
611 9023
                continue;
612 8589
            }
613 8589
614 8589
            $oldColumnName          = new Identifier($oldColumnName);
615 8959
            $columnArray            = $column->toArray();
616
            $columnArray['comment'] = $this->getColumnComment($column);
617 8792
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
618 8792
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
619 5554
        }
620 5554
621 5554
        if (isset($diff->addedIndexes['primary'])) {
622 5554
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
623 5554
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
624
            unset($diff->addedIndexes['primary']);
625
        } elseif (isset($diff->changedIndexes['primary'])) {
626
            // Necessary in case the new primary key includes a new auto_increment column
627
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
628 9023
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
629 9023
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
630
                    $queryParts[] = 'DROP PRIMARY KEY';
631 9023
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
632 9023
                    unset($diff->changedIndexes['primary']);
633 8945
                    break;
634
                }
635 9023
            }
636 9023
        }
637 9023
638 9023
        $sql      = [];
639
        $tableSql = [];
640
641
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
642 9023
            if (count($queryParts) > 0) {
643
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
644
            }
645
            $sql = array_merge(
646
                $this->getPreAlterTableIndexForeignKeySQL($diff),
647
                $sql,
648 9023
                $this->getPostAlterTableIndexForeignKeySQL($diff)
649
            );
650 9023
        }
651 9023
652
        return array_merge($sql, $tableSql, $columnSql);
653 9023
    }
654 8082
655
    /**
656
     * {@inheritDoc}
657 9023
     */
658 8483
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
659
    {
660 8483
        $sql   = [];
661 6837
        $table = $diff->getName($this)->getQuotedName($this);
662 6837
663
        foreach ($diff->changedIndexes as $changedIndex) {
664 6837
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
665
        }
666 6837
667 6837
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
668
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
669
670 6837
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
671 6837
                if ($remIndex->getColumns() === $addIndex->getColumns()) {
672 6837
                    $indexClause = 'INDEX ' . $addIndex->getName();
673
674 6837
                    if ($addIndex->isPrimary()) {
675
                        $indexClause = 'PRIMARY KEY';
676 6837
                    } elseif ($addIndex->isUnique()) {
677
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
678 6837
                    }
679
680
                    $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
681
                    $query .= 'ADD ' . $indexClause;
682
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
683 9023
684
                    $sql[] = $query;
685 9023
686 8355
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
687
688
                    break;
689
                }
690 9023
            }
691 6469
        }
692 6469
693 6469
        $engine = 'INNODB';
694
695
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
696 9023
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
697 9023
        }
698 9023
699 9023
        // Suppress foreign key constraint propagation on non-supporting engines.
700 9023
        if ($engine !== 'INNODB') {
701
            $diff->addedForeignKeys   = [];
702
            $diff->changedForeignKeys = [];
703 9023
            $diff->removedForeignKeys = [];
704
        }
705
706
        $sql = array_merge(
707
            $sql,
708
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
709 8515
            parent::getPreAlterTableIndexForeignKeySQL($diff),
710
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
711 8515
        );
712
713 8515
        return $sql;
714 8483
    }
715
716
    /**
717 8430
     * @return string[]
718
     */
719
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index)
720 8430
    {
721 8430
        $sql = [];
722 6584
723
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
724
            return $sql;
725 8430
        }
726
727 8430
        $tableName = $diff->getName($this)->getQuotedName($this);
728 8424
729
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
730
        foreach ($index->getColumns() as $columnName) {
731 8405
            if (! $diff->fromTable->hasColumn($columnName)) {
732
                continue;
733 8405
            }
734 8405
735
            $column = $diff->fromTable->getColumn($columnName);
736
737 8405
            if ($column->getAutoincrement() !== true) {
738
                continue;
739
            }
740 8430
741
            $column->setAutoincrement(false);
742
743
            $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
744
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
745
746
            // original autoincrement information might be needed later on by other parts of the table alteration
747
            $column->setAutoincrement(true);
748 9023
        }
749
750 9023
        return $sql;
751 9023
    }
752
753 9023
    /**
754
     * @param TableDiff $diff The table diff to gather the SQL for.
755 8082
     *
756 8001
     * @return string[]
757
     */
758
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff)
759 6742
    {
760 6742
        $sql   = [];
761
        $table = $diff->getName($this)->getQuotedName($this);
762
763 6742
        foreach ($diff->changedIndexes as $changedIndex) {
764 6690
            // Changed primary key
765
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
766
                continue;
767
            }
768
769 6722
            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
770
                $column = $diff->fromTable->getColumn($columnName);
771 6722
772 6722
                // Check if an autoincrement column was dropped from the primary key.
773
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) {
774
                    continue;
775
                }
776 6722
777
                // The autoincrement attribute needs to be removed from the dropped column
778
                // before we can drop and recreate the primary key.
779
                $column->setAutoincrement(false);
780 9023
781
                $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
782
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
783
784
                // Restore the autoincrement attribute as it might be needed later on
785
                // by other parts of the table alteration.
786
                $column->setAutoincrement(true);
787
            }
788 8313
        }
789
790 8313
        return $sql;
791 8313
    }
792
793 8313
    /**
794 6497
     * @param TableDiff $diff The table diff to gather the SQL for.
795
     *
796
     * @return string[]
797
     */
798 6497
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
799
    {
800
        $sql       = [];
801 8313
        $tableName = $diff->getName($this)->getQuotedName($this);
802
803
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
804
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
805
                continue;
806
            }
807
808
            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
809
        }
810
811
        return $sql;
812
    }
813
814 8313
    /**
815
     * Returns the remaining foreign key constraints that require one of the renamed indexes.
816 8313
     *
817 8293
     * "Remaining" here refers to the diff between the foreign keys currently defined in the associated
818
     * table and the foreign keys to be removed.
819
     *
820 6778
     * @param TableDiff $diff The table diff to evaluate.
821
     *
822 6778
     * @return ForeignKeyConstraint[]
823 6778
     */
824 6778
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff)
825
    {
826
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
827 6778
            return [];
828 6497
        }
829 6497
830 6497
        $foreignKeys = [];
831
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
832 6497
        $remainingForeignKeys = array_diff_key(
833
            $diff->fromTable->getForeignKeys(),
834
            $diff->removedForeignKeys
835
        );
836
837 6778
        foreach ($remainingForeignKeys as $foreignKey) {
838
            foreach ($diff->renamedIndexes as $index) {
839
                if ($foreignKey->intersectsIndexColumns($index)) {
840
                    $foreignKeys[] = $foreignKey;
841
842
                    break;
843 9023
                }
844
            }
845 9023
        }
846 9023
847 9023
        return $foreignKeys;
848
    }
849
850
    /**
851
     * {@inheritdoc}
852
     */
853
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
854
    {
855
        return array_merge(
856 8313
            parent::getPostAlterTableIndexForeignKeySQL($diff),
857
            $this->getPostAlterTableRenameIndexForeignKeySQL($diff)
858 8313
        );
859 8313
    }
860
861 8313
    /**
862 5850
     * @param TableDiff $diff The table diff to gather the SQL for.
863
     *
864 8305
     * @return string[]
865
     */
866
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
867 8313
    {
868 6497
        $sql     = [];
869
        $newName = $diff->getNewName();
870
871
        if ($newName !== false) {
872 6497
            $tableName = $newName->getQuotedName($this);
873
        } else {
874
            $tableName = $diff->getName($this)->getQuotedName($this);
875 8313
        }
876
877
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
878
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
879
                continue;
880
            }
881 9387
882
            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
883 9387
        }
884 9387
885 9231
        return $sql;
886 9314
    }
887 8496
888 9297
    /**
889 8473
     * {@inheritDoc}
890
     */
891
    protected function getCreateIndexSQLFlags(Index $index)
892 9387
    {
893
        $type = '';
894
        if ($index->isUnique()) {
895
            $type .= 'UNIQUE ';
896
        } elseif ($index->hasFlag('fulltext')) {
897
            $type .= 'FULLTEXT ';
898 9668
        } elseif ($index->hasFlag('spatial')) {
899
            $type .= 'SPATIAL ';
900 9668
        }
901
902
        return $type;
903
    }
904
905
    /**
906 4112
     * {@inheritDoc}
907
     */
908 4112
    public function getIntegerTypeDeclarationSQL(array $field)
909
    {
910
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
911
    }
912
913
    /**
914 4730
     * {@inheritDoc}
915
     */
916 4730
    public function getBigIntTypeDeclarationSQL(array $field)
917
    {
918
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
919
    }
920
921
    /**
922 7483
     * {@inheritDoc}
923
     */
924 7483
    public function getSmallIntTypeDeclarationSQL(array $field)
925
    {
926
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
927
    }
928
929
    /**
930 7550
     * {@inheritdoc}
931
     */
932 7550
    public function getFloatDeclarationSQL(array $field)
933
    {
934
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($field);
935
    }
936
937
    /**
938
     * {@inheritdoc}
939
     */
940
    public function getDecimalTypeDeclarationSQL(array $columnDef)
941
    {
942 9740
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
943
    }
944 9740
945
    /**
946
     * Get unsigned declaration for a column.
947
     *
948
     * @param mixed[] $columnDef
949
     *
950 9668
     * @return string
951
     */
952 9668
    private function getUnsignedDeclaration(array $columnDef)
953 9668
    {
954 9132
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
955
    }
956
957 9668
    /**
958
     * {@inheritDoc}
959
     */
960
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
961
    {
962
        $autoinc = '';
963 8164
        if (! empty($columnDef['autoincrement'])) {
964
            $autoinc = ' AUTO_INCREMENT';
965 8164
        }
966
967
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
968
    }
969
970
    /**
971 9654
     * {@inheritDoc}
972
     */
973 9654
    public function getColumnCharsetDeclarationSQL($charset)
974
    {
975
        return 'CHARACTER SET ' . $charset;
976
    }
977
978
    /**
979 9130
     * {@inheritDoc}
980
     */
981 9130
    public function getColumnCollationDeclarationSQL($collation)
982 9130
    {
983
        return 'COLLATE ' . $this->quoteSingleIdentifier($collation);
984
    }
985 9130
986
    /**
987 9130
     * {@inheritDoc}
988
     */
989
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
990
    {
991
        $query = '';
992
        if ($foreignKey->hasOption('match')) {
993 8485
            $query .= ' MATCH ' . $foreignKey->getOption('match');
994
        }
995 8485
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
996 8465
997 7502
        return $query;
998 7502
    }
999
1000
    /**
1001
     * {@inheritDoc}
1002
     */
1003 8485
    public function getDropIndexSQL($index, $table = null)
1004 4886
    {
1005 8485
        if ($index instanceof Index) {
1006
            $indexName = $index->getQuotedName($this);
1007
        } elseif (is_string($index)) {
1008
            $indexName = $index;
1009 8485
        } else {
1010
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1011
        }
1012 8436
1013
        if ($table instanceof Table) {
1014
            $table = $table->getQuotedName($this);
1015 8447
        } elseif (! is_string($table)) {
1016
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1017
        }
1018
1019
        if ($index instanceof Index && $index->isPrimary()) {
1020
            // mysql primary keys are always named "PRIMARY",
1021
            // so we cannot use them in statements because of them being keyword.
1022
            return $this->getDropPrimaryKeySQL($table);
1023 8436
        }
1024
1025 8436
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
1026
    }
1027
1028
    /**
1029
     * @param string $table
1030
     *
1031 7044
     * @return string
1032
     */
1033 7044
    protected function getDropPrimaryKeySQL($table)
1034
    {
1035
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
1036
    }
1037
1038
    /**
1039 9054
     * {@inheritDoc}
1040
     */
1041 9054
    public function getSetTransactionIsolationSQL($level)
1042
    {
1043
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
1044
    }
1045
1046
    /**
1047
     * {@inheritDoc}
1048
     */
1049
    public function getName()
1050
    {
1051
        return 'mysql';
1052
    }
1053
1054
    /**
1055 8998
     * {@inheritDoc}
1056
     */
1057 8998
    public function getReadLockSQL()
1058
    {
1059
        return 'LOCK IN SHARE MODE';
1060
    }
1061
1062
    /**
1063
     * {@inheritDoc}
1064
     */
1065
    protected function initializeDoctrineTypeMappings()
1066
    {
1067
        $this->doctrineTypeMapping = [
1068
            'tinyint'       => 'boolean',
1069
            'smallint'      => 'smallint',
1070
            'mediumint'     => 'integer',
1071
            'int'           => 'integer',
1072
            'integer'       => 'integer',
1073
            'bigint'        => 'bigint',
1074
            'tinytext'      => 'text',
1075
            'mediumtext'    => 'text',
1076
            'longtext'      => 'text',
1077
            'text'          => 'text',
1078
            'varchar'       => 'string',
1079
            'string'        => 'string',
1080
            'char'          => 'string',
1081
            'date'          => 'date',
1082
            'datetime'      => 'datetime',
1083
            'timestamp'     => 'datetime',
1084
            'time'          => 'time',
1085
            'float'         => 'float',
1086
            'double'        => 'float',
1087
            'real'          => 'float',
1088
            'decimal'       => 'decimal',
1089 8998
            'numeric'       => 'decimal',
1090
            'year'          => 'date',
1091
            'longblob'      => 'blob',
1092
            'blob'          => 'blob',
1093
            'mediumblob'    => 'blob',
1094 9487
            'tinyblob'      => 'blob',
1095
            'binary'        => 'binary',
1096 9487
            'varbinary'     => 'binary',
1097
            'set'           => 'simple_array',
1098
        ];
1099
    }
1100
1101
    /**
1102 7824
     * {@inheritDoc}
1103
     */
1104 7824
    public function getVarcharMaxLength()
1105
    {
1106
        return 65535;
1107
    }
1108
1109
    /**
1110 4247
     * {@inheritdoc}
1111
     */
1112 4247
    public function getBinaryMaxLength()
1113
    {
1114
        return 65535;
1115
    }
1116
1117
    /**
1118
     * {@inheritDoc}
1119
     */
1120
    protected function getReservedKeywordsClass()
1121 4160
    {
1122
        return Keywords\MySQLKeywords::class;
1123 4160
    }
1124
1125 4160
    /**
1126
     * {@inheritDoc}
1127
     *
1128
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
1129 4160
     * if DROP TEMPORARY TABLE is executed.
1130
     */
1131
    public function getDropTemporaryTableSQL($table)
1132
    {
1133
        if ($table instanceof Table) {
1134
            $table = $table->getQuotedName($this);
1135
        } elseif (! is_string($table)) {
1136
            throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1137
        }
1138
1139
        return 'DROP TEMPORARY TABLE ' . $table;
1140
    }
1141 9295
1142
    /**
1143 9295
     * Gets the SQL Snippet used to declare a BLOB column type.
1144 8243
     *     TINYBLOB   : 2 ^  8 - 1 = 255
1145
     *     BLOB       : 2 ^ 16 - 1 = 65535
1146 8243
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
1147 5124
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
1148
     *
1149
     * {@inheritDoc}
1150 8243
     */
1151 5124
    public function getBlobTypeDeclarationSQL(array $field)
1152
    {
1153
        if (! empty($field['length']) && is_numeric($field['length'])) {
1154 8243
            $length = $field['length'];
1155 8243
1156
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1157
                return 'TINYBLOB';
1158
            }
1159 9295
1160
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1161
                return 'BLOB';
1162
            }
1163
1164
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1165 8761
                return 'MEDIUMBLOB';
1166
            }
1167 8761
        }
1168
1169 8761
        return 'LONGBLOB';
1170
    }
1171
1172
    /**
1173
     * {@inheritdoc}
1174
     */
1175 2555
    public function quoteStringLiteral($str)
1176
    {
1177 2555
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1178
1179
        return parent::quoteStringLiteral($str);
1180
    }
1181
1182
    /**
1183 9641
     * {@inheritdoc}
1184
     */
1185 9641
    public function getDefaultTransactionIsolationLevel()
1186
    {
1187
        return TransactionIsolationLevel::REPEATABLE_READ;
1188
    }
1189
1190
    /**
1191
     * {@inheritdoc}
1192
     */
1193
    public function supportsColumnLengthIndexes() : bool
1194
    {
1195
        return true;
1196
    }
1197
}
1198