Completed
Pull Request — 2.11.x (#3956)
by David
14:33
created

MySqlPlatform   F

Complexity

Total Complexity 183

Size/Duplication

Total Lines 1153
Duplicated Lines 0 %

Test Coverage

Coverage 93.35%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 183
eloc 387
dl 0
loc 1153
ccs 379
cts 406
cp 0.9335
rs 2
c 1
b 0
f 0

69 Methods

Rating   Name   Duplication   Size   Complexity  
A buildPartitionOptions() 0 5 2
A getLocateExpression() 0 7 2
A getDateDiffExpression() 0 3 1
A doModifyLimitQuery() 0 14 4
A getListViewsSQL() 0 5 1
A getRegexpExpression() 0 3 1
A getGuidExpression() 0 3 1
A getListDatabasesSQL() 0 3 1
A getConcatExpression() 0 3 1
A getDateArithmeticIntervalExpression() 0 5 2
A getIdentifierQuoteCharacter() 0 3 1
A getListTableConstraintsSQL() 0 3 1
A getListTableIndexesSQL() 0 14 2
A getTimeTypeDeclarationSQL() 0 3 1
A getListTableForeignKeysSQL() 0 21 2
A getDefaultValueDeclarationSQL() 0 8 3
A getSmallIntTypeDeclarationSQL() 0 3 1
A getBigIntTypeDeclarationSQL() 0 3 1
A getReadLockSQL() 0 3 1
A prefersIdentityColumns() 0 3 1
A getCollationFieldDeclaration() 0 3 1
A getColumnCollationDeclarationSQL() 0 3 1
A getDropDatabaseSQL() 0 3 1
A getListTablesSQL() 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 getBooleanTypeDeclarationSQL() 0 3 1
A _getCommonIntegerTypeDeclarationSQL() 0 8 2
A getCreateIndexSQLFlags() 0 12 4
A getListTableColumnsSQL() 0 15 2
A getPostAlterTableIndexForeignKeySQL() 0 5 1
A getAdvancedForeignKeyOptionsSQL() 0 9 2
A getCreateViewSQL() 0 3 1
A getClobTypeDeclarationSQL() 0 19 6
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
B buildTableOptions() 0 45 8
A getName() 0 3 1
A getBinaryMaxLength() 0 3 1
A getDateTimeTypeDeclarationSQL() 0 7 3
A supportsInlineColumnComments() 0 3 1
A getDateTypeDeclarationSQL() 0 3 1
A getVarcharTypeDeclarationSQLSnippet() 0 4 4
A getDropViewSQL() 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
C _getCreateTableSQL() 0 48 14
A getColumnCharsetDeclarationSQL() 0 3 1
A getReservedKeywordsClass() 0 3 1
A supportsColumnLengthIndexes() 0 3 1
A getListTableMetadataSQL() 0 11 2
A getCreateDatabaseSQL() 0 3 1
A quoteStringLiteral() 0 5 1
A supportsIdentityColumns() 0 3 1
A supportsColumnCollation() 0 3 1
A getBinaryTypeDeclarationSQLSnippet() 0 3 4
B getPreAlterTableAlterIndexForeignKeySQL() 0 33 7
A getBlobTypeDeclarationSQL() 0 19 6

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