SQLServerPlatform.php 46.5 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18
 * <http://www.doctrine-project.org>.
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\LockMode;
23
use Doctrine\DBAL\Schema\Column;
24
use Doctrine\DBAL\Schema\TableDiff;
25 26 27
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
28 29

/**
30 31
 * The SQLServerPlatform provides the behavior, features and SQL dialect of the
 * Microsoft SQL Server database platform.
32 33 34 35
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 * @author Jonathan H. Wage <jonwage@gmail.com>
36
 * @author Benjamin Eberlei <kontakt@beberlei.de>
37
 * @author Steve Müller <st.mueller@dzh-online.de>
38
 */
39
class SQLServerPlatform extends AbstractPlatform
40
{
41 42 43
    /**
     * {@inheritDoc}
     */
44
    public function getDateDiffExpression($date1, $date2)
45 46 47
    {
        return 'DATEDIFF(day, ' . $date2 . ',' . $date1 . ')';
    }
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    /**
     * {@inheritDoc}
     */
    public function getDateAddHourExpression($date, $hours)
    {
        return 'DATEADD(hour, ' . $hours . ', ' . $date . ')';
    }

    /**
     * {@inheritDoc}
     */
    public function getDateSubHourExpression($date, $hours)
    {
        return 'DATEADD(hour, -1 * ' . $hours . ', ' . $date . ')';
    }

65 66 67
    /**
     * {@inheritDoc}
     */
68 69 70 71
    public function getDateAddDaysExpression($date, $days)
    {
        return 'DATEADD(day, ' . $days . ', ' . $date . ')';
    }
72

73 74 75
    /**
     * {@inheritDoc}
     */
76 77 78 79
    public function getDateSubDaysExpression($date, $days)
    {
        return 'DATEADD(day, -1 * ' . $days . ', ' . $date . ')';
    }
80

81 82 83
    /**
     * {@inheritDoc}
     */
84 85 86 87
    public function getDateAddMonthExpression($date, $months)
    {
        return 'DATEADD(month, ' . $months . ', ' . $date . ')';
    }
88

89 90 91
    /**
     * {@inheritDoc}
     */
92 93 94 95
    public function getDateSubMonthExpression($date, $months)
    {
        return 'DATEADD(month, -1 * ' . $months . ', ' . $date . ')';
    }
96

97
    /**
98 99
     * {@inheritDoc}
     *
100 101
     * Microsoft SQL Server prefers "autoincrement" identity columns
     * since sequences can only be emulated with a table.
102
     */
103
    public function prefersIdentityColumns()
104
    {
105 106
        return true;
    }
107

108
    /**
109
     * {@inheritDoc}
110
     *
111
     * Microsoft SQL Server supports this through AUTO_INCREMENT columns.
112 113 114 115 116 117 118
     */
    public function supportsIdentityColumns()
    {
        return true;
    }

    /**
119
     * {@inheritDoc}
120
     */
121
    public function supportsReleaseSavepoints()
122 123 124
    {
        return false;
    }
125

126 127 128 129 130 131 132 133
    /**
     * {@inheritdoc}
     */
    public function supportsSchemas()
    {
        return true;
    }

134 135 136 137 138 139 140 141
    /**
     * {@inheritdoc}
     */
    public function getDefaultSchemaName()
    {
        return 'dbo';
    }

142 143 144 145 146 147 148 149
    /**
     * {@inheritDoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

150
    /**
151
     * {@inheritDoc}
152 153 154 155 156
     */
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }
157

158
    /**
159
     * {@inheritDoc}
160 161 162
     */
    public function getDropDatabaseSQL($name)
    {
163 164 165 166
        return 'DROP DATABASE ' . $name;
    }

    /**
167
     * {@inheritDoc}
168
     */
169
    public function supportsCreateDropDatabase()
170 171
    {
        return false;
172 173
    }

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

    /**
     * {@inheritDoc}
     */
    public function schemaNeedsCreation($schemaName)
    {
        return $schemaName !== 'dbo';
    }

190
    /**
191
     * {@inheritDoc}
192 193 194
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
195
        if ($foreignKey instanceof ForeignKeyConstraint) {
196
            $foreignKey = $foreignKey->getQuotedName($this);
197 198
        }

199
        if ($table instanceof Table) {
200
            $table = $table->getQuotedName($this);
201 202 203
        }

        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
204
    }
205 206

    /**
207
     * {@inheritDoc}
208
     */
209
    public function getDropIndexSQL($index, $table = null)
210
    {
211
        if ($index instanceof Index) {
212
            $index = $index->getQuotedName($this);
Steve Müller's avatar
Steve Müller committed
213
        } elseif (!is_string($index)) {
214 215 216
            throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
        }

217 218
        if (!isset($table)) {
            return 'DROP INDEX ' . $index;
219
        }
220

221 222
        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
223
        }
224 225 226 227 228

        return "IF EXISTS (SELECT * FROM sysobjects WHERE name = '$index')
                    ALTER TABLE " . $table . " DROP CONSTRAINT " . $index . "
                ELSE
                    DROP INDEX " . $index . " ON " . $table;
229
    }
