SQLServer2012Platform.php 52.5 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Platforms;
4

5
use Doctrine\DBAL\LockMode;
6
use Doctrine\DBAL\Schema\Column;
7
use Doctrine\DBAL\Schema\ColumnDiff;
8
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
9
use Doctrine\DBAL\Schema\Identifier;
10
use Doctrine\DBAL\Schema\Index;
11
use Doctrine\DBAL\Schema\Sequence;
12
use Doctrine\DBAL\Schema\Table;
13
use Doctrine\DBAL\Schema\TableDiff;
14
use InvalidArgumentException;
15
use const PREG_OFFSET_CAPTURE;
16 17 18 19 20 21
use function array_merge;
use function array_unique;
use function array_values;
use function count;
use function crc32;
use function dechex;
22
use function explode;
23
use function func_get_args;
24
use function implode;
25 26 27 28 29
use function is_array;
use function is_bool;
use function is_numeric;
use function is_string;
use function preg_match;
30
use function preg_match_all;
31
use function sprintf;
32
use function str_replace;
33
use function strpos;
34 35
use function strtoupper;
use function substr_count;
36 37

/**
38
 * Provides the behavior, features and SQL dialect of the Microsoft SQL Server 2012 database platform.
39
 */
40
class SQLServer2012Platform extends AbstractPlatform
41
{
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
    /**
     * {@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);
    }

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

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

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

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

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

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

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

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

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

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

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    /**
     * {@inheritdoc}
     */
    public function supportsSequences() : bool
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getAlterSequenceSQL(Sequence $sequence) : string
    {
        return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
            ' INCREMENT BY ' . $sequence->getAllocationSize();
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateSequenceSQL(Sequence $sequence) : string
    {
        return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
            ' START WITH ' . $sequence->getInitialValue() .
            ' INCREMENT BY ' . $sequence->getAllocationSize() .
            ' MINVALUE ' . $sequence->getInitialValue();
    }

    /**
     * {@inheritdoc}
     */
    public function getDropSequenceSQL($sequence) : string
    {
        if ($sequence instanceof Sequence) {
            $sequence = $sequence->getQuotedName($this);
        }

        return 'DROP SEQUENCE ' . $sequence;
    }

    /**
     * {@inheritdoc}
     */
    public function getListSequencesSQL($database)
    {
        return 'SELECT seq.name,
                       CAST(
                           seq.increment AS VARCHAR(MAX)
                       ) AS increment, -- CAST avoids driver error for sql_variant type
                       CAST(
                           seq.start_value AS VARCHAR(MAX)
                       ) AS start_value -- CAST avoids driver error for sql_variant type
                FROM   sys.sequences AS seq';
    }

    /**
     * {@inheritdoc}
     */
    public function getSequenceNextValSQL($sequenceName)
    {
        return 'SELECT NEXT VALUE FOR ' . $sequenceName;
    }

209 210 211 212 213 214 215 216
    /**
     * {@inheritDoc}
     */
    public function hasNativeGuidType()
    {
        return true;
    }

217
    /**
218
     * {@inheritDoc}
219 220 221 222 223
     */
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }
224

225
    /**
226
     * {@inheritDoc}
227 228 229
     */
    public function getDropDatabaseSQL($name)
    {
230 231 232 233
        return 'DROP DATABASE ' . $name;
    }

    /**
234
     * {@inheritDoc}
235
     */
236
    public function supportsCreateDropDatabase()
237
    {
238
        return true;
239 240
    }

241 242 243 244 245 246 247 248
    /**
     * {@inheritDoc}
     */
    public function getCreateSchemaSQL($schemaName)
    {
        return 'CREATE SCHEMA ' . $schemaName;
    }

249
    /**
250
     * {@inheritDoc}
251 252 253
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
254 255
        if (! $foreignKey instanceof ForeignKeyConstraint) {
            $foreignKey = new Identifier($foreignKey);
256 257
        }

258 259
        if (! $table instanceof Table) {
            $table = new Identifier($table);
260 261
        }

262
        $foreignKey = $foreignKey->getQuotedName($this);
263
        $table      = $table->getQuotedName($this);
264

265
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
266
    }
267 268

    /**
269
     * {@inheritDoc}
270
     */
271
    public function getDropIndexSQL($index, $table = null)
272
    {
273
        if ($index instanceof Index) {
274
            $index = $index->getQuotedName($this);
275 276
        } elseif (! is_string($index)) {
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
277 278
        }

279
        if (! isset($table)) {
280
            return 'DROP INDEX ' . $index;
281
        }
282

283 284
        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
285
        }
286

287 288 289 290 291 292 293 294 295 296 297 298 299 300
        return sprintf(
            <<<SQL
IF EXISTS (SELECT * FROM sysobjects WHERE name = '%s')
    ALTER TABLE %s DROP CONSTRAINT %s
ELSE
    DROP INDEX %s ON %s
SQL
            ,
            $index,
            $table,
            $index,
            $index,
            $table
        );
301
    }
