MySqlPlatform::prefersIdentityColumns()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
    protected function doModifyLimitQuery($query, $limit, $offset)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
69
    {
70
        if ($limit !== null) {
71
            $query .= ' LIMIT ' . $limit;
72
73
            if ($offset > 0) {
74
                $query .= ' OFFSET ' . $offset;
75
            }
76
        } elseif ($offset > 0) {
77
            // 2^64-1 is the maximum of unsigned BIGINT, the biggest limit possible
78
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
79
        }
80
81
        return $query;
82
    }
83
84
    /**
85
     * {@inheritDoc}
86
     */
87
    public function getIdentifierQuoteCharacter()
88
    {
89
        return '`';
90
    }
91
92
    /**
93
     * {@inheritDoc}
94
     */
95
    public function getRegexpExpression()
96
    {
97
        return 'RLIKE';
98
    }
99
100
    /**
101
     * {@inheritDoc}
102
     *
103
     * @deprecated Use application-generated UUIDs instead
104
     */
105
    public function getGuidExpression()
106
    {
107
        return 'UUID()';
108
    }
109
110
    /**
111
     * {@inheritDoc}
112
     */
113 View Code Duplication
    public function getLocateExpression($str, $substr, $startPos = false)
114
    {
115
        if ($startPos == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
116
            return 'LOCATE(' . $substr . ', ' . $str . ')';
117
        }
118
119
        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
120
    }
121
122
    /**
123
     * {@inheritDoc}
124
     */
125
    public function getConcatExpression()