230 231

    /**
232
     * {@inheritDoc}
233 234
     */
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
235
    {
236
        $defaultConstraintsSql = array();
237
        $commentsSql           = array();
238

239
        // @todo does other code breaks because of this?
240
        // force primary keys to be not null
241
        foreach ($columns as &$column) {
242
            /** @var $column \Doctrine\DBAL\Schema\Column */
243 244 245
            if (isset($column['primary']) && $column['primary']) {
                $column['notnull'] = true;
            }
246

247
            // Build default constraints SQL statements.
248
            if (isset($column['default'])) {
249 250 251
                $defaultConstraintsSql[] = 'ALTER TABLE ' . $tableName .
                    ' ADD' . $this->getDefaultConstraintDeclarationSQL($tableName, $column);
            }
252 253 254 255

            if ( ! empty($column['comment']) || is_numeric($column['comment'])) {
                $commentsSql[] = $this->getCreateColumnCommentSQL($tableName, $column['name'], $column['comment']);
            }
256 257
        }

258
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
259 260

        if (isset($options['uniqueConstraints']) && !empty($options['uniqueConstraints'])) {
261 262 263 264
            foreach ($options['uniqueConstraints'] as $name => $definition) {
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }
265 266

        if (isset($options['primary']) && !empty($options['primary'])) {
267 268 269 270 271
            $flags = '';
            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('nonclustered')) {
                $flags = ' NONCLUSTERED';
            }
            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values($options['primary']))) . ')';
272 273 274 275 276
        }

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

        $check = $this->getCheckDeclarationSQL($columns);
277
        if (!empty($check)) {
278 279 280 281 282
            $query .= ', ' . $check;
        }
        $query .= ')';

        $sql[] = $query;
283 284

        if (isset($options['indexes']) && !empty($options['indexes'])) {
285
            foreach ($options['indexes'] as $index) {
286 287 288 289 290
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
            }
        }

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

296
        return array_merge($sql, $commentsSql, $defaultConstraintsSql);
297
    }
298

299
    /**
300
     * {@inheritDoc}
301 302 303 304 305 306 307
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
        $flags = '';
        if ($index->hasFlag('nonclustered')) {
            $flags = ' NONCLUSTERED';
        }
308
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY' . $flags . ' (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')';
309 310
    }

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    /**
     * Returns the SQL statement for creating a column comment.
     *
     * SQL Server does not support native column comments,
     * therefore the extended properties functionality is used
     * as a workaround to store them.
     * The property name used to store column comments is "MS_Description"
     * which provides compatibility with SQL Server Management Studio,
     * as column comments are stored in the same property there when
     * specifying a column's "Description" attribute.
     *
     * @param string $tableName  The quoted table name to which the column belongs.
     * @param string $columnName The quoted column name to create the comment for.
     * @param string $comment    The column's comment.
     *
     * @return string
     */
    protected function getCreateColumnCommentSQL($tableName, $columnName, $comment)
    {
        return $this->getAddExtendedPropertySQL(
            'MS_Description',
            $comment,
            'SCHEMA',
            'dbo',
            'TABLE',
            $tableName,
            'COLUMN',
            $columnName
        );
    }

342 343 344 345 346 347 348 349 350 351 352 353
    /**
     * Returns the SQL snippet for declaring a default constraint.
     *
     * @param string $table  Name of the table to return the default constraint declaration for.
     * @param array  $column Column definition.
     *
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    public function getDefaultConstraintDeclarationSQL($table, array $column)
    {
354
        if ( ! isset($column['default'])) {
355 356 357 358 359 360 361 362 363 364
            throw new \InvalidArgumentException("Incomplete column definition. 'default' required.");
        }

        return
            ' CONSTRAINT ' .
            $this->generateDefaultConstraintName($table, $column['name']) .
            $this->getDefaultValueDeclarationSQL($column) .
            ' FOR ' . $column['name'];
    }

365
    /**
366
     * {@inheritDoc}
367
     */
368
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
369 370
    {
        $constraint = parent::getUniqueConstraintDeclarationSQL($name, $index);
371 372 373 374 375 376 377

        $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);

        return $constraint;
    }

    /**
378
     * {@inheritDoc}
379 380 381 382 383
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
        $constraint = parent::getCreateIndexSQL($index, $table);

Craig Mason's avatar
Craig Mason committed
384
        if ($index->isUnique() && !$index->isPrimary()) {
385 386 387 388 389 390
            $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);
        }

        return $constraint;
    }

391
    /**
392
     * {@inheritDoc}
393 394 395 396 397 398 399 400 401 402
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
        }

        if ($index->hasFlag('clustered')) {
            $type .= 'CLUSTERED ';
Steve Müller's avatar
Steve Müller committed
403
        } elseif ($index->hasFlag('nonclustered')) {
404 405 406 407 408 409
            $type .= 'NONCLUSTERED ';
        }

        return $type;
    }

410
    /**
411
     * Extend unique key constraint with required filters
412
     *
Benjamin Morel's avatar
Benjamin Morel committed
413 414
     * @param string                      $sql
     * @param \Doctrine\DBAL\Schema\Index $index
415
     *
416 417 418 419 420 421
     * @return string
     */
    private function _appendUniqueConstraintDefinition($sql, Index $index)
    {
        $fields = array();

422
        foreach ($index->getQuotedColumns($this) as $field) {
423
            $fields[] = $field . ' IS NOT NULL';
424
        }
425 426 427

        return $sql . ' WHERE ' . implode(' AND ', $fields);
    }
428

429
    /**
430
     * {@inheritDoc}
431
     */
432
    public function getAlterTableSQL(TableDiff $diff)
