SQLServerPlatform.php 51.3 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\ColumnDiff;
25
use Doctrine\DBAL\Schema\Identifier;
26
use Doctrine\DBAL\Schema\TableDiff;
27 28 29
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
30 31

/**
32 33
 * The SQLServerPlatform provides the behavior, features and SQL dialect of the
 * Microsoft SQL Server database platform.
34 35 36 37
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 * @author Jonathan H. Wage <jonwage@gmail.com>
38
 * @author Benjamin Eberlei <kontakt@beberlei.de>
39
 * @author Steve Müller <st.mueller@dzh-online.de>
40
 */
41
class SQLServerPlatform extends AbstractPlatform
42
{
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    /**
     * {@inheritdoc}
     */
    public function getCurrentDateSQL()
    {
        return $this->getConvertExpression('date', 'GETDATE()');
    }

    /**
     * {@inheritdoc}
     */
    public function getCurrentTimeSQL()
    {
        return $this->getConvertExpression('time', 'GETDATE()');
    }

    /**
     * Returns an expression that converts an expression of one data type to another.
     *
     * @param string $dataType   The target native data type. Alias data types cannot be used.
     * @param string $expression The SQL expression to convert.
     *
     * @return string
     */
    private function getConvertExpression($dataType, $expression)
    {
        return sprintf('CONVERT(%s, %s)', $dataType, $expression);
    }

72
    /**
73
     * {@inheritdoc}
74
     */
75
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
76
    {
77
        $factorClause = '';
78

79 80 81
        if ('-' === $operator) {
            $factorClause = '-1 * ';
        }
82

83
        return 'DATEADD(' . $unit . ', ' . $factorClause . $interval . ', ' . $date . ')';
84
    }
85

86 87 88
    /**
     * {@inheritDoc}
     */
89
    public function getDateDiffExpression($date1, $date2)
90
    {
91
        return 'DATEDIFF(day, ' . $date2 . ',' . $date1 . ')';
92
    }
93

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

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

    /**
116
     * {@inheritDoc}
117
     */
118
    public function supportsReleaseSavepoints()
119 120 121
    {
        return false;
    }
122

123 124 125 126 127 128 129 130
    /**
     * {@inheritdoc}
     */
    public function supportsSchemas()
    {
        return true;
    }

131 132 133 134 135 136 137 138
    /**
     * {@inheritdoc}
     */
    public function getDefaultSchemaName()
    {
        return 'dbo';
    }

139 140 141 142 143 144 145 146
    /**
     * {@inheritDoc}
     */
    public function supportsColumnCollation()
    {
        return true;
    }

147 148 149 150 151 152 153 154
    /**
     * {@inheritDoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

155
    /**
156
     * {@inheritDoc}
157 158 159 160 161
     */
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }
162

163
    /**
164
     * {@inheritDoc}
165 166 167
     */
    public function getDropDatabaseSQL($name)
    {
168 169 170 171
        return 'DROP DATABASE ' . $name;
    }

    /**
172
     * {@inheritDoc}
173
     */
174
    public function supportsCreateDropDatabase()
175 176
    {
        return false;
177 178
    }

179 180 181 182 183 184 185 186
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

187
    /**
188
     * {@inheritDoc}
189 190 191
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
192 193
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
194 195
        }

196 197
        if (! $table instanceof Table) {
            $table = new Identifier($table);
198 199
        }

200 201 202
        $foreignKey = $foreignKey->getQuotedName($this);
        $table = $table->getQuotedName($this);

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 242 243 244
        foreach ($columns as &$column) {
            if (isset($column['primary']) && $column['primary']) {
                $column['notnull'] = true;
            }
245

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

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

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

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

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

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

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

        $sql[] = $query;
282 283

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

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

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

298
    /**
299
     * {@inheritDoc}
300 301 302 303 304 305 306
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
        $flags = '';
        if ($index->hasFlag('nonclustered')) {
            $flags = ' NONCLUSTERED';
        }
307

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
            throw new \InvalidArgumentException("Incomplete column definition. 'default' required.");
        }

358 359
        $columnName = new Identifier($column['name']);

360 361 362 363
        return
            ' CONSTRAINT ' .
            $this->generateDefaultConstraintName($table, $column['name']) .
            $this->getDefaultValueDeclarationSQL($column) .
364
            ' FOR ' . $columnName->getQuotedName($this);
365 366
    }

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

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

        return $constraint;
    }

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

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

        return $constraint;
    }

393
    /**
394
     * {@inheritDoc}
395 396 397 398 399 400 401 402 403 404
     */
    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
