Failed Conditions
Pull Request — develop (#3518)
by Michael
29:00 queued 25:29
created

MySqlPlatform::getListViewsSQL()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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