Failed Conditions
Pull Request — develop (#3348)
by Sergei
22:47
created

MySqlPlatform::getDatabaseNameSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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