405
        } elseif ($index->hasFlag('nonclustered')) {
406 407 408 409 410 411
            $type .= 'NONCLUSTERED ';
        }

        return $type;
    }

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

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

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

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

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

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

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

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

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

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

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

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

511
            $requireDropDefaultConstraint = $this->alterColumnRequiresDropDefaultConstraint($columnDiff);
512

513 514 515 516 517
            if ($requireDropDefaultConstraint) {
                $queryParts[] = $this->getAlterTableDropDefaultConstraintClause(
                    $diff->name,
                    $columnDiff->oldColumnName
                );
518 519
            }

520 521
            $columnDef = $column->toArray();

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

525 526
            if (isset($columnDef['default']) && ($requireDropDefaultConstraint || $columnDiff->hasChanged('default'))) {
                $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column);
527
            }
528 529
        }

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

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

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

541 542
            // Recreate default constraint with new column name if necessary (for future reference).
            if ($column->getDefault() !== null) {
543 544 545 546
                $queryParts[] = $this->getAlterTableDropDefaultConstraintClause(
                    $diff->name,
                    $oldColumnName->getQuotedName($this)
                );
547
                $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column);
548
            }
549
        }
550

551 552 553
        $tableSql = array();

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
554
            return array_merge($tableSql, $columnSql);
555
        }
556

557
        foreach ($queryParts as $query) {
558
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
559
        }
560

561
        $sql = array_merge($sql, $commentsSql);
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
562