126
    {
127
        $args = func_get_args();
128
129
        return 'CONCAT(' . join(', ', (array) $args) . ')';
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
136
    {
137
        $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB';
138
139
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
140
    }
141
142
    /**
143
     * {@inheritDoc}
144
     */
145
    public function getDateDiffExpression($date1, $date2)
146
    {
147
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
148
    }
149
150
    /**
151
     * {@inheritDoc}
152
     */
153
    public function getListDatabasesSQL()
154
    {
155
        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 View Code Duplication
    public function getListTableIndexesSQL($table, $currentDatabase = null)
173
    {
174
        if ($currentDatabase) {
175
            $currentDatabase = $this->quoteStringLiteral($currentDatabase);
176
            $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
                   "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
    public function getListViewsSQL($database)
192
    {
193
        $database = $this->quoteStringLiteral($database);
194
195
        return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = " . $database;
196
    }
197
198
    /**
199
     * {@inheritDoc}
200
     */
201
    public function getListTableForeignKeysSQL($table, $database = null)
202
    {
203
        $table = $this->quoteStringLiteral($table);
204
205
        if (null !== $database) {
206
            $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
               "  c.table_name = $table */ WHERE k.table_name = $table";
215
216
        $databaseNameSql = $database ?? 'DATABASE()';
217
218
        $sql .= " AND k.table_schema = $databaseNameSql /*!50116 AND c.constraint_schema = $databaseNameSql */";
219
        $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL";
220
221
        return $sql;
222
    }
223
224
    /**
225
     * {@inheritDoc}
226
     */
227
    public function getCreateViewSQL($name, $sql)
228
    {
229
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
230
    }
231
232
    /**
233
     * {@inheritDoc}
234
     */
235
    public function getDropViewSQL($name)
236
    {
237
        return 'DROP VIEW '. $name;
238
    }
239
240
    /**
241
     * {@inheritDoc}
242
     */
243
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
244
    {
245
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
246
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
247
    }
248
249
    /**
250
     * {@inheritdoc}
251
     */
252
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
253
    {
254
        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 View Code Duplication
    public function getClobTypeDeclarationSQL(array $field)
269
    {
270
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
271
            $length = $field['length'];
272
273
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
274
                return 'TINYTEXT';
275
            }
276
277
            if ($length <= static::LENGTH_LIMIT_TEXT) {
278
                return 'TEXT';
279
            }
280
281
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
282
                return 'MEDIUMTEXT';
283
            }
284
        }
285
286
        return 'LONGTEXT';
287
    }
288
289
    /**
290
     * {@inheritDoc}
291
     */
292 View Code Duplication
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
293
    {
294
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
295
            return 'TIMESTAMP';
296
        }
297
298
        return 'DATETIME';
299
    }
300
301
    /**
302
     * {@inheritDoc}
303
     */
304
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
305
    {
306
        return 'DATE';
307
    }
308
309
    /**
310
     * {@inheritDoc}
311
     */
312
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
313
    {
314
        return 'TIME';
315
    }
316
317
    /**
318
     * {@inheritDoc}
319
     */
320
    public function getBooleanTypeDeclarationSQL(array $field)
321
    {
322
        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
    public function prefersIdentityColumns()
348
    {
349
        return true;
350
    }
351
352
    /**
353
     * {@inheritDoc}
354
     *
355
     * MySql supports this through AUTO_INCREMENT columns.
356
     */
357
    public function supportsIdentityColumns()
358
    {
359
        return true;
360
    }
361
362
    /**
363
     * {@inheritDoc}
364
     */
365
    public function supportsInlineColumnComments()
366
    {
367
        return true;
368
    }
369
370
    /**
371
     * {@inheritDoc}
372
     */
373
    public function supportsColumnCollation()
374
    {
375
        return true;
376
    }
377
378
    /**
379
     * {@inheritDoc}
380
     */
381
    public function getListTablesSQL()
382
    {
383
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
384
    }
385
386
    /**
387
     * {@inheritDoc}
388
     */
389 View Code Duplication
    public function getListTableColumnsSQL($table, $database = null)
390
    {
391
        $table = $this->quoteStringLiteral($table);
392
393
        if ($database) {
394
            $database = $this->quoteStringLiteral($database);
395
        } else {
396
            $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
               "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = " . $database . " AND TABLE_NAME = " . $table;
403
    }
404
405
    /**
406
     * {@inheritDoc}
407
     */
408
    public function getCreateDatabaseSQL($name)
409
    {
410
        return 'CREATE DATABASE ' . $name;
411
    }
412
413
    /**
414
     * {@inheritDoc}
415
     */
416
    public function getDropDatabaseSQL($name)
417
    {
418
        return 'DROP DATABASE ' . $name;
419
    }
420
421
    /**
422
     * {@inheritDoc}
423
     */
424
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
425
    {
426
        $queryFields = $this->getColumnDeclarationListSQL($columns);
427
428
        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
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
436
            foreach ($options['indexes'] as $index => $definition) {
437
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
438
            }
439
        }
440
441
        // attach all primary keys
442 View Code Duplication
        if (isset($options['primary']) && ! empty($options['primary'])) {
443
            $keyColumns = array_unique(array_values($options['primary']));
444
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
445
        }
446
447
        $query = 'CREATE ';
448
449
        if (!empty($options['temporary'])) {
450
            $query .= 'TEMPORARY ';
451
        }
452
453
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
454
        $query .= $this->buildTableOptions($options);
455
        $query .= $this->buildPartitionOptions($options);
456
457
        $sql    = [$query];
458
        $engine = 'INNODB';
459
460
        if (isset($options['engine'])) {
461
            $engine = strtoupper(trim($options['engine']));
462
        }
463
464
        // Propagate foreign key constraints only for InnoDB.
465 View Code Duplication
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
466
            foreach ((array) $options['foreignKeys'] as $definition) {
467
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
468
            }
469
        }
470
471
        return $sql;
472
    }
473
474
    /**
475
     * {@inheritdoc}
476
     */
477
    public function getDefaultValueDeclarationSQL($field)
478
    {
479
        // Unset the default value if the given field definition does not allow default values.
480
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
481
            $field['default'] = null;
482
        }
483
484
        return parent::getDefaultValueDeclarationSQL($field);
485
    }
486
487
    /**
488
     * Build SQL for table options
489
     *
490
     * @param array $options
491
     *
492
     * @return string
493
     */
494
    private function buildTableOptions(array $options)
495
    {
496
        if (isset($options['table_options'])) {
497
            return $options['table_options'];
498
        }
499
500
        $tableOptions = [];
501
502
        // Charset
503
        if ( ! isset($options['charset'])) {
504
            $options['charset'] = 'utf8';
505
        }
506
507
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
508
509
        // Collate
510
        if ( ! isset($options['collate'])) {
511
            $options['collate'] = $options['charset'] . '_unicode_ci';
512
        }
513
514
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
515
516
        // Engine
517
        if ( ! isset($options['engine'])) {
518
            $options['engine'] = 'InnoDB';
519
        }
520
521
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
522
523
        // Auto increment
524
        if (isset($options['auto_increment'])) {
525
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
526
        }
527
528
        // Comment
529 View Code Duplication
        if (isset($options['comment'])) {
530
            $comment = trim($options['comment'], " '");
531
532
            $tableOptions[] = sprintf("COMMENT = %s ", $this->quoteStringLiteral($comment));
533
        }
534
535
        // Row format
536
        if (isset($options['row_format'])) {
537
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
538
        }
539
540
        return implode(' ', $tableOptions);
541
    }
542
543
    /**
544
     * Build SQL for partition options.
545
     *
546
     * @param array $options
547
     *
548
     * @return string
549
     */
550
    private function buildPartitionOptions(array $options)
551
    {
552
        return (isset($options['partition_options']))
553
            ? ' ' . $options['partition_options']
554
            : '';
555
    }
556
557
    /**
558
     * {@inheritDoc}
559
     */
560
    public function getAlterTableSQL(TableDiff $diff)
561
    {
562
        $columnSql = [];
563
        $queryParts = [];
564
        if ($diff->newName !== false) {
565
            $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
566
        }
567
568 View Code Duplication
        foreach ($diff->addedColumns as $column) {
569
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
570
                continue;
571
            }
572
573
            $columnArray = $column->toArray();
574
            $columnArray['comment'] = $this->getColumnComment($column);
575
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
576
        }
577
578 View Code Duplication
        foreach ($diff->removedColumns as $column) {
579
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
580
                continue;
581
            }
582
583
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
584
        }