433
    {
434 435 436 437
        $queryParts  = array();
        $sql         = array();
        $columnSql   = array();
        $commentsSql = array();
438

439
        /** @var \Doctrine\DBAL\Schema\Column $column */
440
        foreach ($diff->addedColumns as $column) {
441 442
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
443 444
            }

445 446 447
            $columnDef = $column->toArray();
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

448
            if (isset($columnDef['default'])) {
449 450 451
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
452 453 454 455 456 457 458 459 460 461

            $comment = $this->getColumnComment($column);

            if ( ! empty($comment) || is_numeric($comment)) {
                $commentsSql[] = $this->getCreateColumnCommentSQL(
                    $diff->name,
                    $column->getQuotedName($this),
                    $comment
                );
            }
462 463
        }

464
        foreach ($diff->removedColumns as $column) {
465 466
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
467 468
            }

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

472
        /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
473
        foreach ($diff->changedColumns as $columnDiff) {
474 475
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
476 477
            }

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            $column     = $columnDiff->column;
            $comment    = $this->getColumnComment($column);
            $hasComment = ! empty ($comment) || is_numeric($comment);

            if ($columnDiff->fromColumn instanceof Column) {
                $fromComment    = $this->getColumnComment($columnDiff->fromColumn);
                $hasFromComment = ! empty ($fromComment) || is_numeric($fromComment);

                if ($hasFromComment && $hasComment && $fromComment != $comment) {
                    $commentsSql[] = $this->getAlterColumnCommentSQL(
                        $diff->name,
                        $column->getQuotedName($this),
                        $comment
                    );
                } elseif ($hasFromComment && ! $hasComment) {
                    $commentsSql[] = $this->getDropColumnCommentSQL($diff->name, $column->getQuotedName($this));
                } elseif ($hasComment) {
                    $commentsSql[] = $this->getCreateColumnCommentSQL(
                        $diff->name,
                        $column->getQuotedName($this),
                        $comment
                    );
                }
            } else {
                // todo: Original comment cannot be determined. What to do? Add, update, drop or skip?
            }

            // Do not add query part if only comment has changed.
            if ($columnDiff->hasChanged('comment') && count($columnDiff->changedProperties) === 1) {
                continue;
            }

            $fromColumnDefault = isset($columnDiff->fromColumn) ? $columnDiff->fromColumn->getDefault() : null;
511 512 513 514 515 516 517 518
            $columnDef = $column->toArray();
            $columnDefaultHasChanged = $columnDiff->hasChanged('default');

            /**
             * Drop existing column default constraint
             * if default value has changed and another
             * default constraint already exists for the column.
             */
519
            if ($columnDefaultHasChanged && null !== $fromColumnDefault) {
520 521 522 523
                $queryParts[] = 'DROP CONSTRAINT ' .
                    $this->generateDefaultConstraintName($diff->name, $columnDiff->oldColumnName);
            }

524
            $queryParts[] = 'ALTER COLUMN ' .
525 526
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

527
            if ($columnDefaultHasChanged && isset($columnDef['default'])) {
528 529 530
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
531 532
        }

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

538 539 540
            $sql[] = "sp_RENAME '". $diff->name. ".". $oldColumnName . "', '".$column->getQuotedName($this)."', 'COLUMN'";

            // todo: Find a way how to implement column comment alteration statements for renamed columns.
541 542 543 544 545 546 547

            $columnDef = $column->toArray();

            /**
             * Drop existing default constraint for the old column name
             * if column has default value.
             */
548
            if (isset($columnDef['default'])) {
549 550 551 552
                $queryParts[] = 'DROP CONSTRAINT ' .
                    $this->generateDefaultConstraintName($diff->name, $oldColumnName);
            }

553
            $queryParts[] = 'ALTER COLUMN ' .
554 555 556 557 558
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

            /**
             * Readd default constraint for the new column name.
             */
559
            if (isset($columnDef['default'])) {
560 561 562
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
563
        }
564

565 566 567
        $tableSql = array();

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
568
            return array_merge($tableSql, $columnSql);
569
        }
570

571
        foreach ($queryParts as $query) {
572
            $sql[] = 'ALTER TABLE ' . $diff->getName()->getQuotedName($this) . ' ' . $query;
573
        }
574

575
        $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff), $commentsSql);
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
576

577
        if ($diff->newName !== false) {
578
            $sql[] = "sp_RENAME '" . $diff->getName()->getQuotedName($this) . "', '" . $diff->getNewName()->getQuotedName($this) . "'";
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

            /**
             * Rename table's default constraints names
             * to match the new table name.
             * This is necessary to ensure that the default
             * constraints can be referenced in future table
             * alterations as the table name is encoded in
             * default constraints' names.
             */
            $sql[] = "DECLARE @sql NVARCHAR(MAX) = N''; " .
                "SELECT @sql += N'EXEC sp_rename N''' + dc.name + ''', N''' " .
                "+ REPLACE(dc.name, '" . $this->generateIdentifierName($diff->name) . "', " .
                "'" . $this->generateIdentifierName($diff->newName) . "') + ''', ''OBJECT'';' " .
                "FROM sys.default_constraints dc " .
                "JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id " .
594
                "WHERE tbl.name = '" . $diff->getNewName()->getQuotedName($this) . "';" .
595
                "EXEC sp_executesql @sql";
596 597
        }

598
        return array_merge($sql, $tableSql, $columnSql);
