MySqlPlatform.php 24.4 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

Benjamin Morel's avatar
Benjamin Morel committed
22 23 24 25
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
26

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

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    /**
     * 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
65
    /**
66
     * {@inheritDoc}
romanb's avatar
romanb committed
67 68 69 70
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
71
    }
72

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

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

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

        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
99 100
    }

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

110 111 112
    /**
     * {@inheritDoc}
     */
113 114 115 116 117
    public function getDateDiffExpression($date1, $date2)
    {
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
    }

118 119 120
    /**
     * {@inheritDoc}
     */
121 122
    public function getDateAddDaysExpression($date, $days)
    {
123
        return 'DATE_ADD(' . $date . ', INTERVAL ' . $days . ' DAY)';
124 125
    }

126 127 128
    /**
     * {@inheritDoc}
     */
129 130
    public function getDateSubDaysExpression($date, $days)
    {
131
        return 'DATE_SUB(' . $date . ', INTERVAL ' . $days . ' DAY)';
132 133
    }

134 135 136
    /**
     * {@inheritDoc}
     */
137 138
    public function getDateAddMonthExpression($date, $months)
    {
139
        return 'DATE_ADD(' . $date . ', INTERVAL ' . $months . ' MONTH)';
140 141
    }

142 143 144
    /**
     * {@inheritDoc}
     */
145 146
    public function getDateSubMonthExpression($date, $months)
    {
147
        return 'DATE_SUB(' . $date . ', INTERVAL ' . $months . ' MONTH)';
148
    }
149

Benjamin Morel's avatar
Benjamin Morel committed
150 151 152
    /**
     * {@inheritDoc}
     */
153
    public function getListDatabasesSQL()
154 155 156 157
    {
        return 'SHOW DATABASES';
    }

Benjamin Morel's avatar
Benjamin Morel committed
158 159 160
    /**
     * {@inheritDoc}
     */
161
    public function getListTableConstraintsSQL($table)
162
    {
163
        return 'SHOW INDEX FROM ' . $table;
164 165
    }

166
    /**
167 168
     * {@inheritDoc}
     *
169
     * Two approaches to listing the table indexes. The information_schema is
Pascal Borreli's avatar
Pascal Borreli committed
170
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
171 172
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
173
    {
174 175 176 177
        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, " .
178
                   "NULLABLE AS `Null`, INDEX_TYPE AS Index_Type, COMMENT AS Comment " .
179 180
                   "FROM information_schema.STATISTICS WHERE TABLE_NAME = '" . $table . "' AND TABLE_SCHEMA = '" . $currentDatabase . "'";
        }
181 182

        return 'SHOW INDEX FROM ' . $table;
183 184
    }

Benjamin Morel's avatar
Benjamin Morel committed
185 186 187
    /**
     * {@inheritDoc}
     */
188
    public function getListViewsSQL($database)
189
    {
190
        return "SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '".$database."'";
191 192
    }

Benjamin Morel's avatar
Benjamin Morel committed
193 194 195
    /**
     * {@inheritDoc}
     */
196
    public function getListTableForeignKeysSQL($table, $database = null)
197
    {
198 199 200
        $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 ".
201
               "INNER JOIN information_schema.referential_constraints c ON ".
202
               "  c.constraint_name = k.constraint_name AND ".
203
               "  c.table_name = '$table' */ WHERE k.table_name = '$table'";
204

205
        if ($database) {
206
            $sql .= " AND k.table_schema = '$database' /*!50116 AND c.constraint_schema = '$database' */";
207 208
        }

209
        $sql .= " AND k.`REFERENCED_COLUMN_NAME` is not NULL";
210 211 212 213

        return $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
214 215 216
    /**
     * {@inheritDoc}
     */
217
    public function getCreateViewSQL($name, $sql)
218 219 220 221
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

Benjamin Morel's avatar
Benjamin Morel committed
222 223 224
    /**
     * {@inheritDoc}
     */
225
    public function getDropViewSQL($name)
226 227 228 229
    {
        return 'DROP VIEW '. $name;
    }

230
    /**
231
     * {@inheritDoc}
232
     */
233
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
234 235
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
236
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
237
    }
238

239
    /**
240 241 242 243 244 245 246 247 248
     * 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
249
     */
250
    public function getClobTypeDeclarationSQL(array $field)
251
    {
252
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
253
            $length = $field['length'];
254

255
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
256
                return 'TINYTEXT';
257 258
            }

259
            if ($length <= static::LENGTH_LIMIT_TEXT) {
260
                return 'TEXT';
261 262
            }

263
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
264 265 266
                return 'MEDIUMTEXT';
            }
        }
267

268 269
        return 'LONGTEXT';
    }
270

271
    /**
272
     * {@inheritDoc}
273
     */
274
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
275
    {
276
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
277 278
            return 'TIMESTAMP';
        }
279 280

        return 'DATETIME';
281
    }
282

283
    /**
284
     * {@inheritDoc}
285
     */
286
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
287 288 289
    {
        return 'DATE';
    }
290

291
    /**
292
     * {@inheritDoc}
293
     */