302 303

    /**
304
     * {@inheritDoc}
305
     */
306
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
307
    {
308 309
        $defaultConstraintsSql = [];
        $commentsSql           = [];
310

311 312 313 314 315
        $tableComment = $options['comment'] ?? null;
        if ($tableComment !== null) {
            $commentsSql[] = $this->getCommentOnTableSQL($tableName, $tableComment);
        }

316
        // @todo does other code breaks because of this?
317
        // force primary keys to be not null
318
        foreach ($columns as &$column) {
319
            if (! empty($column['primary'])) {
320 321
                $column['notnull'] = true;
            }
322

323
            // Build default constraints SQL statements.
324
            if (isset($column['default'])) {
325 326 327
                $defaultConstraintsSql[] = 'ALTER TABLE ' . $tableName .
                    ' ADD' . $this->getDefaultConstraintDeclarationSQL($tableName, $column);
            }
328

329 330
            if (empty($column['comment']) && ! is_numeric($column['comment'])) {
                continue;
331
            }
332 333

            $commentsSql[] = $this->getCreateColumnCommentSQL($tableName, $column['name'], $column['comment']);
334 335
        }

336
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
337

338
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
339 340 341 342
            foreach ($options['uniqueConstraints'] as $name => $definition) {
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }
343

344
        if (isset($options['primary']) && ! empty($options['primary'])) {
345 346 347 348 349
            $flags = '';
            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('nonclustered')) {
                $flags = ' NONCLUSTERED';
            }
            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values($options['primary']))) . ')';
350 351 352 353 354
        }

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

        $check = $this->getCheckDeclarationSQL($columns);
355
        if (! empty($check)) {
356 357 358 359
            $query .= ', ' . $check;
        }
        $query .= ')';

360
        $sql = [$query];
361

362
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
363
            foreach ($options['indexes'] as $index) {
364 365 366 367 368
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
            }
        }

        if (isset($options['foreignKeys'])) {
369
            foreach ((array) $options['foreignKeys'] as $definition) {
370 371 372 373
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }

374
        return array_merge($sql, $commentsSql, $defaultConstraintsSql);
375
    }
376

377
    /**
378
     * {@inheritDoc}
379 380 381
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
Sergei Morozov's avatar
Sergei Morozov committed
382 383 384 385 386 387 388 389
        if ($table instanceof Table) {
            $identifier = $table->getQuotedName($this);
        } else {
            $identifier = $table;
        }

        $sql = 'ALTER TABLE ' . $identifier . ' ADD PRIMARY KEY';

390
        if ($index->hasFlag('nonclustered')) {
Sergei Morozov's avatar
Sergei Morozov committed
391
            $sql .= ' NONCLUSTERED';
392
        }
393

Sergei Morozov's avatar
Sergei Morozov committed
394
        return $sql . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
395 396
    }

397 398 399 400 401 402 403 404 405 406 407
    /**
     * 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.
     *
Sergei Morozov's avatar
Sergei Morozov committed
408 409 410
     * @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|null $comment    The column's comment.
411 412 413 414 415
     *
     * @return string
     */
    protected function getCreateColumnCommentSQL($tableName, $columnName, $comment)
    {
416 417 418 419 420 421 422 423 424
        if (strpos($tableName, '.') !== false) {
            [$schemaSQL, $tableSQL] = explode('.', $tableName);
            $schemaSQL              = $this->quoteStringLiteral($schemaSQL);
            $tableSQL               = $this->quoteStringLiteral($tableSQL);
        } else {
            $schemaSQL = "'dbo'";
            $tableSQL  = $this->quoteStringLiteral($tableName);
        }

425 426 427 428
        return $this->getAddExtendedPropertySQL(
            'MS_Description',
            $comment,
            'SCHEMA',
429
            $schemaSQL,
430
            'TABLE',
431
            $tableSQL,
432 433 434 435 436
            'COLUMN',
            $columnName
        );
    }

437 438 439
    /**
     * Returns the SQL snippet for declaring a default constraint.
     *
440 441
     * @param string  $table  Name of the table to return the default constraint declaration for.
     * @param mixed[] $column Column definition.
442 443 444
     *
     * @return string
     *
445
     * @throws InvalidArgumentException
446 447 448
     */
    public function getDefaultConstraintDeclarationSQL($table, array $column)
    {
449 450
        if (! isset($column['default'])) {
            throw new InvalidArgumentException("Incomplete column definition. 'default' required.");
451 452
        }

453 454
        $columnName = new Identifier($column['name']);

455
        return ' CONSTRAINT ' .
456 457
            $this->generateDefaultConstraintName($table, $column['name']) .
            $this->getDefaultValueDeclarationSQL($column) .
458
            ' FOR ' . $columnName->getQuotedName($this);
459 460
    }

461
    /**
462
     * {@inheritDoc}
463
     */
