Failed Conditions
Pull Request — master (#2929)
by Alexander
62:06
created

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