Completed
Pull Request — 2.10.x (#3967)
by
unknown
11:59
created

MySqlPlatform::prefersIdentityColumns()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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