599
    }
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
    /**
     * Returns the SQL statement for altering a column comment.
     *
     * SQL Server does not support native column comments,
     * therefore the extended properties functionality is used
     * as a workaround to store them.
     * The property name used to store column comments is "MS_Description"
     * which provides compatibility with SQL Server Management Studio,
     * as column comments are stored in the same property there when
     * specifying a column's "Description" attribute.
     *
     * @param string $tableName  The quoted table name to which the column belongs.
     * @param string $columnName The quoted column name to alter the comment for.
     * @param string $comment    The column's comment.
     *
     * @return string
     */
    protected function getAlterColumnCommentSQL($tableName, $columnName, $comment)
    {
        return $this->getUpdateExtendedPropertySQL(
            'MS_Description',
            $comment,
            'SCHEMA',
            'dbo',
            'TABLE',
            $tableName,
            'COLUMN',
            $columnName
        );
    }

    /**
     * Returns the SQL statement for dropping a column comment.
     *
     * SQL Server does not support native column comments,
     * therefore the extended properties functionality is used
     * as a workaround to store them.
     * The property name used to store column comments is "MS_Description"
     * which provides compatibility with SQL Server Management Studio,
     * as column comments are stored in the same property there when
     * specifying a column's "Description" attribute.
     *
     * @param string $tableName  The quoted table name to which the column belongs.
     * @param string $columnName The quoted column name to drop the comment for.
     *
     * @return string
     */
    protected function getDropColumnCommentSQL($tableName, $columnName)
    {
        return $this->getDropExtendedPropertySQL(
            'MS_Description',
            'SCHEMA',
            'dbo',
            'TABLE',
            $tableName,
            'COLUMN',
            $columnName
        );
    }

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
        return array(
            sprintf(
                "EXEC sp_RENAME N'%s.%s', N'%s', N'INDEX'",
                $tableName,
                $oldIndexName,
                $index->getQuotedName($this)
            )
        );
    }

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    /**
     * Returns the SQL statement for adding an extended property to a database object.
     *
     * @param string      $name       The name of the property to add.
     * @param string|null $value      The value of the property to add.
     * @param string|null $level0Type The type of the object at level 0 the property belongs to.
     * @param string|null $level0Name The name of the object at level 0 the property belongs to.
     * @param string|null $level1Type The type of the object at level 1 the property belongs to.
     * @param string|null $level1Name The name of the object at level 1 the property belongs to.
     * @param string|null $level2Type The type of the object at level 2 the property belongs to.
     * @param string|null $level2Name The name of the object at level 2 the property belongs to.
     *
     * @return string
     *
     * @link http://msdn.microsoft.com/en-us/library/ms180047%28v=sql.90%29.aspx
     */
    public function getAddExtendedPropertySQL(
        $name,
        $value = null,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
        return "EXEC sp_addextendedproperty " .
            "N'" . $name . "', N'" . $value . "', " .
            "N'" . $level0Type . "', " . $level0Name . ', ' .
            "N'" . $level1Type . "', " . $level1Name . ', ' .
            "N'" . $level2Type . "', " . $level2Name;
    }

    /**
     * Returns the SQL statement for dropping an extended property from a database object.
     *
     * @param string      $name       The name of the property to drop.
     * @param string|null $level0Type The type of the object at level 0 the property belongs to.
     * @param string|null $level0Name The name of the object at level 0 the property belongs to.
     * @param string|null $level1Type The type of the object at level 1 the property belongs to.
     * @param string|null $level1Name The name of the object at level 1 the property belongs to.
     * @param string|null $level2Type The type of the object at level 2 the property belongs to.
     * @param string|null $level2Name The name of the object at level 2 the property belongs to.
     *
     * @return string
     *
     * @link http://technet.microsoft.com/en-gb/library/ms178595%28v=sql.90%29.aspx
     */
    public function getDropExtendedPropertySQL(
        $name,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
        return "EXEC sp_dropextendedproperty " .
        "N'" . $name . "', " .
        "N'" . $level0Type . "', " . $level0Name . ', ' .
        "N'" . $level1Type . "', " . $level1Name . ', ' .
        "N'" . $level2Type . "', " . $level2Name;
    }

    /**
     * Returns the SQL statement for updating an extended property of a database object.
     *
     * @param string      $name       The name of the property to update.
     * @param string|null $value      The value of the property to update.
     * @param string|null $level0Type The type of the object at level 0 the property belongs to.
     * @param string|null $level0Name The name of the object at level 0 the property belongs to.
     * @param string|null $level1Type The type of the object at level 1 the property belongs to.
     * @param string|null $level1Name The name of the object at level 1 the property belongs to.
     * @param string|null $level2Type The type of the object at level 2 the property belongs to.
     * @param string|null $level2Name The name of the object at level 2 the property belongs to.
     *
     * @return string
     *
     * @link http://msdn.microsoft.com/en-us/library/ms186885%28v=sql.90%29.aspx
     */
    public function getUpdateExtendedPropertySQL(
        $name,
        $value = null,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
        return "EXEC sp_updateextendedproperty " .
        "N'" . $name . "', N'" . $value . "', " .
        "N'" . $level0Type . "', " . $level0Name . ', ' .
        "N'" . $level1Type . "', " . $level1Name . ', ' .
        "N'" . $level2Type . "', " . $level2Name;
    }

773
    /**
774
     * {@inheritDoc}
775
     */
776
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
777
    {
778
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
779 780
    }

781
    /**
782
     * {@inheritDoc}
783
     */
784
    public function getListTablesSQL()