294
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
295 296
    {
        return 'TIME';
297
    }
298

299
    /**
300
     * {@inheritDoc}
301
     */
302
    public function getBooleanTypeDeclarationSQL(array $field)
303 304 305 306
    {
        return 'TINYINT(1)';
    }

307 308 309 310 311
    /**
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
     * of a field declaration to be used in statements like CREATE TABLE.
     *
     * @param string $collation   name of the collation
312
     *
313 314 315 316 317 318 319
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
     *                 of a field declaration.
     */
    public function getCollationFieldDeclaration($collation)
    {
        return 'COLLATE ' . $collation;
    }
320

321
    /**
322 323
     * {@inheritDoc}
     *
324 325 326 327 328 329 330
     * MySql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
     */
    public function prefersIdentityColumns()
    {
        return true;
    }
331

romanb's avatar
romanb committed
332
    /**
333
     * {@inheritDoc}
romanb's avatar
romanb committed
334
     *
335
     * MySql supports this through AUTO_INCREMENT columns.
romanb's avatar
romanb committed
336 337 338 339
     */
    public function supportsIdentityColumns()
    {
        return true;
340 341
    }

342 343 344
    /**
     * {@inheritDoc}
     */
345 346 347
    public function supportsInlineColumnComments()
    {
        return true;
romanb's avatar
romanb committed
348
    }
349

Benjamin Morel's avatar
Benjamin Morel committed
350 351 352
    /**
     * {@inheritDoc}
     */
353
    public function getListTablesSQL()
354
    {
355
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
356
    }
357

Benjamin Morel's avatar
Benjamin Morel committed
358 359 360
    /**
     * {@inheritDoc}
     */
361
    public function getListTableColumnsSQL($table, $database = null)
362
    {
363 364 365 366 367 368
        if ($database) {
            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 CollactionName ".
                   "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '" . $database . "' AND TABLE_NAME = '" . $table . "'";
        }
369 370

        return 'DESCRIBE ' . $table;
371 372
    }

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

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

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

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

        // add all indexes
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
            foreach($options['indexes'] as $index => $definition) {
405
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
406 407 408 409 410
            }
        }

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

        $query = 'CREATE ';
416

417 418 419
        if (!empty($options['temporary'])) {
            $query .= 'TEMPORARY ';
        }
420

421
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
422 423
        $query .= $this->buildTableOptions($options);
        $query .= $this->buildPartitionOptions($options);
424

425 426 427 428 429 430 431
        $sql[] = $query;

        if (isset($options['foreignKeys'])) {
            foreach ((array) $options['foreignKeys'] as $definition) {
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446
        return $sql;
    }

    /**
     * Build SQL for table options
     *
     * @param array $options
     *
     * @return string
     */
    private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
447
        }
448

449 450 451
        $tableOptions = array();

        // Charset
452 453
        if ( ! isset($options['charset'])) {
            $options['charset'] = 'utf8';
454 455
        }

456 457 458
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);

        // Collate
459
        if ( ! isset($options['collate'])) {
460
            $options['collate'] = 'utf8_unicode_ci';
461
        }
462

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

465
        // Engine
466 467
        if ( ! isset($options['engine'])) {
            $options['engine'] = 'InnoDB';
468
        }
469

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

472 473 474
        // Auto increment
        if (isset($options['auto_increment'])) {
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
475
        }
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        // 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']))
502
            ? ' ' . $options['partition_options']
503
            : '';
504
    }
505

506
    /**
507
     * {@inheritDoc}
508
     */
509
    public function getAlterTableSQL(TableDiff $diff)
510
    {
511
        $columnSql = array();
512 513
        $queryParts = array();
        if ($diff->newName !== false) {
514
            $queryParts[] = 'RENAME TO ' . $diff->newName;
515 516
        }

517
        foreach ($diff->addedColumns as $column) {
518 519
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
520 521
            }

522 523 524
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
525 526
        }

527
        foreach ($diff->removedColumns as $column) {
528 529
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
530 531
            }

532
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
533 534
        }

535
        foreach ($diff->changedColumns as $columnDiff) {
536 537
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
538 539
            }

540
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
541
            $column = $columnDiff->column;
542 543
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
544
            $queryParts[] =  'CHANGE ' . ($columnDiff->oldColumnName) . ' '
545
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
546 547
        }

548
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
549 550
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
551 552
            }

553 554
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
555
            $queryParts[] =  'CHANGE ' . $oldColumnName . ' '
556
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
557 558
        }

559
        $sql = array();
560
        $tableSql = array();
561

562
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
563 564 565 566 567 568 569 570
            if (count($queryParts) > 0) {
                $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . implode(", ", $queryParts);
            }
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
571
        }
572 573

        return array_merge($sql, $tableSql, $columnSql);
574
    }
575

