MySqlPlatform.php 26.8 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
23 24 25
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
26 27
use Doctrine\DBAL\Types\BlobType;
use Doctrine\DBAL\Types\TextType;
28

29 30
/**
 * The MySqlPlatform provides the behavior, features and SQL dialect of the
31 32
 * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that
 * uses the InnoDB storage engine.
33
 *
Benjamin Morel's avatar
Benjamin Morel committed
34
 * @since  2.0
35
 * @author Roman Borschel <roman@code-factory.org>
36
 * @author Benjamin Eberlei <kontakt@beberlei.de>
Benjamin Morel's avatar
Benjamin Morel committed
37
 * @todo   Rename: MySQLPlatform
38
 */
39
class MySqlPlatform extends AbstractPlatform
40
{
41 42 43 44 45 46 47 48
    const LENGTH_LIMIT_TINYTEXT   = 255;
    const LENGTH_LIMIT_TEXT       = 65535;
    const LENGTH_LIMIT_MEDIUMTEXT = 16777215;

    const LENGTH_LIMIT_TINYBLOB   = 255;
    const LENGTH_LIMIT_BLOB       = 65535;
    const LENGTH_LIMIT_MEDIUMBLOB = 16777215;

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    /**
     * Adds MySQL-specific LIMIT clause to the query
     * 18446744073709551615 is 2^64-1 maximum of unsigned BIGINT the biggest limit possible
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
        if ($limit !== null) {
            $query .= ' LIMIT ' . $limit;
            if ($offset !== null) {
                $query .= ' OFFSET ' . $offset;
            }
        } elseif ($offset !== null) {
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
        }

        return $query;
    }

romanb's avatar
romanb committed
67
    /**
68
     * {@inheritDoc}
romanb's avatar
romanb committed
69 70 71 72
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
73
    }
74

75
    /**
76
     * {@inheritDoc}
77 78 79 80 81 82 83
     */
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }

    /**
84
     * {@inheritDoc}
85 86 87 88 89 90
     */
    public function getGuidExpression()
    {
        return 'UUID()';
    }

91
    /**
92
     * {@inheritDoc}
93 94 95 96 97 98
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
99 100

        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
101 102
    }

103
    /**
104
     * {@inheritDoc}
105 106 107 108 109 110
     */
    public function getConcatExpression()
    {
        $args = func_get_args();
        return 'CONCAT(' . join(', ', (array) $args) . ')';
    }
111

112
    /**
113
     * {@inheritdoc}
114
     */
115
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
116
    {
117
        $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB';
118

119
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
120 121
    }

122 123 124
    /**
     * {@inheritDoc}
     */
125
    public function getDateDiffExpression($date1, $date2)
126
    {
127
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
128
    }
129

Benjamin Morel's avatar
Benjamin Morel committed
130 131 132
    /**
     * {@inheritDoc}
     */
133
    public function getListDatabasesSQL()
134 135 136 137
    {
        return 'SHOW DATABASES';
    }

Benjamin Morel's avatar
Benjamin Morel committed
138 139 140
    /**
     * {@inheritDoc}
     */
141
    public function getListTableConstraintsSQL($table)
142
    {
143
        return 'SHOW INDEX FROM ' . $table;
144 145
    }

146
    /**
147 148
     * {@inheritDoc}
     *
149
     * Two approaches to listing the table indexes. The information_schema is
Pascal Borreli's avatar
Pascal Borreli committed
150
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
151 152
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
153
    {
154 155 156 157
        if ($currentDatabase) {
            return "SELECT TABLE_NAME AS `Table`, NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, ".
                   "SEQ_IN_INDEX AS Seq_in_index, COLUMN_NAME AS Column_Name, COLLATION AS Collation, ".
                   "CARDINALITY AS Cardinality, SUB_PART AS Sub_Part, PACKED AS Packed, " .
158
                   "NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment " .
159 160
                   "FROM information_schema.STATISTICS WHERE TABLE_NAME = '" . $table . "' AND TABLE_SCHEMA = '" . $currentDatabase . "'";
        }
161 162

        return 'SHOW INDEX FROM ' . $table;
163 164
    }

Benjamin Morel's avatar
Benjamin Morel committed
165 166 167
    /**
     * {@inheritDoc}
     */
168
    public function getListViewsSQL($database)
169
    {
170
        return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '".$database."'";
171 172
    }