585
586 View Code Duplication
        foreach ($diff->changedColumns as $columnDiff) {
587
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
588
                continue;
589
            }
590
591
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
592
            $column = $columnDiff->column;
593
            $columnArray = $column->toArray();
594
595
            // Don't propagate default value changes for unsupported column types.
596
            if ($columnDiff->hasChanged('default') &&
597
                count($columnDiff->changedProperties) === 1 &&
598
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
599
            ) {
600
                continue;
601
            }
602
603
            $columnArray['comment'] = $this->getColumnComment($column);
604
            $queryParts[] =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
605
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
606
        }
607
608 View Code Duplication
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
609
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
610
                continue;
611
            }
612
613
            $oldColumnName = new Identifier($oldColumnName);
614
            $columnArray = $column->toArray();
615
            $columnArray['comment'] = $this->getColumnComment($column);
616
            $queryParts[] =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
617
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
618
        }
619
620
        if (isset($diff->addedIndexes['primary'])) {
621
            $keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
622
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
623
            unset($diff->addedIndexes['primary']);
624
        }
625
626
        $sql = [];
627
        $tableSql = [];
628
629 View Code Duplication
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
630
            if (count($queryParts) > 0) {
631
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(", ", $queryParts);
632
            }
633
            $sql = array_merge(
634
                $this->getPreAlterTableIndexForeignKeySQL($diff),
635
                $sql,
636
                $this->getPostAlterTableIndexForeignKeySQL($diff)
637
            );
638
        }
639
640
        return array_merge($sql, $tableSql, $columnSql);
641
    }
642
643
    /**
644
     * {@inheritDoc}
645
     */
646
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
647
    {
648
        $sql = [];
649
        $table = $diff->getName($this)->getQuotedName($this);
650
651
        foreach ($diff->changedIndexes as $changedIndex) {
652
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
653
        }
654
655
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
656
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
657
658
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
659
                if ($remIndex->getColumns() == $addIndex->getColumns()) {
660
661
                    $indexClause = 'INDEX ' . $addIndex->getName();
662
663
                    if ($addIndex->isPrimary()) {
664
                        $indexClause = 'PRIMARY KEY';
665
                    } elseif ($addIndex->isUnique()) {
666
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
667
                    }
668
669
                    $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
670
                    $query .= 'ADD ' . $indexClause;
671
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')';
672
673
                    $sql[] = $query;
674
675
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
676
677
                    break;
678
                }
679
            }
680
        }
681
682
        $engine = 'INNODB';
683
684
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
685
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
686
        }
687
688
        // Suppress foreign key constraint propagation on non-supporting engines.
689
        if ('INNODB' !== $engine) {
690
            $diff->addedForeignKeys   = [];
691
            $diff->changedForeignKeys = [];
692
            $diff->removedForeignKeys = [];
693
        }
