Completed
Pull Request — master (#3512)
by David
19:31 queued 22s
created

MySqlPlatform   F

Complexity

Total Complexity 182

Size/Duplication

Total Lines 1144
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 182
eloc 387
dl 0
loc 1144
rs 2
c 0
b 0
f 0
ccs 378
cts 405
cp 0.9333

68 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefaultValueDeclarationSQL() 0 8 3
A getDropDatabaseSQL() 0 3 1
A buildPartitionOptions() 0 5 2
C _getCreateTableSQL() 0 48 14
A getCreateDatabaseSQL() 0 3 1
A getLocateExpression() 0 7 2
A getTimeTypeDeclarationSQL() 0 3 1
A getListTableForeignKeysSQL() 0 21 2
A prefersIdentityColumns() 0 3 1
A getCollationFieldDeclaration() 0 3 1
A getDateDiffExpression() 0 3 1
A getListTablesSQL() 0 3 1
A getBooleanTypeDeclarationSQL() 0 3 1
A doModifyLimitQuery() 0 14 4
A getListViewsSQL() 0 5 1
A getCreateViewSQL() 0 3 1
A getClobTypeDeclarationSQL() 0 19 6
A getRegexpExpression() 0 3 1
A getGuidExpression() 0 3 1
A getDateTimeTypeDeclarationSQL() 0 7 3
A supportsInlineColumnComments() 0 3 1
A getDateTypeDeclarationSQL() 0 3 1
A getVarcharTypeDeclarationSQLSnippet() 0 4 4
A getListDatabasesSQL() 0 3 1
A getDropViewSQL() 0 3 1
A getConcatExpression() 0 3 1
A getDateArithmeticIntervalExpression() 0 5 2
A getIdentifierQuoteCharacter() 0 3 1
A getListTableConstraintsSQL() 0 3 1
A supportsIdentityColumns() 0 3 1
A supportsColumnCollation() 0 3 1
A getBinaryTypeDeclarationSQLSnippet() 0 3 4
A getListTableColumnsSQL() 0 15 2
A getListTableIndexesSQL() 0 14 2
A getSmallIntTypeDeclarationSQL() 0 3 1
A getBigIntTypeDeclarationSQL() 0 3 1
A getReadLockSQL() 0 3 1
A getDefaultTransactionIsolationLevel() 0 3 1
A getRemainingForeignKeyConstraintsRequiringRenamedIndexes() 0 24 6
A initializeDoctrineTypeMappings() 0 33 1
A getIntegerTypeDeclarationSQL() 0 3 1
A getPreAlterTableAlterPrimaryKeySQL() 0 32 6
A _getCommonIntegerTypeDeclarationSQL() 0 8 2
A getCreateIndexSQLFlags() 0 12 4
A getPostAlterTableIndexForeignKeySQL() 0 5 1
A getAdvancedForeignKeyOptionsSQL() 0 9 2
B getDropIndexSQL() 0 23 7
B getPreAlterTableIndexForeignKeySQL() 0 56 10
A getPreAlterTableRenameIndexForeignKeySQL() 0 14 3
A getDropTemporaryTableSQL() 0 9 3
A getPostAlterTableRenameIndexForeignKeySQL() 0 20 4
F getAlterTableSQL() 0 93 21
A getDropPrimaryKeySQL() 0 3 1
A getName() 0 3 1
A getBinaryMaxLength() 0 3 1
A getSetTransactionIsolationSQL() 0 3 1
A getFloatDeclarationSQL() 0 3 1
A getDecimalTypeDeclarationSQL() 0 3 1
A getUnsignedDeclaration() 0 3 2
A getVarcharMaxLength() 0 3 1
A getColumnCharsetDeclarationSQL() 0 3 1
A getReservedKeywordsClass() 0 3 1
A supportsColumnLengthIndexes() 0 3 1
A quoteStringLiteral() 0 5 1
B getPreAlterTableAlterIndexForeignKeySQL() 0 33 7
A getBlobTypeDeclarationSQL() 0 19 6
A getListTableMetadataSQL() 0 11 2
B buildTableOptions() 0 47 8

How to fix   Complexity   

Complex Class

Complex classes like MySqlPlatform often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MySqlPlatform, and based on these observations, apply Extract Interface, too.

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