AbstractPlatform.php 103 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
 * <http://www.doctrine-project.org>.
18 19
 */

20 21
namespace Doctrine\DBAL\Platforms;

Grégoire Paris's avatar
Grégoire Paris committed
22 23 24 25 26 27 28 29 30 31 32 33 34
use Doctrine\Common\EventManager;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
use Doctrine\DBAL\Events;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
Benjamin Morel's avatar
Benjamin Morel committed
35
use Doctrine\DBAL\Schema\Constraint;
Grégoire Paris's avatar
Grégoire Paris committed
36 37 38
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Identifier;
use Doctrine\DBAL\Schema\Index;
Benjamin Morel's avatar
Benjamin Morel committed
39 40 41
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
42
use Doctrine\DBAL\TransactionIsolationLevel;
Grégoire Paris's avatar
Grégoire Paris committed
43
use Doctrine\DBAL\Types;
Benjamin Morel's avatar
Benjamin Morel committed
44
use Doctrine\DBAL\Types\Type;
45
use function addcslashes;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
use function array_map;
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function explode;
use function func_get_args;
use function get_class;
use function implode;
use function in_array;
use function is_array;
use function is_bool;
use function is_int;
use function is_string;
use function join;
61 62
use function preg_quote;
use function preg_replace;
63
use function sprintf;
64
use function str_replace;
65
use function strlen;
66 67 68
use function strpos;
use function strtolower;
use function strtoupper;
69 70 71 72 73 74

/**
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
 * They are a passive source of information.
 *
Benjamin Morel's avatar
Benjamin Morel committed
75 76 77 78 79 80 81 82
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @todo   Remove any unnecessary methods.
83
 */
84
abstract class AbstractPlatform
85
{
86
    /**
87
     * @var int
88 89 90 91
     */
    const CREATE_INDEXES = 1;

    /**
92
     * @var int
93 94 95
     */
    const CREATE_FOREIGNKEYS = 2;

96
    /**
97
     * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
98
     */
99
    public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
100 101

    /**
102
     * @deprecated Use DateIntervalUnit::MINUTE.
103
     */
104
    public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
105 106

    /**
107
     * @deprecated Use DateIntervalUnit::HOUR.
108
     */
109
    public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
110 111

    /**
112
     * @deprecated Use DateIntervalUnit::DAY.
113
     */
114
    public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
115 116

    /**
117
     * @deprecated Use DateIntervalUnit::WEEK.
118
     */
119
    public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
120 121

    /**
122
     * @deprecated Use DateIntervalUnit::MONTH.
123
     */
124
    public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
125 126

    /**
127
     * @deprecated Use DateIntervalUnit::QUARTER.
128
     */
129
    public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
130 131

    /**
132
     * @deprecated Use DateIntervalUnit::QUARTER.
133
     */
134
    public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
135

136
    /**
137
     * @var int
138 139
     *
     * @deprecated Use TrimMode::UNSPECIFIED.
140
     */
141
    public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
142 143

    /**
144
     * @var int
145 146
     *
     * @deprecated Use TrimMode::LEADING.
147
     */
148
    public const TRIM_LEADING = TrimMode::LEADING;
149 150

    /**
151
     * @var int
152 153
     *
     * @deprecated Use TrimMode::TRAILING.
154
     */
155
    public const TRIM_TRAILING = TrimMode::TRAILING;
156 157

    /**
158
     * @var int
159 160
     *
     * @deprecated Use TrimMode::BOTH.
161
     */
162
    public const TRIM_BOTH = TrimMode::BOTH;
163

164
    /**
Benjamin Morel's avatar
Benjamin Morel committed
165
     * @var array|null
166 167 168
     */
    protected $doctrineTypeMapping = null;

169 170 171 172
    /**
     * Contains a list of all columns that should generate parseable column comments for type-detection
     * in reverse engineering scenarios.
     *
Benjamin Morel's avatar
Benjamin Morel committed
173
     * @var array|null
174 175 176
     */
    protected $doctrineTypeComments = null;

177
    /**
Konstantin Kuklin's avatar
Konstantin Kuklin committed
178
     * @var \Doctrine\Common\EventManager
179 180 181
     */
    protected $_eventManager;

182 183 184
    /**
     * Holds the KeywordList instance for the current platform.
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
185
     * @var \Doctrine\DBAL\Platforms\Keywords\KeywordList
186 187 188
     */
    protected $_keywords;

189 190 191
    /**
     * Constructor.
     */
Benjamin Morel's avatar
Benjamin Morel committed
192 193 194
    public function __construct()
    {
    }
195

196 197 198
    /**
     * Sets the EventManager used by the Platform.
     *
199
     * @param \Doctrine\Common\EventManager $eventManager
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
     */
    public function setEventManager(EventManager $eventManager)
    {
        $this->_eventManager = $eventManager;
    }

    /**
     * Gets the EventManager used by the Platform.
     *
     * @return \Doctrine\Common\EventManager
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

216
    /**
Benjamin Morel's avatar
Benjamin Morel committed
217
     * Returns the SQL snippet that declares a boolean column.
218 219
     *
     * @param array $columnDef
220
     *
221 222 223 224 225
     * @return string
     */
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
226
     * Returns the SQL snippet that declares a 4 byte integer column.
227 228
     *
     * @param array $columnDef
229
     *
230 231 232 233 234
     * @return string
     */
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
235
     * Returns the SQL snippet that declares an 8 byte integer column.
236 237
     *
     * @param array $columnDef
238
     *
239 240 241 242 243
     * @return string
     */
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
244
     * Returns the SQL snippet that declares a 2 byte integer column.
245 246
     *
     * @param array $columnDef
247
     *
248 249 250 251 252
     * @return string
     */
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
253
     * Returns the SQL snippet that declares common properties of an integer column.
254 255
     *
     * @param array $columnDef
Benjamin Morel's avatar
Benjamin Morel committed
256
     *
257 258 259 260 261
     * @return string
     */
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
262
     * Lazy load Doctrine Type Mappings.
263 264 265 266 267
     *
     * @return void
     */
    abstract protected function initializeDoctrineTypeMappings();

268
    /**
Benjamin Morel's avatar
Benjamin Morel committed
269
     * Initializes Doctrine Type Mappings with the platform defaults
270
     * and with all additional type mappings.
Benjamin Morel's avatar
Benjamin Morel committed
271 272
     *
     * @return void
273 274 275 276 277 278 279 280 281 282 283 284
     */
    private function initializeAllDoctrineTypeMappings()
    {
        $this->initializeDoctrineTypeMappings();

        foreach (Type::getTypesMap() as $typeName => $className) {
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
                $this->doctrineTypeMapping[$dbType] = $typeName;
            }
        }
    }

285
    /**
Benjamin Morel's avatar
Benjamin Morel committed
286
     * Returns the SQL snippet used to declare a VARCHAR column type.
287 288
     *
     * @param array $field
289
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
290
     * @return string
291
     */
292 293 294 295 296 297
    public function getVarcharTypeDeclarationSQL(array $field)
    {
        if ( !isset($field['length'])) {
            $field['length'] = $this->getVarcharDefaultLength();
        }

298
        $fixed = $field['fixed'] ?? false;
299 300 301 302

        if ($field['length'] > $this->getVarcharMaxLength()) {
            return $this->getClobTypeDeclarationSQL($field);
        }
303 304

        return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
305 306
    }

Steve Müller's avatar
Steve Müller committed
307 308 309 310 311 312 313 314 315 316 317 318 319
    /**
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
     *
     * @param array $field The column definition.
     *
     * @return string
     */
    public function getBinaryTypeDeclarationSQL(array $field)
    {
        if ( ! isset($field['length'])) {
            $field['length'] = $this->getBinaryDefaultLength();
        }

320
        $fixed = $field['fixed'] ?? false;
Steve Müller's avatar
Steve Müller committed
321 322 323 324 325 326 327 328

        if ($field['length'] > $this->getBinaryMaxLength()) {
            return $this->getBlobTypeDeclarationSQL($field);
        }

        return $this->getBinaryTypeDeclarationSQLSnippet($field['length'], $fixed);
    }

329
    /**
Benjamin Morel's avatar
Benjamin Morel committed
330
     * Returns the SQL snippet to declare a GUID/UUID field.
331
     *
332
     * By default this maps directly to a CHAR(36) and only maps to more
333 334 335
     * special datatypes when the underlying databases support this datatype.
     *
     * @param array $field
336
     *
337 338
     * @return string
     */
339
    public function getGuidTypeDeclarationSQL(array $field)
340
    {
341 342 343
        $field['length'] = 36;
        $field['fixed']  = true;

344 345 346
        return $this->getVarcharTypeDeclarationSQL($field);
    }

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    /**
     * Returns the SQL snippet to declare a JSON field.
     *
     * By default this maps directly to a CLOB and only maps to more
     * special datatypes when the underlying databases support this datatype.
     *
     * @param array $field
     *
     * @return string
     */
    public function getJsonTypeDeclarationSQL(array $field)
    {
        return $this->getClobTypeDeclarationSQL($field);
    }

Christophe Coevoet's avatar
Christophe Coevoet committed
362
    /**
363 364
     * @param int  $length
     * @param bool $fixed
365
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
366
     * @return string
367
     *
Benjamin Morel's avatar
Benjamin Morel committed
368
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
Christophe Coevoet's avatar
Christophe Coevoet committed
369
     */
370 371 372 373
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
    }
374

Steve Müller's avatar
Steve Müller committed
375 376 377
    /**
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
     *
378 379
     * @param int  $length The length of the column.
     * @param bool $fixed  Whether the column length is fixed.
Steve Müller's avatar
Steve Müller committed
380 381 382 383 384 385 386 387 388 389
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        throw DBALException::notSupported('BINARY/VARBINARY column types are not supported by this platform.');
    }

390
    /**
Benjamin Morel's avatar
Benjamin Morel committed
391
     * Returns the SQL snippet used to declare a CLOB column type.
392 393
     *
     * @param array $field
394 395
     *
     * @return string
396 397 398
     */
    abstract public function getClobTypeDeclarationSQL(array $field);

399
    /**
Benjamin Morel's avatar
Benjamin Morel committed
400
     * Returns the SQL Snippet used to declare a BLOB column type.
401 402
     *
     * @param array $field
403 404
     *
     * @return string
405 406 407
     */
    abstract public function getBlobTypeDeclarationSQL(array $field);

408 409 410 411 412 413 414
    /**
     * Gets the name of the platform.
     *
     * @return string
     */
    abstract public function getName();