464
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
465 466
    {
        $constraint = parent::getUniqueConstraintDeclarationSQL($name, $index);
467 468 469 470 471 472 473

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

        return $constraint;
    }

    /**
474
     * {@inheritDoc}
475 476 477 478 479
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
        $constraint = parent::getCreateIndexSQL($index, $table);

480
        if ($index->isUnique() && ! $index->isPrimary()) {
481 482 483 484 485 486
            $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);
        }

        return $constraint;
    }

487
    /**
488
     * {@inheritDoc}
489 490 491 492 493 494 495 496 497 498
     */
    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
499
        } elseif ($index->hasFlag('nonclustered')) {
500 501 502 503 504 505
            $type .= 'NONCLUSTERED ';
        }

        return $type;
    }

506
    /**
507
     * Extend unique key constraint with required filters
508
     *
509
     * @param string $sql
510
     *
511 512 513 514
     * @return string
     */
    private function _appendUniqueConstraintDefinition($sql, Index $index)
    {
515
        $fields = [];
516

517
        foreach ($index->getQuotedColumns($this) as $field) {
518
            $fields[] = $field . ' IS NOT NULL';
519
        }
520 521 522

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

524
    /**
525
     * {@inheritDoc}
526
     */
527
    public function getAlterTableSQL(TableDiff $diff)
528
    {
529 530 531 532
        $queryParts  = [];
        $sql         = [];
        $columnSql   = [];
        $commentsSql = [];
533

534
        foreach ($diff->addedColumns as $column) {
535 536
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
537 538
            }

539
            $columnDef    = $column->toArray();
540 541
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

542
            if (isset($columnDef['default'])) {
543
                $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column);
544
            }
545 546 547

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

548 549
            if (empty($comment) && ! is_numeric($comment)) {
                continue;
550
            }
551 552 553 554 555 556

            $commentsSql[] = $this->getCreateColumnCommentSQL(
                $diff->name,
                $column->getQuotedName($this),
                $comment
            );
557 558
        }

559
        foreach ($diff->removedColumns as $column) {
560 561
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
562 563
            }

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

567
        foreach ($diff->changedColumns as $columnDiff) {
568 569
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
570 571
            }

572 573
            $column     = $columnDiff->column;
            $comment    = $this->getColumnComment($column);
574
            $hasComment = ! empty($comment) || is_numeric($comment);
575 576 577

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

580
                if ($hasFromComment && $hasComment && $fromComment !== $comment) {
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
                    $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
                    );
                }
            }

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

602
            $requireDropDefaultConstraint = $this->alterColumnRequiresDropDefaultConstraint($columnDiff);
603

604 605 606 607 608
            if ($requireDropDefaultConstraint) {
                $queryParts[] = $this->getAlterTableDropDefaultConstraintClause(
                    $diff->name,
                    $columnDiff->oldColumnName
                );
609 610
            }

611 612
            $columnDef = $column->toArray();

613
            $queryParts[] = 'ALTER COLUMN ' .
614 615
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

616 617
            if (! isset($columnDef['default']) || (! $requireDropDefaultConstraint && ! $columnDiff->hasChanged('default'))) {
                continue;
618
            }
619 620

            $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column);
621 622
        }

623
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
624 625
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
626 627
            }

628 629
            $oldColumnName = new Identifier($oldColumnName);

630
            $sql[] = "sp_RENAME '" .
631
                $diff->getName($this)->getQuotedName($this) . '.' . $oldColumnName->getQuotedName($this) .
632
                "', '" . $column->getQuotedName($this) . "', 'COLUMN'";
633

634
            // Recreate default constraint with new column name if necessary (for future reference).
635 636
            if ($column->getDefault() === null) {
                continue;
637
            }
638 639 640 641 642 643

            $queryParts[] = $this->getAlterTableDropDefaultConstraintClause(
                $diff->name,
                $oldColumnName->getQuotedName($this)
            );
            $queryParts[] = $this->getAlterTableAddDefaultConstraintClause($diff->name, $column);
644
        }
645

646
        $tableSql = [];
647 648

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
649
            return array_merge($tableSql, $columnSql);
650
        }
651

652
        foreach ($queryParts as $query) {
653
            $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . $query;
654
        }
655

656
        $sql = array_merge($sql, $commentsSql);
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
657

