Passed
Pull Request — master (#2412)
by Benoît
13:20
created

MySqlPlatform::getCollationFieldDeclaration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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