415
    /**
Benjamin Morel's avatar
Benjamin Morel committed
416
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
417 418 419
     *
     * @param string $dbType
     * @param string $doctrineType
420
     *
Benjamin Morel's avatar
Benjamin Morel committed
421
     * @throws \Doctrine\DBAL\DBALException If the type is not found.
422 423 424 425
     */
    public function registerDoctrineTypeMapping($dbType, $doctrineType)
    {
        if ($this->doctrineTypeMapping === null) {
426
            $this->initializeAllDoctrineTypeMappings();
427 428 429 430 431 432 433 434
        }

        if (!Types\Type::hasType($doctrineType)) {
            throw DBALException::typeNotFound($doctrineType);
        }

        $dbType = strtolower($dbType);
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
435 436 437 438 439 440

        $doctrineType = Type::getType($doctrineType);

        if ($doctrineType->requiresSQLCommentHint($this)) {
            $this->markDoctrineTypeCommented($doctrineType);
        }
441 442 443
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
444
     * Gets the Doctrine type that is mapped for the given database column type.
445
     *
Benjamin Morel's avatar
Benjamin Morel committed
446
     * @param string $dbType
447
     *
448
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
449 450
     *
     * @throws \Doctrine\DBAL\DBALException
451 452 453 454
     */
    public function getDoctrineTypeMapping($dbType)
    {
        if ($this->doctrineTypeMapping === null) {
455
            $this->initializeAllDoctrineTypeMappings();
456
        }
457

458
        $dbType = strtolower($dbType);
459

460
        if (!isset($this->doctrineTypeMapping[$dbType])) {
461 462
            throw new \Doctrine\DBAL\DBALException("Unknown database type ".$dbType." requested, " . get_class($this) . " may not support it.");
        }
463 464

        return $this->doctrineTypeMapping[$dbType];
465 466
    }

467
    /**
Benjamin Morel's avatar
Benjamin Morel committed
468
     * Checks if a database type is currently supported by this platform.
469 470
     *
     * @param string $dbType
471
     *
472
     * @return bool
473 474 475 476
     */
    public function hasDoctrineTypeMappingFor($dbType)
    {
        if ($this->doctrineTypeMapping === null) {
477
            $this->initializeAllDoctrineTypeMappings();
478 479 480
        }

        $dbType = strtolower($dbType);
Benjamin Morel's avatar
Benjamin Morel committed
481

482 483 484
        return isset($this->doctrineTypeMapping[$dbType]);
    }

485
    /**
Benjamin Morel's avatar
Benjamin Morel committed
486
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
487 488 489 490 491
     *
     * @return void
     */
    protected function initializeCommentedDoctrineTypes()
    {
492
        $this->doctrineTypeComments = [];
493 494 495

        foreach (Type::getTypesMap() as $typeName => $className) {
            $type = Type::getType($typeName);
Benjamin Eberlei's avatar
Benjamin Eberlei committed
496

497 498 499 500
            if ($type->requiresSQLCommentHint($this)) {
                $this->doctrineTypeComments[] = $typeName;
            }
        }
501 502 503 504 505
    }

    /**
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
     *
Benjamin Morel's avatar
Benjamin Morel committed
506
     * @param \Doctrine\DBAL\Types\Type $doctrineType
507
     *
508
     * @return bool
509 510 511 512 513 514 515 516 517 518 519
     */
    public function isCommentedDoctrineType(Type $doctrineType)
    {
        if ($this->doctrineTypeComments === null) {
            $this->initializeCommentedDoctrineTypes();
        }

        return in_array($doctrineType->getName(), $this->doctrineTypeComments);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
520
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
521
     *
Benjamin Morel's avatar
Benjamin Morel committed
522
     * @param string|\Doctrine\DBAL\Types\Type $doctrineType
523
     *
524 525
     * @return void
     */
526
    public function markDoctrineTypeCommented($doctrineType)
527 528 529 530
    {
        if ($this->doctrineTypeComments === null) {
            $this->initializeCommentedDoctrineTypes();
        }
531

532
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
533 534 535
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
536 537 538
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
     *
     * @param \Doctrine\DBAL\Types\Type $doctrineType
539
     *
540 541 542 543 544 545 546
     * @return string
     */
    public function getDoctrineTypeComment(Type $doctrineType)
    {
        return '(DC2Type:' . $doctrineType->getName() . ')';
    }

547
    /**
Benjamin Morel's avatar
Benjamin Morel committed
548 549 550
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
     *
     * @param \Doctrine\DBAL\Schema\Column $column
551
     *
552 553 554 555 556
     * @return string
     */
    protected function getColumnComment(Column $column)
    {
        $comment = $column->getComment();
557

558 559 560
        if ($this->isCommentedDoctrineType($column->getType())) {
            $comment .= $this->getDoctrineTypeComment($column->getType());
        }
561

562 563 564
        return $comment;
    }

565 566 567 568 569 570 571 572 573
    /**
     * Gets the character used for identifier quoting.
     *
     * @return string
     */
    public function getIdentifierQuoteCharacter()
    {
        return '"';
    }
574

575 576 577 578 579 580 581 582 583
    /**
     * Gets the string portion that starts an SQL comment.
     *
     * @return string
     */
    public function getSqlCommentStartString()
    {
        return "--";
    }
584

585
    /**
586
     * Gets the string portion that ends an SQL comment.
587 588 589 590 591 592 593
     *
     * @return string
     */
    public function getSqlCommentEndString()
    {
        return "\n";
    }
594

595 596 597
    /**
     * Gets the maximum length of a varchar field.
     *
598
     * @return int
599 600
     */
    public function getVarcharMaxLength()
601 602 603 604 605 606 607
    {
        return 4000;
    }

    /**
     * Gets the default length of a varchar field.
     *
608
     * @return int
609 610
     */
    public function getVarcharDefaultLength()
611 612 613
    {
        return 255;
    }
614

Steve Müller's avatar
Steve Müller committed
615 616 617
    /**
     * Gets the maximum length of a binary field.
     *
618
     * @return int
Steve Müller's avatar
Steve Müller committed
619 620 621 622 623 624 625 626 627
     */
    public function getBinaryMaxLength()
    {
        return 4000;
    }

    /**
     * Gets the default length of a binary field.
     *
628
     * @return int
Steve Müller's avatar
Steve Müller committed
629 630 631 632 633 634
     */
    public function getBinaryDefaultLength()
    {
        return 255;
    }

635 636 637 638 639 640 641
    /**
     * Gets all SQL wildcard characters of the platform.
     *
     * @return array
     */
    public function getWildcards()
    {
642
        return ['%', '_'];
643
    }
644

645 646 647 648
    /**
     * Returns the regular expression operator.
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
649 650
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
651 652 653
     */
    public function getRegexpExpression()
    {
654
        throw DBALException::notSupported(__METHOD__);
655
    }
656

657
    /**
Benjamin Morel's avatar
Benjamin Morel committed
658 659 660
     * Returns the global unique identifier expression.
     *
     * @return string
661
     *
Benjamin Morel's avatar
Benjamin Morel committed
662
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
663 664 665 666
     */
    public function getGuidExpression()
    {
        throw DBALException::notSupported(__METHOD__);
667 668 669
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
670
     * Returns the SQL snippet to get the average value of a column.
671
     *
Benjamin Morel's avatar
Benjamin Morel committed
672
     * @param string $column The column to use.
673
     *
Benjamin Morel's avatar
Benjamin Morel committed
674
     * @return string Generated SQL including an AVG aggregate function.
675 676 677
     */
    public function getAvgExpression($column)
    {
Benjamin Morel's avatar
Benjamin Morel committed
678
        return 'AVG(' . $column . ')';
679 680 681
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
682
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
683
     *
Benjamin Morel's avatar
Benjamin Morel committed
684
     * If a '*' is used instead of a column the number of selected rows is returned.
685
     *
Benjamin Morel's avatar
Benjamin Morel committed
686
     * @param string|integer $column The column to use.
687
     *
Benjamin Morel's avatar
Benjamin Morel committed
688
     * @return string Generated SQL including a COUNT aggregate function.
689 690 691 692 693 694 695
     */
    public function getCountExpression($column)
    {
        return 'COUNT(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
696 697 698
     * Returns the SQL snippet to get the highest value of a column.
     *
     * @param string $column The column to use.
699
     *
Benjamin Morel's avatar
Benjamin Morel committed
700
     * @return string Generated SQL including a MAX aggregate function.
701 702 703 704 705 706 707
     */
    public function getMaxExpression($column)
    {
        return 'MAX(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
708
     * Returns the SQL snippet to get the lowest value of a column.
709
     *
Benjamin Morel's avatar
Benjamin Morel committed
710 711 712
     * @param string $column The column to use.
     *
     * @return string Generated SQL including a MIN aggregate function.
713 714 715 716 717 718 719
     */
    public function getMinExpression($column)
    {
        return 'MIN(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
720
     * Returns the SQL snippet to get the total sum of a column.
721
     *
Benjamin Morel's avatar
Benjamin Morel committed
722 723 724
     * @param string $column The column to use.
     *
     * @return string Generated SQL including a SUM aggregate function.
725 726 727 728 729 730 731 732 733
     */
    public function getSumExpression($column)
    {
        return 'SUM(' . $column . ')';
    }

    // scalar functions

    /**
Benjamin Morel's avatar
Benjamin Morel committed
734
     * Returns the SQL snippet to get the md5 sum of a field.
735
     *
Benjamin Morel's avatar
Benjamin Morel committed
736
     * Note: Not SQL92, but common functionality.
737
     *
738
     * @param string $column
Benjamin Morel's avatar
Benjamin Morel committed
739
     *
740 741 742 743 744 745 746 747
     * @return string
     */
    public function getMd5Expression($column)
    {
        return 'MD5(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
748
     * Returns the SQL snippet to get the length of a text field.
749
     *
750
     * @param string $column
751
     *
752 753 754 755 756 757 758
     * @return string
     */
    public function getLengthExpression($column)
    {
        return 'LENGTH(' . $column . ')';
    }

759
    /**
Benjamin Morel's avatar
Benjamin Morel committed
760
     * Returns the SQL snippet to get the squared value of a column.
761
     *
Benjamin Morel's avatar
Benjamin Morel committed
762
     * @param string $column The column to use.
763
     *
Benjamin Morel's avatar
Benjamin Morel committed
764
     * @return string Generated SQL including an SQRT aggregate function.
765 766 767 768 769 770
     */
    public function getSqrtExpression($column)
    {
        return 'SQRT(' . $column . ')';
    }

771
    /**
Benjamin Morel's avatar
Benjamin Morel committed
772
     * Returns the SQL snippet to round a numeric field to the number of decimals specified.
773
     *
774 775
     * @param string $column
     * @param int    $decimals
776
     *
777 778 779 780 781 782 783 784
     * @return string
     */
    public function getRoundExpression($column, $decimals = 0)
    {
        return 'ROUND(' . $column . ', ' . $decimals . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
785
     * Returns the SQL snippet to get the remainder of the division operation $expression1 / $expression2.
786 787 788
     *
     * @param string $expression1
     * @param string $expression2
789
     *
790 791 792 793 794 795 796 797
     * @return string
     */
    public function getModExpression($expression1, $expression2)
    {
        return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
798
     * Returns the SQL snippet to trim a string.
799
     *
800 801 802
     * @param string      $str  The expression to apply the trim to.
     * @param int         $mode The position of the trim (leading/trailing/both).
     * @param string|bool $char The char to trim, has to be quoted already. Defaults to space.
803
     *
804 805
     * @return string
     */
806
    public function getTrimExpression($str, $mode = TrimMode::UNSPECIFIED, $char = false)
807
    {
Steve Müller's avatar
Steve Müller committed
808
        $expression = '';
809

810 811
        switch ($mode) {
            case TrimMode::LEADING:
Steve Müller's avatar
Steve Müller committed
812
                $expression = 'LEADING ';
813 814
                break;

815
            case TrimMode::TRAILING:
Steve Müller's avatar
Steve Müller committed
816
                $expression = 'TRAILING ';
817 818
                break;

819
            case TrimMode::BOTH:
Steve Müller's avatar
Steve Müller committed
820
                $expression = 'BOTH ';
821
                break;
822 823
        }

824
        if ($char !== false) {
Steve Müller's avatar
Steve Müller committed
825 826 827
            $expression .= $char . ' ';
        }

828
        if ($mode || $char !== false) {
Steve Müller's avatar
Steve Müller committed
829 830 831 832
            $expression .= 'FROM ';
        }

        return 'TRIM(' . $expression . $str . ')';
833 834 835
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
836
     * Returns the SQL snippet to trim trailing space characters from the expression.
837
     *
Benjamin Morel's avatar
Benjamin Morel committed
838
     * @param string $str Literal string or column name.
839
     *
840 841 842 843 844 845 846 847
     * @return string
     */
    public function getRtrimExpression($str)
    {
        return 'RTRIM(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
848
     * Returns the SQL snippet to trim leading space characters from the expression.
849
     *
Benjamin Morel's avatar
Benjamin Morel committed
850
     * @param string $str Literal string or column name.
851
     *
852 853 854 855 856 857 858 859
     * @return string
     */
    public function getLtrimExpression($str)
    {
        return 'LTRIM(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
860 861
     * Returns the SQL snippet to change all characters from the expression to uppercase,
     * according to the current character set mapping.
862
     *
Benjamin Morel's avatar
Benjamin Morel committed
863
     * @param string $str Literal string or column name.
864
     *
865 866 867 868 869 870 871 872
     * @return string
     */
    public function getUpperExpression($str)
    {
        return 'UPPER(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
873 874
     * Returns the SQL snippet to change all characters from the expression to lowercase,
     * according to the current character set mapping.
875
     *
Benjamin Morel's avatar
Benjamin Morel committed
876
     * @param string $str Literal string or column name.
877
     *
878 879 880 881 882 883 884 885
     * @return string
     */
    public function getLowerExpression($str)
    {
        return 'LOWER(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
886
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
887
     *
888 889 890
     * @param string   $str      Literal string.
     * @param string   $substr   Literal string to find.
     * @param int|bool $startPos Position to start at, beginning of string by default.
891
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
892
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
893 894
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
895
     */
896
    public function getLocateExpression($str, $substr, $startPos = false)
897
    {
898
        throw DBALException::notSupported(__METHOD__);
899 900 901
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
902
     * Returns the SQL snippet to get the current system date.
903 904 905 906 907 908 909 910 911
     *
     * @return string
     */
    public function getNowExpression()
    {
        return 'NOW()';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
912
     * Returns a SQL snippet to get a substring inside an SQL statement.
913 914 915
     *
     * Note: Not SQL92, but common functionality.
     *
Benjamin Morel's avatar
Benjamin Morel committed
916
     * SQLite only supports the 2 parameter variant of this function.
917
     *
918 919 920
     * @param string   $value  An sql string literal or column name/alias.
     * @param int      $from   Where to start the substring portion.
     * @param int|null $length The substring portion length.
921
     *
922
     * @return string
923
     */
924
    public function getSubstringExpression($value, $from, $length = null)
925
    {
926
        if ($length === null) {
927 928
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
        }
929 930

        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
931 932 933
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
934
     * Returns a SQL snippet to concatenate the given expressions.
935
     *
Benjamin Morel's avatar
Benjamin Morel committed
936
     * Accepts an arbitrary number of string parameters. Each parameter must contain an expression.
937
     *
938 939 940 941
     * @return string
     */
    public function getConcatExpression()
    {
942
        return join(' || ', func_get_args());
943 944 945 946 947 948 949 950 951 952 953 954 955
    }

    /**
     * Returns the SQL for a logical not.
     *
     * Example:
     * <code>
     * $q = new Doctrine_Query();
     * $e = $q->expr;
     * $q->select('*')->from('table')
     *   ->where($e->eq('id', $e->not('null'));
     * </code>
     *
956
     * @param string $expression
957
     *
Benjamin Morel's avatar
Benjamin Morel committed
958
     * @return string The logical expression.
959 960 961
     */
    public function getNotExpression($expression)
    {
962
        return 'NOT(' . $expression . ')';
963 964 965
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
966
     * Returns the SQL that checks if an expression is null.
967
     *
Benjamin Morel's avatar
Benjamin Morel committed
968
     * @param string $expression The expression that should be compared to null.
969
     *
Benjamin Morel's avatar
Benjamin Morel committed
970
     * @return string The logical expression.
971 972 973 974 975 976 977
     */
    public function getIsNullExpression($expression)
    {
        return $expression . ' IS NULL';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
978
     * Returns the SQL that checks if an expression is not null.
979
     *
Benjamin Morel's avatar
Benjamin Morel committed
980
     * @param string $expression The expression that should be compared to null.
981
     *
Benjamin Morel's avatar
Benjamin Morel committed
982
     * @return string The logical expression.
983 984 985 986 987 988 989
     */
    public function getIsNotNullExpression($expression)
    {
        return $expression . ' IS NOT NULL';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
990
     * Returns the SQL that checks if an expression evaluates to a value between two values.
991 992 993 994 995 996 997
     *
     * The parameter $expression is checked if it is between $value1 and $value2.
     *
     * Note: There is a slight difference in the way BETWEEN works on some databases.
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
     * independence you should avoid using between().
     *
Benjamin Morel's avatar
Benjamin Morel committed
998 999 1000
     * @param string $expression The value to compare to.
     * @param string $value1     The lower value to compare with.
     * @param string $value2     The higher value to compare with.
1001
     *
Benjamin Morel's avatar
Benjamin Morel committed
1002
     * @return string The logical expression.
1003 1004 1005 1006 1007 1008
     */
    public function getBetweenExpression($expression, $value1, $value2)
    {
        return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1009 1010 1011 1012 1013 1014 1015
    /**
     * Returns the SQL to get the arccosine of a value.
     *
     * @param string $value
     *
     * @return string
     */
1016 1017 1018 1019 1020
    public function getAcosExpression($value)
    {
        return 'ACOS(' . $value . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1021 1022 1023 1024 1025 1026 1027
    /**
     * Returns the SQL to get the sine of a value.
     *
     * @param string $value
     *
     * @return string
     */
1028 1029 1030 1031 1032
    public function getSinExpression($value)
    {
        return 'SIN(' . $value . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1033 1034 1035 1036 1037
    /**
     * Returns the SQL to get the PI value.
     *
     * @return string
     */
1038 1039 1040 1041 1042
    public function getPiExpression()
    {
        return 'PI()';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1043 1044 1045 1046 1047 1048 1049
    /**
     * Returns the SQL to get the cosine of a value.
     *
     * @param string $value
     *
     * @return string
     */
1050 1051 1052 1053
    public function getCosExpression($value)
    {
        return 'COS(' . $value . ')';
    }
1054

1055
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1056
     * Returns the SQL to calculate the difference in days between the two passed dates.
1057
     *
Benjamin Morel's avatar
Benjamin Morel committed
1058
     * Computes diff = date1 - date2.
1059 1060 1061
     *
     * @param string $date1
     * @param string $date2
1062
     *
1063
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1064 1065
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1066 1067 1068 1069
     */
    public function getDateDiffExpression($date1, $date2)
    {
        throw DBALException::notSupported(__METHOD__);
1070 1071
    }

1072 1073 1074
    /**
     * Returns the SQL to add the number of given seconds to a date.
     *
1075 1076
     * @param string $date
     * @param int    $seconds
1077 1078 1079 1080 1081 1082 1083
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddSecondsExpression($date, $seconds)
    {
1084
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, DateIntervalUnit::SECOND);
1085 1086 1087 1088 1089
    }

    /**
     * Returns the SQL to subtract the number of given seconds from a date.
     *
1090 1091
     * @param string $date
     * @param int    $seconds
1092 1093 1094 1095 1096 1097 1098
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubSecondsExpression($date, $seconds)
    {
1099
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, DateIntervalUnit::SECOND);
1100 1101 1102 1103 1104
    }

    /**
     * Returns the SQL to add the number of given minutes to a date.
     *
1105 1106
     * @param string $date
     * @param int    $minutes
1107 1108 1109 1110 1111 1112 1113
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddMinutesExpression($date, $minutes)
    {
1114
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, DateIntervalUnit::MINUTE);
1115 1116 1117 1118 1119
    }

    /**
     * Returns the SQL to subtract the number of given minutes from a date.
     *
1120 1121
     * @param string $date
     * @param int    $minutes
1122 1123 1124 1125 1126 1127 1128
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubMinutesExpression($date, $minutes)
    {
1129
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, DateIntervalUnit::MINUTE);
1130 1131
    }

1132 1133 1134
    /**
     * Returns the SQL to add the number of given hours to a date.
     *
1135 1136
     * @param string $date
     * @param int    $hours
1137 1138 1139 1140 1141 1142 1143
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddHourExpression($date, $hours)
    {
1144
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, DateIntervalUnit::HOUR);
1145 1146 1147 1148 1149
    }

    /**
     * Returns the SQL to subtract the number of given hours to a date.
     *
1150 1151
     * @param string $date
     * @param int    $hours
1152 1153 1154 1155 1156 1157 1158
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubHourExpression($date, $hours)
    {
1159
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, DateIntervalUnit::HOUR);
1160 1161 1162
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1163
     * Returns the SQL to add the number of given days to a date.
1164
     *
1165 1166
     * @param string $date
     * @param int    $days
1167
     *
1168
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1169 1170
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1171 1172 1173
     */
    public function getDateAddDaysExpression($date, $days)
    {
1174
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, DateIntervalUnit::DAY);
1175 1176 1177
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1178
     * Returns the SQL to subtract the number of given days to a date.
1179
     *
1180 1181
     * @param string $date
     * @param int    $days
1182
     *
1183
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1184 1185
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1186 1187 1188
     */
    public function getDateSubDaysExpression($date, $days)
    {
1189
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
1190 1191 1192 1193 1194
    }

    /**
     * Returns the SQL to add the number of given weeks to a date.
     *
1195 1196
     * @param string $date
     * @param int    $weeks
1197 1198 1199 1200 1201 1202 1203
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddWeeksExpression($date, $weeks)
    {
1204
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, DateIntervalUnit::WEEK);
1205 1206 1207 1208 1209
    }

    /**
     * Returns the SQL to subtract the number of given weeks from a date.
     *
1210 1211
     * @param string $date
     * @param int    $weeks
1212 1213 1214 1215 1216 1217 1218
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubWeeksExpression($date, $weeks)
    {
1219
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, DateIntervalUnit::WEEK);
1220 1221 1222
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1223
     * Returns the SQL to add the number of given months to a date.
1224
     *
1225 1226
     * @param string $date
     * @param int    $months
1227
     *
1228
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1229 1230
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1231 1232 1233
     */
    public function getDateAddMonthExpression($date, $months)
    {
1234
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, DateIntervalUnit::MONTH);
1235 1236 1237
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1238
     * Returns the SQL to subtract the number of given months to a date.
1239
     *
1240 1241
     * @param string $date
     * @param int    $months
1242
     *
1243
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1244 1245
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1246 1247
     */
    public function getDateSubMonthExpression($date, $months)
1248
    {
1249
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, DateIntervalUnit::MONTH);
1250 1251 1252 1253 1254
    }

    /**
     * Returns the SQL to add the number of given quarters to a date.
     *
1255 1256
     * @param string $date
     * @param int    $quarters
1257 1258 1259 1260 1261 1262 1263
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddQuartersExpression($date, $quarters)
    {
1264
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, DateIntervalUnit::QUARTER);
1265 1266 1267 1268 1269
    }

    /**
     * Returns the SQL to subtract the number of given quarters from a date.
     *
1270 1271
     * @param string $date
     * @param int    $quarters
1272 1273 1274 1275 1276 1277 1278
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubQuartersExpression($date, $quarters)
    {
1279
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, DateIntervalUnit::QUARTER);
1280 1281 1282 1283 1284
    }

    /**
     * Returns the SQL to add the number of given years to a date.
     *
1285 1286
     * @param string $date
     * @param int    $years
1287 1288 1289 1290 1291 1292 1293
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddYearsExpression($date, $years)
    {
1294
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, DateIntervalUnit::YEAR);
1295 1296 1297 1298 1299
    }

    /**
     * Returns the SQL to subtract the number of given years from a date.
     *
1300 1301
     * @param string $date
     * @param int    $years
1302 1303 1304 1305 1306 1307 1308
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubYearsExpression($date, $years)
    {
1309
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, DateIntervalUnit::YEAR);
1310 1311 1312 1313 1314
    }

    /**
     * Returns the SQL for a date arithmetic expression.
     *
1315 1316 1317 1318 1319
     * @param string $date     The column or literal representing a date to perform the arithmetic operation on.
     * @param string $operator The arithmetic operator (+ or -).
     * @param int    $interval The interval that shall be calculated into the date.
     * @param string $unit     The unit of the interval that shall be calculated into the date.
     *                         One of the DATE_INTERVAL_UNIT_* constants.
1320 1321 1322 1323 1324 1325
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
1326 1327 1328 1329
    {
        throw DBALException::notSupported(__METHOD__);
    }

1330
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1331
     * Returns the SQL bit AND comparison expression.
1332
     *
Benjamin Morel's avatar
Benjamin Morel committed
1333 1334
     * @param string $value1
     * @param string $value2
1335
     *
Benjamin Morel's avatar
Benjamin Morel committed
1336
     * @return string
1337 1338 1339 1340 1341
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
        return '(' . $value1 . ' & ' . $value2 . ')';
    }
Fabio B. Silva's avatar
Fabio B. Silva committed
1342

1343
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1344
     * Returns the SQL bit OR comparison expression.
1345
     *
Benjamin Morel's avatar
Benjamin Morel committed
1346 1347
     * @param string $value1
     * @param string $value2
1348
     *
Benjamin Morel's avatar
Benjamin Morel committed
1349
     * @return string
1350 1351 1352 1353 1354 1355
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
        return '(' . $value1 . ' | ' . $value2 . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1356 1357
    /**
     * Returns the FOR UPDATE expression.
1358
     *
Benjamin Morel's avatar
Benjamin Morel committed
1359 1360
     * @return string
     */
1361
    public function getForUpdateSQL()
1362 1363 1364
    {
        return 'FOR UPDATE';
    }
1365

1366 1367 1368
    /**
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
     *
1369 1370 1371
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
     *                             be appended to the FROM clause.
1372
     *
1373 1374 1375 1376 1377 1378 1379 1380
     * @return string
     */
    public function appendLockHint($fromClause, $lockMode)
    {
        return $fromClause;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1381
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1382
     *
1383
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
     * vendors allow to lighten this constraint up to be a real read lock.
     *
     * @return string
     */
    public function getReadLockSQL()
    {
        return $this->getForUpdateSQL();
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1394
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1395
     *
1396
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1397 1398 1399 1400 1401 1402 1403 1404
     *
     * @return string
     */
    public function getWriteLockSQL()
    {
        return $this->getForUpdateSQL();
    }

1405
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1406
     * Returns the SQL snippet to drop an existing database.
1407
     *
Benjamin Morel's avatar
Benjamin Morel committed
1408
     * @param string $database The name of the database that should be dropped.
1409 1410 1411
     *
     * @return string
     */
1412
    public function getDropDatabaseSQL($database)
1413 1414 1415
    {
        return 'DROP DATABASE ' . $database;
    }
1416

1417
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1418
     * Returns the SQL snippet to drop an existing table.
1419
     *
Benjamin Morel's avatar
Benjamin Morel committed
1420
     * @param \Doctrine\DBAL\Schema\Table|string $table
1421
     *
1422
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1423 1424
     *
     * @throws \InvalidArgumentException
1425
     */
1426
    public function getDropTableSQL($table)
1427
    {
1428 1429
        $tableArg = $table;

1430
        if ($table instanceof Table) {
1431
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
1432
        } elseif (!is_string($table)) {
1433
            throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1434 1435
        }

1436
        if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1437
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1438 1439 1440 1441 1442 1443
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);

            if ($eventArgs->isDefaultPrevented()) {
                return $eventArgs->getSql();
            }
        }
1444

1445 1446
        return 'DROP TABLE ' . $table;
    }
1447

1448
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1449
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1450
     *
Benjamin Morel's avatar
Benjamin Morel committed
1451
     * @param \Doctrine\DBAL\Schema\Table|string $table
1452
     *
1453 1454 1455 1456 1457 1458 1459
     * @return string
     */
    public function getDropTemporaryTableSQL($table)
    {
        return $this->getDropTableSQL($table);
    }

1460
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1461
     * Returns the SQL to drop an index from a table.
1462
     *
Benjamin Morel's avatar
Benjamin Morel committed
1463 1464
     * @param \Doctrine\DBAL\Schema\Index|string $index
     * @param \Doctrine\DBAL\Schema\Table|string $table
1465
     *
1466
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1467 1468
     *
     * @throws \InvalidArgumentException
1469
     */
1470
    public function getDropIndexSQL($index, $table = null)
1471
    {
1472
        if ($index instanceof Index) {
1473
            $index = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
1474
        } elseif (!is_string($index)) {
1475
            throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1476 1477 1478
        }

        return 'DROP INDEX ' . $index;
1479
    }
1480

1481
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1482
     * Returns the SQL to drop a constraint.
1483
     *
Benjamin Morel's avatar
Benjamin Morel committed
1484 1485
     * @param \Doctrine\DBAL\Schema\Constraint|string $constraint
     * @param \Doctrine\DBAL\Schema\Table|string      $table
1486
     *
1487 1488
     * @return string
     */
1489
    public function getDropConstraintSQL($constraint, $table)
1490
    {
1491 1492
        if (! $constraint instanceof Constraint) {
            $constraint = new Identifier($constraint);
1493 1494
        }

1495 1496
        if (! $table instanceof Table) {
            $table = new Identifier($table);
1497 1498
        }

1499 1500 1501
        $constraint = $constraint->getQuotedName($this);
        $table = $table->getQuotedName($this);

1502
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1503
    }
1504

1505
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1506
     * Returns the SQL to drop a foreign key.
1507
     *
Benjamin Morel's avatar
Benjamin Morel committed
1508 1509
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint|string $foreignKey
     * @param \Doctrine\DBAL\Schema\Table|string                $table
1510
     *
1511 1512
     * @return string
     */
1513
    public function getDropForeignKeySQL($foreignKey, $table)
1514
    {
1515 1516
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
1517 1518
        }

1519 1520
        if (! $table instanceof Table) {
            $table = new Identifier($table);
1521 1522
        }

1523 1524 1525
        $foreignKey = $foreignKey->getQuotedName($this);
        $table = $table->getQuotedName($this);

1526
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1527
    }
1528

1529
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1530
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1531
     * on this platform.
1532
     *
1533 1534
     * @param \Doctrine\DBAL\Schema\Table $table
     * @param int                         $createFlags
1535
     *
1536
     * @return array The sequence of SQL statements.
Benjamin Morel's avatar
Benjamin Morel committed
1537 1538 1539
     *
     * @throws \Doctrine\DBAL\DBALException
     * @throws \InvalidArgumentException
1540
     */
1541
    public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES)
1542
    {
1543
        if ( ! is_int($createFlags)) {
1544
            throw new \InvalidArgumentException("Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.");
1545 1546
        }

1547
        if (count($table->getColumns()) === 0) {
1548 1549 1550
            throw DBALException::noColumnsSpecifiedForTable($table->getName());
        }

1551
        $tableName = $table->getQuotedName($this);
1552
        $options = $table->getOptions();
1553 1554 1555
        $options['uniqueConstraints'] = [];
        $options['indexes'] = [];
        $options['primary'] = [];
1556

1557
        if (($createFlags&self::CREATE_INDEXES) > 0) {
1558
            foreach ($table->getIndexes() as $index) {
1559 1560
                /* @var $index Index */
                if ($index->isPrimary()) {
Steve Müller's avatar
Steve Müller committed
1561
                    $options['primary']       = $index->getQuotedColumns($this);
1562
                    $options['primary_index'] = $index;
1563
                } else {
1564
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1565
                }
1566 1567
            }
        }
1568

1569 1570
        $columnSql = [];
        $columns = [];
1571

1572
        foreach ($table->getColumns() as $column) {
1573
            /* @var \Doctrine\DBAL\Schema\Column $column */
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585

            if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);

                $columnSql = array_merge($columnSql, $eventArgs->getSql());

                if ($eventArgs->isDefaultPrevented()) {
                    continue;
                }
            }

1586
            $columnData = $column->toArray();
1587
            $columnData['name'] = $column->getQuotedName($this);
1588
            $columnData['version'] = $column->hasPlatformOption("version") ? $column->getPlatformOption('version') : false;
1589
            $columnData['comment'] = $this->getColumnComment($column);
1590

1591
            if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
1592 1593
                $columnData['length'] = 255;
            }
1594 1595

            if (in_array($column->getName(), $options['primary'])) {
1596 1597 1598 1599 1600 1601
                $columnData['primary'] = true;
            }

            $columns[$columnData['name']] = $columnData;
        }

1602
        if (($createFlags&self::CREATE_FOREIGNKEYS) > 0) {
1603
            $options['foreignKeys'] = [];
1604
            foreach ($table->getForeignKeys() as $fkConstraint) {
1605 1606 1607 1608
                $options['foreignKeys'][] = $fkConstraint;
            }
        }

1609 1610 1611
        if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1612

Jan Sorgalla's avatar
Jan Sorgalla committed
1613 1614 1615
            if ($eventArgs->isDefaultPrevented()) {
                return array_merge($eventArgs->getSql(), $columnSql);
            }
1616
        }
1617

1618 1619
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
        if ($this->supportsCommentOnStatement()) {
1620
            foreach ($table->getColumns() as $column) {
1621 1622 1623 1624
                $comment = $this->getColumnComment($column);

                if (null !== $comment && '' !== $comment) {
                    $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1625 1626 1627
                }
            }
        }
1628

Jan Sorgalla's avatar
Jan Sorgalla committed
1629
        return array_merge($sql, $columnSql);
1630 1631
    }

Benjamin Morel's avatar
Benjamin Morel committed
1632 1633 1634 1635 1636 1637 1638
    /**
     * @param string $tableName
     * @param string $columnName
     * @param string $comment
     *
     * @return string
     */
1639 1640
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
1641 1642
        $tableName = new Identifier($tableName);
        $columnName = new Identifier($columnName);
1643 1644
        $comment = $this->quoteStringLiteral($comment);

1645 1646
        return "COMMENT ON COLUMN " . $tableName->getQuotedName($this) . "." . $columnName->getQuotedName($this) .
            " IS " . $comment;
1647 1648
    }

1649 1650 1651 1652 1653 1654
    /**
     * Returns the SQL to create inline comment on a column.
     *
     * @param string $comment
     *
     * @return string
1655 1656
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1657 1658 1659
     */
    public function getInlineColumnCommentSQL($comment)
    {
1660 1661 1662 1663
        if (! $this->supportsInlineColumnComments()) {
            throw DBALException::notSupported(__METHOD__);
        }

1664 1665 1666
        return "COMMENT " . $this->quoteStringLiteral($comment);
    }

1667
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1668
     * Returns the SQL used to create a table.
1669
     *
1670
     * @param string $tableName
Benjamin Morel's avatar
Benjamin Morel committed
1671 1672
     * @param array  $columns
     * @param array  $options
1673
     *
1674 1675
     * @return array
     */
1676
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
1677
    {
1678
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1679

1680
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1681
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1682
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1683 1684
            }
        }
1685

1686
        if (isset($options['primary']) && ! empty($options['primary'])) {
1687
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1688 1689 1690
        }

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Steve Müller's avatar
Steve Müller committed
1691
            foreach ($options['indexes'] as $index => $definition) {
1692
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1693 1694 1695
            }
        }

1696
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1697

1698
        $check = $this->getCheckDeclarationSQL($columns);
1699 1700
        if ( ! empty($check)) {
            $query .= ', ' . $check;
1701
        }
1702 1703 1704 1705 1706
        $query .= ')';

        $sql[] = $query;

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

1712 1713
        return $sql;
    }
1714

Benjamin Morel's avatar
Benjamin Morel committed
1715 1716 1717
    /**
     * @return string
     */
1718
    public function getCreateTemporaryTableSnippetSQL()
1719 1720 1721
    {
        return "CREATE TEMPORARY TABLE";
    }
1722

1723
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1724
     * Returns the SQL to create a sequence on this platform.
1725
     *
1726
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
1727 1728 1729
     *
     * @return string
     *
Benjamin Morel's avatar
Benjamin Morel committed
1730
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1731
     */
1732
    public function getCreateSequenceSQL(Sequence $sequence)
1733
    {
1734
        throw DBALException::notSupported(__METHOD__);
1735
    }
1736

1737
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1738
     * Returns the SQL to change a sequence on this platform.
1739 1740
     *
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
1741
     *
1742
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1743 1744
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1745
     */
1746
    public function getAlterSequenceSQL(Sequence $sequence)
1747 1748 1749
    {
        throw DBALException::notSupported(__METHOD__);
    }
1750

1751
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1752
     * Returns the SQL to create a constraint on a table on this platform.
1753
     *
Benjamin Morel's avatar
Benjamin Morel committed
1754 1755
     * @param \Doctrine\DBAL\Schema\Constraint   $constraint
     * @param \Doctrine\DBAL\Schema\Table|string $table
1756
     *
1757
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1758 1759
     *
     * @throws \InvalidArgumentException
1760
     */
1761
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1762
    {
1763
        if ($table instanceof Table) {
1764
            $table = $table->getQuotedName($this);
1765 1766
        }

1767
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1768

1769
        $columnList = '('. implode(', ', $constraint->getQuotedColumns($this)) . ')';
1770 1771

        $referencesClause = '';
1772
        if ($constraint instanceof Index) {
Steve Müller's avatar
Steve Müller committed
1773
            if ($constraint->isPrimary()) {
1774 1775 1776 1777 1778
                $query .= ' PRIMARY KEY';
            } elseif ($constraint->isUnique()) {
                $query .= ' UNIQUE';
            } else {
                throw new \InvalidArgumentException(
1779
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1780 1781
                );
            }
Steve Müller's avatar
Steve Müller committed
1782
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1783 1784
            $query .= ' FOREIGN KEY';

1785
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1786
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1787 1788
        }
        $query .= ' '.$columnList.$referencesClause;
1789 1790 1791

        return $query;
    }
1792

1793
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1794
     * Returns the SQL to create an index on a table on this platform.
1795
     *
Benjamin Morel's avatar
Benjamin Morel committed
1796 1797
     * @param \Doctrine\DBAL\Schema\Index        $index
     * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created.
1798
     *
1799
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1800 1801
     *
     * @throws \InvalidArgumentException
1802
     */
1803
    public function getCreateIndexSQL(Index $index, $table)
1804
    {
1805
        if ($table instanceof Table) {
1806
            $table = $table->getQuotedName($this);
1807
        }
1808
        $name = $index->getQuotedName($this);
1809
        $columns = $index->getQuotedColumns($this);
1810 1811 1812

        if (count($columns) == 0) {
            throw new \InvalidArgumentException("Incomplete definition. 'columns' required.");
1813
        }
1814

1815 1816
        if ($index->isPrimary()) {
            return $this->getCreatePrimaryKeySQL($index, $table);
1817 1818
        }

1819
        $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1820
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')' . $this->getPartialIndexSQL($index);
1821

1822 1823
        return $query;
    }
1824

1825 1826 1827 1828 1829 1830 1831 1832 1833
    /**
     * Adds condition for partial index.
     *
     * @param \Doctrine\DBAL\Schema\Index $index
     *
     * @return string
     */
    protected function getPartialIndexSQL(Index $index)
    {
1834 1835 1836
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
            return  ' WHERE ' . $index->getOption('where');
        }
1837 1838

        return '';
1839 1840
    }

1841
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1842
     * Adds additional flags for index generation.
1843
     *
Benjamin Morel's avatar
Benjamin Morel committed
1844
     * @param \Doctrine\DBAL\Schema\Index $index
1845
     *
1846 1847 1848 1849
     * @return string
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
1850
        return $index->isUnique() ? 'UNIQUE ' : '';
1851 1852
    }

1853
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1854
     * Returns the SQL to create an unnamed primary key constraint.
1855
     *
Benjamin Morel's avatar
Benjamin Morel committed
1856 1857
     * @param \Doctrine\DBAL\Schema\Index        $index
     * @param \Doctrine\DBAL\Schema\Table|string $table
1858
     *
1859 1860 1861 1862
     * @return string
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
1863
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')';
1864
    }
1865

1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
    /**
     * Returns the SQL to create a named schema.
     *
     * @param string $schemaName
     *
     * @return string
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getCreateSchemaSQL($schemaName)
    {
        throw DBALException::notSupported(__METHOD__);
    }

1879
    /**
1880
     * Quotes a string so that it can be safely used as a table or column name,
1881
     * even if it is a reserved word of the platform. This also detects identifier
1882
     * chains separated by dot and quotes them independently.
1883
     *
1884
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
Benjamin Morel's avatar
Benjamin Morel committed
1885
     * you SHOULD use them. In general, they end up causing way more
1886 1887
     * problems than they solve.
     *
Benjamin Morel's avatar
Benjamin Morel committed
1888
     * @param string $str The identifier name to be quoted.
1889
     *
Benjamin Morel's avatar
Benjamin Morel committed
1890
     * @return string The quoted identifier string.
1891 1892
     */
    public function quoteIdentifier($str)
1893 1894
    {
        if (strpos($str, ".") !== false) {
1895
            $parts = array_map([$this, "quoteSingleIdentifier"], explode(".", $str));
1896

1897 1898 1899 1900 1901 1902 1903
            return implode(".", $parts);
        }

        return $this->quoteSingleIdentifier($str);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1904
     * Quotes a single identifier (no dot chain separation).
1905
     *
Benjamin Morel's avatar
Benjamin Morel committed
1906
     * @param string $str The identifier name to be quoted.
1907
     *
Benjamin Morel's avatar
Benjamin Morel committed
1908
     * @return string The quoted identifier string.
1909 1910
     */
    public function quoteSingleIdentifier($str)
1911 1912 1913
    {
        $c = $this->getIdentifierQuoteCharacter();

1914
        return $c . str_replace($c, $c.$c, $str) . $c;
1915
    }
1916

1917
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1918
     * Returns the SQL to create a new foreign key.
1919
     *
Benjamin Morel's avatar
Benjamin Morel committed
1920 1921
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The foreign key constraint.
     * @param \Doctrine\DBAL\Schema\Table|string         $table      The name of the table on which the foreign key is to be created.
1922
     *
1923 1924
     * @return string
     */
1925
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
1926
    {
1927
        if ($table instanceof Table) {
1928
            $table = $table->getQuotedName($this);
1929 1930
        }

1931
        $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1932 1933 1934

        return $query;
    }
1935

1936
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1937
     * Gets the SQL statements for altering an existing table.
1938
     *
Benjamin Morel's avatar
Benjamin Morel committed
1939
     * This method returns an array of SQL statements, since some platforms need several statements.
1940
     *
Benjamin Morel's avatar
Benjamin Morel committed
1941
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
1942
     *
1943
     * @return array
Benjamin Morel's avatar
Benjamin Morel committed
1944 1945
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1946
     */
1947
    public function getAlterTableSQL(TableDiff $diff)
1948
    {
1949
        throw DBALException::notSupported(__METHOD__);
1950
    }
1951

1952
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1953 1954 1955
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
1956
     *
1957
     * @return bool
1958 1959 1960 1961 1962 1963 1964
     */
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1965
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
            return false;
        }

        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);

        $columnSql = array_merge($columnSql, $eventArgs->getSql());

        return $eventArgs->isDefaultPrevented();
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1978 1979 1980
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
1981
     *
1982
     * @return bool
1983 1984 1985 1986 1987 1988 1989
     */
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1990
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
            return false;
        }

        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);

        $columnSql = array_merge($columnSql, $eventArgs->getSql());

        return $eventArgs->isDefaultPrevented();
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2003 2004 2005
     * @param \Doctrine\DBAL\Schema\ColumnDiff $columnDiff
     * @param \Doctrine\DBAL\Schema\TableDiff  $diff
     * @param array                            $columnSql
2006
     *
2007
     * @return bool
2008 2009 2010 2011 2012 2013 2014
     */
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

2015
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
            return false;
        }

        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);

        $columnSql = array_merge($columnSql, $eventArgs->getSql());

        return $eventArgs->isDefaultPrevented();
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2028 2029 2030 2031
     * @param string                          $oldColumnName
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
2032
     *
2033
     * @return bool
2034 2035 2036 2037 2038 2039 2040
     */
    protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

2041
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
            return false;
        }

        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);

        $columnSql = array_merge($columnSql, $eventArgs->getSql());

        return $eventArgs->isDefaultPrevented();
    }
Christophe Coevoet's avatar
Christophe Coevoet committed
2052

2053
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2054 2055
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $sql
2056
     *
2057
     * @return bool
2058 2059 2060 2061 2062 2063 2064
     */
    protected function onSchemaAlterTable(TableDiff $diff, &$sql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

2065
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
            return false;
        }

        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);

        $sql = array_merge($sql, $eventArgs->getSql());

        return $eventArgs->isDefaultPrevented();
    }
2076

Benjamin Morel's avatar
Benjamin Morel committed
2077 2078 2079 2080 2081
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
2082 2083
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
2084
        $tableName = $diff->getName($this)->getQuotedName($this);
2085

2086
        $sql = [];
2087
        if ($this->supportsForeignKeyConstraints()) {
2088
            foreach ($diff->removedForeignKeys as $foreignKey) {
2089 2090
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
            }
2091
            foreach ($diff->changedForeignKeys as $foreignKey) {
2092 2093 2094 2095
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
            }
        }

2096
        foreach ($diff->removedIndexes as $index) {
2097 2098
            $sql[] = $this->getDropIndexSQL($index, $tableName);
        }
2099
        foreach ($diff->changedIndexes as $index) {
2100 2101 2102 2103 2104
            $sql[] = $this->getDropIndexSQL($index, $tableName);
        }

        return $sql;
    }
2105

Benjamin Morel's avatar
Benjamin Morel committed
2106 2107 2108 2109 2110
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
2111
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
2112
    {
2113 2114
        $tableName = (false !== $diff->newName)
            ? $diff->getNewName()->getQuotedName($this)
2115
            : $diff->getName($this)->getQuotedName($this);
2116

2117
        $sql = [];
2118

2119
        if ($this->supportsForeignKeyConstraints()) {
2120
            foreach ($diff->addedForeignKeys as $foreignKey) {
2121
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2122
            }
2123

2124
            foreach ($diff->changedForeignKeys as $foreignKey) {
2125
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2126 2127 2128
            }
        }

2129
        foreach ($diff->addedIndexes as $index) {
2130
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2131
        }
2132

2133
        foreach ($diff->changedIndexes as $index) {
2134
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2135 2136
        }

2137 2138 2139 2140 2141 2142 2143 2144
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
            $oldIndexName = new Identifier($oldIndexName);
            $sql          = array_merge(
                $sql,
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
            );
        }

2145 2146
        return $sql;
    }
