Completed
Push — develop ( 0c4aa7...b62acb )
by Sergei
55s queued 14s
created

MySqlPlatform::getBinaryMaxLength()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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