Failed Conditions
Push — 3.0.x ( 655b6b...430dce )
by Grégoire
16:57 queued 12:22
created

getPreAlterTableIndexForeignKeySQL()   B

Complexity

Conditions 10
Paths 48

Size

Total Lines 58
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 10.0203

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 58
ccs 32
cts 34
cp 0.9412
rs 7.6666
c 0
b 0
f 0
cc 10
nc 48
nop 1
crap 10.0203

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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