2147

2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
    /**
     * Returns the SQL for renaming an index on a table.
     *
     * @param string                      $oldIndexName The name of the index to rename from.
     * @param \Doctrine\DBAL\Schema\Index $index        The definition of the index to rename to.
     * @param string                      $tableName    The table to rename the given index on.
     *
     * @return array The sequence of SQL statements for renaming the given index.
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
2159
        return [
2160 2161
            $this->getDropIndexSQL($oldIndexName, $tableName),
            $this->getCreateIndexSQL($index, $tableName)
2162
        ];
2163 2164
    }

2165 2166 2167
    /**
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2168
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
2169
     *
2170 2171 2172 2173 2174 2175
     * @return array
     */
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
    }
2176

2177
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2178
     * Gets declaration of a number of fields in bulk.
2179
     *
Benjamin Morel's avatar
Benjamin Morel committed
2180 2181 2182 2183 2184
     * @param array $fields A multidimensional associative array.
     *                      The first dimension determines the field name, while the second
     *                      dimension is keyed with the name of the properties
     *                      of the field being declared as array indexes. Currently, the types
     *                      of supported field properties are as follows:
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
     *
     *      length
     *          Integer value that determines the maximum length of the text
     *          field. If this argument is missing the field should be
     *          declared to have the longest length allowed by the DBMS.
     *
     *      default
     *          Text value to be used as default for this field.
     *
     *      notnull
     *          Boolean flag that indicates whether this field is constrained
     *          to not be set to null.
     *      charset
     *          Text value with the default CHARACTER SET for this field.
     *      collation
     *          Text value with the default COLLATION for this field.
     *      unique
     *          unique constraint
     *
     * @return string
     */
