AbstractPlatform.php 99.2 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;

Benjamin Morel's avatar
Benjamin Morel committed
22 23
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Connection;
24
use Doctrine\DBAL\Schema\Identifier;
Benjamin Morel's avatar
Benjamin Morel committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
use Doctrine\DBAL\Types;
use Doctrine\DBAL\Schema\Constraint;
use Doctrine\DBAL\Schema\Sequence;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Events;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
45 46 47 48 49 50

/**
 * 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
51 52 53 54 55 56 57 58
 * @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.
59
 */
60
abstract class AbstractPlatform
61
{
62
    /**
63
     * @var integer
64 65 66 67
     */
    const CREATE_INDEXES = 1;

    /**
68
     * @var integer
69 70 71
     */
    const CREATE_FOREIGNKEYS = 2;

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_SECOND = 'SECOND';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_MINUTE = 'MINUTE';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_HOUR = 'HOUR';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_DAY = 'DAY';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_WEEK = 'WEEK';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_MONTH = 'MONTH';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_QUARTER = 'QUARTER';

    /**
     * @var string
     */
    const DATE_INTERVAL_UNIT_YEAR = 'YEAR';

112
    /**
113
     * @var integer
114 115 116 117
     */
    const TRIM_UNSPECIFIED = 0;

    /**
118
     * @var integer
119 120 121 122
     */
    const TRIM_LEADING = 1;

    /**
123
     * @var integer
124 125 126 127
     */
    const TRIM_TRAILING = 2;

    /**
128
     * @var integer
129 130 131
     */
    const TRIM_BOTH = 3;

132
    /**
Benjamin Morel's avatar
Benjamin Morel committed
133
     * @var array|null
134 135 136
     */
    protected $doctrineTypeMapping = null;

137 138 139 140
    /**
     * 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
141
     * @var array|null
142 143 144
     */
    protected $doctrineTypeComments = null;

145
    /**
Konstantin Kuklin's avatar
Konstantin Kuklin committed
146
     * @var \Doctrine\Common\EventManager
147 148 149
     */
    protected $_eventManager;

150 151 152
    /**
     * Holds the KeywordList instance for the current platform.
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
153
     * @var \Doctrine\DBAL\Platforms\Keywords\KeywordList
154 155 156
     */
    protected $_keywords;

157 158 159
    /**
     * Constructor.
     */
Benjamin Morel's avatar
Benjamin Morel committed
160 161 162
    public function __construct()
    {
    }
163

164 165 166
    /**
     * Sets the EventManager used by the Platform.
     *
jsor's avatar
jsor committed
167
     * @param \Doctrine\Common\EventManager
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
     */
    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;
    }

184
    /**
Benjamin Morel's avatar
Benjamin Morel committed
185
     * Returns the SQL snippet that declares a boolean column.
186 187
     *
     * @param array $columnDef
188
     *
189 190 191 192 193
     * @return string
     */
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
194
     * Returns the SQL snippet that declares a 4 byte integer column.
195 196
     *
     * @param array $columnDef
197
     *
198 199 200 201 202
     * @return string
     */
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
203
     * Returns the SQL snippet that declares an 8 byte integer column.
204 205
     *
     * @param array $columnDef
206
     *
207 208 209 210 211
     * @return string
     */
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
212
     * Returns the SQL snippet that declares a 2 byte integer column.
213 214
     *
     * @param array $columnDef
215
     *
216 217 218 219 220
     * @return string
     */
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
221
     * Returns the SQL snippet that declares common properties of an integer column.
222 223
     *
     * @param array $columnDef
Benjamin Morel's avatar
Benjamin Morel committed
224
     *
225 226 227 228 229
     * @return string
     */
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);

    /**
Benjamin Morel's avatar
Benjamin Morel committed
230
     * Lazy load Doctrine Type Mappings.
231 232 233 234 235
     *
     * @return void
     */
    abstract protected function initializeDoctrineTypeMappings();