Benjamin Morel's avatar
Benjamin Morel committed
173 174 175
    /**
     * {@inheritDoc}
     */
176
    public function getListTableForeignKeysSQL($table, $database = null)
177
    {
178 179 180
        $sql = "SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ".
               "k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ".
               "FROM information_schema.key_column_usage k /*!50116 ".
181
               "INNER JOIN information_schema.referential_constraints c ON ".
182
               "  c.constraint_name = k.constraint_name AND ".
183
               "  c.table_name = '$table' */ WHERE k.table_name = '$table'";
184

185
        if ($database) {
186
            $sql .= " AND k.table_schema = '$database' /*!50116 AND c.constraint_schema = '$database' */";
187 188
        }

189
        $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL";
190 191 192 193

        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
194 195 196
    /**
     * {@inheritDoc}
     */
197
    public function getCreateViewSQL($name, $sql)
198 199 200 201
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
202 203 204
    /**
     * {@inheritDoc}
     */
205
    public function getDropViewSQL($name)
206 207 208 209
    {
        return 'DROP VIEW '. $name;
    }

210
    /**
211
     * {@inheritDoc}
212
     */
213
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
214 215
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
216
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
217
    }
218

Steve Müller's avatar
Steve Müller committed
219 220 221 222 223 224 225 226
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
    }

227
    /**
228 229 230 231 232 233 234 235 236
     * Gets the SQL snippet used to declare a CLOB column type.
     *     TINYTEXT   : 2 ^  8 - 1 = 255
     *     TEXT       : 2 ^ 16 - 1 = 65535
     *     MEDIUMTEXT : 2 ^ 24 - 1 = 16777215
     *     LONGTEXT   : 2 ^ 32 - 1 = 4294967295
     *
     * @param array $field
     *
     * @return string
237
     */
238
    public function getClobTypeDeclarationSQL(array $field)
239
    {
240
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
241
            $length = $field['length'];
242

243
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
244
                return 'TINYTEXT';
245 246
            }

247
            if ($length <= static::LENGTH_LIMIT_TEXT) {
248
                return 'TEXT';
249 250
            }

251
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
252 253 254
                return 'MEDIUMTEXT';
            }
        }
255

256 257
        return 'LONGTEXT';
    }
258

259
    /**
260
     * {@inheritDoc}
261
     */
262
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
263
    {
264
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
265 266
            return 'TIMESTAMP';
        }
267 268

        return 'DATETIME';
269
    }
270

271
    /**
272
     * {@inheritDoc}
273
     */
274
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
275 276 277
    {
        return 'DATE';
    }
278

279
    /**
280
     * {@inheritDoc}
281
     */
282
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
283 284
    {
        return 'TIME';
285
    }
286

287
    /**
288
     * {@inheritDoc}
289
     */
290
    public function getBooleanTypeDeclarationSQL(array $field)
291 292 293 294
    {
        return 'TINYINT(1)';
    }

295 296 297 298
    /**
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
     * of a field declaration to be used in statements like CREATE TABLE.
     *
299 300
     * @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
     *
301
     * @param string $collation   name of the collation
302
     *
303 304 305 306 307
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
     *                 of a field declaration.
     */
    public function getCollationFieldDeclaration($collation)
    {
308
        return $this->getColumnCollationDeclarationSQL($collation);
309
    }
310

311
    /**
312 313
     * {@inheritDoc}
     *
314 315 316 317 318 319 320
     * MySql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
     */
    public function prefersIdentityColumns()
    {
        return true;
    }
321

romanb's avatar
romanb committed
322
    /**
323
     * {@inheritDoc}
romanb's avatar
romanb committed
324
     *
325
     * MySql supports this through AUTO_INCREMENT columns.
romanb's avatar
romanb committed
326 327 328 329
     */
    public function supportsIdentityColumns()
    {
        return true;
330 331
    }

332 333 334
    /**
     * {@inheritDoc}
     */
335 336 337
    public function supportsInlineColumnComments()
    {
        return true;
romanb's avatar
romanb committed
338
    }
339

Benjamin Morel's avatar
Benjamin Morel committed
340 341 342
    /**
     * {@inheritDoc}
     */
343 344 345 346 347
    public function supportsColumnCollation()
    {
        return true;
    }

348
    public function getListTablesSQL()
349
    {
350
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
351
    }
352

Benjamin Morel's avatar
Benjamin Morel committed
353 354 355
    /**
     * {@inheritDoc}
     */