2206
    public function getColumnDeclarationListSQL(array $fields)
2207
    {
2208
        $queryFields = [];
2209

2210
        foreach ($fields as $fieldName => $field) {
2211
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
2212
        }
2213

2214 2215 2216 2217
        return implode(', ', $queryFields);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2218
     * Obtains DBMS specific SQL code portion needed to declare a generic type
2219 2220
     * field to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2221 2222 2223 2224
     * @param string $name  The name the field to be declared.
     * @param array  $field An associative array with the name of the properties
     *                      of the field being declared as array indexes. Currently, the types
     *                      of supported field properties are as follows:
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
     *
     *      length
     *          Integer value that determines the maximum length of the text
     *          field. If this argument is missing the field should be
     *          declared to have the longest length allowed by the DBMS.
     *
     *      default
     *          Text value to be used as default for this field.
     *
     *      notnull
     *          Boolean flag that indicates whether this field is constrained
     *          to not be set to null.
     *      charset
     *          Text value with the default CHARACTER SET for this field.
     *      collation
     *          Text value with the default COLLATION for this field.
     *      unique
     *          unique constraint
     *      check
     *          column check constraint
2245 2246
     *      columnDefinition
     *          a string that defines the complete column
2247
     *
Benjamin Morel's avatar
Benjamin Morel committed
2248
     * @return string DBMS specific SQL code portion that should be used to declare the column.
2249
     */
2250
    public function getColumnDeclarationSQL($name, array $field)
2251
    {
2252
        if (isset($field['columnDefinition'])) {
2253
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
2254
        } else {
2255
            $default = $this->getDefaultValueDeclarationSQL($field);
2256

2257
            $charset = (isset($field['charset']) && $field['charset']) ?
2258
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
2259

2260
            $collation = (isset($field['collation']) && $field['collation']) ?
2261
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
2262

2263
            $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : '';
2264

2265
            $unique = (isset($field['unique']) && $field['unique']) ?
2266
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
2267

2268
            $check = (isset($field['check']) && $field['check']) ?
2269
                ' ' . $field['check'] : '';
2270

2271
            $typeDecl = $field['type']->getSQLDeclaration($field, $this);
2272
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
2273

2274 2275 2276
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
            }
2277 2278
        }

2279
        return $name . ' ' . $columnDef;
2280
    }