236
    /**
Benjamin Morel's avatar
Benjamin Morel committed
237
     * Initializes Doctrine Type Mappings with the platform defaults
238
     * and with all additional type mappings.
Benjamin Morel's avatar
Benjamin Morel committed
239 240
     *
     * @return void
241 242 243 244 245 246 247 248 249 250 251 252
     */
    private function initializeAllDoctrineTypeMappings()
    {
        $this->initializeDoctrineTypeMappings();

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

253
    /**
Benjamin Morel's avatar
Benjamin Morel committed
254
     * Returns the SQL snippet used to declare a VARCHAR column type.
255 256
     *
     * @param array $field
257
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
258
     * @return string
259
     */
260 261 262 263 264 265 266 267 268 269 270
    public function getVarcharTypeDeclarationSQL(array $field)
    {
        if ( !isset($field['length'])) {
            $field['length'] = $this->getVarcharDefaultLength();
        }

        $fixed = (isset($field['fixed'])) ? $field['fixed'] : false;

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

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

Steve Müller's avatar
Steve Müller committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    /**
     * 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();
        }

        $fixed = isset($field['fixed']) ? $field['fixed'] : false;

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

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

297
    /**
Benjamin Morel's avatar
Benjamin Morel committed
298
     * Returns the SQL snippet to declare a GUID/UUID field.
299 300 301 302 303
     *
     * By default this maps directly to a VARCHAR and only maps to more
     * special datatypes when the underlying databases support this datatype.
     *
     * @param array $field
304
     *
305 306
     * @return string
     */
307
    public function getGuidTypeDeclarationSQL(array $field)
308 309 310 311
    {
        return $this->getVarcharTypeDeclarationSQL($field);
    }

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    /**
     * 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
327
    /**
328
     * @param integer $length
Christophe Coevoet's avatar
Christophe Coevoet committed
329
     * @param boolean $fixed
330
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
331
     * @return string
332
     *
Benjamin Morel's avatar
Benjamin Morel committed
333
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
Christophe Coevoet's avatar
Christophe Coevoet committed
334
     */
335 336 337 338
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
    }
339

Steve Müller's avatar
Steve Müller committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    /**
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
     *
     * @param integer $length The length of the column.
     * @param boolean $fixed  Whether the column length is fixed.
     *
     * @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.');
    }

355
    /**
Benjamin Morel's avatar
Benjamin Morel committed
356
     * Returns the SQL snippet used to declare a CLOB column type.
357 358
     *
     * @param array $field
359 360
     *
     * @return string
361 362 363
     */
    abstract public function getClobTypeDeclarationSQL(array $field);

364
    /**
Benjamin Morel's avatar
Benjamin Morel committed
365
     * Returns the SQL Snippet used to declare a BLOB column type.
366 367
     *
     * @param array $field
368 369
     *
     * @return string
370 371 372
     */
    abstract public function getBlobTypeDeclarationSQL(array $field);

373 374 375 376 377 378 379
    /**
     * Gets the name of the platform.
     *
     * @return string
     */
    abstract public function getName();

380
    /**
Benjamin Morel's avatar
Benjamin Morel committed
381
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
382 383 384
     *
     * @param string $dbType
     * @param string $doctrineType
385
     *
Benjamin Morel's avatar
Benjamin Morel committed
386
     * @throws \Doctrine\DBAL\DBALException If the type is not found.
387 388 389 390
     */
    public function registerDoctrineTypeMapping($dbType, $doctrineType)
    {
        if ($this->doctrineTypeMapping === null) {
391
            $this->initializeAllDoctrineTypeMappings();
392 393 394 395 396 397 398 399 400 401 402
        }

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

        $dbType = strtolower($dbType);
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
403
     * Gets the Doctrine type that is mapped for the given database column type.
404
     *
Benjamin Morel's avatar
Benjamin Morel committed
405
     * @param string $dbType
406
     *
407
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
408 409
     *
     * @throws \Doctrine\DBAL\DBALException
410 411 412 413
     */
    public function getDoctrineTypeMapping($dbType)
    {
        if ($this->doctrineTypeMapping === null) {
414
            $this->initializeAllDoctrineTypeMappings();
415
        }
416

417
        $dbType = strtolower($dbType);
418

419
        if (!isset($this->doctrineTypeMapping[$dbType])) {
420 421
            throw new \Doctrine\DBAL\DBALException("Unknown database type ".$dbType." requested, " . get_class($this) . " may not support it.");
        }
422 423

        return $this->doctrineTypeMapping[$dbType];
424 425
    }

426
    /**
Benjamin Morel's avatar
Benjamin Morel committed
427
     * Checks if a database type is currently supported by this platform.
428 429
     *
     * @param string $dbType
430 431
     *
     * @return boolean
432 433 434 435
     */
    public function hasDoctrineTypeMappingFor($dbType)
    {
        if ($this->doctrineTypeMapping === null) {
436
            $this->initializeAllDoctrineTypeMappings();
437 438 439
        }

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

441 442 443
        return isset($this->doctrineTypeMapping[$dbType]);
    }

444
    /**
Benjamin Morel's avatar
Benjamin Morel committed
445
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
446 447 448 449 450
     *
     * @return void
     */
    protected function initializeCommentedDoctrineTypes()
    {
451 452 453 454
        $this->doctrineTypeComments = array();

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

456 457 458 459
            if ($type->requiresSQLCommentHint($this)) {
                $this->doctrineTypeComments[] = $typeName;
            }
        }
460 461 462 463 464
    }

    /**
     * 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
465
     * @param \Doctrine\DBAL\Types\Type $doctrineType
466
     *
467
     * @return boolean
468 469 470 471 472 473 474 475 476 477 478
     */
    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
479
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
480
     *
Benjamin Morel's avatar
Benjamin Morel committed
481
     * @param string|\Doctrine\DBAL\Types\Type $doctrineType
482
     *
483 484
     * @return void
     */
485
    public function markDoctrineTypeCommented($doctrineType)
486 487 488 489
    {
        if ($this->doctrineTypeComments === null) {
            $this->initializeCommentedDoctrineTypes();
        }
490

491
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
492 493 494
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
495 496 497
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
     *
     * @param \Doctrine\DBAL\Types\Type $doctrineType
498
     *
499 500 501 502 503 504 505
     * @return string
     */
    public function getDoctrineTypeComment(Type $doctrineType)
    {
        return '(DC2Type:' . $doctrineType->getName() . ')';
    }

506
    /**
Benjamin Morel's avatar
Benjamin Morel committed
507 508 509
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
     *
     * @param \Doctrine\DBAL\Schema\Column $column
510
     *
511 512 513 514 515
     * @return string
     */
    protected function getColumnComment(Column $column)
    {
        $comment = $column->getComment();
516

517 518 519
        if ($this->isCommentedDoctrineType($column->getType())) {
            $comment .= $this->getDoctrineTypeComment($column->getType());
        }
520

521 522 523
        return $comment;
    }

524 525 526 527 528 529 530 531 532
    /**
     * Gets the character used for identifier quoting.
     *
     * @return string
     */
    public function getIdentifierQuoteCharacter()
    {
        return '"';
    }
533

534 535 536 537 538 539 540 541 542
    /**
     * Gets the string portion that starts an SQL comment.
     *
     * @return string
     */
    public function getSqlCommentStartString()
    {
        return "--";
    }
543

544
    /**
545
     * Gets the string portion that ends an SQL comment.
546 547 548 549 550 551 552
     *
     * @return string
     */
    public function getSqlCommentEndString()
    {
        return "\n";
    }
553

554 555 556 557 558 559
    /**
     * Gets the maximum length of a varchar field.
     *
     * @return integer
     */
    public function getVarcharMaxLength()
560 561 562 563 564 565 566 567 568 569
    {
        return 4000;
    }

    /**
     * Gets the default length of a varchar field.
     *
     * @return integer
     */
    public function getVarcharDefaultLength()
570 571 572
    {
        return 255;
    }
573

Steve Müller's avatar
Steve Müller committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    /**
     * Gets the maximum length of a binary field.
     *
     * @return integer
     */
    public function getBinaryMaxLength()
    {
        return 4000;
    }

    /**
     * Gets the default length of a binary field.
     *
     * @return integer
     */
    public function getBinaryDefaultLength()
    {
        return 255;
    }

594 595 596 597 598 599 600 601 602
    /**
     * Gets all SQL wildcard characters of the platform.
     *
     * @return array
     */
    public function getWildcards()
    {
        return array('%', '_');
    }
603

604 605 606 607
    /**
     * Returns the regular expression operator.
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
608 609
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
610 611 612
     */
    public function getRegexpExpression()
    {
613
        throw DBALException::notSupported(__METHOD__);
614
    }
615

616
    /**
Benjamin Morel's avatar
Benjamin Morel committed
617 618 619
     * Returns the global unique identifier expression.
     *
     * @return string
620
     *
Benjamin Morel's avatar
Benjamin Morel committed
621
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
622 623 624 625
     */
    public function getGuidExpression()
    {
        throw DBALException::notSupported(__METHOD__);
626 627 628
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
629
     * Returns the SQL snippet to get the average value of a column.
630
     *
Benjamin Morel's avatar
Benjamin Morel committed
631
     * @param string $column The column to use.
632
     *
Benjamin Morel's avatar
Benjamin Morel committed
633
     * @return string Generated SQL including an AVG aggregate function.
634 635 636
     */
    public function getAvgExpression($column)
    {
Benjamin Morel's avatar
Benjamin Morel committed
637
        return 'AVG(' . $column . ')';
638 639 640
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
641
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
642
     *
Benjamin Morel's avatar
Benjamin Morel committed
643
     * If a '*' is used instead of a column the number of selected rows is returned.
644
     *
Benjamin Morel's avatar
Benjamin Morel committed
645
     * @param string|integer $column The column to use.
646
     *
Benjamin Morel's avatar
Benjamin Morel committed
647
     * @return string Generated SQL including a COUNT aggregate function.
648 649 650 651 652 653 654
     */
    public function getCountExpression($column)
    {
        return 'COUNT(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
655 656 657
     * Returns the SQL snippet to get the highest value of a column.
     *
     * @param string $column The column to use.
658
     *
Benjamin Morel's avatar
Benjamin Morel committed
659
     * @return string Generated SQL including a MAX aggregate function.
660 661 662 663 664 665 666
     */
    public function getMaxExpression($column)
    {
        return 'MAX(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
667
     * Returns the SQL snippet to get the lowest value of a column.
668
     *
Benjamin Morel's avatar
Benjamin Morel committed
669 670 671
     * @param string $column The column to use.
     *
     * @return string Generated SQL including a MIN aggregate function.
672 673 674 675 676 677 678
     */
    public function getMinExpression($column)
    {
        return 'MIN(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
679
     * Returns the SQL snippet to get the total sum of a column.
680
     *
Benjamin Morel's avatar
Benjamin Morel committed
681 682 683
     * @param string $column The column to use.
     *
     * @return string Generated SQL including a SUM aggregate function.
684 685 686 687 688 689 690 691 692
     */
    public function getSumExpression($column)
    {
        return 'SUM(' . $column . ')';
    }

    // scalar functions

    /**
Benjamin Morel's avatar
Benjamin Morel committed
693
     * Returns the SQL snippet to get the md5 sum of a field.
694
     *
Benjamin Morel's avatar
Benjamin Morel committed
695
     * Note: Not SQL92, but common functionality.
696
     *
697
     * @param string $column
Benjamin Morel's avatar
Benjamin Morel committed
698
     *
699 700 701 702 703 704 705 706
     * @return string
     */
    public function getMd5Expression($column)
    {
        return 'MD5(' . $column . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
707
     * Returns the SQL snippet to get the length of a text field.
708
     *
709
     * @param string $column
710
     *
711 712 713 714 715 716 717
     * @return string
     */
    public function getLengthExpression($column)
    {
        return 'LENGTH(' . $column . ')';
    }

718
    /**
Benjamin Morel's avatar
Benjamin Morel committed
719
     * Returns the SQL snippet to get the squared value of a column.
720
     *
Benjamin Morel's avatar
Benjamin Morel committed
721
     * @param string $column The column to use.
722
     *
Benjamin Morel's avatar
Benjamin Morel committed
723
     * @return string Generated SQL including an SQRT aggregate function.
724 725 726 727 728 729
     */
    public function getSqrtExpression($column)
    {
        return 'SQRT(' . $column . ')';
    }

730
    /**
Benjamin Morel's avatar
Benjamin Morel committed
731
     * Returns the SQL snippet to round a numeric field to the number of decimals specified.
732
     *
Benjamin Morel's avatar
Benjamin Morel committed
733
     * @param string  $column
734
     * @param integer $decimals
735
     *
736 737 738 739 740 741 742 743
     * @return string
     */
    public function getRoundExpression($column, $decimals = 0)
    {
        return 'ROUND(' . $column . ', ' . $decimals . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
744
     * Returns the SQL snippet to get the remainder of the division operation $expression1 / $expression2.
745 746 747
     *
     * @param string $expression1
     * @param string $expression2
748
     *
749 750 751 752 753 754 755 756
     * @return string
     */
    public function getModExpression($expression1, $expression2)
    {
        return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
757
     * Returns the SQL snippet to trim a string.
758
     *
Benjamin Morel's avatar
Benjamin Morel committed
759 760 761
     * @param string         $str  The expression to apply the trim to.
     * @param integer        $pos  The position of the trim (leading/trailing/both).
     * @param string|boolean $char The char to trim, has to be quoted already. Defaults to space.
762
     *
763 764
     * @return string
     */
765
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
766
    {
Steve Müller's avatar
Steve Müller committed
767
        $expression = '';
768

769 770
        switch ($pos) {
            case self::TRIM_LEADING:
Steve Müller's avatar
Steve Müller committed
771
                $expression = 'LEADING ';
772 773 774
                break;

            case self::TRIM_TRAILING:
Steve Müller's avatar
Steve Müller committed
775
                $expression = 'TRAILING ';
776 777 778
                break;

            case self::TRIM_BOTH:
Steve Müller's avatar
Steve Müller committed
779
                $expression = 'BOTH ';
780
                break;
781 782
        }

Steve Müller's avatar
Steve Müller committed
783 784 785 786 787 788 789 790 791
        if (false !== $char) {
            $expression .= $char . ' ';
        }

        if ($pos || false !== $char) {
            $expression .= 'FROM ';
        }

        return 'TRIM(' . $expression . $str . ')';
792 793 794
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
795
     * Returns the SQL snippet to trim trailing space characters from the expression.
796
     *
Benjamin Morel's avatar
Benjamin Morel committed
797
     * @param string $str Literal string or column name.
798
     *
799 800 801 802 803 804 805 806
     * @return string
     */
    public function getRtrimExpression($str)
    {
        return 'RTRIM(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
807
     * Returns the SQL snippet to trim leading space characters from the expression.
808
     *
Benjamin Morel's avatar
Benjamin Morel committed
809
     * @param string $str Literal string or column name.
810
     *
811 812 813 814 815 816 817 818
     * @return string
     */
    public function getLtrimExpression($str)
    {
        return 'LTRIM(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
819 820
     * Returns the SQL snippet to change all characters from the expression to uppercase,
     * according to the current character set mapping.
821
     *
Benjamin Morel's avatar
Benjamin Morel committed
822
     * @param string $str Literal string or column name.
823
     *
824 825 826 827 828 829 830 831
     * @return string
     */
    public function getUpperExpression($str)
    {
        return 'UPPER(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
832 833
     * Returns the SQL snippet to change all characters from the expression to lowercase,
     * according to the current character set mapping.
834
     *
Benjamin Morel's avatar
Benjamin Morel committed
835
     * @param string $str Literal string or column name.
836
     *
837 838 839 840 841 842 843 844
     * @return string
     */
    public function getLowerExpression($str)
    {
        return 'LOWER(' . $str . ')';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
845
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
846
     *
Benjamin Morel's avatar
Benjamin Morel committed
847 848 849
     * @param string          $str      Literal string.
     * @param string          $substr   Literal string to find.
     * @param integer|boolean $startPos Position to start at, beginning of string by default.
850
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
851
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
852 853
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
854
     */
855
    public function getLocateExpression($str, $substr, $startPos = false)
856
    {
857
        throw DBALException::notSupported(__METHOD__);
858 859 860
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
861
     * Returns the SQL snippet to get the current system date.
862 863 864 865 866 867 868 869 870
     *
     * @return string
     */
    public function getNowExpression()
    {
        return 'NOW()';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
871
     * Returns a SQL snippet to get a substring inside an SQL statement.
872 873 874
     *
     * Note: Not SQL92, but common functionality.
     *
Benjamin Morel's avatar
Benjamin Morel committed
875
     * SQLite only supports the 2 parameter variant of this function.
876
     *
Benjamin Morel's avatar
Benjamin Morel committed
877 878 879
     * @param string       $value  An sql string literal or column name/alias.
     * @param integer      $from   Where to start the substring portion.
     * @param integer|null $length The substring portion length.
880
     *
881
     * @return string
882
     */
883
    public function getSubstringExpression($value, $from, $length = null)
884
    {
885
        if ($length === null) {
886 887
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
        }
888 889

        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
890 891 892
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
893
     * Returns a SQL snippet to concatenate the given expressions.
894
     *
Benjamin Morel's avatar
Benjamin Morel committed
895
     * Accepts an arbitrary number of string parameters. Each parameter must contain an expression.
896
     *
897 898 899 900
     * @return string
     */
    public function getConcatExpression()
    {
901
        return join(' || ' , func_get_args());
902 903 904 905 906 907 908 909 910 911 912 913 914
    }

    /**
     * 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>
     *
915
     * @param string $expression
916
     *
Benjamin Morel's avatar
Benjamin Morel committed
917
     * @return string The logical expression.
918 919 920
     */
    public function getNotExpression($expression)
    {
921
        return 'NOT(' . $expression . ')';
922 923 924
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
925
     * Returns the SQL that checks if an expression is null.
926
     *
Benjamin Morel's avatar
Benjamin Morel committed
927
     * @param string $expression The expression that should be compared to null.
928
     *
Benjamin Morel's avatar
Benjamin Morel committed
929
     * @return string The logical expression.
930 931 932 933 934 935 936
     */
    public function getIsNullExpression($expression)
    {
        return $expression . ' IS NULL';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
937
     * Returns the SQL that checks if an expression is not null.
938
     *
Benjamin Morel's avatar
Benjamin Morel committed
939
     * @param string $expression The expression that should be compared to null.
940
     *
Benjamin Morel's avatar
Benjamin Morel committed
941
     * @return string The logical expression.
942 943 944 945 946 947 948
     */
    public function getIsNotNullExpression($expression)
    {
        return $expression . ' IS NOT NULL';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
949
     * Returns the SQL that checks if an expression evaluates to a value between two values.
950 951 952 953 954 955 956
     *
     * 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
957 958 959
     * @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.
960
     *
Benjamin Morel's avatar
Benjamin Morel committed
961
     * @return string The logical expression.
962 963 964 965 966 967
     */
    public function getBetweenExpression($expression, $value1, $value2)
    {
        return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2;
    }

Benjamin Morel's avatar
Benjamin Morel committed
968 969 970 971 972 973 974
    /**
     * Returns the SQL to get the arccosine of a value.
     *
     * @param string $value
     *
     * @return string
     */
975 976 977 978 979
    public function getAcosExpression($value)
    {
        return 'ACOS(' . $value . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
980 981 982 983 984 985 986
    /**
     * Returns the SQL to get the sine of a value.
     *
     * @param string $value
     *
     * @return string
     */
987 988 989 990 991
    public function getSinExpression($value)
    {
        return 'SIN(' . $value . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
992 993 994 995 996
    /**
     * Returns the SQL to get the PI value.
     *
     * @return string
     */
997 998 999 1000 1001
    public function getPiExpression()
    {
        return 'PI()';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1002 1003 1004 1005 1006 1007 1008
    /**
     * Returns the SQL to get the cosine of a value.
     *
     * @param string $value
     *
     * @return string
     */
1009 1010 1011 1012
    public function getCosExpression($value)
    {
        return 'COS(' . $value . ')';
    }
1013

1014
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1015
     * Returns the SQL to calculate the difference in days between the two passed dates.
1016
     *
Benjamin Morel's avatar
Benjamin Morel committed
1017
     * Computes diff = date1 - date2.
1018 1019 1020
     *
     * @param string $date1
     * @param string $date2
1021
     *
1022
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1023 1024
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1025 1026 1027 1028
     */
    public function getDateDiffExpression($date1, $date2)
    {
        throw DBALException::notSupported(__METHOD__);
1029 1030
    }

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    /**
     * Returns the SQL to add the number of given seconds to a date.
     *
     * @param string  $date
     * @param integer $seconds
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddSecondsExpression($date, $seconds)
    {
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, self::DATE_INTERVAL_UNIT_SECOND);
    }

    /**
     * Returns the SQL to subtract the number of given seconds from a date.
     *
     * @param string  $date
     * @param integer $seconds
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubSecondsExpression($date, $seconds)
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, self::DATE_INTERVAL_UNIT_SECOND);
    }

    /**
     * Returns the SQL to add the number of given minutes to a date.
     *
     * @param string  $date
     * @param integer $minutes
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddMinutesExpression($date, $minutes)
    {
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, self::DATE_INTERVAL_UNIT_MINUTE);
    }

    /**
     * Returns the SQL to subtract the number of given minutes from a date.
     *
     * @param string  $date
     * @param integer $minutes
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubMinutesExpression($date, $minutes)
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, self::DATE_INTERVAL_UNIT_MINUTE);
    }

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    /**
     * Returns the SQL to add the number of given hours to a date.
     *
     * @param string  $date
     * @param integer $hours
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddHourExpression($date, $hours)
    {
1103
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, self::DATE_INTERVAL_UNIT_HOUR);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    }

    /**
     * Returns the SQL to subtract the number of given hours to a date.
     *
     * @param string  $date
     * @param integer $hours
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubHourExpression($date, $hours)
    {
1118
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, self::DATE_INTERVAL_UNIT_HOUR);
1119 1120 1121
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1122
     * Returns the SQL to add the number of given days to a date.
1123
     *
Benjamin Morel's avatar
Benjamin Morel committed
1124
     * @param string  $date
1125 1126
     * @param integer $days
     *
1127
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1128 1129
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1130 1131 1132
     */
    public function getDateAddDaysExpression($date, $days)
    {
1133
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, self::DATE_INTERVAL_UNIT_DAY);
1134 1135 1136
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1137
     * Returns the SQL to subtract the number of given days to a date.
1138
     *
Benjamin Morel's avatar
Benjamin Morel committed
1139
     * @param string  $date
1140 1141
     * @param integer $days
     *
1142
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1143 1144
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1145 1146 1147
     */
    public function getDateSubDaysExpression($date, $days)
    {
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, self::DATE_INTERVAL_UNIT_DAY);
    }

    /**
     * Returns the SQL to add the number of given weeks to a date.
     *
     * @param string  $date
     * @param integer $weeks
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddWeeksExpression($date, $weeks)
    {
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, self::DATE_INTERVAL_UNIT_WEEK);
    }

    /**
     * Returns the SQL to subtract the number of given weeks from a date.
     *
     * @param string  $date
     * @param integer $weeks
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubWeeksExpression($date, $weeks)
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, self::DATE_INTERVAL_UNIT_WEEK);
1179 1180 1181
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1182
     * Returns the SQL to add the number of given months to a date.
1183
     *
Benjamin Morel's avatar
Benjamin Morel committed
1184
     * @param string  $date
1185 1186
     * @param integer $months
     *
1187
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1188 1189
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1190 1191 1192
     */
    public function getDateAddMonthExpression($date, $months)
    {
1193
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, self::DATE_INTERVAL_UNIT_MONTH);
1194 1195 1196
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1197
     * Returns the SQL to subtract the number of given months to a date.
1198
     *
Benjamin Morel's avatar
Benjamin Morel committed
1199
     * @param string  $date
1200 1201
     * @param integer $months
     *
1202
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1203 1204
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1205 1206
     */
    public function getDateSubMonthExpression($date, $months)
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, self::DATE_INTERVAL_UNIT_MONTH);
    }

    /**
     * Returns the SQL to add the number of given quarters to a date.
     *
     * @param string  $date
     * @param integer $quarters
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddQuartersExpression($date, $quarters)
    {
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, self::DATE_INTERVAL_UNIT_QUARTER);
    }

    /**
     * Returns the SQL to subtract the number of given quarters from a date.
     *
     * @param string  $date
     * @param integer $quarters
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubQuartersExpression($date, $quarters)
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, self::DATE_INTERVAL_UNIT_QUARTER);
    }

    /**
     * Returns the SQL to add the number of given years to a date.
     *
     * @param string  $date
     * @param integer $years
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateAddYearsExpression($date, $years)
    {
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, self::DATE_INTERVAL_UNIT_YEAR);
    }

    /**
     * Returns the SQL to subtract the number of given years from a date.
     *
     * @param string  $date
     * @param integer $years
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getDateSubYearsExpression($date, $years)
    {
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, self::DATE_INTERVAL_UNIT_YEAR);
    }

    /**
     * Returns the SQL for a date arithmetic expression.
     *
     * @param string  $date     The column or literal representing a date to perform the arithmetic operation on.
     * @param string  $operator The arithmetic operator (+ or -).
     * @param integer $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.
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
1285 1286 1287 1288
    {
        throw DBALException::notSupported(__METHOD__);
    }

1289
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1290
     * Returns the SQL bit AND comparison expression.
1291
     *
Benjamin Morel's avatar
Benjamin Morel committed
1292 1293
     * @param string $value1
     * @param string $value2
1294
     *
Benjamin Morel's avatar
Benjamin Morel committed
1295
     * @return string
1296 1297 1298 1299 1300
     */
    public function getBitAndComparisonExpression($value1, $value2)
    {
        return '(' . $value1 . ' & ' . $value2 . ')';
    }
Fabio B. Silva's avatar
Fabio B. Silva committed
1301

1302
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1303
     * Returns the SQL bit OR comparison expression.
1304
     *
Benjamin Morel's avatar
Benjamin Morel committed
1305 1306
     * @param string $value1
     * @param string $value2
1307
     *
Benjamin Morel's avatar
Benjamin Morel committed
1308
     * @return string
1309 1310 1311 1312 1313 1314
     */
    public function getBitOrComparisonExpression($value1, $value2)
    {
        return '(' . $value1 . ' | ' . $value2 . ')';
    }

Benjamin Morel's avatar
Benjamin Morel committed
1315 1316
    /**
     * Returns the FOR UPDATE expression.
1317
     *
Benjamin Morel's avatar
Benjamin Morel committed
1318 1319
     * @return string
     */
1320
    public function getForUpdateSQL()
1321 1322 1323
    {
        return 'FOR UPDATE';
    }
1324

1325 1326 1327
    /**
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
     *
1328 1329 1330
     * @param string       $fromClause The FROM clause to append the hint for the given lock mode to.
     * @param integer|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
     *                                 be appended to the FROM clause.
1331
     *
1332 1333 1334 1335 1336 1337 1338 1339
     * @return string
     */
    public function appendLockHint($fromClause, $lockMode)
    {
        return $fromClause;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1340
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1341
     *
1342
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
     * 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
1353
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1354
     *
1355
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1356 1357 1358 1359 1360 1361 1362 1363
     *
     * @return string
     */
    public function getWriteLockSQL()
    {
        return $this->getForUpdateSQL();
    }

1364
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1365
     * Returns the SQL snippet to drop an existing database.
1366
     *
Benjamin Morel's avatar
Benjamin Morel committed
1367
     * @param string $database The name of the database that should be dropped.
1368 1369 1370
     *
     * @return string
     */
1371
    public function getDropDatabaseSQL($database)
1372 1373 1374
    {
        return 'DROP DATABASE ' . $database;
    }
1375

1376
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1377
     * Returns the SQL snippet to drop an existing table.
1378
     *
Benjamin Morel's avatar
Benjamin Morel committed
1379
     * @param \Doctrine\DBAL\Schema\Table|string $table
1380
     *
1381
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1382 1383
     *
     * @throws \InvalidArgumentException
1384
     */
1385
    public function getDropTableSQL($table)
1386
    {
1387 1388
        $tableArg = $table;

1389
        if ($table instanceof Table) {
1390
            $table = $table->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
1391
        } elseif (!is_string($table)) {
1392
            throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1393 1394
        }

1395
        if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1396
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1397 1398 1399 1400 1401 1402
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);

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

1404 1405
        return 'DROP TABLE ' . $table;
    }
1406

1407
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1408
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1409
     *
Benjamin Morel's avatar
Benjamin Morel committed
1410
     * @param \Doctrine\DBAL\Schema\Table|string $table
1411
     *
1412 1413 1414 1415 1416 1417 1418
     * @return string
     */
    public function getDropTemporaryTableSQL($table)
    {
        return $this->getDropTableSQL($table);
    }

1419
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1420
     * Returns the SQL to drop an index from a table.
1421
     *
Benjamin Morel's avatar
Benjamin Morel committed
1422 1423
     * @param \Doctrine\DBAL\Schema\Index|string $index
     * @param \Doctrine\DBAL\Schema\Table|string $table
1424
     *
1425
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1426 1427
     *
     * @throws \InvalidArgumentException
1428
     */
1429
    public function getDropIndexSQL($index, $table = null)
1430
    {
1431
        if ($index instanceof Index) {
1432
            $index = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
1433
        } elseif (!is_string($index)) {
1434
            throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1435 1436 1437
        }

        return 'DROP INDEX ' . $index;
1438
    }
1439

1440
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1441
     * Returns the SQL to drop a constraint.
1442
     *
Benjamin Morel's avatar
Benjamin Morel committed
1443 1444
     * @param \Doctrine\DBAL\Schema\Constraint|string $constraint
     * @param \Doctrine\DBAL\Schema\Table|string      $table
1445
     *
1446 1447
     * @return string
     */
1448
    public function getDropConstraintSQL($constraint, $table)
1449
    {
1450
        if ($constraint instanceof Constraint) {
1451
            $constraint = $constraint->getQuotedName($this);
1452 1453
        }

1454
        if ($table instanceof Table) {
1455
            $table = $table->getQuotedName($this);
1456 1457 1458
        }

        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1459
    }
1460

1461
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1462
     * Returns the SQL to drop a foreign key.
1463
     *
Benjamin Morel's avatar
Benjamin Morel committed
1464 1465
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint|string $foreignKey
     * @param \Doctrine\DBAL\Schema\Table|string                $table
1466
     *
1467 1468
     * @return string
     */
1469
    public function getDropForeignKeySQL($foreignKey, $table)
1470
    {
1471
        if ($foreignKey instanceof ForeignKeyConstraint) {
1472
            $foreignKey = $foreignKey->getQuotedName($this);
1473 1474
        }

1475
        if ($table instanceof Table) {
1476
            $table = $table->getQuotedName($this);
1477 1478 1479
        }

        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1480
    }
1481

1482
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1483
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1484
     * on this platform.
1485
     *
Benjamin Morel's avatar
Benjamin Morel committed
1486 1487
     * @param \Doctrine\DBAL\Schema\Table   $table
     * @param integer                       $createFlags
1488
     *
1489
     * @return array The sequence of SQL statements.
Benjamin Morel's avatar
Benjamin Morel committed
1490 1491 1492
     *
     * @throws \Doctrine\DBAL\DBALException
     * @throws \InvalidArgumentException
1493
     */
1494
    public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES)
1495
    {
1496
        if ( ! is_int($createFlags)) {
1497
            throw new \InvalidArgumentException("Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.");
1498 1499
        }

1500
        if (count($table->getColumns()) === 0) {
1501 1502 1503
            throw DBALException::noColumnsSpecifiedForTable($table->getName());
        }

1504
        $tableName = $table->getQuotedName($this);
1505 1506 1507 1508 1509
        $options = $table->getOptions();
        $options['uniqueConstraints'] = array();
        $options['indexes'] = array();
        $options['primary'] = array();

1510
        if (($createFlags&self::CREATE_INDEXES) > 0) {
1511
            foreach ($table->getIndexes() as $index) {
1512 1513
                /* @var $index Index */
                if ($index->isPrimary()) {
Steve Müller's avatar
Steve Müller committed
1514
                    $options['primary']       = $index->getQuotedColumns($this);
1515
                    $options['primary_index'] = $index;
1516 1517 1518
                } else {
                    $options['indexes'][$index->getName()] = $index;
                }
1519 1520
            }
        }
1521

1522
        $columnSql = array();
1523
        $columns = array();
1524

1525
        foreach ($table->getColumns() as $column) {
1526
            /* @var \Doctrine\DBAL\Schema\Column $column */
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538

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

1539
            $columnData = $column->toArray();
1540
            $columnData['name'] = $column->getQuotedName($this);
1541
            $columnData['version'] = $column->hasPlatformOption("version") ? $column->getPlatformOption('version') : false;
1542
            $columnData['comment'] = $this->getColumnComment($column);
1543 1544

            if (strtolower($columnData['type']) == "string" && $columnData['length'] === null) {
1545 1546
                $columnData['length'] = 255;
            }
1547 1548

            if (in_array($column->getName(), $options['primary'])) {
1549 1550 1551 1552 1553 1554
                $columnData['primary'] = true;
            }

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

1555 1556
        if (($createFlags&self::CREATE_FOREIGNKEYS) > 0) {
            $options['foreignKeys'] = array();
1557
            foreach ($table->getForeignKeys() as $fkConstraint) {
1558 1559 1560 1561
                $options['foreignKeys'][] = $fkConstraint;
            }
        }

1562 1563 1564
        if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1565

Jan Sorgalla's avatar
Jan Sorgalla committed
1566 1567 1568
            if ($eventArgs->isDefaultPrevented()) {
                return array_merge($eventArgs->getSql(), $columnSql);
            }
1569
        }
1570

1571 1572
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
        if ($this->supportsCommentOnStatement()) {
1573
            foreach ($table->getColumns() as $column) {
1574
                if ($this->getColumnComment($column)) {
1575
                    $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $this->getColumnComment($column));
1576 1577 1578
                }
            }
        }
1579

Jan Sorgalla's avatar
Jan Sorgalla committed
1580
        return array_merge($sql, $columnSql);
1581 1582
    }

Benjamin Morel's avatar
Benjamin Morel committed
1583 1584 1585 1586 1587 1588 1589
    /**
     * @param string $tableName
     * @param string $columnName
     * @param string $comment
     *
     * @return string
     */
1590 1591
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
    {
1592
        return "COMMENT ON COLUMN " . $tableName . "." . $columnName . " IS '" . $comment . "'";
1593 1594 1595
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1596
     * Returns the SQL used to create a table.
1597
     *
1598
     * @param string $tableName
Benjamin Morel's avatar
Benjamin Morel committed
1599 1600
     * @param array  $columns
     * @param array  $options
1601
     *
1602 1603
     * @return array
     */
1604
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
1605
    {
1606
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1607

1608
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1609
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1610
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1611 1612
            }
        }
1613

1614
        if (isset($options['primary']) && ! empty($options['primary'])) {
1615
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1616 1617 1618
        }

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Steve Müller's avatar
Steve Müller committed
1619
            foreach ($options['indexes'] as $index => $definition) {
1620
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1621 1622 1623
            }
        }

1624
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1625

1626
        $check = $this->getCheckDeclarationSQL($columns);
1627 1628
        if ( ! empty($check)) {
            $query .= ', ' . $check;
1629
        }
1630 1631 1632 1633 1634
        $query .= ')';

        $sql[] = $query;

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

1640 1641
        return $sql;
    }
1642

Benjamin Morel's avatar
Benjamin Morel committed
1643 1644 1645
    /**
     * @return string
     */
1646
    public function getCreateTemporaryTableSnippetSQL()
1647 1648 1649
    {
        return "CREATE TEMPORARY TABLE";
    }
1650

1651
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1652
     * Returns the SQL to create a sequence on this platform.
1653
     *
1654
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
1655 1656 1657
     *
     * @return string
     *
Benjamin Morel's avatar
Benjamin Morel committed
1658
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1659
     */
1660
    public function getCreateSequenceSQL(Sequence $sequence)
1661
    {
1662
        throw DBALException::notSupported(__METHOD__);
1663
    }
1664

1665
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1666
     * Returns the SQL to change a sequence on this platform.
1667 1668
     *
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
1669
     *
1670
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1671 1672
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1673
     */
1674
    public function getAlterSequenceSQL(Sequence $sequence)
1675 1676 1677
    {
        throw DBALException::notSupported(__METHOD__);
    }
1678

1679
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1680
     * Returns the SQL to create a constraint on a table on this platform.
1681
     *
Benjamin Morel's avatar
Benjamin Morel committed
1682 1683
     * @param \Doctrine\DBAL\Schema\Constraint   $constraint
     * @param \Doctrine\DBAL\Schema\Table|string $table
1684
     *
1685
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1686 1687
     *
     * @throws \InvalidArgumentException
1688
     */
1689
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1690
    {
1691
        if ($table instanceof Table) {
1692
            $table = $table->getQuotedName($this);
1693 1694
        }

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

1697
        $columnList = '('. implode(', ', $constraint->getQuotedColumns($this)) . ')';
1698 1699

        $referencesClause = '';
1700
        if ($constraint instanceof Index) {
Steve Müller's avatar
Steve Müller committed
1701
            if ($constraint->isPrimary()) {
1702 1703 1704 1705 1706
                $query .= ' PRIMARY KEY';
            } elseif ($constraint->isUnique()) {
                $query .= ' UNIQUE';
            } else {
                throw new \InvalidArgumentException(
1707
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1708 1709
                );
            }
Steve Müller's avatar
Steve Müller committed
1710
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1711 1712
            $query .= ' FOREIGN KEY';

1713
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1714
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1715 1716
        }
        $query .= ' '.$columnList.$referencesClause;
1717 1718 1719

        return $query;
    }
1720

1721
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1722
     * Returns the SQL to create an index on a table on this platform.
1723
     *
Benjamin Morel's avatar
Benjamin Morel committed
1724 1725
     * @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.
1726
     *
1727
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
1728 1729
     *
     * @throws \InvalidArgumentException
1730
     */
1731
    public function getCreateIndexSQL(Index $index, $table)
1732
    {
1733
        if ($table instanceof Table) {
1734
            $table = $table->getQuotedName($this);
1735
        }
1736
        $name = $index->getQuotedName($this);
1737
        $columns = $index->getQuotedColumns($this);
1738 1739 1740

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

1743 1744
        if ($index->isPrimary()) {
            return $this->getCreatePrimaryKeySQL($index, $table);
1745 1746
        }

1747
        $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1748
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')' . $this->getPartialIndexSQL($index);
1749

1750 1751
        return $query;
    }
1752

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    /**
     * Adds condition for partial index.
     *
     * @param \Doctrine\DBAL\Schema\Index $index
     *
     * @return string
     */
    protected function getPartialIndexSQL(Index $index)
    {
        $where = $index->getWhere();

        return $this->supportsPartialIndexes() && $where ? ' WHERE ' . $where : '';
    }

1767
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1768
     * Adds additional flags for index generation.
1769
     *
Benjamin Morel's avatar
Benjamin Morel committed
1770
     * @param \Doctrine\DBAL\Schema\Index $index
1771
     *
1772 1773 1774 1775
     * @return string
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
1776
        return $index->isUnique() ? 'UNIQUE ' : '';
1777 1778
    }

1779
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1780
     * Returns the SQL to create an unnamed primary key constraint.
1781
     *
Benjamin Morel's avatar
Benjamin Morel committed
1782 1783
     * @param \Doctrine\DBAL\Schema\Index        $index
     * @param \Doctrine\DBAL\Schema\Table|string $table
1784
     *
1785 1786 1787 1788
     * @return string
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
1789
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')';
1790
    }
1791

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
    /**
     * 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__);
    }

    /**
     * Checks whether the schema $schemaName needs creating.
     *
     * @param string $schemaName
     *
     * @return boolean
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function schemaNeedsCreation($schemaName)
    {
        throw DBALException::notSupported(__METHOD__);
    }

1818
    /**
1819
     * Quotes a string so that it can be safely used as a table or column name,
1820
     * even if it is a reserved word of the platform. This also detects identifier
1821
     * chains separated by dot and quotes them independently.
1822
     *
1823
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
Benjamin Morel's avatar
Benjamin Morel committed
1824
     * you SHOULD use them. In general, they end up causing way more
1825 1826
     * problems than they solve.
     *
Benjamin Morel's avatar
Benjamin Morel committed
1827
     * @param string $str The identifier name to be quoted.
1828
     *
Benjamin Morel's avatar
Benjamin Morel committed
1829
     * @return string The quoted identifier string.
1830 1831
     */
    public function quoteIdentifier($str)
1832 1833 1834
    {
        if (strpos($str, ".") !== false) {
            $parts = array_map(array($this, "quoteIdentifier"), explode(".", $str));
1835

1836 1837 1838 1839 1840 1841 1842
            return implode(".", $parts);
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1843
     * Quotes a single identifier (no dot chain separation).
1844
     *
Benjamin Morel's avatar
Benjamin Morel committed
1845
     * @param string $str The identifier name to be quoted.
1846
     *
Benjamin Morel's avatar
Benjamin Morel committed
1847
     * @return string The quoted identifier string.
1848 1849
     */
    public function quoteSingleIdentifier($str)
1850 1851 1852
    {
        $c = $this->getIdentifierQuoteCharacter();

1853
        return $c . str_replace($c, $c.$c, $str) . $c;
1854
    }
1855

1856
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1857
     * Returns the SQL to create a new foreign key.
1858
     *
Benjamin Morel's avatar
Benjamin Morel committed
1859 1860
     * @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.
1861
     *
1862 1863
     * @return string
     */
1864
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
1865
    {
1866
        if ($table instanceof Table) {
1867
            $table = $table->getQuotedName($this);
1868 1869
        }

1870
        $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1871 1872 1873

        return $query;
    }
1874

1875
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1876
     * Gets the SQL statements for altering an existing table.
1877
     *
Benjamin Morel's avatar
Benjamin Morel committed
1878
     * This method returns an array of SQL statements, since some platforms need several statements.
1879
     *
Benjamin Morel's avatar
Benjamin Morel committed
1880
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
1881
     *
1882
     * @return array
Benjamin Morel's avatar
Benjamin Morel committed
1883 1884
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
1885
     */
1886
    public function getAlterTableSQL(TableDiff $diff)
1887
    {
1888
        throw DBALException::notSupported(__METHOD__);
1889
    }
1890

1891
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1892 1893 1894
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
1895
     *
1896
     * @return boolean
1897 1898 1899 1900 1901 1902 1903
     */
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1904
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
            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
1917 1918 1919
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
1920
     *
1921
     * @return boolean
1922 1923 1924 1925 1926 1927 1928
     */
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1929
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
            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
1942 1943 1944
     * @param \Doctrine\DBAL\Schema\ColumnDiff $columnDiff
     * @param \Doctrine\DBAL\Schema\TableDiff  $diff
     * @param array                            $columnSql
1945
     *
1946
     * @return boolean
1947 1948 1949 1950 1951 1952 1953
     */
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1954
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
            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
1967 1968 1969 1970
     * @param string                          $oldColumnName
     * @param \Doctrine\DBAL\Schema\Column    $column
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $columnSql
1971
     *
1972
     * @return boolean
1973 1974 1975 1976 1977 1978 1979
     */
    protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

1980
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
            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
1991

1992
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1993 1994
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     * @param array                           $sql
1995
     *
1996
     * @return boolean
1997 1998 1999 2000 2001 2002 2003
     */
    protected function onSchemaAlterTable(TableDiff $diff, &$sql)
    {
        if (null === $this->_eventManager) {
            return false;
        }

2004
        if ( ! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
            return false;
        }

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

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

        return $eventArgs->isDefaultPrevented();
    }
2015

Benjamin Morel's avatar
Benjamin Morel committed
2016 2017 2018 2019 2020
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
2021 2022
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
2023
        $tableName = $diff->getName()->getQuotedName($this);
2024

2025 2026
        $sql = array();
        if ($this->supportsForeignKeyConstraints()) {
2027
            foreach ($diff->removedForeignKeys as $foreignKey) {
2028 2029
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
            }
2030
            foreach ($diff->changedForeignKeys as $foreignKey) {
2031 2032 2033 2034
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
            }
        }

2035
        foreach ($diff->removedIndexes as $index) {
2036 2037
            $sql[] = $this->getDropIndexSQL($index, $tableName);
        }
2038
        foreach ($diff->changedIndexes as $index) {
2039 2040 2041 2042 2043
            $sql[] = $this->getDropIndexSQL($index, $tableName);
        }

        return $sql;
    }
2044

Benjamin Morel's avatar
Benjamin Morel committed
2045 2046 2047 2048 2049
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
2050
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
2051
    {
2052 2053 2054
        $tableName = (false !== $diff->newName)
            ? $diff->getNewName()->getQuotedName($this)
            : $diff->getName()->getQuotedName($this);
2055

2056
        $sql = array();
2057

2058
        if ($this->supportsForeignKeyConstraints()) {
2059
            foreach ($diff->addedForeignKeys as $foreignKey) {
2060
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2061
            }
2062

2063
            foreach ($diff->changedForeignKeys as $foreignKey) {
2064
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2065 2066 2067
            }
        }

2068
        foreach ($diff->addedIndexes as $index) {
2069
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2070
        }
2071

2072
        foreach ($diff->changedIndexes as $index) {
2073
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2074 2075
        }

2076 2077 2078 2079 2080 2081 2082 2083
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
            $oldIndexName = new Identifier($oldIndexName);
            $sql          = array_merge(
                $sql,
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
            );
        }

2084 2085
        return $sql;
    }
2086

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    /**
     * 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)
    {
        return array(
            $this->getDropIndexSQL($oldIndexName, $tableName),
            $this->getCreateIndexSQL($index, $tableName)
        );
    }

2104 2105 2106
    /**
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2107
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
2108
     *
2109 2110 2111 2112 2113 2114
     * @return array
     */
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
    }
2115

2116
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2117
     * Gets declaration of a number of fields in bulk.
2118
     *
Benjamin Morel's avatar
Benjamin Morel committed
2119 2120 2121 2122 2123
     * @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:
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
     *
     *      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
     */
2145
    public function getColumnDeclarationListSQL(array $fields)
2146
    {
2147
        $queryFields = array();
2148

2149
        foreach ($fields as $fieldName => $field) {
2150
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
2151
        }
2152

2153 2154 2155 2156
        return implode(', ', $queryFields);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2157
     * Obtains DBMS specific SQL code portion needed to declare a generic type
2158 2159
     * field to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2160 2161 2162 2163
     * @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:
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
     *
     *      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
2184 2185
     *      columnDefinition
     *          a string that defines the complete column
2186
     *
Benjamin Morel's avatar
Benjamin Morel committed
2187
     * @return string DBMS specific SQL code portion that should be used to declare the column.
2188
     */
2189
    public function getColumnDeclarationSQL($name, array $field)
2190
    {
2191
        if (isset($field['columnDefinition'])) {
2192
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
2193
        } else {
2194
            $default = $this->getDefaultValueDeclarationSQL($field);
2195

2196
            $charset = (isset($field['charset']) && $field['charset']) ?
2197
                    ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
2198

2199
            $collation = (isset($field['collation']) && $field['collation']) ?
2200
                    ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
2201

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

2204
            $unique = (isset($field['unique']) && $field['unique']) ?
2205
                    ' ' . $this->getUniqueFieldDeclarationSQL() : '';
2206

2207 2208
            $check = (isset($field['check']) && $field['check']) ?
                    ' ' . $field['check'] : '';
2209

2210 2211 2212
            $typeDecl = $field['type']->getSqlDeclaration($field, $this);
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
        }
2213

2214 2215 2216 2217
        if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment']) {
            $columnDef .= " COMMENT '" . $field['comment'] . "'";
        }

2218
        return $name . ' ' . $columnDef;
2219
    }
2220

2221
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2222
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
2223 2224
     *
     * @param array $columnDef
2225
     *
2226 2227
     * @return string
     */
2228
    public function getDecimalTypeDeclarationSQL(array $columnDef)
2229 2230
    {
        $columnDef['precision'] = ( ! isset($columnDef['precision']) || empty($columnDef['precision']))
2231
            ? 10 : $columnDef['precision'];
2232 2233
        $columnDef['scale'] = ( ! isset($columnDef['scale']) || empty($columnDef['scale']))
            ? 0 : $columnDef['scale'];
2234

2235 2236
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
    }
2237 2238

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2239
     * Obtains DBMS specific SQL code portion needed to set a default value
2240 2241
     * declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2242
     * @param array $field The field definition array.
2243
     *
Benjamin Morel's avatar
Benjamin Morel committed
2244
     * @return string DBMS specific SQL code portion needed to set a default value.
2245
     */
2246
    public function getDefaultValueDeclarationSQL($field)
2247
    {
2248
        $default = empty($field['notnull']) ? ' DEFAULT NULL' : '';
2249

2250
        if (isset($field['default'])) {
2251 2252 2253 2254
            $default = " DEFAULT '".$field['default']."'";
            if (isset($field['type'])) {
                if (in_array((string)$field['type'], array("Integer", "BigInteger", "SmallInteger"))) {
                    $default = " DEFAULT ".$field['default'];
Steve Müller's avatar
Steve Müller committed
2255
                } elseif ((string)$field['type'] == 'DateTime' && $field['default'] == $this->getCurrentTimestampSQL()) {
2256
                    $default = " DEFAULT ".$this->getCurrentTimestampSQL();
Steve Müller's avatar
Steve Müller committed
2257
                } elseif ((string)$field['type'] == 'Time' && $field['default'] == $this->getCurrentTimeSQL()) {
2258
                    $default = " DEFAULT ".$this->getCurrentTimeSQL();
Steve Müller's avatar
Steve Müller committed
2259
                } elseif ((string)$field['type'] == 'Date' && $field['default'] == $this->getCurrentDateSQL()) {
2260
                    $default = " DEFAULT ".$this->getCurrentDateSQL();
Steve Müller's avatar
Steve Müller committed
2261
                } elseif ((string) $field['type'] == 'Boolean') {
2262
                    $default = " DEFAULT '" . $this->convertBooleans($field['default']) . "'";
2263 2264
                }
            }
2265
        }
Benjamin Morel's avatar
Benjamin Morel committed
2266

2267 2268 2269 2270
        return $default;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2271
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2272 2273
     * declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2274
     * @param array $definition The check definition.
2275
     *
Benjamin Morel's avatar
Benjamin Morel committed
2276
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2277
     */
2278
    public function getCheckDeclarationSQL(array $definition)
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    {
        $constraints = array();
        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);
    }
2297

2298
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2299
     * Obtains DBMS specific SQL code portion needed to set a unique
2300 2301
     * constraint declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2302 2303
     * @param string                       $name  The name of the unique constraint.
     * @param \Doctrine\DBAL\Schema\Index  $index The index definition.
2304
     *
Benjamin Morel's avatar
Benjamin Morel committed
2305 2306 2307
     * @return string DBMS specific SQL code portion needed to set a constraint.
     *
     * @throws \InvalidArgumentException
2308
     */
2309
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
2310
    {
2311 2312 2313
        $columns = $index->getQuotedColumns($this);

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

2317
        return 'CONSTRAINT ' . $name . ' UNIQUE ('
2318
             . $this->getIndexFieldDeclarationListSQL($columns)
2319
             . ')' . $this->getPartialIndexSQL($index);
2320
    }
2321 2322

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2323
     * Obtains DBMS specific SQL code portion needed to set an index
2324 2325
     * declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2326 2327 2328 2329
     * @param string                       $name  The name of the index.
     * @param \Doctrine\DBAL\Schema\Index  $index The index definition.
     *
     * @return string DBMS specific SQL code portion needed to set an index.
2330
     *
Benjamin Morel's avatar
Benjamin Morel committed
2331
     * @throws \InvalidArgumentException
2332
     */
2333
    public function getIndexDeclarationSQL($name, Index $index)
2334
    {
2335 2336 2337
        $columns = $index->getQuotedColumns($this);

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

2341
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ('
2342 2343
                . $this->getIndexFieldDeclarationListSQL($columns)
                . ')' . $this->getPartialIndexSQL($index);
2344 2345
    }

2346
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2347
     * Obtains SQL code portion needed to create a custom column,
2348 2349 2350
     * e.g. when a field has the "columnDefinition" keyword.
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
     *
2351
     * @param array $columnDef
2352
     *
2353 2354
     * @return string
     */
2355
    public function getCustomTypeDeclarationSQL(array $columnDef)
2356 2357 2358 2359
    {
        return $columnDef['columnDefinition'];
    }

2360
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2361
     * Obtains DBMS specific SQL code portion needed to set an index
2362 2363
     * declaration to be used in statements like CREATE TABLE.
     *
2364
     * @param array $fields
2365
     *
2366 2367
     * @return string
     */
2368
    public function getIndexFieldDeclarationListSQL(array $fields)
2369 2370
    {
        $ret = array();
2371

2372 2373
        foreach ($fields as $field => $definition) {
            if (is_array($definition)) {
2374
                $ret[] = $field;
2375
            } else {
2376
                $ret[] = $definition;
2377 2378
            }
        }
2379

2380 2381 2382 2383
        return implode(', ', $ret);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2384
     * Returns the required SQL string that fits between CREATE ... TABLE
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
     * 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.
     */
2397
    public function getTemporaryTableSQL()
2398 2399 2400
    {
        return 'TEMPORARY';
    }
2401

2402 2403 2404
    /**
     * Some vendors require temporary table names to be qualified specially.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2405
     * @param string $tableName
2406
     *
2407 2408 2409 2410 2411 2412 2413
     * @return string
     */
    public function getTemporaryTableName($tableName)
    {
        return $tableName;
    }

2414 2415 2416 2417
    /**
     * 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
2418
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey
2419
     *
Benjamin Morel's avatar
Benjamin Morel committed
2420 2421
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
     *                of a field declaration.
2422
     */
2423
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
2424
    {
2425 2426
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2427 2428 2429 2430 2431

        return $sql;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2432
     * Returns the FOREIGN KEY query section dealing with non-standard options
2433 2434
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
     *
Benjamin Morel's avatar
Benjamin Morel committed
2435
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The foreign key definition.
2436
     *
2437 2438
     * @return string
     */
2439
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
2440 2441
    {
        $query = '';
2442
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2443
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2444
        }
2445
        if ($foreignKey->hasOption('onDelete')) {
2446
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2447
        }
Benjamin Morel's avatar
Benjamin Morel committed
2448

2449 2450 2451 2452
        return $query;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2453
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2454
     *
Benjamin Morel's avatar
Benjamin Morel committed
2455
     * @param string $action The foreign key referential action.
2456
     *
2457
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2458 2459
     *
     * @throws \InvalidArgumentException if unknown referential action given
2460
     */
2461
    public function getForeignKeyReferentialActionSQL($action)
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
    {
        $upper = strtoupper($action);
        switch ($upper) {
            case 'CASCADE':
            case 'SET NULL':
            case 'NO ACTION':
            case 'RESTRICT':
            case 'SET DEFAULT':
                return $upper;
            default:
2472
                throw new \InvalidArgumentException('Invalid foreign key action: ' . $upper);
2473 2474 2475 2476
        }
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2477
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2478 2479
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2480
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey
2481
     *
2482
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2483 2484
     *
     * @throws \InvalidArgumentException
2485
     */
2486
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
2487 2488
    {
        $sql = '';
2489
        if (strlen($foreignKey->getName())) {
2490
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2491 2492 2493
        }
        $sql .= 'FOREIGN KEY (';

2494
        if (count($foreignKey->getLocalColumns()) === 0) {
2495
            throw new \InvalidArgumentException("Incomplete definition. 'local' required.");
2496
        }
2497
        if (count($foreignKey->getForeignColumns()) === 0) {
2498
            throw new \InvalidArgumentException("Incomplete definition. 'foreign' required.");
2499
        }
2500
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2501
            throw new \InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
2502 2503
        }

2504
        $sql .= implode(', ', $foreignKey->getQuotedLocalColumns($this))
2505
              . ') REFERENCES '
2506
              . $foreignKey->getQuotedForeignTableName($this) . ' ('
2507
              . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2508 2509 2510 2511 2512

        return $sql;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2513
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2514 2515
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2516 2517
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
     *                of a field declaration.
2518
     */
2519
    public function getUniqueFieldDeclarationSQL()
2520 2521 2522 2523 2524
    {
        return 'UNIQUE';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2525
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2526 2527
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2528
     * @param string $charset The name of the charset.
2529
     *
Benjamin Morel's avatar
Benjamin Morel committed
2530 2531
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
     *                of a field declaration.
2532
     */
2533
    public function getColumnCharsetDeclarationSQL($charset)
2534 2535 2536 2537 2538
    {
        return '';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2539
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2540 2541
     * of a field declaration to be used in statements like CREATE TABLE.
     *
Benjamin Morel's avatar
Benjamin Morel committed
2542
     * @param string $collation The name of the collation.
2543
     *
Benjamin Morel's avatar
Benjamin Morel committed
2544 2545
     * @return string DBMS specific SQL code portion needed to set the COLLATION
     *                of a field declaration.
2546
     */
2547
    public function getColumnCollationDeclarationSQL($collation)
2548
    {
2549
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2550
    }
2551

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
    /**
     * Whether the platform prefers sequences for ID generation.
     * Subclasses should override this method to return TRUE if they prefer sequences.
     *
     * @return boolean
     */
    public function prefersSequences()
    {
        return false;
    }
2562

2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
    /**
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
     * Subclasses should override this method to return TRUE if they prefer identity columns.
     *
     * @return boolean
     */
    public function prefersIdentityColumns()
    {
        return false;
    }
2573

2574 2575
    /**
     * Some platforms need the boolean values to be converted.
2576
     *
romanb's avatar
romanb committed
2577
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2578
     *
2579 2580
     * Note: if the input is not a boolean the original input might be returned.
     *
2581 2582
     * There are two contexts when converting booleans: Literals and Prepared Statements.
     * This method should handle the literal case
2583
     *
2584 2585
     * @param mixed $item A boolean or an array of them.
     * @return mixed A boolean database value or an array of them.
2586
     */
2587
    public function convertBooleans($item)
2588 2589 2590 2591 2592 2593 2594
    {
        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
2595
        } elseif (is_bool($item)) {
romanb's avatar
romanb committed
2596
            $item = (int) $item;
2597
        }
2598

2599 2600
        return $item;
    }
2601 2602
    
    /**
2603
     * Some platforms have boolean literals that needs to be correctly converted
2604 2605 2606 2607 2608
     *
     * The default conversion tries to convert value into bool "(bool)$item"
     *
     * @param mixed $item
     *
2609
     * @return bool|null
2610 2611 2612
     */
    public function convertFromBoolean($item)
    {
2613
        return null === $item ? null: (bool) $item ;
2614
    }
2615

2616 2617 2618 2619
    /**
     * This method should handle the prepared statements case. When there is no
     * distinction, it's OK to use the same method.
     *
2620 2621 2622 2623
     * Note: if the input is not a boolean the original input might be returned.
     *
     * @param mixed $item A boolean or an array of them.
     * @return mixed A boolean database value or an array of them.
2624
     */
2625
    public function convertBooleansToDatabaseValue($item)
2626
    {
2627
        return $this->convertBooleans($item);
2628 2629
    }

2630
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2631
     * Returns the SQL specific for the platform to get the current date.
2632 2633 2634
     *
     * @return string
     */
2635
    public function getCurrentDateSQL()
2636 2637 2638 2639 2640
    {
        return 'CURRENT_DATE';
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2641
     * Returns the SQL specific for the platform to get the current time.
2642 2643 2644
     *
     * @return string
     */
2645
    public function getCurrentTimeSQL()
2646 2647 2648 2649
    {
        return 'CURRENT_TIME';
    }

2650
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2651
     * Returns the SQL specific for the platform to get the current timestamp
2652 2653 2654
     *
     * @return string
     */
2655
    public function getCurrentTimestampSQL()
2656 2657 2658
    {
        return 'CURRENT_TIMESTAMP';
    }
2659

romanb's avatar
romanb committed
2660
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2661
     * Returns the SQL for a given transaction isolation level Connection constant.
romanb's avatar
romanb committed
2662
     *
2663
     * @param integer $level
2664
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2665
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2666 2667
     *
     * @throws \InvalidArgumentException
romanb's avatar
romanb committed
2668
     */
2669
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
2670 2671
    {
        switch ($level) {
2672
            case Connection::TRANSACTION_READ_UNCOMMITTED:
romanb's avatar
romanb committed
2673
                return 'READ UNCOMMITTED';
2674
            case Connection::TRANSACTION_READ_COMMITTED:
romanb's avatar
romanb committed
2675
                return 'READ COMMITTED';
2676
            case Connection::TRANSACTION_REPEATABLE_READ:
romanb's avatar
romanb committed
2677
                return 'REPEATABLE READ';
2678
            case Connection::TRANSACTION_SERIALIZABLE:
romanb's avatar
romanb committed
2679 2680
                return 'SERIALIZABLE';
            default:
2681
                throw new \InvalidArgumentException('Invalid isolation level:' . $level);
2682 2683 2684
        }
    }

Benjamin Morel's avatar
Benjamin Morel committed
2685 2686 2687 2688 2689
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2690
    public function getListDatabasesSQL()
2691
    {
2692
        throw DBALException::notSupported(__METHOD__);
2693 2694
    }

Benjamin Morel's avatar
Benjamin Morel committed
2695 2696 2697 2698 2699 2700 2701
    /**
     * @param string $database
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2702
    public function getListSequencesSQL($database)
2703
    {
2704
        throw DBALException::notSupported(__METHOD__);
2705 2706
    }

Benjamin Morel's avatar
Benjamin Morel committed
2707 2708 2709 2710 2711 2712 2713
    /**
     * @param string $table
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2714
    public function getListTableConstraintsSQL($table)
2715
    {
2716
        throw DBALException::notSupported(__METHOD__);
2717 2718
    }

Benjamin Morel's avatar
Benjamin Morel committed
2719 2720 2721 2722 2723 2724 2725 2726
    /**
     * @param string      $table
     * @param string|null $database
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2727
    public function getListTableColumnsSQL($table, $database = null)
2728
    {
2729
        throw DBALException::notSupported(__METHOD__);
2730 2731
    }

Benjamin Morel's avatar
Benjamin Morel committed
2732 2733 2734 2735 2736
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2737
    public function getListTablesSQL()
2738
    {
2739
        throw DBALException::notSupported(__METHOD__);
2740 2741
    }

Benjamin Morel's avatar
Benjamin Morel committed
2742 2743 2744 2745 2746
    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2747
    public function getListUsersSQL()
2748
    {
2749
        throw DBALException::notSupported(__METHOD__);
2750 2751
    }

2752
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2753
     * Returns the SQL to list all views of a database or user.
2754 2755
     *
     * @param string $database
2756
     *
2757
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2758 2759
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2760
     */
2761
    public function getListViewsSQL($database)
2762
    {
2763
        throw DBALException::notSupported(__METHOD__);
2764 2765
    }

2766
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2767
     * Returns the list of indexes for the current database.
2768
     *
2769 2770
     * 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.
2771
     *
2772 2773 2774
     * Attention: Some platforms only support currentDatabase when they
     * are connected with that database. Cross-database information schema
     * requests may be impossible.
2775
     *
2776
     * @param string $table
2777
     * @param string $currentDatabase
2778
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2779
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2780 2781
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2782 2783
     */
    public function getListTableIndexesSQL($table, $currentDatabase = null)
2784
    {
2785
        throw DBALException::notSupported(__METHOD__);
2786 2787
    }

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

Benjamin Morel's avatar
Benjamin Morel committed
2800 2801 2802 2803 2804 2805 2806 2807
    /**
     * @param string $name
     * @param string $sql
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2808
    public function getCreateViewSQL($name, $sql)
2809
    {
2810
        throw DBALException::notSupported(__METHOD__);
2811 2812
    }

Benjamin Morel's avatar
Benjamin Morel committed
2813 2814 2815 2816 2817 2818 2819
    /**
     * @param string $name
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2820
    public function getDropViewSQL($name)
2821
    {
2822
        throw DBALException::notSupported(__METHOD__);
2823 2824
    }

2825
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2826
     * Returns the SQL snippet to drop an existing sequence.
2827
     *
jeroendedauw's avatar
jeroendedauw committed
2828
     * @param Sequence|string $sequence
2829 2830
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2831 2832
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2833
     */
2834
    public function getDropSequenceSQL($sequence)
2835
    {
2836
        throw DBALException::notSupported(__METHOD__);
2837 2838
    }

Benjamin Morel's avatar
Benjamin Morel committed
2839 2840 2841 2842 2843 2844 2845
    /**
     * @param string $sequenceName
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
2846
    public function getSequenceNextValSQL($sequenceName)
2847
    {
2848
        throw DBALException::notSupported(__METHOD__);
romanb's avatar
romanb committed
2849
    }
2850

2851
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2852
     * Returns the SQL to create a new database.
2853
     *
Benjamin Morel's avatar
Benjamin Morel committed
2854
     * @param string $database The name of the database that should be created.
2855 2856
     *
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2857 2858
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2859
     */
2860
    public function getCreateDatabaseSQL($database)
2861
    {
2862
        throw DBALException::notSupported(__METHOD__);
2863 2864
    }

romanb's avatar
romanb committed
2865
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2866
     * Returns the SQL to set the transaction isolation level.
romanb's avatar
romanb committed
2867
     *
2868
     * @param integer $level
2869
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2870
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2871 2872
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
romanb's avatar
romanb committed
2873
     */
2874
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
2875
    {
2876
        throw DBALException::notSupported(__METHOD__);
romanb's avatar
romanb committed
2877
    }
2878

2879
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2880 2881
     * Obtains DBMS specific SQL to be used to create datetime fields in
     * statements like CREATE TABLE.
2882
     *
2883
     * @param array $fieldDeclaration
2884
     *
2885
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2886 2887
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2888
     */
2889
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
2890
    {
2891
        throw DBALException::notSupported(__METHOD__);
2892
    }
2893 2894

    /**
Benjamin Morel's avatar
Benjamin Morel committed
2895
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
2896
     *
2897
     * @param array $fieldDeclaration
2898
     *
Christophe Coevoet's avatar
Christophe Coevoet committed
2899
     * @return string
2900 2901 2902
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
    {
2903
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
2904
    }
2905 2906


2907
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2908
     * Obtains DBMS specific SQL to be used to create date fields in statements
2909
     * like CREATE TABLE.
2910
     *
2911
     * @param array $fieldDeclaration
2912
     *
2913
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2914 2915
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2916
     */
2917
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
2918
    {
2919
        throw DBALException::notSupported(__METHOD__);
2920
    }
2921

2922
    /**
Benjamin Morel's avatar
Benjamin Morel committed
2923
     * Obtains DBMS specific SQL to be used to create time fields in statements
2924 2925 2926
     * like CREATE TABLE.
     *
     * @param array $fieldDeclaration
2927
     *
2928
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
2929 2930
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
2931
     */
2932
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
2933
    {
2934
        throw DBALException::notSupported(__METHOD__);
2935 2936
    }

Benjamin Morel's avatar
Benjamin Morel committed
2937 2938 2939 2940 2941
    /**
     * @param array $fieldDeclaration
     *
     * @return string
     */
2942 2943 2944 2945 2946
    public function getFloatDeclarationSQL(array $fieldDeclaration)
    {
        return 'DOUBLE PRECISION';
    }

romanb's avatar
romanb committed
2947 2948 2949 2950
    /**
     * Gets the default transaction isolation level of the platform.
     *
     * @return integer The default isolation level.
2951
     *
2952
     * @see Doctrine\DBAL\Connection\TRANSACTION_* constants.
romanb's avatar
romanb committed
2953 2954 2955
     */
    public function getDefaultTransactionIsolationLevel()
    {
2956
        return Connection::TRANSACTION_READ_COMMITTED;
romanb's avatar
romanb committed
2957
    }
2958

2959
    /* supports*() methods */
2960 2961 2962 2963 2964 2965

    /**
     * Whether the platform supports sequences.
     *
     * @return boolean
     */
2966 2967 2968 2969
    public function supportsSequences()
    {
        return false;
    }
2970 2971 2972

    /**
     * Whether the platform supports identity columns.
Benjamin Morel's avatar
Benjamin Morel committed
2973
     *
Pascal Borreli's avatar
Pascal Borreli committed
2974
     * Identity columns are columns that receive an auto-generated value from the
2975 2976 2977 2978
     * database on insert of a row.
     *
     * @return boolean
     */
2979 2980 2981 2982
    public function supportsIdentityColumns()
    {
        return false;
    }
2983

2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
    /**
     * 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.
     *
     * @return boolean
     */
    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__);
    }

3015 3016 3017 3018 3019
    /**
     * Whether the platform supports indexes.
     *
     * @return boolean
     */
3020 3021 3022 3023
    public function supportsIndexes()
    {
        return true;
    }
3024

3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
    /**
     * Whether the platform supports partial indexes.
     *
     * @return boolean
     */
    public function supportsPartialIndexes()
    {
        return false;
    }

3035 3036 3037 3038 3039
    /**
     * Whether the platform supports altering tables.
     *
     * @return boolean
     */
3040 3041 3042 3043 3044
    public function supportsAlterTable()
    {
        return true;
    }

3045 3046 3047 3048 3049
    /**
     * Whether the platform supports transactions.
     *
     * @return boolean
     */
3050 3051 3052 3053
    public function supportsTransactions()
    {
        return true;
    }
3054 3055 3056 3057 3058 3059

    /**
     * Whether the platform supports savepoints.
     *
     * @return boolean
     */
3060 3061 3062 3063
    public function supportsSavepoints()
    {
        return true;
    }
3064

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
    /**
     * Whether the platform supports releasing savepoints.
     *
     * @return boolean
     */
    public function supportsReleaseSavepoints()
    {
        return $this->supportsSavepoints();
    }

3075 3076 3077 3078 3079
    /**
     * Whether the platform supports primary key constraints.
     *
     * @return boolean
     */
3080 3081 3082 3083
    public function supportsPrimaryConstraints()
    {
        return true;
    }
3084 3085

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3086
     * Whether the platform supports foreign key constraints.
3087 3088 3089
     *
     * @return boolean
     */
3090 3091 3092 3093
    public function supportsForeignKeyConstraints()
    {
        return true;
    }
3094 3095

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3096
     * Whether this platform supports onUpdate in foreign key constraints.
3097
     *
3098
     * @return boolean
3099 3100 3101 3102 3103
     */
    public function supportsForeignKeyOnUpdate()
    {
        return ($this->supportsForeignKeyConstraints() && true);
    }
3104

3105 3106
    /**
     * Whether the platform supports database schemas.
3107
     *
3108 3109 3110 3111 3112 3113
     * @return boolean
     */
    public function supportsSchemas()
    {
        return false;
    }
3114

3115
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3116
     * Whether this platform can emulate schemas.
3117 3118 3119 3120 3121
     *
     * Platforms that either support or emulate schemas don't automatically
     * filter a schema for the namespaced elements in {@link
     * AbstractManager#createSchema}.
     *
3122
     * @return boolean
3123 3124 3125 3126 3127 3128
     */
    public function canEmulateSchemas()
    {
        return false;
    }

3129 3130 3131 3132 3133 3134 3135
    /**
     * Returns the default schema name.
     *
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
3136
    public function getDefaultSchemaName()
3137 3138 3139 3140
    {
        throw DBALException::notSupported(__METHOD__);
    }

3141
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3142 3143
     * Whether this platform supports create database.
     *
3144 3145
     * Some databases don't allow to create and drop databases at all or only with certain tools.
     *
3146
     * @return boolean
3147 3148 3149 3150 3151 3152
     */
    public function supportsCreateDropDatabase()
    {
        return true;
    }

3153
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3154
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
3155 3156 3157
     *
     * @return boolean
     */
3158 3159 3160 3161
    public function supportsGettingAffectedRows()
    {
        return true;
    }
3162

3163
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3164
     * Whether this platform support to add inline column comments as postfix.
3165
     *
3166
     * @return boolean
3167 3168 3169 3170 3171 3172 3173
     */
    public function supportsInlineColumnComments()
    {
        return false;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3174
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
3175
     *
3176
     * @return boolean
3177 3178 3179 3180 3181 3182
     */
    public function supportsCommentOnStatement()
    {
        return false;
    }

3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
    /**
     * Does this platform have native guid type.
     *
     * @return boolean
     */
    public function hasNativeGuidType()
    {
        return false;
    }

3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
    /**
     * Does this platform have native JSON type.
     *
     * @return boolean
     */
    public function hasNativeJsonType()
    {
        return false;
    }

3203 3204 3205 3206
    /**
     * @deprecated
     * @todo Remove in 3.0
     */
3207
    public function getIdentityColumnNullInsertSQL()
3208 3209 3210 3211
    {
        return "";
    }

3212
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3213
     * Whether this platform supports views.
3214 3215
     *
     * @return boolean
3216 3217 3218 3219 3220 3221
     */
    public function supportsViews()
    {
        return true;
    }

3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
    /**
     * Does this platform support column collation?
     *
     * @return boolean
     */
    public function supportsColumnCollation()
    {
        return false;
    }

3232
    /**
3233 3234
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored datetime value of this platform.
3235
     *
3236
     * @return string The format string.
3237 3238 3239 3240 3241 3242
     */
    public function getDateTimeFormatString()
    {
        return 'Y-m-d H:i:s';
    }

3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
    /**
     * 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';
    }

3254 3255 3256
    /**
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored date value of this platform.
3257
     *
3258 3259
     * @return string The format string.
     */
3260 3261
    public function getDateFormatString()
    {
3262
        return 'Y-m-d';
3263
    }
3264

3265 3266 3267
    /**
     * Gets the format string, as accepted by the date() function, that describes
     * the format of a stored time value of this platform.
3268
     *
3269 3270
     * @return string The format string.
     */
3271 3272 3273 3274 3275
    public function getTimeFormatString()
    {
        return 'H:i:s';
    }

3276
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3277
     * Adds an driver-specific LIMIT clause to the query.
3278
     *
Benjamin Morel's avatar
Benjamin Morel committed
3279 3280 3281
     * @param string       $query
     * @param integer|null $limit
     * @param integer|null $offset
3282
     *
3283
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3284 3285
     *
     * @throws DBALException
3286 3287 3288
     */
    final public function modifyLimitQuery($query, $limit, $offset = null)
    {
3289
        if ($limit !== null) {
3290 3291 3292
            $limit = (int)$limit;
        }

3293
        if ($offset !== null) {
3294
            $offset = (int)$offset;
3295 3296 3297 3298

            if ($offset < 0) {
                throw new DBALException("LIMIT argument offset=$offset is not valid");
            }
3299
            if ($offset > 0 && ! $this->supportsLimitOffset()) {
3300 3301
                throw new DBALException(sprintf("Platform %s does not support offset values in limit queries.", $this->getName()));
            }
3302 3303 3304 3305 3306 3307
        }

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3308
     * Adds an driver-specific LIMIT clause to the query.
3309
     *
Benjamin Morel's avatar
Benjamin Morel committed
3310 3311 3312
     * @param string  $query
     * @param integer|null $limit
     * @param integer|null $offset
3313
     *
3314 3315 3316
     * @return string
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
3317
    {
3318
        if ($limit !== null) {
3319
            $query .= ' LIMIT ' . $limit;
3320 3321
        }

3322
        if ($offset !== null) {
3323 3324 3325
            $query .= ' OFFSET ' . $offset;
        }

3326 3327
        return $query;
    }
3328

3329
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3330
     * Whether the database platform support offsets in modify limit clauses.
3331
     *
3332
     * @return boolean
3333 3334 3335 3336 3337 3338
     */
    public function supportsLimitOffset()
    {
        return true;
    }

3339 3340
    /**
     * Gets the character casing of a column in an SQL result set of this platform.
3341
     *
3342
     * @param string $column The column name for which to get the correct character casing.
3343
     *
3344 3345
     * @return string The column name in the character casing used in SQL result sets.
     */
3346
    public function getSQLResultCasing($column)
3347 3348 3349
    {
        return $column;
    }
3350

3351 3352 3353
    /**
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
     * by restrictions of the platform, like a maximum length.
3354
     *
3355
     * @param string $schemaElementName
3356
     *
3357 3358 3359 3360 3361 3362
     * @return string
     */
    public function fixSchemaElementName($schemaElementName)
    {
        return $schemaElementName;
    }
3363

3364
    /**
Pascal Borreli's avatar
Pascal Borreli committed
3365
     * Maximum length of any given database identifier, like tables or column names.
3366
     *
3367
     * @return integer
3368 3369 3370 3371 3372 3373
     */
    public function getMaxIdentifierLength()
    {
        return 63;
    }

3374
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3375
     * Returns the insert SQL for an empty insert statement.
3376
     *
3377 3378
     * @param string $tableName
     * @param string $identifierColumnName
3379
     *
Benjamin Morel's avatar
Benjamin Morel committed
3380
     * @return string
3381
     */
3382
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
3383 3384 3385
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
    }
3386 3387

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3388
     * Generates a Truncate Table SQL statement for a given table.
3389 3390 3391 3392
     *
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
     * following the foreign keys.
     *
Benjamin Morel's avatar
Benjamin Morel committed
3393 3394
     * @param string  $tableName
     * @param boolean $cascade
3395
     *
3396 3397
     * @return string
     */
3398
    public function getTruncateTableSQL($tableName, $cascade = false)
3399 3400 3401
    {
        return 'TRUNCATE '.$tableName;
    }
3402 3403 3404

    /**
     * This is for test reasons, many vendors have special requirements for dummy statements.
3405
     *
3406 3407 3408 3409 3410 3411
     * @return string
     */
    public function getDummySelectSQL()
    {
        return 'SELECT 1';
    }
3412 3413

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3414
     * Returns the SQL to create a new savepoint.
3415 3416
     *
     * @param string $savepoint
3417
     *
3418 3419 3420 3421 3422 3423 3424 3425
     * @return string
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVEPOINT ' . $savepoint;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3426
     * Returns the SQL to release a savepoint.
3427 3428
     *
     * @param string $savepoint
3429
     *
3430 3431 3432 3433 3434 3435 3436 3437
     * @return string
     */
    public function releaseSavePoint($savepoint)
    {
        return 'RELEASE SAVEPOINT ' . $savepoint;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3438
     * Returns the SQL to rollback a savepoint.
3439 3440
     *
     * @param string $savepoint
3441
     *
3442 3443 3444 3445 3446 3447
     * @return string
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
    }
3448 3449

    /**
Benjamin Morel's avatar
Benjamin Morel committed
3450
     * Returns the keyword list instance of this platform.
3451
     *
3452
     * @return \Doctrine\DBAL\Platforms\Keywords\KeywordList
Benjamin Morel's avatar
Benjamin Morel committed
3453 3454
     *
     * @throws \Doctrine\DBAL\DBALException If no keyword list is specified.
3455 3456 3457
     */
    final public function getReservedKeywordsList()
    {
3458
        // Check for an existing instantiation of the keywords class.
3459 3460
        if ($this->_keywords) {
            return $this->_keywords;
3461 3462
        }

3463 3464
        $class = $this->getReservedKeywordsClass();
        $keywords = new $class;
3465
        if ( ! $keywords instanceof \Doctrine\DBAL\Platforms\Keywords\KeywordList) {
3466 3467
            throw DBALException::notSupported(__METHOD__);
        }
3468 3469

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

3472 3473
        return $keywords;
    }
3474

3475
    /**
Benjamin Morel's avatar
Benjamin Morel committed
3476
     * Returns the class name of the reserved keywords list.
3477
     *
3478
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
3479 3480
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
3481 3482 3483 3484 3485
     */
    protected function getReservedKeywordsClass()
    {
        throw DBALException::notSupported(__METHOD__);
    }
3486
}