563
        if ($diff->newName !== false) {
564
            $sql[] = "sp_RENAME '" . $diff->getName($this)->getQuotedName($this) . "', '" . $diff->getNewName()->getName() . "'";
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

            /**
             * 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 " .
580
                "WHERE tbl.name = '" . $diff->getNewName()->getName() . "';" .
581
                "EXEC sp_executesql @sql";
582 583
        }

584 585 586 587 588 589
        $sql = array_merge(
            $this->getPreAlterTableIndexForeignKeySQL($diff),
            $sql,
            $this->getPostAlterTableIndexForeignKeySQL($diff)
        );

590
        return array_merge($sql, $tableSql, $columnSql);
591
    }
592

593 594 595
    /**
     * Returns the SQL clause for adding a default constraint in an ALTER TABLE statement.
     *
596 597
     * @param string $tableName The name of the table to generate the clause for.
     * @param Column $column    The column to generate the clause for.
598 599 600 601 602 603 604 605 606 607 608 609 610 611
     *
     * @return string
     */
    private function getAlterTableAddDefaultConstraintClause($tableName, Column $column)
    {
        $columnDef = $column->toArray();
        $columnDef['name'] = $column->getQuotedName($this);

        return 'ADD' . $this->getDefaultConstraintDeclarationSQL($tableName, $columnDef);
    }

    /**
     * Returns the SQL clause for dropping an existing default constraint in an ALTER TABLE statement.
     *
612 613
     * @param string $tableName  The name of the table to generate the clause for.
     * @param string $columnName The name of the column to generate the clause for.
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
     *
     * @return string
     */
    private function getAlterTableDropDefaultConstraintClause($tableName, $columnName)
    {
        return 'DROP CONSTRAINT ' . $this->generateDefaultConstraintName($tableName, $columnName);
    }

    /**
     * Checks whether a column alteration requires dropping its default constraint first.
     *
     * Different to other database vendors SQL Server implements column default values
     * as constraints and therefore changes in a column's default value as well as changes
     * in a column's type require dropping the default constraint first before being to
     * alter the particular column to the new definition.
     *
630
     * @param ColumnDiff $columnDiff The column diff to evaluate.
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 661 662
     *
     * @return boolean True if the column alteration requires dropping its default constraint first, false otherwise.
     */
    private function alterColumnRequiresDropDefaultConstraint(ColumnDiff $columnDiff)
    {
        // We can only decide whether to drop an existing default constraint
        // if we know the original default value.
        if ( ! $columnDiff->fromColumn instanceof Column) {
            return false;
        }

        // We only need to drop an existing default constraint if we know the
        // column was defined with a default value before.
        if ($columnDiff->fromColumn->getDefault() === null) {
            return false;
        }

        // We need to drop an existing default constraint if the column was
        // defined with a default value before and it has changed.
        if ($columnDiff->hasChanged('default')) {
            return true;
        }

        // We need to drop an existing default constraint if the column was
        // defined with a default value before and the native column type has changed.
        if ($columnDiff->hasChanged('type') || $columnDiff->hasChanged('fixed')) {
            return true;
        }

        return false;
    }

663 664 665 666 667 668 669 670 671 672 673 674 675 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
    /**
     * 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
        );
    }

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    /**
     * {@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)
            )
        );
    }

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
    /**
     * 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 " .
765 766 767 768
            "N" . $this->quoteStringLiteral($name) . ", N" . $this->quoteStringLiteral($value) . ", " .
            "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' .
            "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' .
            "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    }

    /**
     * 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 " .
796 797 798 799
            "N" . $this->quoteStringLiteral($name) . ", " .
            "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' .
            "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' .
            "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    }

    /**
     * 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 " .
829 830 831 832
        "N" . $this->quoteStringLiteral($name) . ", N" . $this->quoteStringLiteral($value) . ", " .
        "N" . $this->quoteStringLiteral($level0Type) . ", " . $level0Name . ', ' .
        "N" . $this->quoteStringLiteral($level1Type) . ", " . $level1Name . ', ' .
        "N" . $this->quoteStringLiteral($level2Type) . ", " . $level2Name;
833 834
    }

835
    /**
836
     * {@inheritDoc}
837
     */
838
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
839
    {
840
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
841 842
    }

843
    /**
844
     * {@inheritDoc}
845
     */
846
    public function getListTablesSQL()
847
    {
848
        // "sysdiagrams" table must be ignored as it's internal SQL Server table for Database Diagrams
849 850
        // Category 2 must be ignored as it is "MS SQL Server 'pseudo-system' object[s]" for replication
        return "SELECT name FROM sysobjects WHERE type = 'U' AND name != 'sysdiagrams' AND category != 2 ORDER BY name";
851 852 853
    }

    /**
854
     * {@inheritDoc}
855
     */
856
    public function getListTableColumnsSQL($table, $database = null)
857
    {
858 859 860 861 862 863 864 865
        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,
866 867
                          col.collation_name AS collation,
                          CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
868 869 870 871 872
                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
873 874
                JOIN      sys.schemas AS scm
                ON        obj.schema_id = scm.schema_id
875 876 877
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
878 879 880 881
                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'
882
                WHERE     obj.type = 'U'
883
                AND       " . $this->getTableWhereClause($table, 'scm.name', 'obj.name');
884 885 886
    }

    /**
887
     * {@inheritDoc}
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
     */
    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
904 905
                WHERE " .
                $this->getTableWhereClause($table, 'SCHEMA_NAME (f.schema_id)', 'OBJECT_NAME (f.parent_object_id)');
906 907 908
    }

    /**
909
     * {@inheritDoc}
910
     */
911
    public function getListTableIndexesSQL($table, $currentDatabase = null)
912
    {
913 914
        return "SELECT idx.name AS key_name,
                       col.name AS column_name,
Steve Müller's avatar
Steve Müller committed
915 916
                       ~idx.is_unique AS non_unique,
                       idx.is_primary_key AS [primary],
917 918 919 920 921 922
                       CASE idx.type
                           WHEN '1' THEN 'clustered'
                           WHEN '2' THEN 'nonclustered'
                           ELSE NULL
                       END AS flags
                FROM sys.tables AS tbl
923
                JOIN sys.schemas AS scm ON tbl.schema_id = scm.schema_id
924 925 926
                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
927
                WHERE " . $this->getTableWhereClause($table, 'scm.name', 'tbl.name') . "
928
                ORDER BY idx.index_id ASC, idxcol.key_ordinal ASC";
929
    }
930 931

    /**
932
     * {@inheritDoc}
933
     */
934
    public function getCreateViewSQL($name, $sql)
935 936 937
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
938 939

    /**
940
     * {@inheritDoc}
941
     */