2281

2282
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2283
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
2284 2285
     *
     * @param array $columnDef
2286
     *
2287 2288
     * @return string
     */
2289
    public function getDecimalTypeDeclarationSQL(array $columnDef)
2290 2291
    {
        $columnDef['precision'] = ( ! isset($columnDef['precision']) || empty($columnDef['precision']))
2292
            ? 10 : $columnDef['precision'];
2293 2294
        $columnDef['scale'] = ( ! isset($columnDef['scale']) || empty($columnDef['scale']))
            ? 0 : $columnDef['scale'];
2295

2296 2297
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
    }
2298 2299

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2300
     * Obtains DBMS specific SQL code portion needed to set a default value
2301 2302
     * declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2303
     * @param array $field The field definition array.
2304
     *
Benjamin Morel's avatar
Benjamin Morel committed
2305
     * @return string DBMS specific SQL code portion needed to set a default value.
2306
     */
2307
    public function getDefaultValueDeclarationSQL($field)
2308
    {
2309 2310 2311 2312 2313 2314 2315
        if ( ! isset($field['default'])) {
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
        }

        $default = $field['default'];

        if ( ! isset($field['type'])) {
2316
            return " DEFAULT '" . $default . "'";
2317 2318 2319 2320 2321
        }

        $type = $field['type'];

        if ($type instanceof Types\PhpIntegerMappingType) {
2322
            return ' DEFAULT ' . $default;
2323 2324 2325
        }

        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2326
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2327 2328 2329
        }

        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2330
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2331 2332 2333
        }

        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2334
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2335 2336 2337 2338
        }

        if ($type instanceof Types\BooleanType) {
            return " DEFAULT '" . $this->convertBooleans($default) . "'";
2339
        }