356
    public function getListTableColumnsSQL($table, $database = null)
357
    {
358
        if ($database) {
359 360 361
            $database = "'" . $database . "'";
        } else {
            $database = 'DATABASE()';
362
        }
363

364 365 366 367
        return "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ".
               "COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, " .
               "CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ".
               "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = " . $database . " AND TABLE_NAME = '" . $table . "'";
368 369
    }

370
    /**
371
     * {@inheritDoc}
372
     */
373
    public function getCreateDatabaseSQL($name)
374
    {
375
        return 'CREATE DATABASE ' . $name;
376
    }
377

378
    /**
379
     * {@inheritDoc}
380
     */
381
    public function getDropDatabaseSQL($name)
382
    {
383
        return 'DROP DATABASE ' . $name;
384
    }
385

386
    /**
387
     * {@inheritDoc}
388
     */
389
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
390
    {
391
        $queryFields = $this->getColumnDeclarationListSQL($columns);
392

393
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
394
            foreach ($options['uniqueConstraints'] as $index => $definition) {
395
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($index, $definition);
396
            }
397 398 399 400
        }

        // add all indexes
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Steve Müller's avatar
Steve Müller committed
401
            foreach ($options['indexes'] as $index => $definition) {
402
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
403 404 405 406 407
            }
        }

        // attach all primary keys
        if (isset($options['primary']) && ! empty($options['primary'])) {
408
            $keyColumns = array_unique(array_values($options['primary']));
409 410 411 412
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
        }

        $query = 'CREATE ';
413

414 415 416
        if (!empty($options['temporary'])) {
            $query .= 'TEMPORARY ';
        }
417

418
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
419 420
        $query .= $this->buildTableOptions($options);
        $query .= $this->buildPartitionOptions($options);
421

422 423
        $sql[]  = $query;
        $engine = 'INNODB';
424

425 426 427 428 429 430
        if (isset($options['engine'])) {
            $engine = strtoupper(trim($options['engine']));
        }

        // Propagate foreign key constraints only for InnoDB.
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
431 432 433 434
            foreach ((array) $options['foreignKeys'] as $definition) {
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }
435

436 437 438
        return $sql;
    }

439 440 441 442 443 444 445 446 447 448 449 450 451
    /**
     * {@inheritdoc}
     */
    public function getDefaultValueDeclarationSQL($field)
    {
        // Unset the default value if the given field definition does not allow default values.
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
            $field['default'] = null;
        }

        return parent::getDefaultValueDeclarationSQL($field);
    }

452 453 454 455 456 457 458 459 460 461 462
    /**
     * Build SQL for table options
     *
     * @param array $options
     *
     * @return string
     */
    private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
463
        }
464

465 466 467
        $tableOptions = array();

        // Charset
468 469
        if ( ! isset($options['charset'])) {
            $options['charset'] = 'utf8';
470 471
        }

472 473 474
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);

        // Collate
475
        if ( ! isset($options['collate'])) {
476
            $options['collate'] = 'utf8_unicode_ci';
477
        }
478

479
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
480

481
        // Engine
482 483
        if ( ! isset($options['engine'])) {
            $options['engine'] = 'InnoDB';
484
        }
485

486
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
487

488 489 490
        // Auto increment
        if (isset($options['auto_increment'])) {
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
491
        }
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        // Comment
        if (isset($options['comment'])) {
            $comment = trim($options['comment'], " '");

            $tableOptions[] = sprintf("COMMENT = '%s' ", str_replace("'", "''", $comment));
        }

        // Row format
        if (isset($options['row_format'])) {
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
        }

        return implode(' ', $tableOptions);
    }

    /**
     * Build SQL for partition options.
     *
     * @param array $options
     *
     * @return string
     */
    private function buildPartitionOptions(array $options)
    {
        return (isset($options['partition_options']))
518
            ? ' ' . $options['partition_options']
519
            : '';
520
    }
521

522
    /**
523
     * {@inheritDoc}
524
     */
525
    public function getAlterTableSQL(TableDiff $diff)
526
    {
527
        $columnSql = array();
528 529
        $queryParts = array();
        if ($diff->newName !== false) {
530
            $queryParts[] = 'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
531 532
        }

533
        foreach ($diff->addedColumns as $column) {
534 535
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
536 537
            }

538 539 540
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
541 542
        }

