DrizzlePlatform.php 17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * 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 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Platforms;

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;
Steve Müller's avatar
Steve Müller committed
26
use Doctrine\DBAL\Types\BinaryType;
27 28 29

/**
 * Drizzle platform
30 31
 *
 * @author Kim Hemsø Rasmussen <kimhemsoe@gmail.com>
32 33 34 35
 */
class DrizzlePlatform extends AbstractPlatform
{
    /**
36
     * {@inheritDoc}
37 38 39 40 41 42 43
     */
    public function getName()
    {
        return 'drizzle';
    }

    /**
44
     * {@inheritDoc}
45 46 47 48 49 50
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
    }

51 52
    /**
     * {@inheritDoc}
Benjamin Morel's avatar
Benjamin Morel committed
53 54
     */
    public function getConcatExpression()
55 56
    {
        $args = func_get_args();
57

58 59 60
        return 'CONCAT(' . join(', ', (array) $args) . ')';
    }

61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
65
    {
66
        $function = '+' === $operator ? 'DATE_ADD' : 'DATE_SUB';
67

68
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
69 70
    }

71 72 73
    /**
     * {@inheritDoc}
     */
74
    public function getDateDiffExpression($date1, $date2)
75
    {
76
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
77 78
    }

79
    /**
80
     * {@inheritDoc}
81 82 83 84 85 86
     */
    public function getBooleanTypeDeclarationSQL(array $field)
    {
        return 'BOOLEAN';
    }

87 88 89
    /**
     * {@inheritDoc}
     */
90 91 92 93 94
    public function getIntegerTypeDeclarationSQL(array $field)
    {
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

95 96 97
    /**
     * {@inheritDoc}
     */
98 99 100 101 102 103
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
    {
        $autoinc = '';
        if ( ! empty($columnDef['autoincrement'])) {
            $autoinc = ' AUTO_INCREMENT';
        }
104

105 106 107
        return $autoinc;
    }

108 109 110
    /**
     * {@inheritDoc}
     */
111 112 113 114 115
    public function getBigIntTypeDeclarationSQL(array $field)
    {
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

116 117 118
    /**
     * {@inheritDoc}
     */
119 120 121 122 123
    public function getSmallIntTypeDeclarationSQL(array $field)
    {
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

124 125 126
    /**
     * {@inheritDoc}
     */
127 128 129 130 131
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)';
    }

Steve Müller's avatar
Steve Müller committed
132 133 134 135 136 137 138 139
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'VARBINARY(' . ($length ?: 255) . ')';
    }

140 141 142
    /**
     * {@inheritDoc}
     */
143 144 145 146 147
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
            'boolean'       => 'boolean',
            'varchar'       => 'string',
Steve Müller's avatar
Steve Müller committed
148
            'varbinary'     => 'binary',
149
            'integer'       => 'integer',
Steve Müller's avatar
Steve Müller committed
150
            'blob'          => 'blob',
151 152 153 154
            'decimal'       => 'decimal',
            'datetime'      => 'datetime',
            'date'          => 'date',
            'time'          => 'time',
155 156
            'text'          => 'text',
            'timestamp'     => 'datetime',
157 158
            'double'        => 'float',
            'bigint'        => 'bigint',
159 160 161
        );
    }

162 163 164
    /**
     * {@inheritDoc}
     */
165 166 167 168 169 170
    public function getClobTypeDeclarationSQL(array $field)
    {
        return 'TEXT';
    }

    /**
171
     * {@inheritDoc}
172 173 174 175 176 177
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }

178 179 180
    /**
     * {@inheritDoc}
     */
181 182 183 184 185
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }

186 187 188
    /**
     * {@inheritDoc}
     */
189 190 191 192 193
    public function getDropDatabaseSQL($name)
    {
        return 'DROP DATABASE ' . $name;
    }

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    /**
     * {@inheritDoc}
     */
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
    {
        $queryFields = $this->getColumnDeclarationListSQL($columns);

        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
            foreach ($options['uniqueConstraints'] as $index => $definition) {
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($index, $definition);
            }
        }

        // add all indexes
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
209
            foreach ($options['indexes'] as $index => $definition) {
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
            }
        }

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

        $query = 'CREATE ';

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

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

        $sql[] = $query;

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

        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'];
        }

        $tableOptions = array();

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

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

        // Engine
        if ( ! isset($options['engine'])) {
            $options['engine'] = 'InnoDB';
        }

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

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

        // Comment
        if (isset($options['comment'])) {
            $comment = trim($options['comment'], " '");

279
            $tableOptions[] = sprintf("COMMENT = %s ", $this->quoteStringLiteral($comment));
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        }

        // 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']))
            ? ' ' . $options['partition_options']
            : '';
    }