942
    public function getListViewsSQL($database)
943 944 945 946
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

947 948 949 950
    /**
     * Returns the where clause to filter schema and table name in a query.
     *
     * @param string $table        The full qualified name of the table.
951 952
     * @param string $schemaColumn The name of the column to compare the schema to in the where clause.
     * @param string $tableColumn  The name of the column to compare the table to in the where clause.
953 954 955 956 957 958 959
     *
     * @return string
     */
    private function getTableWhereClause($table, $schemaColumn, $tableColumn)
    {
        if (strpos($table, ".") !== false) {
            list($schema, $table) = explode(".", $table);
960 961
            $schema = $this->quoteStringLiteral($schema);
            $table = $this->quoteStringLiteral($table);
962 963
        } else {
            $schema = "SCHEMA_NAME()";
964
            $table = $this->quoteStringLiteral($table);
965 966
        }

967
        return "({$tableColumn} = {$table} AND {$schemaColumn} = {$schema})";
968 969
    }

970
    /**
971
     * {@inheritDoc}
972 973 974
     */
    public function getDropViewSQL($name)
    {
975
        return 'DROP VIEW ' . $name;
976
    }
977 978

    /**
979
     * {@inheritDoc}
980 981 982
     */
    public function getGuidExpression()
    {
983
        return 'NEWID()';
984
    }
985 986

    /**
987
     * {@inheritDoc}
988
     */
989
    public function getLocateExpression($str, $substr, $startPos = false)
990
    {
991 992 993
        if ($startPos == false) {
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        }
994 995

        return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
996
    }
997

998
    /**
999
     * {@inheritDoc}
1000
     */
1001
    public function getModExpression($expression1, $expression2)
1002
    {
1003
        return $expression1 . ' % ' . $expression2;
1004
    }
1005

1006
    /**
1007
     * {@inheritDoc}
1008
     */