543
        foreach ($diff->removedColumns as $column) {
544 545
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
546 547
            }

548
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
549 550
        }

551
        foreach ($diff->changedColumns as $columnDiff) {
552 553
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
554 555
            }

556
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
557
            $column = $columnDiff->column;
558
            $columnArray = $column->toArray();
559 560 561 562 563 564 565 566 567

            // Don't propagate default value changes for unsupported column types.
            if ($columnDiff->hasChanged('default') &&
                count($columnDiff->changedProperties) === 1 &&
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
            ) {
                continue;
            }

568
            $columnArray['comment'] = $this->getColumnComment($column);
569
            $queryParts[] =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
570
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
571 572
        }

573
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
574 575
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
576 577
            }

578
            $oldColumnName = new Identifier($oldColumnName);
579 580
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
581
            $queryParts[] =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
582
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
583 584
        }

585 586 587 588 589 590
        if (isset($diff->addedIndexes['primary'])) {
            $keyColumns = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
            unset($diff->addedIndexes['primary']);
        }

591
        $sql = array();
592
        $tableSql = array();
593

594
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
595
            if (count($queryParts) > 0) {
596
                $sql[] = 'ALTER TABLE ' . $diff->getName()->getQuotedName($this) . ' ' . implode(", ", $queryParts);
597 598 599 600 601 602
            }
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
603
        }
604 605

        return array_merge($sql, $tableSql, $columnSql);
606
    }
607

608
    /**
609
     * {@inheritDoc}
610 611 612 613
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        $sql = array();
614
        $table = $diff->getName()->getQuotedName($this);
615

616
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
617 618 619 620 621 622 623 624 625 626 627 628 629
            // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
            if ($remIndex->isPrimary() && $diff->fromTable instanceof Table) {
                foreach ($remIndex->getColumns() as $columnName) {
                    $column = $diff->fromTable->getColumn($columnName);

                    if ($column->getAutoincrement() === true) {
                        $column->setAutoincrement(false);

                        $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
                            $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
                    }
                }
            }
630 631 632 633

            foreach ($diff->addedIndexes as $addKey => $addIndex) {
                if ($remIndex->getColumns() == $addIndex->getColumns()) {

634 635 636 637 638 639
                    $indexClause = 'INDEX ' . $addIndex->getName();

                    if ($addIndex->isPrimary()) {
                        $indexClause = 'PRIMARY KEY';
                    } elseif ($addIndex->isUnique()) {
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
640 641 642
                    }

                    $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
643
                    $query .= 'ADD ' . $indexClause;
644
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')';
645 646 647 648 649 650 651 652 653 654 655

                    $sql[] = $query;

                    unset($diff->removedIndexes[$remKey]);
                    unset($diff->addedIndexes[$addKey]);

                    break;
                }
            }
        }

656 657 658 659 660 661 662 663 664 665 666 667 668
        $engine = 'INNODB';

        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
        }

        // Suppress foreign key constraint propagation on non-supporting engines.
        if ('INNODB' !== $engine) {
            $diff->addedForeignKeys   = array();
            $diff->changedForeignKeys = array();
            $diff->removedForeignKeys = array();
        }

669 670 671 672 673
        $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff));

        return $sql;
    }

674
    /**
675
     * {@inheritDoc}
676 677 678 679 680 681
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
Steve Müller's avatar
Steve Müller committed
682
        } elseif ($index->hasFlag('fulltext')) {
683
            $type .= 'FULLTEXT ';
684 685
        } elseif ($index->hasFlag('spatial')) {
            $type .= 'SPATIAL ';
686 687 688 689 690
        }

        return $type;
    }

691
    /**
692
     * {@inheritDoc}
693
     */
694
    public function getIntegerTypeDeclarationSQL(array $field)
695
    {
696
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
697 698
    }

699 700 701
    /**
     * {@inheritDoc}
     */
702
    public function getBigIntTypeDeclarationSQL(array $field)
703
    {
704
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
705 706
    }

707 708 709
    /**
     * {@inheritDoc}
     */
710
    public function getSmallIntTypeDeclarationSQL(array $field)
711
    {
712
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
713 714
    }

715 716 717
    /**
     * {@inheritDoc}
     */
718
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
719
    {
720
        $autoinc = '';
721
        if ( ! empty($columnDef['autoincrement'])) {
722 723
            $autoinc = ' AUTO_INCREMENT';
        }
724
        $unsigned = (isset($columnDef['unsigned']) && $columnDef['unsigned']) ? ' UNSIGNED' : '';
725

726
        return $unsigned . $autoinc;
727
    }