Benjamin Morel's avatar
Benjamin Morel committed
304 305 306
    /**
     * {@inheritDoc}
     */
307 308 309 310 311
    public function getListDatabasesSQL()
    {
        return "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME='LOCAL'";
    }

312 313 314
    /**
     * {@inheritDoc}
     */
315 316 317 318 319
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\DrizzleKeywords';
    }

Benjamin Morel's avatar
Benjamin Morel committed
320 321 322
    /**
     * {@inheritDoc}
     */
323 324 325 326 327
    public function getListTablesSQL()
    {
        return "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE' AND TABLE_SCHEMA=DATABASE()";
    }

Benjamin Morel's avatar
Benjamin Morel committed
328 329 330
    /**
     * {@inheritDoc}
     */
331 332 333 334 335 336 337 338
    public function getListTableColumnsSQL($table, $database = null)
    {
        if ($database) {
            $database = "'" . $database . "'";
        } else {
            $database = 'DATABASE()';
        }

339
        return "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, IS_AUTO_INCREMENT, CHARACTER_MAXIMUM_LENGTH, COLUMN_DEFAULT," .
340
               " NUMERIC_PRECISION, NUMERIC_SCALE, COLLATION_NAME" .
341 342 343 344
               " FROM DATA_DICTIONARY.COLUMNS" .
               " WHERE TABLE_SCHEMA=" . $database . " AND TABLE_NAME = '" . $table . "'";
    }

Benjamin Morel's avatar
Benjamin Morel committed
345 346 347
    /**
     * {@inheritDoc}
     */
348 349
    public function getListTableForeignKeysSQL($table, $database = null)
    {
350 351 352 353 354 355 356 357 358
        if ($database) {
            $database = "'" . $database . "'";
        } else {
            $database = 'DATABASE()';
        }

        return "SELECT CONSTRAINT_NAME, CONSTRAINT_COLUMNS, REFERENCED_TABLE_NAME, REFERENCED_TABLE_COLUMNS, UPDATE_RULE, DELETE_RULE" .
               " FROM DATA_DICTIONARY.FOREIGN_KEYS" .
               " WHERE CONSTRAINT_SCHEMA=" . $database . " AND CONSTRAINT_TABLE='" . $table . "'";
359 360
    }

361 362 363
    /**
     * {@inheritDoc}
     */
364 365
    public function getListTableIndexesSQL($table, $database = null)
    {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
366 367 368 369 370 371 372 373 374
        if ($database) {
            $database = "'" . $database . "'";
        } else {
            $database = 'DATABASE()';
        }

        return "SELECT INDEX_NAME AS 'key_name', COLUMN_NAME AS 'column_name', IS_USED_IN_PRIMARY AS 'primary', IS_UNIQUE=0 AS 'non_unique'" .
               " FROM DATA_DICTIONARY.INDEX_PARTS" .
               " WHERE TABLE_SCHEMA=" . $database . " AND TABLE_NAME='" . $table . "'";
375 376
    }

377 378 379
    /**
     * {@inheritDoc}
     */
380 381 382 383 384
    public function prefersIdentityColumns()
    {
        return true;
    }

385 386 387
    /**
     * {@inheritDoc}
     */
388 389 390 391
    public function supportsIdentityColumns()
    {
        return true;
    }
392

393 394 395
    /**
     * {@inheritDoc}
     */
396 397 398 399
    public function supportsInlineColumnComments()
    {
        return true;
    }
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
400

401 402 403
    /**
     * {@inheritDoc}
     */
404 405 406 407 408
    public function supportsViews()
    {
        return false;
    }

409 410 411 412 413 414 415 416
    /**
     * {@inheritdoc}
     */
    public function supportsColumnCollation()
    {
        return true;
    }

