Completed
Push — 2.11.x ( 0a2e2f...a8544c )
by Grégoire
23s queued 16s
created

MySqlPlatform   F

Complexity

Total Complexity 183

Size/Duplication

Total Lines 1154
Duplicated Lines 0 %

Test Coverage

Coverage 93.12%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 183
eloc 388
dl 0
loc 1154
ccs 379
cts 407
cp 0.9312
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 prefersIdentityColumns() 0 3 1
A getCollationFieldDeclaration() 0 3 1
A getDropDatabaseSQL() 0 3 1
A getListTablesSQL() 0 3 1
A getBooleanTypeDeclarationSQL() 0 3 1
A getListTableColumnsSQL() 0 15 2
A getCreateViewSQL() 0 3 1
A getClobTypeDeclarationSQL() 0 19 6
B buildTableOptions() 0 45 8
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
C _getCreateTableSQL() 0 48 14
A getListTableMetadataSQL() 0 11 2
A getCreateDatabaseSQL() 0 3 1
A supportsIdentityColumns() 0 3 1
A supportsColumnCollation() 0 3 1
A getBinaryTypeDeclarationSQLSnippet() 0 3 4
F getAlterTableSQL() 0 94 21
A getSmallIntTypeDeclarationSQL() 0 3 1
A getBigIntTypeDeclarationSQL() 0 3 1
A getReadLockSQL() 0 3 1
A getColumnCollationDeclarationSQL() 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 10 2
B getDropIndexSQL() 0 23 7
B getPreAlterTableIndexForeignKeySQL() 0 58 10
A getPreAlterTableRenameIndexForeignKeySQL() 0 14 3
A getDropTemporaryTableSQL() 0 9 3
A getPostAlterTableRenameIndexForeignKeySQL() 0 20 4
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

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