Benjamin Morel's avatar
Benjamin Morel committed
2340

2341
        return " DEFAULT '" . $default . "'";
2342 2343 2344
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2345
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2346 2347
     * declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2348
     * @param array $definition The check definition.
2349
     *
Benjamin Morel's avatar
Benjamin Morel committed
2350
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2351
     */
2352
    public function getCheckDeclarationSQL(array $definition)
2353
    {
2354
        $constraints = [];
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
        foreach ($definition as $field => $def) {
            if (is_string($def)) {
                $constraints[] = 'CHECK (' . $def . ')';
            } else {
                if (isset($def['min'])) {
                    $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')';
                }

                if (isset($def['max'])) {
                    $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')';
                }
            }
        }

        return implode(', ', $constraints);
    }
2371

2372
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2373
     * Obtains DBMS specific SQL code portion needed to set a unique
2374 2375
     * constraint declaration to be used in statements like CREATE TABLE.
     *
2376 2377
     * @param string                      $name  The name of the unique constraint.
     * @param \Doctrine\DBAL\Schema\Index $index The index definition.
2378
     *
Benjamin Morel's avatar
Benjamin Morel committed
2379 2380 2381
     * @return string DBMS specific SQL code portion needed to set a constraint.
     *
     * @throws \InvalidArgumentException
2382
     */
2383
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
2384
    {
2385
        $columns = $index->getQuotedColumns($this);
2386
        $name = new Identifier($name);
2387 2388

        if (count($columns) === 0) {
2389
            throw new \InvalidArgumentException("Incomplete definition. 'columns' required.");
2390
        }
2391

2392
        return 'CONSTRAINT ' . $name->getQuotedName($this) . ' UNIQUE ('
2393 2394
            . $this->getIndexFieldDeclarationListSQL($columns)
            . ')' . $this->getPartialIndexSQL($index);
2395
    }
2396 2397

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2398
     * Obtains DBMS specific SQL code portion needed to set an index
2399 2400
     * declaration to be used in statements like CREATE TABLE.
     *
2401 2402
     * @param string                      $name  The name of the index.
     * @param \Doctrine\DBAL\Schema\Index $index The index definition.
Benjamin Morel's avatar
Benjamin Morel committed
2403 2404
     *
     * @return string DBMS specific SQL code portion needed to set an index.
2405
     *
Benjamin Morel's avatar
Benjamin Morel committed
2406
     * @throws \InvalidArgumentException
2407
     */
2408
    public function getIndexDeclarationSQL($name, Index $index)
2409
    {
2410
        $columns = $index->getQuotedColumns($this);
2411
        $name = new Identifier($name);
2412 2413

        if (count($columns) === 0) {
2414
            throw new \InvalidArgumentException("Incomplete definition. 'columns' required.");
2415 2416
        }

2417
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this) . ' ('
2418 2419
            . $this->getIndexFieldDeclarationListSQL($columns)
            . ')' . $this->getPartialIndexSQL($index);
2420 2421
    }

2422
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2423
     * Obtains SQL code portion needed to create a custom column,
2424 2425 2426
     * e.g. when a field has the "columnDefinition" keyword.
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
     *
2427
     * @param array $columnDef
2428
     *
2429 2430
     * @return string
     */
2431
    public function getCustomTypeDeclarationSQL(array $columnDef)
2432 2433 2434 2435
    {
        return $columnDef['columnDefinition'];
    }

2436
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2437
     * Obtains DBMS specific SQL code portion needed to set an index
2438 2439
     * declaration to be used in statements like CREATE TABLE.
     *
2440
     * @param array $fields
2441
     *
2442 2443
     * @return string
     */
2444
    public function getIndexFieldDeclarationListSQL(array $fields)
