DrizzlePlatform.php 16.6 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Platforms;

5
use Doctrine\DBAL\Schema\ColumnDiff;
6
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
7 8
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
9
use Doctrine\DBAL\Schema\TableDiff;
Steve Müller's avatar
Steve Müller committed
10
use Doctrine\DBAL\Types\BinaryType;
11
use InvalidArgumentException;
12 13 14 15 16 17 18 19 20 21 22 23
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function func_get_args;
use function implode;
use function is_array;
use function is_bool;
use function is_numeric;
use function is_string;
use function sprintf;
use function trim;
24 25 26 27 28 29 30

/**
 * Drizzle platform
 */
class DrizzlePlatform extends AbstractPlatform
{
    /**
31
     * {@inheritDoc}
32 33 34 35 36 37 38
     */
    public function getName()
    {
        return 'drizzle';
    }

    /**
39
     * {@inheritDoc}
40 41 42 43 44 45
     */
    public function getIdentifierQuoteCharacter()
    {
        return '`';
    }

46 47
    /**
     * {@inheritDoc}
Benjamin Morel's avatar
Benjamin Morel committed
48 49
     */
    public function getConcatExpression()
50 51
    {
        $args = func_get_args();
52

53
        return 'CONCAT(' . implode(', ', (array) $args) . ')';
54 55
    }

56
    /**
57
     * {@inheritdoc}
58
     */
59
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
60
    {
61
        $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB';
62

63
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
64 65
    }

66 67 68
    /**
     * {@inheritDoc}
     */
69
    public function getDateDiffExpression($date1, $date2)
70
    {
71
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
72 73
    }

74
    /**
75
     * {@inheritDoc}
76 77 78 79 80 81
     */
    public function getBooleanTypeDeclarationSQL(array $field)
    {
        return 'BOOLEAN';
    }

82 83 84
    /**
     * {@inheritDoc}
     */
85 86 87 88 89
    public function getIntegerTypeDeclarationSQL(array $field)
    {
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

90 91 92
    /**
     * {@inheritDoc}
     */
93 94 95
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
    {
        $autoinc = '';
96
        if (! empty($columnDef['autoincrement'])) {
97 98
            $autoinc = ' AUTO_INCREMENT';
        }
99

100 101 102
        return $autoinc;
    }

103 104 105
    /**
     * {@inheritDoc}
     */
106 107 108 109 110
    public function getBigIntTypeDeclarationSQL(array $field)
    {
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

111 112 113
    /**
     * {@inheritDoc}
     */
114 115 116 117 118
    public function getSmallIntTypeDeclarationSQL(array $field)
    {
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
    }

119 120 121
    /**
     * {@inheritDoc}
     */
122 123 124 125 126
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)';
    }

Steve Müller's avatar
Steve Müller committed
127 128 129 130 131 132 133 134
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'VARBINARY(' . ($length ?: 255) . ')';
    }

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

157 158 159
    /**
     * {@inheritDoc}
     */
160 161 162 163 164 165
    public function getClobTypeDeclarationSQL(array $field)
    {
        return 'TEXT';
    }

    /**
166
     * {@inheritDoc}
167 168 169 170 171 172
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }

173 174 175
    /**
     * {@inheritDoc}
     */
176 177 178 179 180
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }

181 182 183
    /**
     * {@inheritDoc}
     */
184 185 186 187 188
    public function getDropDatabaseSQL($name)
    {
        return 'DROP DATABASE ' . $name;
    }

189 190 191
    /**
     * {@inheritDoc}
     */
192
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
193 194 195 196 197 198 199 200 201 202 203
    {
        $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'])) {
204
            foreach ($options['indexes'] as $index => $definition) {
205 206 207 208 209 210
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
            }
        }

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

        $query = 'CREATE ';

217
        if (! empty($options['temporary'])) {
218 219 220 221 222 223 224
            $query .= 'TEMPORARY ';
        }

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

225
        $sql = [$query];