417 418 419
    /**
     * {@inheritDoc}
     */
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
420 421
    public function getDropIndexSQL($index, $table=null)
    {
422
        if ($index instanceof Index) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
423
            $indexName = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
424
        } elseif (is_string($index)) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
425 426 427 428 429
            $indexName = $index;
        } else {
            throw new \InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
        }

430
        if ($table instanceof Table) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
431
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
432
        } elseif (!is_string($table)) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
433 434 435 436 437 438 439 440 441 442 443 444 445
            throw new \InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
        }

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

        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
446
     * {@inheritDoc}
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
447 448 449 450 451 452
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
    }

453 454 455
    /**
     * {@inheritDoc}
     */
456 457 458 459 460
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
            return 'TIMESTAMP';
        }
461 462

        return 'DATETIME';
463 464
    }

465 466 467
    /**
     * {@inheritDoc}
     */
468 469 470 471 472
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIME';
    }

473 474 475
    /**
     * {@inheritDoc}
     */
476 477 478 479
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATE';
    }
480

481
    /**
482
     * {@inheritDoc}
483
     */
484 485 486 487 488 489
    public function getAlterTableSQL(TableDiff $diff)
    {
        $columnSql = array();
        $queryParts = array();

        if ($diff->newName !== false) {
490
            $queryParts[] =  'RENAME TO ' . $diff->getNewName()->getQuotedName($this);
491 492
        }

493
        foreach ($diff->addedColumns as $column) {
494 495 496 497 498 499 500 501 502
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }

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

503
        foreach ($diff->removedColumns as $column) {
504 505 506 507 508 509 510
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

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

511
        foreach ($diff->changedColumns as $columnDiff) {
512 513 514 515
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
            }

516
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
517 518
            $column = $columnDiff->column;
            $columnArray = $column->toArray();
Steve Müller's avatar
Steve Müller committed
519 520 521 522

            // Do not generate column alteration clause if type is binary and only fixed property has changed.
            // Drizzle only supports binary type columns with variable length.
            // Avoids unnecessary table alteration statements.
523
            if ($columnArray['type'] instanceof BinaryType &&
Steve Müller's avatar
Steve Müller committed
524 525 526 527 528 529
                $columnDiff->hasChanged('fixed') &&
                count($columnDiff->changedProperties) === 1
            ) {
                continue;
            }

530
            $columnArray['comment'] = $this->getColumnComment($column);
531
            $queryParts[] =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
532 533 534
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
        }

535
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
536 537 538 539
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
            }

540 541
            $oldColumnName = new Identifier($oldColumnName);

542 543
            $columnArray = $column->toArray();
            $columnArray['comment'] = $this->getColumnComment($column);
544
            $queryParts[] =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
545 546 547 548 549 550
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
        }

        $sql = array();
        $tableSql = array();

551
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
552
            if (count($queryParts) > 0) {
553
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(", ", $queryParts);
554 555 556 557 558 559 560 561 562 563
            }
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
        }

        return array_merge($sql, $tableSql, $columnSql);
    }
564

565 566 567
    /**
     * {@inheritDoc}
     */
568 569
    public function getDropTemporaryTableSQL($table)
    {
570
        if ($table instanceof Table) {
571
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
572
        } elseif (!is_string($table)) {
573 574 575 576 577
            throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
        }

        return 'DROP TEMPORARY TABLE ' . $table;
    }
578

579 580 581
    /**
     * {@inheritDoc}
     */
582 583 584 585 586 587 588 589
    public function convertBooleans($item)
    {
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
                    $item[$key] = ($value) ? 'true' : 'false';
                }
            }
Steve Müller's avatar
Steve Müller committed
590
        } elseif (is_bool($item) || is_numeric($item)) {
591
           $item = ($item) ? 'true' : 'false';
592
        }
593

594 595
        return $item;
    }
596

597 598 599
    /**
     * {@inheritDoc}
     */
600 601 602 603 604
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
605 606

        return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
607 608
    }

609 610 611
    /**
     * {@inheritDoc}
     */
612 613 614 615 616
    public function getGuidExpression()
    {
        return 'UUID()';
    }

617 618 619
    /**
     * {@inheritDoc}
     */
620 621 622 623
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }
624
}