785
    {
786 787
        // "sysdiagrams" table must be ignored as it's internal SQL Server table for Database Diagrams
        return "SELECT name FROM sysobjects WHERE type = 'U' AND name != 'sysdiagrams' ORDER BY name";
788 789 790
    }

    /**
791
     * {@inheritDoc}
792
     */
793
    public function getListTableColumnsSQL($table, $database = null)
794
    {
795 796 797 798 799 800 801 802
        return "SELECT    col.name,
                          type.name AS type,
                          col.max_length AS length,
                          ~col.is_nullable AS notnull,
                          def.definition AS [default],
                          col.scale,
                          col.precision,
                          col.is_identity AS autoincrement,
803 804
                          col.collation_name AS collation,
                          CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
805 806 807 808 809
                FROM      sys.columns AS col
                JOIN      sys.types AS type
                ON        col.user_type_id = type.user_type_id
                JOIN      sys.objects AS obj
                ON        col.object_id = obj.object_id
810 811
                JOIN      sys.schemas AS scm
                ON        obj.schema_id = scm.schema_id
812 813 814
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
815 816 817 818
                LEFT JOIN sys.extended_properties AS prop
                ON        obj.object_id = prop.major_id
                AND       col.column_id = prop.minor_id
                AND       prop.name = 'MS_Description'
819
                WHERE     obj.type = 'U'
820
                AND       " . $this->getTableWhereClause($table, 'scm.name', 'obj.name');
821 822 823
    }

    /**
824
     * {@inheritDoc}
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
        return "SELECT f.name AS ForeignKey,
                SCHEMA_NAME (f.SCHEMA_ID) AS SchemaName,
                OBJECT_NAME (f.parent_object_id) AS TableName,
                COL_NAME (fc.parent_object_id,fc.parent_column_id) AS ColumnName,
                SCHEMA_NAME (o.SCHEMA_ID) ReferenceSchemaName,
                OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
                COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName,
                f.delete_referential_action_desc,
                f.update_referential_action_desc
                FROM sys.foreign_keys AS f
                INNER JOIN sys.foreign_key_columns AS fc
                INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
                ON f.OBJECT_ID = fc.constraint_object_id
841 842
                WHERE " .
                $this->getTableWhereClause($table, 'SCHEMA_NAME (f.schema_id)', 'OBJECT_NAME (f.parent_object_id)');
843 844 845
    }

    /**
846
     * {@inheritDoc}
847
     */
848
    public function getListTableIndexesSQL($table, $currentDatabase = null)
849
    {
850 851
        return "SELECT idx.name AS key_name,
                       col.name AS column_name,
Steve Müller's avatar
Steve Müller committed
852 853
                       ~idx.is_unique AS non_unique,
                       idx.is_primary_key AS [primary],
854 855 856 857 858 859
                       CASE idx.type
                           WHEN '1' THEN 'clustered'
                           WHEN '2' THEN 'nonclustered'
                           ELSE NULL
                       END AS flags
                FROM sys.tables AS tbl
860
                JOIN sys.schemas AS scm ON tbl.schema_id = scm.schema_id
861 862 863
                JOIN sys.indexes AS idx ON tbl.object_id = idx.object_id
                JOIN sys.index_columns AS idxcol ON idx.object_id = idxcol.object_id AND idx.index_id = idxcol.index_id
                JOIN sys.columns AS col ON idxcol.object_id = col.object_id AND idxcol.column_id = col.column_id
864
                WHERE " . $this->getTableWhereClause($table, 'scm.name', 'tbl.name') . "
865
                ORDER BY idx.index_id ASC, idxcol.index_column_id ASC";
866
    }
867 868

    /**
869
     * {@inheritDoc}
870
     */
871
    public function getCreateViewSQL($name, $sql)
872 873 874
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
875 876

    /**
877
     * {@inheritDoc}
878
     */
879
    public function getListViewsSQL($database)
880 881 882 883
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    /**
     * Returns the where clause to filter schema and table name in a query.
     *
     * @param string $table        The full qualified name of the table.
     * @param string $tableColumn  The name of the column to compare the schema to in the where clause.
     * @param string $schemaColumn The name of the column to compare the table to in the where clause.
     *
     * @return string
     */
    private function getTableWhereClause($table, $schemaColumn, $tableColumn)
    {
        if (strpos($table, ".") !== false) {
            list($schema, $table) = explode(".", $table);
            $schema = "'" . $schema . "'";
        } else {
            $schema = "SCHEMA_NAME()";
        }

        return "({$tableColumn} = '{$table}' AND {$schemaColumn} = {$schema})";
    }

905
    /**
906
     * {@inheritDoc}
907 908 909
     */
    public function getDropViewSQL($name)
    {
910
        return 'DROP VIEW ' . $name;
911
    }
912 913

    /**
914
     * {@inheritDoc}
915 916 917
     */
    public function getGuidExpression()
    {
918
        return 'NEWID()';
919
    }
920 921

    /**
922
     * {@inheritDoc}
923
     */
924
    public function getLocateExpression($str, $substr, $startPos = false)
925
    {
926 927 928
        if ($startPos == false) {
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        }
929 930

        return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
931
    }
932

933
    /**
934
     * {@inheritDoc}
935
     */
936
    public function getModExpression($expression1, $expression2)
937
    {
938
        return $expression1 . ' % ' . $expression2;
939
    }
940

941
    /**
942
     * {@inheritDoc}
943
     */