226 227 228 229 230 231 232 233 234 235 236 237 238

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

        return $sql;
    }

    /**
     * Build SQL for table options
     *
239
     * @param mixed[] $options
240 241 242 243 244 245 246 247 248
     *
     * @return string
     */
    private function buildTableOptions(array $options)
    {
        if (isset($options['table_options'])) {
            return $options['table_options'];
        }

249
        $tableOptions = [];
250 251

        // Collate
252
        if (! isset($options['collate'])) {
253 254 255 256 257 258
            $options['collate'] = 'utf8_unicode_ci';
        }

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

        // Engine
259
        if (! isset($options['engine'])) {
260 261 262 263 264 265 266 267 268 269 270 271 272 273
            $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'], " '");

274
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
275 276 277 278 279 280 281 282 283 284 285 286 287
        }

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

        return implode(' ', $tableOptions);
    }

    /**
     * Build SQL for partition options.
     *
288
     * @param mixed[] $options
289 290 291 292 293
     *
     * @return string
     */
    private function buildPartitionOptions(array $options)
    {
294
        return isset($options['partition_options'])
295 296 297 298
            ? ' ' . $options['partition_options']
            : '';
    }

Benjamin Morel's avatar
Benjamin Morel committed
299 300 301
    /**
     * {@inheritDoc}
     */
302 303 304 305 306
    public function getListDatabasesSQL()
    {
        return "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME='LOCAL'";
    }

307 308 309
    /**
     * {@inheritDoc}
     */
310 311
    protected function getReservedKeywordsClass()
    {
312
        return Keywords\DrizzleKeywords::class;
313 314
    }

Benjamin Morel's avatar
Benjamin Morel committed
315 316 317
    /**
     * {@inheritDoc}
     */
318 319 320 321 322
    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
323 324 325
    /**
     * {@inheritDoc}
     */
326 327 328
    public function getListTableColumnsSQL($table, $database = null)
    {
        if ($database) {
329
            $databaseSQL = $this->quoteStringLiteral($database);
330
        } else {
331
            $databaseSQL = 'DATABASE()';
332 333
        }

334 335 336
        return 'SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, IS_AUTO_INCREMENT, CHARACTER_MAXIMUM_LENGTH, COLUMN_DEFAULT,' .
               ' NUMERIC_PRECISION, NUMERIC_SCALE, COLLATION_NAME' .
               ' FROM DATA_DICTIONARY.COLUMNS' .
337
               ' WHERE TABLE_SCHEMA=' . $databaseSQL . ' AND TABLE_NAME = ' . $this->quoteStringLiteral($table);
338 339
    }

Benjamin Morel's avatar
Benjamin Morel committed
340 341 342
    /**
     * {@inheritDoc}
     */
343 344
    public function getListTableForeignKeysSQL($table, $database = null)
    {
345
        if ($database) {
346
            $databaseSQL = $this->quoteStringLiteral($database);
347
        } else {
348
            $databaseSQL = 'DATABASE()';
349 350
        }

351 352
        return 'SELECT CONSTRAINT_NAME, CONSTRAINT_COLUMNS, REFERENCED_TABLE_NAME, REFERENCED_TABLE_COLUMNS, UPDATE_RULE, DELETE_RULE' .
               ' FROM DATA_DICTIONARY.FOREIGN_KEYS' .
353
               ' WHERE CONSTRAINT_SCHEMA=' . $databaseSQL . ' AND CONSTRAINT_TABLE=' . $this->quoteStringLiteral($table);
354 355
    }

356 357 358
    /**
     * {@inheritDoc}
     */
359 360
    public function getListTableIndexesSQL($table, $database = null)
    {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
361
        if ($database) {
362
            $databaseSQL = $this->quoteStringLiteral($database);
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
363
        } else {
364
            $databaseSQL = 'DATABASE()';
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
365 366 367
        }

        return "SELECT INDEX_NAME AS 'key_name', COLUMN_NAME AS 'column_name', IS_USED_IN_PRIMARY AS 'primary', IS_UNIQUE=0 AS 'non_unique'" .
368
               ' FROM DATA_DICTIONARY.INDEX_PARTS' .
369
               ' WHERE TABLE_SCHEMA=' . $databaseSQL . ' AND TABLE_NAME=' . $this->quoteStringLiteral($table);
370 371
    }

372 373 374
    /**
     * {@inheritDoc}
     */