1009
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
1010
    {
1011
        if ( ! $char) {
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            switch ($pos) {
                case self::TRIM_LEADING:
                    $trimFn = 'LTRIM';
                    break;

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

                default:
                    return 'LTRIM(RTRIM(' . $str . '))';
1023 1024 1025 1026
            }

            return $trimFn . '(' . $str . ')';
        }
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

        /** 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))';
1048
    }
1049

1050
    /**
1051
     * {@inheritDoc}
1052 1053
     */
    public function getConcatExpression()
1054
    {
1055
        $args = func_get_args();
1056

1057
        return '(' . implode(' + ', $args) . ')';
1058
    }
1059

Benjamin Morel's avatar
Benjamin Morel committed
1060 1061 1062
    /**
     * {@inheritDoc}
     */
1063
    public function getListDatabasesSQL()
1064
    {
1065
        return 'SELECT * FROM sys.databases';
1066
    }
1067

1068 1069 1070 1071 1072
    /**
     * {@inheritDoc}
     */
    public function getListNamespacesSQL()
    {
1073
        return "SELECT name FROM sys.schemas WHERE name NOT IN('guest', 'INFORMATION_SCHEMA', 'sys')";
1074 1075
    }

1076
    /**
1077
     * {@inheritDoc}
1078
     */
1079
    public function getSubstringExpression($value, $from, $length = null)
1080
    {
1081 1082
        if (!is_null($length)) {
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
1083
        }
1084

1085
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
1086
    }
1087

1088
    /**
1089
     * {@inheritDoc}
1090
     */
1091
    public function getLengthExpression($column)
1092
    {
1093
        return 'LEN(' . $column . ')';
1094 1095
    }

1096
    /**
1097
     * {@inheritDoc}
1098
     */
1099
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
1100
    {
1101
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
1102
    }
1103

1104
    /**
1105
     * {@inheritDoc}
1106
     */
1107
    public function getIntegerTypeDeclarationSQL(array $field)
1108
    {
1109
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1110 1111
    }

1112
    /**
1113
     * {@inheritDoc}
1114
     */
1115
    public function getBigIntTypeDeclarationSQL(array $field)
1116
    {
1117
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1118 1119
    }

1120
    /**
1121
     * {@inheritDoc}
1122
     */
1123
    public function getSmallIntTypeDeclarationSQL(array $field)
1124
    {
1125
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1126 1127
    }

1128
    /**
1129
     * {@inheritDoc}
1130
     */
1131
    public function getGuidTypeDeclarationSQL(array $field)
1132 1133 1134 1135
    {
        return 'UNIQUEIDENTIFIER';
    }

1136 1137 1138
    /**
     * {@inheritDoc}
     */
1139
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1140
    {
1141
        return $fixed ? ($length ? 'NCHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
1142
    }
1143

Steve Müller's avatar
Steve Müller committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
    }

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

1160 1161 1162
    /**
     * {@inheritDoc}
     */
1163
    public function getClobTypeDeclarationSQL(array $field)
1164
    {
1165
        return 'VARCHAR(MAX)';
1166
    }
1167

1168
    /**
1169
     * {@inheritDoc}
1170
     */
1171
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1172
    {
1173
        return (!empty($columnDef['autoincrement'])) ? ' IDENTITY' : '';
1174
    }
1175

1176
    /**
1177
     * {@inheritDoc}
1178
     */
1179
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
1180
    {
1181
        return 'DATETIME';
1182 1183
    }

1184
    /**
1185
     * {@inheritDoc}
1186
     */
1187
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
1188
    {
1189
        return 'DATETIME';
1190
    }
1191 1192

    /**
1193
     * {@inheritDoc}
1194
     */
1195
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1196
    {
1197
        return 'DATETIME';
1198
    }
1199

1200
    /**
1201
     * {@inheritDoc}
1202
     */
1203
    public function getBooleanTypeDeclarationSQL(array $field)
1204 1205 1206 1207
    {
        return 'BIT';
    }

1208
    /**
1209
     * {@inheritDoc}
1210
     */
1211
    protected function doModifyLimitQuery($query, $limit, $offset = null)
1212
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
1213
        if ($limit === null) {
Fabio B. Silva's avatar
Fabio B. Silva committed
1214 1215
            return $query;
        }
1216

Fabio B. Silva's avatar
Fabio B. Silva committed
1217 1218
        $start   = $offset + 1;
        $end     = $offset + $limit;
1219

1220
        // We'll find a SELECT or SELECT distinct and prepend TOP n to it
1221 1222 1223
        // Even if the TOP n is very large, the use of a CTE will
        // allow the SQL Server query planner to optimize it so it doesn't
        // actually scan the entire range covered by the TOP clause.
1224
        $selectPattern = '/^(\s*SELECT\s+(?:DISTINCT\s+)?)(.*)$/i';
1225 1226 1227 1228 1229
        $replacePattern = sprintf('$1%s $2', "TOP $end");
        $query = preg_replace($selectPattern, $replacePattern, $query);

        if (stristr($query, "ORDER BY")) {
            // Inner order by is not valid in SQL Server for our purposes
1230
            // unless it's in a TOP N subquery.
1231
            $query = $this->scrubInnerOrderBy($query);
Fabio B. Silva's avatar
Fabio B. Silva committed
1232 1233
        }

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
        // Build a new limited query around the original, using a CTE
        return sprintf(
            "WITH dctrn_cte AS (%s) "
            . "SELECT * FROM ("
            . "SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS doctrine_rownum FROM dctrn_cte"
            . ") AS doctrine_tbl "
            . "WHERE doctrine_rownum BETWEEN %d AND %d ORDER BY doctrine_rownum ASC",
            $query,
            $start,
            $end
        );
    }
1246

1247 1248
    /**
     * Remove ORDER BY clauses in subqueries - they're not supported by SQL Server.
1249
     * Caveat: will leave ORDER BY in TOP N subqueries.
1250 1251 1252 1253
     *
     * @param $query
     * @return string
     */