944
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
945
    {
946
        if ( ! $char) {
947 948 949 950 951 952 953 954 955 956 957
            switch ($pos) {
                case self::TRIM_LEADING:
                    $trimFn = 'LTRIM';
                    break;

                case self::TRIM_TRAILING:
                    $trimFn = 'RTRIM';
                    break;

                default:
                    return 'LTRIM(RTRIM(' . $str . '))';
958 959 960 961
            }

            return $trimFn . '(' . $str . ')';
        }
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

        /** Original query used to get those expressions
          declare @c varchar(100) = 'xxxBarxxx', @trim_char char(1) = 'x';
          declare @pat varchar(10) = '%[^' + @trim_char + ']%';
          select @c as string
          , @trim_char as trim_char
          , stuff(@c, 1, patindex(@pat, @c) - 1, null) as trim_leading
          , reverse(stuff(reverse(@c), 1, patindex(@pat, reverse(@c)) - 1, null)) as trim_trailing
          , reverse(stuff(reverse(stuff(@c, 1, patindex(@pat, @c) - 1, null)), 1, patindex(@pat, reverse(stuff(@c, 1, patindex(@pat, @c) - 1, null))) - 1, null)) as trim_both;
         */
        $pattern = "'%[^' + $char + ']%'";

        if ($pos == self::TRIM_LEADING) {
            return 'stuff(' . $str . ', 1, patindex(' . $pattern . ', ' . $str . ') - 1, null)';
        }

        if ($pos == self::TRIM_TRAILING) {
            return 'reverse(stuff(reverse(' . $str . '), 1, patindex(' . $pattern . ', reverse(' . $str . ')) - 1, null))';
        }

        return 'reverse(stuff(reverse(stuff(' . $str . ', 1, patindex(' . $pattern . ', ' . $str . ') - 1, null)), 1, patindex(' . $pattern . ', reverse(stuff(' . $str . ', 1, patindex(' . $pattern . ', ' . $str . ') - 1, null))) - 1, null))';
983
    }
984

985
    /**
986
     * {@inheritDoc}
987 988
     */
    public function getConcatExpression()
989
    {
990
        $args = func_get_args();
991

992
        return '(' . implode(' + ', $args) . ')';
993
    }
994

Benjamin Morel's avatar
Benjamin Morel committed
995 996 997
    /**
     * {@inheritDoc}
     */
998
    public function getListDatabasesSQL()
999 1000 1001
    {
        return 'SELECT * FROM SYS.DATABASES';
    }
1002

1003
    /**
1004
     * {@inheritDoc}
1005
     */
1006
    public function getSubstringExpression($value, $from, $length = null)
1007
    {
1008 1009
        if (!is_null($length)) {
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
1010
        }
1011

1012
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
1013
    }
1014

1015
    /**
1016
     * {@inheritDoc}
1017
     */
1018
    public function getLengthExpression($column)
1019
    {
1020
        return 'LEN(' . $column . ')';
1021 1022
    }

1023
    /**
1024
     * {@inheritDoc}
1025
     */
1026
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
1027
    {
1028
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
1029
    }
1030

1031
    /**
1032
     * {@inheritDoc}
1033
     */
1034
    public function getIntegerTypeDeclarationSQL(array $field)
1035
    {
1036
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1037 1038
    }

1039
    /**
1040
     * {@inheritDoc}
1041
     */
1042
    public function getBigIntTypeDeclarationSQL(array $field)
1043
    {
1044
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1045 1046
    }

1047
    /**
1048
     * {@inheritDoc}
1049
     */
1050
    public function getSmallIntTypeDeclarationSQL(array $field)
1051
    {
1052
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1053 1054
    }

1055
    /**
1056
     * {@inheritDoc}
1057
     */
1058
    public function getGuidTypeDeclarationSQL(array $field)
1059 1060 1061 1062
    {
        return 'UNIQUEIDENTIFIER';
    }

1063 1064 1065
    /**
     * {@inheritDoc}
     */
1066
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1067
    {
1068
        return $fixed ? ($length ? 'NCHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
1069
    }
1070

Steve Müller's avatar
Steve Müller committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 8000;
    }

1087 1088 1089
    /**
     * {@inheritDoc}
     */
1090
    public function getClobTypeDeclarationSQL(array $field)
1091
    {
1092
        return 'VARCHAR(MAX)';
1093
    }
1094

1095
    /**
1096
     * {@inheritDoc}
1097
     */
1098
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1099
    {
1100
        return (!empty($columnDef['autoincrement'])) ? ' IDENTITY' : '';
1101
    }
1102

1103
    /**
1104
     * {@inheritDoc}
1105
     */
1106
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
1107
    {
1108
        return 'DATETIME';
1109 1110
    }

1111
    /**
1112
     * {@inheritDoc}
1113
     */
1114
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
1115
    {
1116
        return 'DATETIME';
1117
    }
1118 1119

    /**
1120
     * {@inheritDoc}
1121
     */
1122
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1123
    {
1124
        return 'DATETIME';
1125
    }
1126

1127
    /**
1128
     * {@inheritDoc}
1129
     */
1130
    public function getBooleanTypeDeclarationSQL(array $field)
1131 1132 1133 1134
    {
        return 'BIT';
    }

1135
    /**
1136
     * {@inheritDoc}
1137
     */
1138
    protected function doModifyLimitQuery($query, $limit, $offset = null)
1139
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
1140
        if ($limit === null) {
Fabio B. Silva's avatar
Fabio B. Silva committed
1141 1142
            return $query;
        }
1143