375 376 377 378 379
    public function prefersIdentityColumns()
    {
        return true;
    }

380 381 382
    /**
     * {@inheritDoc}
     */
383 384 385 386
    public function supportsIdentityColumns()
    {
        return true;
    }
387

388 389 390
    /**
     * {@inheritDoc}
     */
391 392 393 394
    public function supportsInlineColumnComments()
    {
        return true;
    }
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
395

396 397 398
    /**
     * {@inheritDoc}
     */
399 400 401 402 403
    public function supportsViews()
    {
        return false;
    }

404 405 406 407 408 409 410 411
    /**
     * {@inheritdoc}
     */
    public function supportsColumnCollation()
    {
        return true;
    }

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

425
        if ($table instanceof Table) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
426
            $table = $table->getQuotedName($this);
427 428
        } elseif (! is_string($table)) {
            throw new InvalidArgumentException('DrizzlePlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
429 430 431 432 433 434 435 436 437 438 439 440
        }

        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
441
     * {@inheritDoc}
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
442 443 444 445 446 447
     */
    protected function getDropPrimaryKeySQL($table)
    {
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
    }

448 449 450
    /**
     * {@inheritDoc}
     */
451 452
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
453
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) {
454 455
            return 'TIMESTAMP';
        }
456 457

        return 'DATETIME';
458 459
    }

460 461 462
    /**
     * {@inheritDoc}
     */
463 464 465 466 467
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIME';
    }

468 469 470
    /**
     * {@inheritDoc}
     */
471 472 473 474
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATE';
    }
475

476
    /**
477
     * {@inheritDoc}
478
     */
479 480
    public function getAlterTableSQL(TableDiff $diff)
    {
481
        $columnSql  = [];
482
        $queryParts = [];
483 484

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

488
        foreach ($diff->addedColumns as $column) {
489 490 491 492
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }

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

498
        foreach ($diff->removedColumns as $column) {
499 500 501 502 503 504 505
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

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

506
        foreach ($diff->changedColumns as $columnDiff) {
507 508 509 510
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
            }

511 512
            /** @var ColumnDiff $columnDiff */
            $column      = $columnDiff->column;
513
            $columnArray = $column->toArray();
Steve Müller's avatar
Steve Müller committed
514 515 516 517

            // 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.
518
            if ($columnArray['type'] instanceof BinaryType &&
Steve Müller's avatar
Steve Müller committed
519 520 521 522 523 524
                $columnDiff->hasChanged('fixed') &&
                count($columnDiff->changedProperties) === 1
            ) {
                continue;
            }

525
            $columnArray['comment'] = $this->getColumnComment($column);
526
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
527 528 529
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
        }

530
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
531 532 533 534
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
            }

535 536
            $oldColumnName = new Identifier($oldColumnName);

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

543
        $sql      = [];
544
        $tableSql = [];
545

546
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
547
            if (count($queryParts) > 0) {
548
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
549 550 551 552 553 554 555 556 557 558
            }
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
        }

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

560 561 562
    /**
     * {@inheritDoc}
     */
563 564
    public function getDropTemporaryTableSQL($table)
    {
565
        if ($table instanceof Table) {
566
            $table = $table->getQuotedName($this);
567 568
        } elseif (! is_string($table)) {
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
569 570 571 572
        }

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

574 575 576
    /**
     * {@inheritDoc}
     */
577 578 579 580
    public function convertBooleans($item)
    {
        if (is_array($item)) {
            foreach ($item as $key => $value) {
581 582
                if (! is_bool($value) && ! is_numeric($item)) {
                    continue;
583
                }
584 585

                $item[$key] = $value ? 'true' : 'false';
586
            }
Steve Müller's avatar
Steve Müller committed
587
        } elseif (is_bool($item) || is_numeric($item)) {
588
            $item = $item ? 'true' : 'false';
589
        }
590

591 592
        return $item;
    }
593

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

603
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
604 605
    }

606 607
    /**
     * {@inheritDoc}
608 609
     *
     * @deprecated Use application-generated UUIDs instead
610
     */
611 612 613 614 615
    public function getGuidExpression()
    {
        return 'UUID()';
    }

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