694
695
        $sql = array_merge(
696
            $sql,
697
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
698
            parent::getPreAlterTableIndexForeignKeySQL($diff),
699
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
700
        );
701
702
        return $sql;
703
    }
704
705
    /**
706
     * @param TableDiff $diff
707
     * @param Index     $index
708
     *
709
     * @return string[]
710
     */
711
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index)
712
    {
713
        $sql = [];
714
715
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
716
            return $sql;
717
        }
718
719
        $tableName = $diff->getName($this)->getQuotedName($this);
720
721
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
722 View Code Duplication
        foreach ($index->getColumns() as $columnName) {
723
            if (! $diff->fromTable->hasColumn($columnName)) {
724
                continue;
725
            }
726
727
            $column = $diff->fromTable->getColumn($columnName);
728
729
            if ($column->getAutoincrement() === true) {
730
                $column->setAutoincrement(false);
731
732
                $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
733
                    $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
                $column->setAutoincrement(true);
737
            }
738
        }
739
740
        return $sql;
741
    }
742
743
    /**
744
     * @param TableDiff $diff The table diff to gather the SQL for.
745
     *
746
     * @return array
747
     */
748
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff)
749
    {
750
        $sql = [];
751
        $table = $diff->getName($this)->getQuotedName($this);
752
753
        foreach ($diff->changedIndexes as $changedIndex) {
754
            // Changed primary key
755
            if ($changedIndex->isPrimary() && $diff->fromTable instanceof Table) {
756 View Code Duplication
                foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
757
                    $column = $diff->fromTable->getColumn($columnName);
758
759
                    // Check if an autoincrement column was dropped from the primary key.
760
                    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
                        $column->setAutoincrement(false);
764
765
                        $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
766
                            $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
                        $column->setAutoincrement(true);
771
                    }
772
                }
773
            }
774
        }
775
776
        return $sql;
777
    }
778
779
    /**
780
     * @param TableDiff $diff The table diff to gather the SQL for.
781
     *
782
     * @return array
783
     */
784
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
785
    {
786
        $sql = [];
787
        $tableName = $diff->getName($this)->getQuotedName($this);
788
789 View Code Duplication
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
790
            if (! in_array($foreignKey, $diff->changedForeignKeys, true)) {
791
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
792
            }
793
        }
794
795
        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
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff)
809
    {
810
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
811
            return [];
812
        }
813
814
        $foreignKeys = [];
815
        /** @var \Doctrine\DBAL\Schema\ForeignKeyConstraint[] $remainingForeignKeys */
816
        $remainingForeignKeys = array_diff_key(
817
            $diff->fromTable->getForeignKeys(),
818
            $diff->removedForeignKeys
819
        );
820
821
        foreach ($remainingForeignKeys as $foreignKey) {
822
            foreach ($diff->renamedIndexes as $index) {
823
                if ($foreignKey->intersectsIndexColumns($index)) {
824
                    $foreignKeys[] = $foreignKey;
825
826
                    break;
827
                }
828
            }
829
        }
830
831
        return $foreignKeys;
832
    }
833
834
    /**
835
     * {@inheritdoc}
836
     */
837
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
838
    {
839
        return array_merge(
840
            parent::getPostAlterTableIndexForeignKeySQL($diff),
841
            $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
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff)
851
    {
852
        $sql = [];
853
        $tableName = (false !== $diff->newName)
854
            ? $diff->getNewName()->getQuotedName($this)
855
            : $diff->getName($this)->getQuotedName($this);
856
857 View Code Duplication
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
858
            if (! in_array($foreignKey, $diff->changedForeignKeys, true)) {
859
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
860
            }
861
        }
862
863
        return $sql;
864
    }
865
866
    /**
867
     * {@inheritDoc}
868
     */
869 View Code Duplication
    protected function getCreateIndexSQLFlags(Index $index)
870
    {
871
        $type = '';
872
        if ($index->isUnique()) {
873
            $type .= 'UNIQUE ';
874
        } elseif ($index->hasFlag('fulltext')) {
875
            $type .= 'FULLTEXT ';
876
        } elseif ($index->hasFlag('spatial')) {
877
            $type .= 'SPATIAL ';
878
        }
879
880
        return $type;
881
    }
882
883
    /**
884
     * {@inheritDoc}
885
     */
886
    public function getIntegerTypeDeclarationSQL(array $field)
887
    {
888
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
889
    }