2445
    {
2446
        $ret = [];
2447

2448 2449
        foreach ($fields as $field => $definition) {
            if (is_array($definition)) {
2450
                $ret[] = $field;
2451
            } else {
2452
                $ret[] = $definition;
2453 2454
            }
        }
2455

2456 2457 2458 2459
        return implode(', ', $ret);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2460
     * Returns the required SQL string that fits between CREATE ... TABLE
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
     * to create the table as a temporary table.
     *
     * Should be overridden in driver classes to return the correct string for the
     * specific database type.
     *
     * The default is to return the string "TEMPORARY" - this will result in a
     * SQL error for any database that does not support temporary tables, or that
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
     *
     * @return string The string required to be placed between "CREATE" and "TABLE"
     *                to generate a temporary table, if possible.
     */
2473
    public function getTemporaryTableSQL()
2474 2475 2476
    {
        return 'TEMPORARY';
    }
2477

2478 2479 2480
    /**
     * Some vendors require temporary table names to be qualified specially.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2481
     * @param string $tableName
2482
     *
2483 2484 2485 2486 2487 2488 2489
     * @return string
     */
    public function getTemporaryTableName($tableName)
    {
        return $tableName;
    }

2490 2491 2492 2493
    /**
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2494
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey
2495
     *
Benjamin Morel's avatar
Benjamin Morel committed
2496 2497
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     *                of a field declaration.
2498
     */
2499
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
2500
    {
2501 2502
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2503 2504 2505 2506 2507

        return $sql;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2508
     * Returns the FOREIGN KEY query section dealing with non-standard options
2509 2510
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
     *
Benjamin Morel's avatar
Benjamin Morel committed
2511
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The foreign key definition.
2512
     *
2513 2514
     * @return string
     */
2515
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
2516 2517
    {
        $query = '';
2518
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2519
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2520
        }
2521
        if ($foreignKey->hasOption('onDelete')) {
2522
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2523
        }
Benjamin Morel's avatar
Benjamin Morel committed
2524

2525 2526 2527 2528
        return $query;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2529
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2530
     *
Benjamin Morel's avatar
Benjamin Morel committed
2531
     * @param string $action The foreign key referential action.
2532
     *
2533
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2534 2535
     *
     * @throws \InvalidArgumentException if unknown referential action given
2536
     */
2537
    public function getForeignKeyReferentialActionSQL($action)
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
    {
        $upper = strtoupper($action);
        switch ($upper) {
            case 'CASCADE':
            case 'SET NULL':
            case 'NO ACTION':
            case 'RESTRICT':
            case 'SET DEFAULT':
                return $upper;
            default:
2548
                throw new \InvalidArgumentException('Invalid foreign key action: ' . $upper);
2549 2550 2551 2552
        }
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2553
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2554 2555
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2556
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey
2557
     *
2558
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2559 2560
     *
     * @throws \InvalidArgumentException
2561
     */
2562
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
2563 2564
    {
        $sql = '';
2565
        if (strlen($foreignKey->getName())) {
2566
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2567 2568 2569
        }
        $sql .= 'FOREIGN KEY (';

2570
        if (count($foreignKey->getLocalColumns()) === 0) {
2571
            throw new \InvalidArgumentException("Incomplete definition. 'local' required.");
2572
        }
2573
        if (count($foreignKey->getForeignColumns()) === 0) {
2574
            throw new \InvalidArgumentException("Incomplete definition. 'foreign' required.");
2575
        }
2576
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2577
            throw new \InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
2578 2579
        }

2580
        $sql .= implode(', ', $foreignKey->getQuotedLocalColumns($this))
2581 2582 2583
            . ') REFERENCES '
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2584 2585 2586 2587 2588

        return $sql;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2589
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2590 2591
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2592 2593
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
     *                of a field declaration.
2594
     */
2595
    public function getUniqueFieldDeclarationSQL()
2596 2597 2598 2599 2600
    {
        return 'UNIQUE';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2601
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2602 2603
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2604
     * @param string $charset The name of the charset.
2605
     *
Benjamin Morel's avatar
Benjamin Morel committed
2606 2607
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
     *                of a field declaration.
2608
     */
2609
    public function getColumnCharsetDeclarationSQL($charset)
2610 2611 2612 2613 2614
    {
        return '';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2615
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2616 2617
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2618
     * @param string $collation The name of the collation.
2619
     *
Benjamin Morel's avatar
Benjamin Morel committed
2620 2621
     * @return string DBMS specific SQL code portion needed to set the COLLATION
     *                of a field declaration.
2622
     */
2623
    public function getColumnCollationDeclarationSQL($collation)
2624
    {
2625
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2626
    }
2627

2628 2629 2630 2631
    /**
     * Whether the platform prefers sequences for ID generation.
     * Subclasses should override this method to return TRUE if they prefer sequences.
     *
2632
     * @return bool
2633 2634 2635 2636 2637
     */
    public function prefersSequences()
    {
        return false;
    }
2638

2639 2640 2641 2642
    /**
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
     * Subclasses should override this method to return TRUE if they prefer identity columns.
     *
2643
     * @return bool
2644 2645 2646 2647 2648
     */
    public function prefersIdentityColumns()
    {
        return false;
    }
2649

2650 2651
    /**
     * Some platforms need the boolean values to be converted.
2652
     *
romanb's avatar
romanb committed
2653
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2654
     *
2655 2656
     * Note: if the input is not a boolean the original input might be returned.
     *
2657 2658
     * There are two contexts when converting booleans: Literals and Prepared Statements.
     * This method should handle the literal case
2659
     *
2660
     * @param mixed $item A boolean or an array of them.
2661
     *
2662
     * @return mixed A boolean database value or an array of them.
2663
     */
2664
    public function convertBooleans($item)
2665 2666 2667 2668 2669 2670 2671
    {
        if (is_array($item)) {
            foreach ($item as $k => $value) {
                if (is_bool($value)) {
                    $item[$k] = (int) $value;
                }
            }
Steve Müller's avatar
Steve Müller committed
2672
        } elseif (is_bool($item)) {
romanb's avatar
romanb committed
2673
            $item = (int) $item;
2674
        }
2675

2676 2677
        return $item;
    }
2678

2679
    /**
2680
     * Some platforms have boolean literals that needs to be correctly converted
2681 2682 2683 2684 2685
     *
     * The default conversion tries to convert value into bool "(bool)$item"
     *
     * @param mixed $item
     *
2686
     * @return bool|null
2687 2688 2689
     */
    public function convertFromBoolean($item)
    {
2690
        return null === $item ? null: (bool) $item ;
2691
    }
2692

2693 2694 2695 2696
    /**
     * This method should handle the prepared statements case. When there is no
     * distinction, it's OK to use the same method.
     *
2697 2698 2699
     * Note: if the input is not a boolean the original input might be returned.
     *
     * @param mixed $item A boolean or an array of them.
2700
     *
2701
     * @return mixed A boolean database value or an array of them.
2702
     */
2703
    public function convertBooleansToDatabaseValue($item)
2704
    {
2705
        return $this->convertBooleans($item);
2706 2707
    }

2708
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2709
     * Returns the SQL specific for the platform to get the current date.
2710 2711 2712
     *
     * @return string
     */
2713
    public function getCurrentDateSQL()
2714 2715 2716 2717 2718
    {
        return 'CURRENT_DATE';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2719
     * Returns the SQL specific for the platform to get the current time.
2720 2721 2722
     *
     * @return string
     */
2723
    public function getCurrentTimeSQL()
2724 2725 2726 2727
    {
        return 'CURRENT_TIME';
    }

2728
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2729
     * Returns the SQL specific for the platform to get the current timestamp
2730 2731 2732
     *
     * @return string
     */
2733
    public function getCurrentTimestampSQL()
2734 2735 2736
    {
        return 'CURRENT_TIMESTAMP';
    }
2737

romanb's avatar
romanb committed
2738
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2739
     * Returns the SQL for a given transaction isolation level Connection constant.
romanb's avatar
romanb committed
2740
     *
2741
     * @param int $level
2742
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2743
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2744 2745
     *
     * @throws \InvalidArgumentException
romanb's avatar
romanb committed
2746
     */
2747
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
2748 2749
    {
        switch ($level) {
2750
            case TransactionIsolationLevel::READ_UNCOMMITTED:
romanb's avatar
romanb committed
2751
                return 'READ UNCOMMITTED';
2752
            case TransactionIsolationLevel::READ_COMMITTED:
romanb's avatar
romanb committed
2753
                return 'READ COMMITTED';
2754
            case TransactionIsolationLevel::REPEATABLE_READ:
romanb's avatar
romanb committed
2755
                return 'REPEATABLE READ';
2756
            case TransactionIsolationLevel::SERIALIZABLE:
romanb's avatar
romanb committed
2757 2758
                return 'SERIALIZABLE';
            default:
2759
                throw new \InvalidArgumentException('Invalid isolation level:' . $level);
2760 2761 2762
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
2763 2764 2765 2766 2767
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2768
    public function getListDatabasesSQL()
2769
    {
2770
        throw DBALException::notSupported(__METHOD__);
2771 2772
    }

2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
    /**
     * Returns the SQL statement for retrieving the namespaces defined in the database.
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getListNamespacesSQL()
    {
        throw DBALException::notSupported(__METHOD__);
    }

Benjamin Morel's avatar
Benjamin Morel committed
2785 2786 2787 2788 2789 2790 2791
    /**
     * @param string $database
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2792
    public function getListSequencesSQL($database)
2793
    {
2794
        throw DBALException::notSupported(__METHOD__);
2795 2796
    }

Benjamin Morel's avatar
Benjamin Morel committed
2797 2798 2799 2800 2801 2802 2803
    /**
     * @param string $table
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2804
    public function getListTableConstraintsSQL($table)
2805
    {
2806
        throw DBALException::notSupported(__METHOD__);
2807 2808
    }

Benjamin Morel's avatar
Benjamin Morel committed
2809 2810 2811 2812 2813 2814 2815 2816
    /**
     * @param string      $table
     * @param string|null $database
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2817
    public function getListTableColumnsSQL($table, $database = null)
2818
    {
2819
        throw DBALException::notSupported(__METHOD__);
2820 2821
    }

Benjamin Morel's avatar
Benjamin Morel committed
2822 2823 2824 2825 2826
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2827
    public function getListTablesSQL()
2828
    {
2829
        throw DBALException::notSupported(__METHOD__);
2830 2831
    }

Benjamin Morel's avatar
Benjamin Morel committed
2832 2833 2834 2835 2836
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2837
    public function getListUsersSQL()
2838
    {
2839
        throw DBALException::notSupported(__METHOD__);
2840 2841
    }

2842
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2843
     * Returns the SQL to list all views of a database or user.
2844 2845
     *
     * @param string $database
2846
     *
2847
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2848 2849
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2850
     */
2851
    public function getListViewsSQL($database)
2852
    {
2853
        throw DBALException::notSupported(__METHOD__);
2854 2855
    }

2856
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2857
     * Returns the list of indexes for the current database.
2858
     *
2859 2860
     * The current database parameter is optional but will always be passed
     * when using the SchemaManager API and is the database the given table is in.
2861
     *
2862 2863 2864
     * Attention: Some platforms only support currentDatabase when they
     * are connected with that database. Cross-database information schema
     * requests may be impossible.
2865
     *
2866
     * @param string $table
2867
     * @param string $currentDatabase
2868
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2869
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2870 2871
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2872 2873
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
2874
    {
2875
        throw DBALException::notSupported(__METHOD__);
2876 2877
    }

Benjamin Morel's avatar
Benjamin Morel committed
2878 2879 2880 2881 2882 2883 2884
    /**
     * @param string $table
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2885
    public function getListTableForeignKeysSQL($table)
2886
    {
2887
        throw DBALException::notSupported(__METHOD__);
2888 2889
    }

Benjamin Morel's avatar
Benjamin Morel committed
2890 2891 2892 2893 2894 2895 2896 2897
    /**
     * @param string $name
     * @param string $sql
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2898
    public function getCreateViewSQL($name, $sql)
2899
    {
2900
        throw DBALException::notSupported(__METHOD__);
2901 2902
    }

Benjamin Morel's avatar
Benjamin Morel committed
2903 2904 2905 2906 2907 2908 2909
    /**
     * @param string $name
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2910
    public function getDropViewSQL($name)
2911
    {
2912
        throw DBALException::notSupported(__METHOD__);
2913 2914
    }

2915
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2916
     * Returns the SQL snippet to drop an existing sequence.
2917
     *
jeroendedauw's avatar
jeroendedauw committed
2918
     * @param Sequence|string $sequence
2919 2920
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2921 2922
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2923
     */
2924
    public function getDropSequenceSQL($sequence)
2925
    {
2926
        throw DBALException::notSupported(__METHOD__);
2927 2928
    }

Benjamin Morel's avatar
Benjamin Morel committed
2929 2930 2931 2932 2933 2934 2935
    /**
     * @param string $sequenceName
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2936
    public function getSequenceNextValSQL($sequenceName)
2937
    {
2938
        throw DBALException::notSupported(__METHOD__);
romanb's avatar
romanb committed
2939
    }
2940

2941
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2942
     * Returns the SQL to create a new database.
2943
     *
Benjamin Morel's avatar
Benjamin Morel committed
2944
     * @param string $database The name of the database that should be created.
2945 2946
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2947 2948
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2949
     */
2950
    public function getCreateDatabaseSQL($database)
2951
    {
2952
        throw DBALException::notSupported(__METHOD__);
2953 2954
    }

romanb's avatar
romanb committed
2955
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2956
     * Returns the SQL to set the transaction isolation level.
romanb's avatar
romanb committed
2957
     *
2958
     * @param int $level
2959
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2960
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2961 2962
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
romanb's avatar
romanb committed
2963
     */
2964
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
2965
    {
2966
        throw DBALException::notSupported(__METHOD__);
romanb's avatar
romanb committed
2967
    }
2968

2969
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2970 2971
     * Obtains DBMS specific SQL to be used to create datetime fields in
     * statements like CREATE TABLE.
2972
     *
2973
     * @param array $fieldDeclaration
2974
     *
2975
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2976 2977
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2978
     */
2979
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
2980
    {
2981
        throw DBALException::notSupported(__METHOD__);
2982
    }
2983 2984

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2985
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
2986
     *
2987
     * @param array $fieldDeclaration
2988
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2989
     * @return string
2990 2991 2992
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
    {
2993
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
2994
    }
2995 2996


2997
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2998
     * Obtains DBMS specific SQL to be used to create date fields in statements
2999
     * like CREATE TABLE.
3000
     *
3001
     * @param array $fieldDeclaration
3002
     *
3003
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3004 3005
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
3006
     */
3007
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
3008
    {
3009
        throw DBALException::notSupported(__METHOD__);
3010
    }
3011

3012
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3013
     * Obtains DBMS specific SQL to be used to create time fields in statements
3014 3015 3016
     * like CREATE TABLE.
     *
     * @param array $fieldDeclaration
3017
     *
3018
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3019 3020
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
3021
     */
3022
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
3023
    {
3024
        throw DBALException::notSupported(__METHOD__);
3025 3026
    }

Benjamin Morel's avatar
Benjamin Morel committed
3027 3028 3029 3030 3031
    /**
     * @param array $fieldDeclaration
     *
     * @return string
     */
3032 3033 3034 3035 3036
    public function getFloatDeclarationSQL(array $fieldDeclaration)
    {
        return 'DOUBLE PRECISION';
    }

romanb's avatar
romanb committed
3037 3038 3039
    /**
     * Gets the default transaction isolation level of the platform.
     *
3040
     * @return int The default isolation level.
3041
     *
3042
     * @see TransactionIsolationLevel
romanb's avatar
romanb committed
3043 3044 3045
     */
    public function getDefaultTransactionIsolationLevel()
    {
3046
        return TransactionIsolationLevel::READ_COMMITTED;
romanb's avatar
romanb committed
3047
    }
3048

3049
    /* supports*() methods */
3050 3051 3052 3053

    /**
     * Whether the platform supports sequences.
     *
3054
     * @return bool
3055
     */
3056 3057 3058 3059
    public function supportsSequences()
    {
        return false;
    }
3060 3061 3062

    /**
     * Whether the platform supports identity columns.
Benjamin Morel's avatar
Benjamin Morel committed
3063
     *
Pascal Borreli's avatar
Pascal Borreli committed
3064
     * Identity columns are columns that receive an auto-generated value from the
3065 3066
     * database on insert of a row.
     *
3067
     * @return bool
3068
     */
3069 3070 3071 3072
    public function supportsIdentityColumns()
    {
        return false;
    }
3073

3074 3075 3076 3077 3078 3079 3080
    /**
     * Whether the platform emulates identity columns through sequences.
     *
     * Some platforms that do not support identity columns natively
     * but support sequences can emulate identity columns by using
     * sequences.
     *
3081
     * @return bool
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
     */
    public function usesSequenceEmulatedIdentityColumns()
    {
        return false;
    }

    /**
     * Returns the name of the sequence for a particular identity column in a particular table.
     *
     * @param string $tableName  The name of the table to return the sequence name for.
     * @param string $columnName The name of the identity column in the table to return the sequence name for.
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     *
     * @see    usesSequenceEmulatedIdentityColumns
     */
    public function getIdentitySequenceName($tableName, $columnName)
    {
        throw DBALException::notSupported(__METHOD__);
    }

3105 3106 3107
    /**
     * Whether the platform supports indexes.
     *
3108
     * @return bool
3109
     */
3110 3111 3112 3113
    public function supportsIndexes()
    {
        return true;
    }
3114

3115 3116 3117
    /**
     * Whether the platform supports partial indexes.
     *
3118
     * @return bool
3119 3120 3121 3122 3123 3124
     */
    public function supportsPartialIndexes()
    {
        return false;
    }

3125 3126 3127
    /**
     * Whether the platform supports altering tables.
     *
3128
     * @return bool
3129
     */
3130 3131 3132 3133 3134
    public function supportsAlterTable()
    {
        return true;
    }

3135 3136 3137
    /**
     * Whether the platform supports transactions.
     *
3138
     * @return bool
3139
     */
3140 3141 3142 3143
    public function supportsTransactions()
    {
        return true;
    }
3144 3145 3146 3147

    /**
     * Whether the platform supports savepoints.
     *
3148
     * @return bool
3149
     */
3150 3151 3152 3153
    public function supportsSavepoints()
    {
        return true;
    }
3154

3155 3156 3157
    /**
     * Whether the platform supports releasing savepoints.
     *
3158
     * @return bool
3159 3160 3161 3162 3163 3164
     */
    public function supportsReleaseSavepoints()
    {
        return $this->supportsSavepoints();
    }

3165 3166 3167
    /**
     * Whether the platform supports primary key constraints.
     *
3168
     * @return bool
3169
     */
3170 3171 3172 3173
    public function supportsPrimaryConstraints()
    {
        return true;
    }
3174 3175

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3176
     * Whether the platform supports foreign key constraints.
3177
     *
3178
     * @return bool
3179
     */
3180 3181 3182 3183
    public function supportsForeignKeyConstraints()
    {
        return true;
    }
3184 3185

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3186
     * Whether this platform supports onUpdate in foreign key constraints.
3187
     *
3188
     * @return bool
3189 3190 3191 3192 3193
     */
    public function supportsForeignKeyOnUpdate()
    {
        return ($this->supportsForeignKeyConstraints() && true);
    }
3194

3195 3196
    /**
     * Whether the platform supports database schemas.
3197
     *
3198
     * @return bool
3199 3200 3201 3202 3203
     */
    public function supportsSchemas()
    {
        return false;
    }
3204

3205
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3206
     * Whether this platform can emulate schemas.
3207 3208 3209 3210 3211
     *
     * Platforms that either support or emulate schemas don't automatically
     * filter a schema for the namespaced elements in {@link
     * AbstractManager#createSchema}.
     *
3212
     * @return bool
3213 3214 3215 3216 3217 3218
     */
    public function canEmulateSchemas()
    {
        return false;
    }

3219 3220 3221 3222 3223 3224 3225
    /**
     * Returns the default schema name.
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
3226
    public function getDefaultSchemaName()
3227 3228 3229 3230
    {
        throw DBALException::notSupported(__METHOD__);
    }

3231
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3232 3233
     * Whether this platform supports create database.
     *
3234 3235
     * Some databases don't allow to create and drop databases at all or only with certain tools.
     *
3236
     * @return bool
3237 3238 3239 3240 3241 3242
     */
    public function supportsCreateDropDatabase()
    {
        return true;
    }

3243
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3244
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
3245
     *
3246
     * @return bool
3247
     */
3248 3249 3250 3251
    public function supportsGettingAffectedRows()
    {
        return true;
    }
3252

3253
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3254
     * Whether this platform support to add inline column comments as postfix.
3255
     *
3256
     * @return bool
3257 3258 3259 3260 3261 3262 3263
     */
    public function supportsInlineColumnComments()
    {
        return false;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3264
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
3265
     *
3266
     * @return bool
3267 3268 3269 3270 3271 3272
     */
    public function supportsCommentOnStatement()
    {
        return false;
    }

3273 3274 3275
    /**
     * Does this platform have native guid type.
     *
3276
     * @return bool
3277 3278 3279 3280 3281 3282
     */
    public function hasNativeGuidType()
    {
        return false;
    }

3283 3284 3285
    /**
     * Does this platform have native JSON type.
     *
3286
     * @return bool
3287 3288 3289 3290 3291 3292
     */
    public function hasNativeJsonType()
    {
        return false;
    }

3293 3294 3295 3296
    /**
     * @deprecated
     * @todo Remove in 3.0
     */
3297
    public function getIdentityColumnNullInsertSQL()
3298 3299 3300 3301
    {
        return "";
    }

3302
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3303
     * Whether this platform supports views.
3304
     *
3305
     * @return bool
3306 3307 3308 3309 3310 3311
     */
    public function supportsViews()
    {
        return true;
    }

3312 3313 3314
    /**
     * Does this platform support column collation?
     *
3315
     * @return bool
3316 3317 3318 3319 3320 3321
     */
    public function supportsColumnCollation()
    {
        return false;
    }

3322
    /**
3323 3324
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored datetime value of this platform.
3325
     *
3326
     * @return string The format string.
3327 3328 3329 3330 3331 3332
     */
    public function getDateTimeFormatString()
    {
        return 'Y-m-d H:i:s';
    }

3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
    /**
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored datetime with timezone value of this platform.
     *
     * @return string The format string.
     */
    public function getDateTimeTzFormatString()
    {
        return 'Y-m-d H:i:s';
    }

3344 3345 3346
    /**
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored date value of this platform.
3347
     *
3348 3349
     * @return string The format string.
     */
3350 3351
    public function getDateFormatString()
    {
3352
        return 'Y-m-d';
3353
    }
3354

3355 3356 3357
    /**
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored time value of this platform.
3358
     *
3359 3360
     * @return string The format string.
     */
3361 3362 3363 3364 3365
    public function getTimeFormatString()
    {
        return 'H:i:s';
    }

3366
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3367
     * Adds an driver-specific LIMIT clause to the query.
3368
     *
3369 3370 3371
     * @param string   $query
     * @param int|null $limit
     * @param int|null $offset
3372
     *
3373
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3374 3375
     *
     * @throws DBALException
3376 3377 3378
     */
    final public function modifyLimitQuery($query, $limit, $offset = null)
    {
3379
        if ($limit !== null) {
3380
            $limit = (int) $limit;
3381 3382
        }

3383
        if ($offset !== null) {
3384
            $offset = (int) $offset;
3385 3386 3387 3388

            if ($offset < 0) {
                throw new DBALException("LIMIT argument offset=$offset is not valid");
            }
3389
            if ($offset > 0 && ! $this->supportsLimitOffset()) {
3390 3391
                throw new DBALException(sprintf("Platform %s does not support offset values in limit queries.", $this->getName()));
            }
3392 3393 3394 3395 3396 3397
        }

        return $this->doModifyLimitQuery($query, $limit, $offset);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3398
     * Adds an driver-specific LIMIT clause to the query.
3399
     *
3400 3401 3402
     * @param string   $query
     * @param int|null $limit
     * @param int|null $offset
3403
     *
3404 3405 3406
     * @return string
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
3407
    {
3408
        if ($limit !== null) {
3409
            $query .= ' LIMIT ' . $limit;
3410 3411
        }

3412
        if ($offset !== null) {
3413 3414 3415
            $query .= ' OFFSET ' . $offset;
        }

3416 3417
        return $query;
    }
3418

3419
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3420
     * Whether the database platform support offsets in modify limit clauses.
3421
     *
3422
     * @return bool
3423 3424 3425 3426 3427 3428
     */
    public function supportsLimitOffset()
    {
        return true;
    }

3429 3430
    /**
     * Gets the character casing of a column in an SQL result set of this platform.
3431
     *
3432
     * @param string $column The column name for which to get the correct character casing.
3433
     *
3434 3435
     * @return string The column name in the character casing used in SQL result sets.
     */
3436
    public function getSQLResultCasing($column)
3437 3438 3439
    {
        return $column;
    }
3440

3441 3442 3443
    /**
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
     * by restrictions of the platform, like a maximum length.
3444
     *
3445
     * @param string $schemaElementName
3446
     *
3447 3448 3449 3450 3451 3452
     * @return string
     */
    public function fixSchemaElementName($schemaElementName)
    {
        return $schemaElementName;
    }
3453

3454
    /**
Pascal Borreli's avatar
Pascal Borreli committed
3455
     * Maximum length of any given database identifier, like tables or column names.
3456
     *
3457
     * @return int
3458 3459 3460 3461 3462 3463
     */
    public function getMaxIdentifierLength()
    {
        return 63;
    }

3464
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3465
     * Returns the insert SQL for an empty insert statement.
3466
     *
3467 3468
     * @param string $tableName
     * @param string $identifierColumnName
3469
     *
Benjamin Morel's avatar
Benjamin Morel committed
3470
     * @return string
3471
     */
3472
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
3473 3474 3475
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
    }
3476 3477

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3478
     * Generates a Truncate Table SQL statement for a given table.
3479 3480 3481 3482
     *
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
     * following the foreign keys.
     *
3483 3484
     * @param string $tableName
     * @param bool   $cascade
3485
     *
3486 3487
     * @return string
     */
3488
    public function getTruncateTableSQL($tableName, $cascade = false)
3489
    {
3490 3491 3492
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3493
    }
3494 3495 3496

    /**
     * This is for test reasons, many vendors have special requirements for dummy statements.
3497
     *
3498 3499 3500 3501 3502 3503
     * @return string
     */
    public function getDummySelectSQL()
    {
        return 'SELECT 1';
    }
3504 3505

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3506
     * Returns the SQL to create a new savepoint.
3507 3508
     *
     * @param string $savepoint
3509
     *
3510 3511 3512 3513 3514 3515 3516 3517
     * @return string
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVEPOINT ' . $savepoint;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3518
     * Returns the SQL to release a savepoint.
3519 3520
     *
     * @param string $savepoint
3521
     *
3522 3523 3524 3525 3526 3527 3528 3529
     * @return string
     */
    public function releaseSavePoint($savepoint)
    {
        return 'RELEASE SAVEPOINT ' . $savepoint;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3530
     * Returns the SQL to rollback a savepoint.
3531 3532
     *
     * @param string $savepoint
3533
     *
3534 3535 3536 3537 3538 3539
     * @return string
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
    }
3540 3541

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3542
     * Returns the keyword list instance of this platform.
3543
     *
3544
     * @return \Doctrine\DBAL\Platforms\Keywords\KeywordList
Benjamin Morel's avatar
Benjamin Morel committed
3545 3546
     *
     * @throws \Doctrine\DBAL\DBALException If no keyword list is specified.
3547 3548 3549
     */
    final public function getReservedKeywordsList()
    {
3550
        // Check for an existing instantiation of the keywords class.
3551 3552
        if ($this->_keywords) {
            return $this->_keywords;
3553 3554
        }

3555 3556
        $class = $this->getReservedKeywordsClass();
        $keywords = new $class;
3557
        if ( ! $keywords instanceof \Doctrine\DBAL\Platforms\Keywords\KeywordList) {
3558 3559
            throw DBALException::notSupported(__METHOD__);
        }
3560 3561

        // Store the instance so it doesn't need to be generated on every request.
3562
        $this->_keywords = $keywords;
3563

3564 3565
        return $keywords;
    }
3566

3567
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3568
     * Returns the class name of the reserved keywords list.
3569
     *
3570
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3571 3572
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
3573 3574 3575 3576 3577
     */
    protected function getReservedKeywordsClass()
    {
        throw DBALException::notSupported(__METHOD__);
    }
3578 3579

    /**
3580 3581 3582 3583
     * Quotes a literal string.
     * This method is NOT meant to fix SQL injections!
     * It is only meant to escape this platform's string literal
     * quote character inside the given literal string.
3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
     *
     * @param string $str The literal string to be quoted.
     *
     * @return string The quoted literal string.
     */
    public function quoteStringLiteral($str)
    {
        $c = $this->getStringLiteralQuoteCharacter();

        return $c . str_replace($c, $c . $c, $str) . $c;
    }

    /**
     * Gets the character used for string literal quoting.
     *
     * @return string
     */
    public function getStringLiteralQuoteCharacter()
    {
        return "'";
    }
3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615

    /**
     * Escapes metacharacters in a string intended to be used with a LIKE
     * operator.
     *
     * @param string $inputString a literal, unquoted string
     * @param string $escapeChar  should be reused by the caller in the LIKE
     *                            expression.
     */
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
    {
3616
        return preg_replace(
3617
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3618 3619 3620
            addcslashes($escapeChar, '\\') . '$1',
            $inputString
        );
3621 3622
    }

3623
    protected function getLikeWildcardCharacters() : string
3624
    {
3625
        return '%_';
3626
    }
3627
}