576
    /**
577
     * {@inheritDoc}
578 579 580 581 582 583
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        $sql = array();
        $table = $diff->name;

584
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
585 586 587 588 589 590 591 592 593 594 595 596 597
            // 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());
                    }
                }
            }
598 599 600 601 602 603 604 605 606 607 608

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

                    $type = '';
                    if ($addIndex->isUnique()) {
                        $type = 'UNIQUE ';
                    }

                    $query = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
                    $query .= 'ADD ' . $type . 'INDEX ' . $addIndex->getName();
609
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')';
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

                    $sql[] = $query;

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

                    break;
                }
            }
        }

        $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff));

        return $sql;
    }

626
    /**
627
     * {@inheritDoc}
628 629 630 631 632 633 634 635 636 637 638 639 640
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
        } else if ($index->hasFlag('fulltext')) {
            $type .= 'FULLTEXT ';
        }

        return $type;
    }

641
    /**
642
     * {@inheritDoc}
643
     */
644
    public function getIntegerTypeDeclarationSQL(array $field)
645
    {
646
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
647 648
    }

649 650 651
    /**
     * {@inheritDoc}
     */
652
    public function getBigIntTypeDeclarationSQL(array $field)
653
    {
654
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
655 656
    }

657 658 659
    /**
     * {@inheritDoc}
     */
660
    public function getSmallIntTypeDeclarationSQL(array $field)
661
    {
662
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
663 664
    }

665 666 667
    /**
     * {@inheritDoc}
     */
668
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
669
    {
670
        $autoinc = '';
671
        if ( ! empty($columnDef['autoincrement'])) {
672 673
            $autoinc = ' AUTO_INCREMENT';
        }
674
        $unsigned = (isset($columnDef['unsigned']) && $columnDef['unsigned']) ? ' UNSIGNED' : '';
675

676
        return $unsigned . $autoinc;
677
    }
678

679
    /**
680
     * {@inheritDoc}
681
     */
682
    public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
683 684
    {
        $query = '';
685 686
        if ($foreignKey->hasOption('match')) {
            $query .= ' MATCH ' . $foreignKey->getOption('match');
687
        }
688
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
689 690
        return $query;
    }
691

692
    /**
693
     * {@inheritDoc}
694
     */
695
    public function getDropIndexSQL($index, $table=null)
696
    {
697
        if ($index instanceof Index) {
698 699 700 701
            $indexName = $index->getQuotedName($this);
        } else if(is_string($index)) {
            $indexName = $index;
        } else {
702
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
703
        }
704

705
        if ($table instanceof Table) {
706
            $table = $table->getQuotedName($this);
707
        } else if(!is_string($table)) {
708
            throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
709
        }
710

711
        if ($index instanceof Index && $index->isPrimary()) {
712
            // mysql primary keys are always named "PRIMARY",
713 714 715
            // so we cannot use them in statements because of them being keyword.
            return $this->getDropPrimaryKeySQL($table);
        }
716

717 718
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
    }
719

720
    /**
721 722 723
     * @param string $table
     *
     * @return string
724 725 726 727
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
728
    }
729

730 731 732
    /**
     * {@inheritDoc}
     */
733
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
734
    {
735
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
736
    }
737 738

    /**
739
     * {@inheritDoc}
740 741 742 743 744
     */
    public function getName()
    {
        return 'mysql';
    }
745

746 747 748
    /**
     * {@inheritDoc}
     */
749 750 751 752
    public function getReadLockSQL()
    {
        return 'LOCK IN SHARE MODE';
    }
753

754 755 756
    /**
     * {@inheritDoc}
     */
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    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',
777 778 779
            'float'         => 'float',
            'double'        => 'float',
            'real'          => 'float',
780 781 782
            'decimal'       => 'decimal',
            'numeric'       => 'decimal',
            'year'          => 'date',
783 784 785 786
            'longblob'      => 'blob',
            'blob'          => 'blob',
            'mediumblob'    => 'blob',
            'tinyblob'      => 'blob',
787
            'binary'        => 'blob',
788
            'varbinary'     => 'blob',
789
            'set'           => 'simple_array',
790 791
        );
    }
792

793 794 795
    /**
     * {@inheritDoc}
     */
796 797 798 799
    public function getVarcharMaxLength()
    {
        return 65535;
    }
800

801 802 803
    /**
     * {@inheritDoc}
     */
804 805 806 807
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords';
    }
808 809

    /**
810
     * {@inheritDoc}
811 812 813 814 815 816
     *
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
     * if DROP TEMPORARY TABLE is executed.
     */
    public function getDropTemporaryTableSQL($table)
    {
817
        if ($table instanceof Table) {
818 819 820 821 822 823 824
            $table = $table->getQuotedName($this);
        } else if(!is_string($table)) {
            throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
        }

        return 'DROP TEMPORARY TABLE ' . $table;
    }
825 826

    /**
827 828 829 830 831 832 833 834 835
     * 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
836 837 838
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
839 840 841
        if ( ! empty($field['length']) && is_numeric($field['length'])) {
            $length = $field['length'];

842
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
843 844 845
                return 'TINYBLOB';
            }

846
            if ($length <= static::LENGTH_LIMIT_BLOB) {
847 848 849
                return 'BLOB';
            }

850
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
851 852 853 854
                return 'MEDIUMBLOB';
            }
        }

855 856
        return 'LONGBLOB';
    }
857
}