890
891
    /**
892
     * {@inheritDoc}
893
     */
894
    public function getBigIntTypeDeclarationSQL(array $field)
895
    {
896
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
897
    }
898
899
    /**
900
     * {@inheritDoc}
901
     */
902
    public function getSmallIntTypeDeclarationSQL(array $field)
903
    {
904
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
905
    }
906
907
    /**
908
     * {@inheritdoc}
909
     */
910
    public function getFloatDeclarationSQL(array $field)
911
    {
912
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($field);
913
    }
914
915
    /**
916
     * {@inheritdoc}
917
     */
918
    public function getDecimalTypeDeclarationSQL(array $columnDef)
919
    {
920
        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
    private function getUnsignedDeclaration(array $columnDef)
931
    {
932
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
933
    }
934
935
    /**
936
     * {@inheritDoc}
937
     */
938
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
939
    {
940
        $autoinc = '';
941
        if ( ! empty($columnDef['autoincrement'])) {
942
            $autoinc = ' AUTO_INCREMENT';
943
        }
944
945
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
946
    }
947
948
    /**
949
     * {@inheritDoc}
950
     */
951
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
952
    {
953
        $query = '';
954
        if ($foreignKey->hasOption('match')) {
955
            $query .= ' MATCH ' . $foreignKey->getOption('match');
956
        }
957
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
958
959
        return $query;
960
    }
961
962
    /**
963
     * {@inheritDoc}
964
     */
965 View Code Duplication
    public function getDropIndexSQL($index, $table=null)
966
    {
967
        if ($index instanceof Index) {
968
            $indexName = $index->getQuotedName($this);
969
        } elseif (is_string($index)) {
970
            $indexName = $index;
971
        } else {
972
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
973
        }
974
975
        if ($table instanceof Table) {
976
            $table = $table->getQuotedName($this);
977
        } elseif (!is_string($table)) {
978
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
979
        }
980
981
        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
            return $this->getDropPrimaryKeySQL($table);
985
        }
986
987
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
988
    }
989
990
    /**
991
     * @param string $table
992
     *
993
     * @return string
994
     */
995
    protected function getDropPrimaryKeySQL($table)
996
    {
997
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
998
    }
999
1000
    /**
1001
     * {@inheritDoc}
1002
     */
1003
    public function getSetTransactionIsolationSQL($level)
1004
    {
1005
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
1006
    }
1007
1008
    /**
1009
     * {@inheritDoc}
1010
     */
1011
    public function getName()
1012
    {
1013
        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
    protected function initializeDoctrineTypeMappings()
1028
    {
1029
        $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
    }
1062
1063
    /**
1064
     * {@inheritDoc}
1065
     */
1066
    public function getVarcharMaxLength()
1067
    {
1068
        return 65535;
1069
    }
1070
1071
    /**
1072
     * {@inheritdoc}
1073
     */
1074
    public function getBinaryMaxLength()
1075
    {
1076
        return 65535;
1077
    }
1078
1079
    /**
1080
     * {@inheritDoc}
1081
     */
1082
    protected function getReservedKeywordsClass()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1083
    {
1084
        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 View Code Duplication
    public function getDropTemporaryTableSQL($table)
1094
    {
1095
        if ($table instanceof Table) {
1096
            $table = $table->getQuotedName($this);
1097
        } elseif (!is_string($table)) {
1098
            throw new \InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1099
        }
1100
1101
        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 View Code Duplication
    public function getBlobTypeDeclarationSQL(array $field)
1116
    {
1117
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
1118
            $length = $field['length'];
1119
1120
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1121
                return 'TINYBLOB';
1122
            }
1123
1124
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1125
                return 'BLOB';
1126
            }
1127
1128
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1129
                return 'MEDIUMBLOB';
1130
            }
1131
        }
1132
1133
        return 'LONGBLOB';
1134
    }
1135
1136
    /**
1137
     * {@inheritdoc}
1138
     */
1139
    public function quoteStringLiteral($str)
1140
    {
1141
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1142
1143
        return parent::quoteStringLiteral($str);
1144
    }
1145
1146
    /**
1147
     * {@inheritdoc}
1148
     */
1149
    public function getDefaultTransactionIsolationLevel()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
1150
    {
1151
        return TransactionIsolationLevel::REPEATABLE_READ;
1152
    }
1153
}
1154