Bill Schaller's avatar
Bill Schaller committed
1254 1255
    private function scrubInnerOrderBy($query)
    {
1256
        $count = substr_count(strtoupper($query), 'ORDER BY');
1257
        $offset = 0;
Bill Schaller's avatar
Bill Schaller committed
1258

1259
        while ($count-- > 0) {
1260
            $orderByPos = stripos($query, ' ORDER BY', $offset);
1261 1262 1263 1264 1265
            if ($orderByPos === false) {
                break;
            }

            $qLen = strlen($query);
1266 1267
            $parenCount = 0;
            $currentPosition = $orderByPos;
1268

1269
            while ($parenCount >= 0 && $currentPosition < $qLen) {
1270
                if ($query[$currentPosition] === '(') {
1271
                    $parenCount++;
1272
                } elseif ($query[$currentPosition] === ')') {
1273
                    $parenCount--;
Fabio B. Silva's avatar
Fabio B. Silva committed
1274
                }
1275

1276 1277
                $currentPosition++;
            }
1278 1279 1280 1281 1282 1283 1284 1285

            if ($this->isOrderByInTopNSubquery($query, $orderByPos)) {
                // If the order by clause is in a TOP N subquery, do not remove
                // it and continue iteration from the current position.
                $offset = $currentPosition;
                continue;
            }

1286 1287
            if ($currentPosition < $qLen - 1) {
                $query = substr($query, 0, $orderByPos) . substr($query, $currentPosition - 1);
1288
                $offset = $orderByPos;
Fabio B. Silva's avatar
Fabio B. Silva committed
1289
            }
1290
        }
1291
        return $query;
1292
    }
1293

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    /**
     * Check an ORDER BY clause to see if it is in a TOP N query or subquery.
     *
     * @param string $query The query
     * @param int $currentPosition Start position of ORDER BY clause
     * @return bool true if ORDER BY is in a TOP N query, false otherwise
     */
    private function isOrderByInTopNSubquery($query, $currentPosition)
    {
        // Grab query text on the same nesting level as the ORDER BY clause we're examining.
        $subQueryBuffer = '';
        $parenCount = 0;

Bill Schaller's avatar
Bill Schaller committed
1307
        // If $parenCount goes negative, we've exited the subquery we're examining.
1308 1309
        // If $currentPosition goes negative, we've reached the beginning of the query.
        while ($parenCount >= 0 && $currentPosition >= 0) {
1310
            if ($query[$currentPosition] === '(') {
1311
                $parenCount--;
Bill Schaller's avatar
Bill Schaller committed
1312
            } elseif ($query[$currentPosition] === ')') {
1313 1314
                $parenCount++;
            }
1315 1316

            // Only yank query text on the same nesting level as the ORDER BY clause.
1317
            $subQueryBuffer = ($parenCount === 0 ? $query[$currentPosition] : ' ') . $subQueryBuffer;
1318 1319 1320 1321

            $currentPosition--;
        }

1322
        if (preg_match('/SELECT\s+(DISTINCT\s+)?TOP\s/i', $subQueryBuffer)) {
1323 1324 1325 1326 1327 1328
            return true;
        }

        return false;
    }

1329
    /**
1330
     * {@inheritDoc}
1331 1332 1333 1334 1335 1336
     */
    public function supportsLimitOffset()
    {
        return false;
    }

1337
    /**
1338
     * {@inheritDoc}
1339
     */
1340
    public function convertBooleans($item)
1341
    {
1342 1343 1344
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
1345
                    $item[$key] = ($value) ? 1 : 0;
1346 1347
                }
            }
Steve Müller's avatar
Steve Müller committed
1348
        } elseif (is_bool($item) || is_numeric($item)) {
1349
            $item = ($item) ? 1 : 0;
1350
        }
1351

1352
        return $item;
1353
    }
1354 1355

    /**
1356
     * {@inheritDoc}
1357
     */
1358
    public function getCreateTemporaryTableSnippetSQL()
1359
    {
1360
        return "CREATE TABLE";
1361
    }
1362

1363
    /**
1364
     * {@inheritDoc}
1365 1366 1367 1368 1369 1370
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

1371
    /**
1372
     * {@inheritDoc}
1373 1374 1375
     */
    public function getDateTimeFormatString()
    {
1376 1377
        return 'Y-m-d H:i:s.000';
    }
1378

1379
    /**
1380
     * {@inheritDoc}
1381
     */
1382 1383 1384 1385 1386 1387
    public function getDateFormatString()
    {
        return 'Y-m-d H:i:s.000';
    }

    /**
1388
     * {@inheritDoc}
1389
     */
1390 1391 1392
    public function getTimeFormatString()
    {
        return 'Y-m-d H:i:s.000';
1393
    }
1394

1395
    /**
1396
     * {@inheritDoc}
1397 1398 1399 1400 1401
     */
    public function getDateTimeTzFormatString()
    {
        return $this->getDateTimeFormatString();
    }