Fabio B. Silva's avatar
Fabio B. Silva committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        $start   = $offset + 1;
        $end     = $offset + $limit;
        $orderBy = stristr($query, 'ORDER BY');
        $query   = preg_replace('/\s+ORDER\s+BY\s+([^\)]*)/', '', $query); //Remove ORDER BY from $query
        $format  = 'SELECT * FROM (%s) AS doctrine_tbl WHERE doctrine_rownum BETWEEN %d AND %d';

        if ( ! $orderBy) {
            //Replace only first occurrence of FROM with OVER to prevent changing FROM also in subqueries.
            $query = preg_replace('/\sFROM\s/i', ', ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM ', $query, 1);

            return sprintf($format, $query, $start, $end);
        }

        //Clear ORDER BY
        $orderBy        = preg_replace('/ORDER\s+BY\s+([^\)]*)(.*)/', '$1', $orderBy);
        $orderByParts   = explode(',', $orderBy);
        $orderbyColumns = array();

        //Split ORDER BY into parts
        foreach ($orderByParts as &$part) {
Fabio B. Silva's avatar
Fabio B. Silva committed
1164 1165

            if (preg_match('/(([^\s]*)\.)?([^\.\s]*)\s*(ASC|DESC)?/i', trim($part), $matches)) {
Fabio B. Silva's avatar
Fabio B. Silva committed
1166 1167 1168 1169 1170 1171
                $orderbyColumns[] = array(
                    'column'    => $matches[3],
                    'hasTable'  => ( ! empty($matches[2])),
                    'sort'      => isset($matches[4]) ? $matches[4] : null,
                    'table'     => empty($matches[2]) ? '[^\.\s]*' : $matches[2]
                );
1172
            }
Fabio B. Silva's avatar
Fabio B. Silva committed
1173 1174
        }

flip111's avatar
flip111 committed
1175
        $isWrapped = (preg_match('/SELECT DISTINCT .* FROM \(.*\) dctrn_result/', $query)) ? true : false;
1176

Fabio B. Silva's avatar
Fabio B. Silva committed
1177 1178 1179
        //Find alias for each colum used in ORDER BY
        if ( ! empty($orderbyColumns)) {
            foreach ($orderbyColumns as $column) {
1180

1181 1182
                $pattern    = sprintf('/%s\.%s\s+(?:AS\s+)?([^,\s)]+)/i', $column['table'], $column['column']);

1183
                if ($isWrapped) {
1184 1185
                    $overColumn = preg_match($pattern, $query, $matches)
                        ? $matches[1] : '';
1186 1187
                } else {
                    $overColumn = preg_match($pattern, $query, $matches)
1188 1189
                        ? ($column['hasTable'] ? $column['table']  . '.' : '') . $column['column']
                        : $column['column'];
1190
                }
1191

Fabio B. Silva's avatar
Fabio B. Silva committed
1192 1193 1194
                if (isset($column['sort'])) {
                    $overColumn .= ' ' . $column['sort'];
                }
1195

Fabio B. Silva's avatar
Fabio B. Silva committed
1196 1197
                $overColumns[] = $overColumn;
            }
1198 1199
        }

Fabio B. Silva's avatar
Fabio B. Silva committed
1200 1201 1202 1203 1204
        //Replace only first occurrence of FROM with $over to prevent changing FROM also in subqueries.
        $over  = 'ORDER BY ' . implode(', ', $overColumns);
        $query = preg_replace('/\sFROM\s/i', ", ROW_NUMBER() OVER ($over) AS doctrine_rownum FROM ", $query, 1);

        return sprintf($format, $query, $start, $end);
1205
    }
1206

1207
    /**
1208
     * {@inheritDoc}
1209 1210 1211 1212 1213 1214
     */
    public function supportsLimitOffset()
    {
        return false;
    }

1215
    /**
1216
     * {@inheritDoc}
1217
     */
1218
    public function convertBooleans($item)
1219
    {
1220 1221 1222
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
1223
                    $item[$key] = ($value) ? 1 : 0;
1224 1225
                }
            }
Steve Müller's avatar
Steve Müller committed
1226
        } elseif (is_bool($item) || is_numeric($item)) {
1227
            $item = ($item) ? 1 : 0;
1228
        }
1229

1230
        return $item;
1231
    }
1232 1233

    /**
1234
     * {@inheritDoc}
1235
     */
1236
    public function getCreateTemporaryTableSnippetSQL()
1237
    {
1238
        return "CREATE TABLE";
1239
    }
1240

1241
    /**
1242
     * {@inheritDoc}
1243 1244 1245 1246 1247 1248
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

1249
    /**
1250
     * {@inheritDoc}
1251 1252 1253
     */
    public function getDateTimeFormatString()
    {
1254 1255
        return 'Y-m-d H:i:s.000';
    }
1256

1257
    /**
1258
     * {@inheritDoc}
1259
     */
1260 1261 1262 1263 1264 1265
    public function getDateFormatString()
    {
        return 'Y-m-d H:i:s.000';
    }

    /**
1266
     * {@inheritDoc}
1267
     */
1268 1269 1270
    public function getTimeFormatString()
    {
        return 'Y-m-d H:i:s.000';
1271
    }
1272

1273
    /**
1274
     * {@inheritDoc}
1275 1276 1277 1278 1279
     */
    public function getDateTimeTzFormatString()
    {
        return $this->getDateTimeFormatString();
    }
1280

1281
    /**
1282
     * {@inheritDoc}
1283
     */