728

729
    /**
730
     * {@inheritDoc}
731
     */
732
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
733 734
    {
        $query = '';
735 736
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
737
        }
738
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
739 740
        return $query;
    }
741

742
    /**
743
     * {@inheritDoc}
744
     */
745
    public function getDropIndexSQL($index, $table=null)
746
    {
747
        if ($index instanceof Index) {
748
            $indexName = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
749
        } elseif (is_string($index)) {
750 751
            $indexName = $index;
        } else {
752
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
753
        }
754

755
        if ($table instanceof Table) {
756
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
757
        } elseif (!is_string($table)) {
758
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
759
        }
760

761
        if ($index instanceof Index && $index->isPrimary()) {
762
            // mysql primary keys are always named "PRIMARY",
763 764 765
            // so we cannot use them in statements because of them being keyword.
            return $this->getDropPrimaryKeySQL($table);
        }
766

767 768
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
    }
769

770
    /**
771 772 773
     * @param string $table
     *
     * @return string
774 775 776 777
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
778
    }
779

780 781 782
    /**
     * {@inheritDoc}
     */
783
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
784
    {
785
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
786
    }
787 788

    /**
789
     * {@inheritDoc}
790 791 792 793 794
     */
    public function getName()
    {
        return 'mysql';
    }
795

796 797 798
    /**
     * {@inheritDoc}
     */
799 800 801 802
    public function getReadLockSQL()
    {
        return 'LOCK IN SHARE MODE';
    }
803

804 805 806
    /**
     * {@inheritDoc}
     */
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
            'tinyint'       => 'boolean',
            'smallint'      => 'smallint',
            'mediumint'     => 'integer',
            'int'           => 'integer',
            'integer'       => 'integer',
            'bigint'        => 'bigint',
            'tinytext'      => 'text',
            'mediumtext'    => 'text',
            'longtext'      => 'text',
            'text'          => 'text',
            'varchar'       => 'string',
            'string'        => 'string',
            'char'          => 'string',
            'date'          => 'date',
            'datetime'      => 'datetime',
            'timestamp'     => 'datetime',
            'time'          => 'time',
827 828 829
            'float'         => 'float',
            'double'        => 'float',
            'real'          => 'float',
830 831 832
            'decimal'       => 'decimal',
            'numeric'       => 'decimal',
            'year'          => 'date',
833 834 835 836
            'longblob'      => 'blob',
            'blob'          => 'blob',
            'mediumblob'    => 'blob',
            'tinyblob'      => 'blob',
Steve Müller's avatar
Steve Müller committed
837 838
            'binary'        => 'binary',
            'varbinary'     => 'binary',
839
            'set'           => 'simple_array',
840 841
        );
    }
842

843 844 845
    /**
     * {@inheritDoc}
     */
846 847 848 849
    public function getVarcharMaxLength()
    {
        return 65535;
    }
850

Steve Müller's avatar
Steve Müller committed
851 852 853 854 855 856 857 858
    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 65535;
    }

859 860 861
    /**
     * {@inheritDoc}
     */
862 863 864 865
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords';
    }
866 867

    /**
868
     * {@inheritDoc}
869 870 871 872 873 874
     *
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
     * if DROP TEMPORARY TABLE is executed.
     */
    public function getDropTemporaryTableSQL($table)
    {
875
        if ($table instanceof Table) {
876
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
877
        } elseif (!is_string($table)) {
878 879 880 881 882
            throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
        }

        return 'DROP TEMPORARY TABLE ' . $table;
    }
883 884

    /**
885 886 887 888 889 890 891 892 893
     * Gets the SQL Snippet used to declare a BLOB column type.
     *     TINYBLOB   : 2 ^  8 - 1 = 255
     *     BLOB       : 2 ^ 16 - 1 = 65535
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
     *
     * @param array $field
     *
     * @return string
894 895 896
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
897 898 899
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
            $length = $field['length'];

900
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
901 902 903
                return 'TINYBLOB';
            }

904
            if ($length <= static::LENGTH_LIMIT_BLOB) {
905 906 907
                return 'BLOB';
            }

908
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
909 910 911 912
                return 'MEDIUMBLOB';
            }
        }

913 914
        return 'LONGBLOB';
    }
915
}