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

namespace Doctrine\DBAL\Platforms;

5
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
6 7
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
8
use Doctrine\DBAL\Schema\TableDiff;
Steve Müller's avatar
Steve Müller committed
9
use Doctrine\DBAL\Types\BinaryType;
10
use InvalidArgumentException;
11

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

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

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

48 49
    /**
     * {@inheritDoc}
Benjamin Morel's avatar
Benjamin Morel committed
50 51
     */
    public function getConcatExpression()
52
    {
Sergei Morozov's avatar
Sergei Morozov committed
53
        return 'CONCAT(' . implode(', ', func_get_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 343 344
     * @param string      $table
     * @param string|null $database
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
345
     */
346 347
    public function getListTableForeignKeysSQL($table, $database = null)
    {
348
        if ($database) {
349
            $databaseSQL = $this->quoteStringLiteral($database);
350
        } else {
351
            $databaseSQL = 'DATABASE()';
352 353
        }

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

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

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

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

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

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

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

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

415 416 417
    /**
     * {@inheritDoc}
     */
418
    public function getDropIndexSQL($index, $table = null)
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
419
    {
420
        if ($index instanceof Index) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
421
            $indexName = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
422
        } elseif (is_string($index)) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
423 424
            $indexName = $index;
        } else {
425
            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
426 427
        }

428
        if ($table instanceof Table) {
Kim Hemsø Rasmussen's avatar
Kim Hemsø Rasmussen committed
429
            $table = $table->getQuotedName($this);
430 431
        } 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
432 433 434 435 436 437 438 439 440 441 442 443
        }

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

    /**
444
     * @param string $table
445 446
     *
     * @return string
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
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
458
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) {
459 460
            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
    public function getAlterTableSQL(TableDiff $diff)
    {
486
        $columnSql  = [];
487
        $queryParts = [];
488

Sergei Morozov's avatar
Sergei Morozov committed
489 490 491 492
        $newName = $diff->getNewName();

        if ($newName !== false) {
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
493 494
        }

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

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

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

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

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

518
            $column      = $columnDiff->column;
519
            $columnArray = $column->toArray();
Steve Müller's avatar
Steve Müller committed
520 521 522 523

            // 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.
524 525
            if (
                $columnArray['type'] instanceof BinaryType &&
Steve Müller's avatar
Steve Müller committed
526 527 528 529 530 531
                $columnDiff->hasChanged('fixed') &&
                count($columnDiff->changedProperties) === 1
            ) {
                continue;
            }

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

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

542 543
            $oldColumnName = new Identifier($oldColumnName);

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

550
        $sql      = [];
551
        $tableSql = [];
552

553
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
554
            if (count($queryParts) > 0) {
555
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
556
            }
Grégoire Paris's avatar
Grégoire Paris committed
557

558 559 560 561 562 563 564 565 566
            $sql = array_merge(
                $this->getPreAlterTableIndexForeignKeySQL($diff),
                $sql,
                $this->getPostAlterTableIndexForeignKeySQL($diff)
            );
        }

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

568 569 570
    /**
     * {@inheritDoc}
     */
571 572
    public function getDropTemporaryTableSQL($table)
    {
573
        if ($table instanceof Table) {
574
            $table = $table->getQuotedName($this);
575 576
        } elseif (! is_string($table)) {
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
577 578 579 580
        }

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

582 583 584
    /**
     * {@inheritDoc}
     */
585 586 587 588
    public function convertBooleans($item)
    {
        if (is_array($item)) {
            foreach ($item as $key => $value) {
589
                if (! is_bool($value) && ! is_numeric($value)) {
590
                    continue;
591
                }
592 593

                $item[$key] = $value ? 'true' : 'false';
594
            }
Steve Müller's avatar
Steve Müller committed
595
        } elseif (is_bool($item) || is_numeric($item)) {
596
            $item = $item ? 'true' : 'false';
597
        }
598

599 600
        return $item;
    }
601

602 603 604
    /**
     * {@inheritDoc}
     */
605 606
    public function getLocateExpression($str, $substr, $startPos = false)
    {
607
        if ($startPos === false) {
608 609
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        }
610

611
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
612 613
    }

614 615
    /**
     * {@inheritDoc}
616 617
     *
     * @deprecated Use application-generated UUIDs instead
618
     */
619 620 621 622 623
    public function getGuidExpression()
    {
        return 'UUID()';
    }

624 625 626
    /**
     * {@inheritDoc}
     */
627 628 629 630
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }
631
}