Sergei Morozov's avatar
Sergei Morozov committed
658 659 660 661
        $newName = $diff->getNewName();

        if ($newName !== false) {
            $sql[] = "sp_RENAME '" . $diff->getName($this)->getQuotedName($this) . "', '" . $newName->getName() . "'";
662 663 664 665 666 667 668 669 670 671 672 673

            /**
             * 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) . "', " .
Sergei Morozov's avatar
Sergei Morozov committed
674
                "'" . $this->generateIdentifierName($newName->getName()) . "') + ''', ''OBJECT'';' " .
675 676
                'FROM sys.default_constraints dc ' .
                'JOIN sys.tables tbl ON dc.parent_object_id = tbl.object_id ' .
Sergei Morozov's avatar
Sergei Morozov committed
677
                "WHERE tbl.name = '" . $newName->getName() . "';" .
678
                'EXEC sp_executesql @sql';
679 680
        }

681 682 683 684 685 686
        $sql = array_merge(
            $this->getPreAlterTableIndexForeignKeySQL($diff),
            $sql,
            $this->getPostAlterTableIndexForeignKeySQL($diff)
        );

687
        return array_merge($sql, $tableSql, $columnSql);
688
    }
689

690 691 692
    /**
     * Returns the SQL clause for adding a default constraint in an ALTER TABLE statement.
     *
693 694
     * @param string $tableName The name of the table to generate the clause for.
     * @param Column $column    The column to generate the clause for.
695 696 697 698 699
     *
     * @return string
     */
    private function getAlterTableAddDefaultConstraintClause($tableName, Column $column)
    {
700
        $columnDef         = $column->toArray();
701 702 703 704 705 706 707 708
        $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.
     *
709 710
     * @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.
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
     *
     * @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.
     *
727
     * @param ColumnDiff $columnDiff The column diff to evaluate.
728
     *
729
     * @return bool True if the column alteration requires dropping its default constraint first, false otherwise.
730 731 732 733 734
     */
    private function alterColumnRequiresDropDefaultConstraint(ColumnDiff $columnDiff)
    {
        // We can only decide whether to drop an existing default constraint
        // if we know the original default value.
735
        if (! $columnDiff->fromColumn instanceof Column) {
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
            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.
Gabriel Caruso's avatar
Gabriel Caruso committed
753
        return $columnDiff->hasChanged('type') || $columnDiff->hasChanged('fixed');
754 755
    }

756 757 758 759 760 761 762 763 764 765 766
    /**
     * 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.
     *
Sergei Morozov's avatar
Sergei Morozov committed
767 768 769
     * @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|null $comment    The column's comment.
770 771 772 773 774
     *
     * @return string
     */
    protected function getAlterColumnCommentSQL($tableName, $columnName, $comment)
    {
775 776 777 778 779 780 781 782 783
        if (strpos($tableName, '.') !== false) {
            [$schemaSQL, $tableSQL] = explode('.', $tableName);
            $schemaSQL              = $this->quoteStringLiteral($schemaSQL);
            $tableSQL               = $this->quoteStringLiteral($tableSQL);
        } else {
            $schemaSQL = "'dbo'";
            $tableSQL  = $this->quoteStringLiteral($tableName);
        }

784 785 786 787
        return $this->getUpdateExtendedPropertySQL(
            'MS_Description',
            $comment,
            'SCHEMA',
788
            $schemaSQL,
789
            'TABLE',
790
            $tableSQL,
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
            '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)
    {
814 815 816 817 818 819 820 821 822
        if (strpos($tableName, '.') !== false) {
            [$schemaSQL, $tableSQL] = explode('.', $tableName);
            $schemaSQL              = $this->quoteStringLiteral($schemaSQL);
            $tableSQL               = $this->quoteStringLiteral($tableSQL);
        } else {
            $schemaSQL = "'dbo'";
            $tableSQL  = $this->quoteStringLiteral($tableName);
        }

823 824 825
        return $this->getDropExtendedPropertySQL(
            'MS_Description',
            'SCHEMA',
826
            $schemaSQL,
827
            'TABLE',
828
            $tableSQL,
829 830 831 832 833
            'COLUMN',
            $columnName
        );
    }

834 835 836 837 838
    /**
     * {@inheritdoc}
     */
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
    {
839 840 841 842 843 844
        return [sprintf(
            "EXEC sp_RENAME N'%s.%s', N'%s', N'INDEX'",
            $tableName,
            $oldIndexName,
            $index->getQuotedName($this)
        ),
845
        ];
846 847
    }

848 849 850
    /**
     * Returns the SQL statement for adding an extended property to a database object.
     *
851 852
     * @link http://msdn.microsoft.com/en-us/library/ms180047%28v=sql.90%29.aspx
     *
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
     * @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
     */
    public function getAddExtendedPropertySQL(
        $name,
        $value = null,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
874
        return 'EXEC sp_addextendedproperty ' .
Sergei Morozov's avatar
Sergei Morozov committed
875 876 877 878
            'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral((string) $value) . ', ' .
            'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
879 880 881 882 883
    }

    /**
     * Returns the SQL statement for dropping an extended property from a database object.
     *
884 885
     * @link http://technet.microsoft.com/en-gb/library/ms178595%28v=sql.90%29.aspx
     *
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
     * @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
     */
    public function getDropExtendedPropertySQL(
        $name,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
905 906
        return 'EXEC sp_dropextendedproperty ' .
            'N' . $this->quoteStringLiteral($name) . ', ' .
Sergei Morozov's avatar
Sergei Morozov committed
907 908 909
            'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
910 911 912 913 914
    }

    /**
     * Returns the SQL statement for updating an extended property of a database object.
     *
915 916
     * @link http://msdn.microsoft.com/en-us/library/ms186885%28v=sql.90%29.aspx
     *
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
     * @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
     */
    public function getUpdateExtendedPropertySQL(
        $name,
        $value = null,
        $level0Type = null,
        $level0Name = null,
        $level1Type = null,
        $level1Name = null,
        $level2Type = null,
        $level2Name = null
    ) {
938
        return 'EXEC sp_updateextendedproperty ' .
Sergei Morozov's avatar
Sergei Morozov committed
939 940 941 942
            'N' . $this->quoteStringLiteral($name) . ', N' . $this->quoteStringLiteral((string) $value) . ', ' .
            'N' . $this->quoteStringLiteral((string) $level0Type) . ', ' . $level0Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level1Type) . ', ' . $level1Name . ', ' .
            'N' . $this->quoteStringLiteral((string) $level2Type) . ', ' . $level2Name;
943 944
    }

945
    /**
946
     * {@inheritDoc}
947
     */
948
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
949
    {
950
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
951 952
    }

953
    /**
954
     * {@inheritDoc}
955
     */
956
    public function getListTablesSQL()
957
    {
958
        // "sysdiagrams" table must be ignored as it's internal SQL Server table for Database Diagrams
959
        // Category 2 must be ignored as it is "MS SQL Server 'pseudo-system' object[s]" for replication
960
        return "SELECT name, SCHEMA_NAME (uid) AS schema_name FROM sysobjects WHERE type = 'U' AND name != 'sysdiagrams' AND category != 2 ORDER BY name";
961 962 963
    }

    /**
964
     * {@inheritDoc}
965
     */
966
    public function getListTableColumnsSQL($table, $database = null)
967
    {
968 969 970 971 972 973 974 975
        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,
976 977
                          col.collation_name AS collation,
                          CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
978 979 980 981 982
                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
983 984
                JOIN      sys.schemas AS scm
                ON        obj.schema_id = scm.schema_id
985 986 987
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
988 989 990 991
                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'
992
                WHERE     obj.type = 'U'
993
                AND       " . $this->getTableWhereClause($table, 'scm.name', 'obj.name');
994 995 996
    }

    /**
997 998 999 1000
     * @param string      $table
     * @param string|null $database
     *
     * @return string
1001 1002 1003
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
1004
        return 'SELECT f.name AS ForeignKey,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
                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
1017
                WHERE ' .
1018
                $this->getTableWhereClause($table, 'SCHEMA_NAME (f.schema_id)', 'OBJECT_NAME (f.parent_object_id)');
1019 1020 1021
    }

    /**
1022
     * {@inheritDoc}
1023
     */
1024
    public function getListTableIndexesSQL($table, $currentDatabase = null)
1025
    {
1026 1027
        return "SELECT idx.name AS key_name,
                       col.name AS column_name,
Steve Müller's avatar
Steve Müller committed
1028 1029
                       ~idx.is_unique AS non_unique,
                       idx.is_primary_key AS [primary],
1030 1031 1032 1033 1034 1035
                       CASE idx.type
                           WHEN '1' THEN 'clustered'
                           WHEN '2' THEN 'nonclustered'
                           ELSE NULL
                       END AS flags
                FROM sys.tables AS tbl
1036
                JOIN sys.schemas AS scm ON tbl.schema_id = scm.schema_id
1037 1038 1039
                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
1040 1041
                WHERE " . $this->getTableWhereClause($table, 'scm.name', 'tbl.name') . '
                ORDER BY idx.index_id ASC, idxcol.key_ordinal ASC';
1042
    }
1043 1044

    /**
1045
     * {@inheritDoc}
1046
     */
1047
    public function getCreateViewSQL($name, $sql)
1048 1049 1050
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
1051 1052

    /**
1053
     * {@inheritDoc}
1054
     */
1055
    public function getListViewsSQL($database)
1056 1057 1058 1059
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

1060 1061 1062 1063
    /**
     * Returns the where clause to filter schema and table name in a query.
     *
     * @param string $table        The full qualified name of the table.
1064 1065
     * @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.
1066 1067 1068 1069 1070
     *
     * @return string
     */
    private function getTableWhereClause($table, $schemaColumn, $tableColumn)
    {
1071 1072 1073 1074
        if (strpos($table, '.') !== false) {
            [$schema, $table] = explode('.', $table);
            $schema           = $this->quoteStringLiteral($schema);
            $table            = $this->quoteStringLiteral($table);
1075
        } else {
1076 1077
            $schema = 'SCHEMA_NAME()';
            $table  = $this->quoteStringLiteral($table);
1078 1079
        }

1080
        return sprintf('(%s = %s AND %s = %s)', $tableColumn, $table, $schemaColumn, $schema);
1081 1082
    }

1083
    /**
1084
     * {@inheritDoc}
1085 1086 1087
     */
    public function getDropViewSQL($name)
    {
1088
        return 'DROP VIEW ' . $name;
1089
    }
1090 1091

    /**
1092
     * {@inheritDoc}
1093 1094
     *
     * @deprecated Use application-generated UUIDs instead
1095 1096 1097
     */
    public function getGuidExpression()
    {
1098
        return 'NEWID()';
1099
    }
1100 1101

    /**
1102
     * {@inheritDoc}
1103
     */
1104
    public function getLocateExpression($str, $substr, $startPos = false)
1105
    {
1106
        if ($startPos === false) {
1107 1108
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        }
1109 1110

        return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
1111
    }
1112

1113
    /**
1114
     * {@inheritDoc}
1115
     */
1116
    public function getModExpression($expression1, $expression2)
1117
    {
1118
        return $expression1 . ' % ' . $expression2;
1119
    }
1120

1121
    /**
1122
     * {@inheritDoc}
1123
     */
1124
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
1125
    {
1126
        if ($char === false) {
1127
            switch ($pos) {
1128
                case TrimMode::LEADING:
1129 1130 1131
                    $trimFn = 'LTRIM';
                    break;

1132
                case TrimMode::TRAILING:
1133 1134 1135 1136 1137
                    $trimFn = 'RTRIM';
                    break;

                default:
                    return 'LTRIM(RTRIM(' . $str . '))';
1138 1139 1140 1141
            }

            return $trimFn . '(' . $str . ')';
        }
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151

        /** 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;
         */
1152
        $pattern = "'%[^' + " . $char . " + ']%'";
1153

1154
        if ($pos === TrimMode::LEADING) {
1155 1156 1157
            return 'stuff(' . $str . ', 1, patindex(' . $pattern . ', ' . $str . ') - 1, null)';
        }

1158
        if ($pos === TrimMode::TRAILING) {
1159 1160 1161 1162
            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))';
1163
    }
1164

1165
    /**
1166
     * {@inheritDoc}
1167 1168
     */
    public function getConcatExpression()
1169
    {
1170
        $args = func_get_args();
1171

1172
        return '(' . implode(' + ', $args) . ')';
1173
    }
1174

Benjamin Morel's avatar
Benjamin Morel committed
1175 1176 1177
    /**
     * {@inheritDoc}
     */
1178
    public function getListDatabasesSQL()
1179
    {
1180
        return 'SELECT * FROM sys.databases';
1181
    }
1182

1183 1184 1185 1186 1187
    /**
     * {@inheritDoc}
     */
    public function getListNamespacesSQL()
    {
1188
        return "SELECT name FROM sys.schemas WHERE name NOT IN('guest', 'INFORMATION_SCHEMA', 'sys')";
1189 1190
    }

1191
    /**
1192
     * {@inheritDoc}
1193
     */
1194
    public function getSubstringExpression($value, $from, $length = null)
1195
    {
1196
        if ($length !== null) {
1197
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
1198
        }
1199

1200
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
1201
    }
1202

1203
    /**
1204
     * {@inheritDoc}
1205
     */
1206
    public function getLengthExpression($column)
1207
    {
1208
        return 'LEN(' . $column . ')';
1209 1210
    }

1211
    /**
1212
     * {@inheritDoc}
1213
     */
1214
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
1215
    {
1216
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
1217
    }
1218

1219
    /**
1220
     * {@inheritDoc}
1221
     */
1222
    public function getIntegerTypeDeclarationSQL(array $field)
1223
    {
1224
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1225 1226
    }

1227
    /**
1228
     * {@inheritDoc}
1229
     */
1230
    public function getBigIntTypeDeclarationSQL(array $field)
1231
    {
1232
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1233 1234
    }

1235
    /**
1236
     * {@inheritDoc}
1237
     */
1238
    public function getSmallIntTypeDeclarationSQL(array $field)
1239
    {
1240
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
1241 1242
    }

1243
    /**
1244
     * {@inheritDoc}
1245
     */
1246
    public function getGuidTypeDeclarationSQL(array $field)
1247 1248 1249 1250
    {
        return 'UNIQUEIDENTIFIER';
    }

1251 1252 1253 1254 1255 1256 1257 1258
    /**
     * {@inheritDoc}
     */
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATETIMEOFFSET(6)';
    }

1259 1260 1261
    /**
     * {@inheritDoc}
     */
1262
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
1263
    {
1264 1265 1266
        return $fixed
            ? ($length > 0 ? 'NCHAR(' . $length . ')' : 'CHAR(255)')
            : ($length > 0 ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
1267
    }
1268

Steve Müller's avatar
Steve Müller committed
1269 1270 1271 1272 1273
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
1274 1275 1276
        return $fixed
            ? 'BINARY(' . ($length > 0 ? $length : 255) . ')'
            : 'VARBINARY(' . ($length > 0 ? $length : 255) . ')';
Steve Müller's avatar
Steve Müller committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
    }

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

1287 1288 1289
    /**
     * {@inheritDoc}
     */
1290
    public function getClobTypeDeclarationSQL(array $field)
1291
    {
1292
        return 'VARCHAR(MAX)';
1293
    }
1294

1295
    /**
1296
     * {@inheritDoc}
1297
     */
1298
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
1299
    {
1300
        return ! empty($columnDef['autoincrement']) ? ' IDENTITY' : '';
1301
    }
1302

1303
    /**
1304
     * {@inheritDoc}
1305
     */
1306
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
1307
    {
1308 1309 1310
        // 3 - microseconds precision length
        // http://msdn.microsoft.com/en-us/library/ms187819.aspx
        return 'DATETIME2(6)';
1311 1312
    }

1313
    /**
1314
     * {@inheritDoc}
1315
     */
1316
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
1317
    {
1318
        return 'DATE';
1319
    }
1320 1321

    /**
1322
     * {@inheritDoc}
1323
     */
1324
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
1325
    {
1326
        return 'TIME(0)';
1327
    }
1328

1329
    /**
1330
     * {@inheritDoc}
1331
     */
1332
    public function getBooleanTypeDeclarationSQL(array $field)
1333 1334 1335 1336
    {
        return 'BIT';
    }

1337
    /**
1338
     * {@inheritDoc}
1339
     */
1340
    protected function doModifyLimitQuery($query, $limit, $offset = null)
1341
    {
1342
        if ($limit === null && $offset <= 0) {
1343 1344
            return $query;
        }
1345

1346 1347 1348 1349 1350 1351 1352 1353
        // Queries using OFFSET... FETCH MUST have an ORDER BY clause
        // Find the position of the last instance of ORDER BY and ensure it is not within a parenthetical statement
        // but can be in a newline
        $matches      = [];
        $matchesCount = preg_match_all('/[\\s]+order\\s+by\\s/im', $query, $matches, PREG_OFFSET_CAPTURE);
        $orderByPos   = false;
        if ($matchesCount > 0) {
            $orderByPos = $matches[0][($matchesCount - 1)][1];
Sergei Morozov's avatar
Sergei Morozov committed
1354 1355
        }

1356
        if ($orderByPos === false
1357
            || substr_count($query, '(', $orderByPos) !== substr_count($query, ')', $orderByPos)
1358
        ) {
1359
            if (preg_match('/^SELECT\s+DISTINCT/im', $query) > 0) {
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
                // SQL Server won't let us order by a non-selected column in a DISTINCT query,
                // so we have to do this madness. This says, order by the first column in the
                // result. SQL Server's docs say that a nonordered query's result order is non-
                // deterministic anyway, so this won't do anything that a bunch of update and
                // deletes to the table wouldn't do anyway.
                $query .= ' ORDER BY 1';
            } else {
                // In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you
                // use constant expressions in the order by list.
                $query .= ' ORDER BY (SELECT 0)';
1370
            }
1371
        }
1372

1373 1374 1375 1376
        // This looks somewhat like MYSQL, but limit/offset are in inverse positions
        // Supposedly SQL:2008 core standard.
        // Per TSQL spec, FETCH NEXT n ROWS ONLY is not valid without OFFSET n ROWS.
        $query .= sprintf(' OFFSET %d ROWS', $offset);
1377

1378 1379
        if ($limit !== null) {
            $query .= sprintf(' FETCH NEXT %d ROWS ONLY', $limit);
1380 1381
        }

1382
        return $query;
1383 1384
    }

1385
    /**
1386
     * {@inheritDoc}
1387 1388 1389
     */
    public function supportsLimitOffset()
    {
1390
        return true;
1391 1392
    }

1393
    /**
1394
     * {@inheritDoc}
1395
     */
1396
    public function convertBooleans($item)
1397
    {
1398 1399
        if (is_array($item)) {
            foreach ($item as $key => $value) {
1400
                if (! is_bool($value) && ! is_numeric($value)) {
1401
                    continue;
1402
                }
1403

1404
                $item[$key] = (int) (bool) $value;
1405
            }
Steve Müller's avatar
Steve Müller committed
1406
        } elseif (is_bool($item) || is_numeric($item)) {
1407
            $item = (int) (bool) $item;
1408
        }
1409

1410
        return $item;
1411
    }
1412 1413

    /**
1414
     * {@inheritDoc}
1415
     */
1416
    public function getCreateTemporaryTableSnippetSQL()
1417
    {
1418
        return 'CREATE TABLE';
1419
    }
1420

1421
    /**
1422
     * {@inheritDoc}
1423 1424 1425 1426 1427 1428
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

1429
    /**
1430
     * {@inheritDoc}
1431 1432 1433
     */
    public function getDateTimeFormatString()
    {
1434
        return 'Y-m-d H:i:s.u';
1435
    }
1436

1437
    /**
1438
     * {@inheritDoc}
1439
     */
1440 1441
    public function getDateFormatString()
    {
1442
        return 'Y-m-d';
1443 1444 1445
    }

    /**
1446
     * {@inheritDoc}
1447
     */
1448 1449
    public function getTimeFormatString()
    {
1450
        return 'H:i:s';
1451
    }
1452

1453
    /**
1454
     * {@inheritDoc}
1455 1456 1457
     */
    public function getDateTimeTzFormatString()
    {
1458
        return 'Y-m-d H:i:s.u P';
1459
    }
1460

1461
    /**
1462
     * {@inheritDoc}
1463
     */
1464
    public function getName()
1465
    {
1466
        return 'mssql';
1467
    }
1468

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1469
    /**
1470
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1471
     */
1472 1473
    protected function initializeDoctrineTypeMappings()
    {
1474
        $this->doctrineTypeMapping = [
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            'bigint'           => 'bigint',
            'binary'           => 'binary',
            'bit'              => 'boolean',
            'char'             => 'string',
            'date'             => 'date',
            'datetime'         => 'datetime',
            'datetime2'        => 'datetime',
            'datetimeoffset'   => 'datetimetz',
            'decimal'          => 'decimal',
            'double'           => 'float',
1485
            'double precision' => 'float',
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
            'float'            => 'float',
            'image'            => 'blob',
            'int'              => 'integer',
            'money'            => 'integer',
            'nchar'            => 'string',
            'ntext'            => 'text',
            'numeric'          => 'decimal',
            'nvarchar'         => 'string',
            'real'             => 'float',
            'smalldatetime'    => 'datetime',
            'smallint'         => 'smallint',
            'smallmoney'       => 'integer',
            'text'             => 'text',
            'time'             => 'time',
            'tinyint'          => 'smallint',
1501
            'uniqueidentifier' => 'guid',
1502 1503
            'varbinary'        => 'binary',
            'varchar'          => 'string',
1504
        ];
1505
    }
1506 1507

    /**
1508
     * {@inheritDoc}
1509 1510 1511 1512 1513 1514 1515
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
1516
     * {@inheritDoc}
1517 1518 1519 1520 1521 1522 1523
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
1524
     * {@inheritDoc}
1525 1526 1527 1528
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
1529
    }
1530

1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
    /**
     * {@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);
    }

1544
    /**
1545
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1546
     */
1547
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1548
    {
1549
        switch (true) {
1550
            case $lockMode === LockMode::NONE:
1551
                return $fromClause . ' WITH (NOLOCK)';
1552

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

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

Steve Müller's avatar
Steve Müller committed
1559
            default:
1560
                return $fromClause;
Steve Müller's avatar
Steve Müller committed
1561
        }
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1562 1563 1564
    }

    /**
1565
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1566 1567 1568 1569 1570
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
1571

1572 1573 1574
    /**
     * {@inheritDoc}
     */
1575 1576
    protected function getReservedKeywordsClass()
    {
1577
        return Keywords\SQLServer2012Keywords::class;
1578
    }
1579 1580

    /**
1581
     * {@inheritDoc}
1582
     */
1583
    public function quoteSingleIdentifier($str)
1584
    {
1585
        return '[' . str_replace(']', '][', $str) . ']';
1586
    }
1587

1588 1589 1590
    /**
     * {@inheritDoc}
     */
1591 1592
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
1593 1594 1595
        $tableIdentifier = new Identifier($tableName);

        return 'TRUNCATE TABLE ' . $tableIdentifier->getQuotedName($this);
1596
    }
1597 1598

    /**
1599
     * {@inheritDoc}
1600 1601 1602 1603 1604
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
1605

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    /**
     * {@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 {
1616
            $collation = ! empty($field['collation']) ?
1617
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
1618

1619
            $notnull = ! empty($field['notnull']) ? ' NOT NULL' : '';
1620

1621
            $unique = ! empty($field['unique']) ?
1622 1623
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';

1624
            $check = ! empty($field['check']) ?
1625 1626
                ' ' . $field['check'] : '';

1627
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
1628
            $columnDef = $typeDecl . $collation . $notnull . $unique . $check;
1629 1630 1631 1632
        }

        return $name . ' ' . $columnDef;
    }
1633

1634 1635 1636 1637 1638 1639 1640 1641
    /**
     * {@inheritdoc}
     */
    protected function getLikeWildcardCharacters() : string
    {
        return parent::getLikeWildcardCharacters() . '[]^';
    }

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    /**
     * 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)
    {
1664 1665 1666 1667
        // Always generate name for unquoted identifiers to ensure consistency.
        $identifier = new Identifier($identifier);

        return strtoupper(dechex(crc32($identifier->getName())));
1668
    }
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

    protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
    {
        return sprintf(
            <<<'SQL'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', 
  @value=N%s, @level0type=N'SCHEMA', @level0name=N'dbo', 
  @level1type=N'TABLE', @level1name=N%s
SQL
            ,
            $this->quoteStringLiteral((string) $comment),
            $this->quoteStringLiteral($tableName)
        );
    }

    public function getListTableMetadataSQL(string $table) : string
    {
        return sprintf(
            <<<'SQL'
SELECT
  p.value AS [table_comment]
FROM
  sys.tables AS tbl
  INNER JOIN sys.extended_properties AS p ON p.major_id=tbl.object_id AND p.minor_id=0 AND p.class=1
WHERE
  (tbl.name=N%s and SCHEMA_NAME(tbl.schema_id)=N'dbo' and p.name=N'MS_Description')
SQL
            ,
            $this->quoteStringLiteral($table)
        );
    }
1700
}