1284
    public function getName()
1285
    {
1286
        return 'mssql';
1287
    }
1288

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1289
    /**
1290
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1291
     */
1292 1293
    protected function initializeDoctrineTypeMappings()
    {
1294
        $this->doctrineTypeMapping = array(
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
            'bigint' => 'bigint',
            'numeric' => 'decimal',
            'bit' => 'boolean',
            'smallint' => 'smallint',
            'decimal' => 'decimal',
            'smallmoney' => 'integer',
            'int' => 'integer',
            'tinyint' => 'smallint',
            'money' => 'integer',
            'float' => 'float',
            'real' => 'float',
            'double' => 'float',
            'double precision' => 'float',
            'smalldatetime' => 'datetime',
            'datetime' => 'datetime',
            'char' => 'string',
            'varchar' => 'string',
            'text' => 'text',
            'nchar' => 'string',
            'nvarchar' => 'string',
            'ntext' => 'text',
Steve Müller's avatar
Steve Müller committed
1316 1317
            'binary' => 'binary',
            'varbinary' => 'binary',
1318
            'image' => 'blob',
1319
            'uniqueidentifier' => 'guid',
1320
        );
1321
    }
1322 1323

    /**
1324
     * {@inheritDoc}
1325 1326 1327 1328 1329 1330 1331
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
1332
     * {@inheritDoc}
1333 1334 1335 1336 1337 1338 1339
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
1340
     * {@inheritDoc}
1341 1342 1343 1344
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
1345
    }
1346 1347

    /**
1348
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1349
     */
1350
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1351
    {
Steve Müller's avatar
Steve Müller committed
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        switch ($lockMode) {
            case LockMode::NONE:
                $lockClause = ' WITH (NOLOCK)';
                break;
            case LockMode::PESSIMISTIC_READ:
                $lockClause = ' WITH (HOLDLOCK, ROWLOCK)';
                break;
            case LockMode::PESSIMISTIC_WRITE:
                $lockClause = ' WITH (UPDLOCK, ROWLOCK)';
                break;
            default:
                $lockClause = '';
        }

        return $fromClause . $lockClause;
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1367 1368 1369
    }

    /**
1370
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1371 1372 1373 1374 1375
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
1376

1377 1378 1379
    /**
     * {@inheritDoc}
     */
1380 1381
    protected function getReservedKeywordsClass()
    {
1382
        return 'Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords';
1383
    }
1384 1385

    /**
1386
     * {@inheritDoc}
1387
     */
1388
    public function quoteSingleIdentifier($str)
1389
    {
1390
        return "[" . str_replace("]", "][", $str) . "]";
1391
    }
1392

1393 1394 1395
    /**
     * {@inheritDoc}
     */
1396 1397 1398 1399
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
        return 'TRUNCATE TABLE '.$tableName;
    }
1400 1401

    /**
1402
     * {@inheritDoc}
1403 1404 1405 1406 1407
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
1408 1409 1410 1411

    /**
     * {@inheritDoc}
     */
1412 1413
    public function getDefaultValueDeclarationSQL($field)
    {
1414 1415 1416 1417 1418 1419
        if ( ! isset($field['default'])) {
            return empty($field['notnull']) ? ' NULL' : '';
        }

        if ( ! isset($field['type'])) {
            return " DEFAULT '" . $field['default'] . "'";
1420
        }
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434

        if (in_array((string) $field['type'], array('Integer', 'BigInteger', 'SmallInteger'))) {
            return " DEFAULT " . $field['default'];
        }

        if ((string) $field['type'] == 'DateTime' && $field['default'] == $this->getCurrentTimestampSQL()) {
            return " DEFAULT " . $this->getCurrentTimestampSQL();
        }

        if ((string) $field['type'] == 'Boolean') {
            return " DEFAULT '" . $this->convertBooleans($field['default']) . "'";
        }

        return " DEFAULT '" . $field['default'] . "'";
1435
    }
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466

    /**
     * {@inheritdoc}
     */
    public function getColumnCollationDeclarationSQL($collation)
    {
        return 'COLLATE ' . $collation;
    }

    /**
     * {@inheritdoc}
     *
     * Modifies column declaration order as it differs in Microsoft SQL Server.
     */
    public function getColumnDeclarationSQL($name, array $field)
    {
        if (isset($field['columnDefinition'])) {
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
        } else {
            $collation = (isset($field['collate']) && $field['collate']) ?
                ' ' . $this->getColumnCollationDeclarationSQL($field['collate']) : '';

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

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

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

            $typeDecl = $field['type']->getSqlDeclaration($field, $this);
1467
            $columnDef = $typeDecl . $collation . $notnull . $unique . $check;
1468 1469 1470 1471
        }

        return $name . ' ' . $columnDef;
    }
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496

    /**
     * Returns a unique default constraint name for a table and column.
     *
     * @param string $table  Name of the table to generate the unique default constraint name for.
     * @param string $column Name of the column in the table to generate the unique default constraint name for.
     *
     * @return string
     */
    private function generateDefaultConstraintName($table, $column)
    {
        return 'DF_' . $this->generateIdentifierName($table) . '_' . $this->generateIdentifierName($column);
    }

    /**
     * Returns a hash value for a given identifier.
     *
     * @param string $identifier Identifier to generate a hash value for.
     *
     * @return string
     */
    private function generateIdentifierName($identifier)
    {
        return strtoupper(dechex(crc32($identifier)));
    }
1497
}