1402

1403
    /**
1404
     * {@inheritDoc}
1405
     */
1406
    public function getName()
1407
    {
1408
        return 'mssql';
1409
    }
1410

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1411
    /**
1412
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1413
     */
1414 1415
    protected function initializeDoctrineTypeMappings()
    {
1416
        $this->doctrineTypeMapping = array(
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
            '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
1438 1439
            'binary' => 'binary',
            'varbinary' => 'binary',
1440
            'image' => 'blob',
1441
            'uniqueidentifier' => 'guid',
1442
        );
1443
    }
1444 1445

    /**
1446
     * {@inheritDoc}
1447 1448 1449 1450 1451 1452 1453
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
1454
     * {@inheritDoc}
1455 1456 1457 1458 1459 1460 1461
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
1462
     * {@inheritDoc}
1463 1464 1465 1466
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
1467
    }
1468

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    /**
     * {@inheritdoc}
     */
    public function getForeignKeyReferentialActionSQL($action)
    {
        // RESTRICT is not supported, therefore falling back to NO ACTION.
        if (strtoupper($action) === 'RESTRICT') {
            return 'NO ACTION';
        }

        return parent::getForeignKeyReferentialActionSQL($action);
    }

1482
    /**
1483
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1484
     */
1485
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1486
    {
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        switch (true) {
            case LockMode::NONE === $lockMode:
                return $fromClause . ' WITH (NOLOCK)';

            case LockMode::PESSIMISTIC_READ === $lockMode:
                return $fromClause . ' WITH (HOLDLOCK, ROWLOCK)';

            case LockMode::PESSIMISTIC_WRITE === $lockMode:
                return $fromClause . ' WITH (UPDLOCK, ROWLOCK)';

Steve Müller's avatar
Steve Müller committed
1497
            default:
1498
                return $fromClause;
Steve Müller's avatar
Steve Müller committed
1499
        }
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1500 1501 1502
    }

    /**
1503
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1504 1505 1506 1507 1508
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
1509

1510 1511 1512
    /**
     * {@inheritDoc}
     */
1513 1514
    protected function getReservedKeywordsClass()
    {
1515
        return 'Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords';
1516
    }
1517 1518

    /**
1519
     * {@inheritDoc}
1520
     */
1521
    public function quoteSingleIdentifier($str)
1522
    {
1523
        return "[" . str_replace("]", "][", $str) . "]";
1524
    }
1525

1526 1527 1528
    /**
     * {@inheritDoc}
     */
1529 1530
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
1531 1532 1533
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1534
    }
1535 1536

    /**
1537
     * {@inheritDoc}
1538 1539 1540 1541 1542
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
1543 1544 1545 1546

    /**
     * {@inheritDoc}
     */
1547 1548
    public function getDefaultValueDeclarationSQL($field)
    {
1549 1550 1551 1552 1553 1554
        if ( ! isset($field['default'])) {
            return empty($field['notnull']) ? ' NULL' : '';
        }

        if ( ! isset($field['type'])) {
            return " DEFAULT '" . $field['default'] . "'";
1555
        }
1556

1557
        if (in_array((string) $field['type'], array('Integer', 'BigInt', 'SmallInt'))) {
1558 1559 1560
            return " DEFAULT " . $field['default'];
        }

1561
        if (in_array((string) $field['type'], array('DateTime', 'DateTimeTz')) && $field['default'] == $this->getCurrentTimestampSQL()) {
1562 1563 1564 1565 1566 1567 1568 1569
            return " DEFAULT " . $this->getCurrentTimestampSQL();
        }

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

        return " DEFAULT '" . $field['default'] . "'";
1570
    }
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581

    /**
     * {@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 {
1582 1583
            $collation = (isset($field['collation']) && $field['collation']) ?
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

            $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);
1594
            $columnDef = $typeDecl . $collation . $notnull . $unique . $check;
1595 1596 1597 1598
        }

        return $name . ' ' . $columnDef;
    }
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621

    /**
     * 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)
    {
1622 1623 1624 1625
        // Always generate name for unquoted identifiers to ensure consistency.
        $identifier = new Identifier($identifier);

        return strtoupper(dechex(crc32($identifier->getName())));
1626
    }
1627
}