SQLServerPlatform.php 34.9 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 24
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\DBALException;
25 26 27
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
28 29

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
207
     * {@inheritDoc}
208
     */
209
    public function getDropIndexSQL($index, $table = null)
210
    {
211
        if ($index instanceof Index) {
212
            $index = $index->getQuotedName($this);
213
        } else if (!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 237
        $defaultConstraintsSql = array();

238
        // @todo does other code breaks because of this?
239
        // force primary keys to be not null
240 241 242 243
        foreach ($columns as &$column) {
            if (isset($column['primary']) && $column['primary']) {
                $column['notnull'] = true;
            }
244 245 246 247 248 249 250 251

            /**
             * Build default constraints SQL statements
             */
            if ( ! empty($column['default']) || is_numeric($column['default'])) {
                $defaultConstraintsSql[] = 'ALTER TABLE ' . $tableName .
                    ' ADD' . $this->getDefaultConstraintDeclarationSQL($tableName, $column);
            }
252 253
        }

254
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
255 256

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

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

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

        $check = $this->getCheckDeclarationSQL($columns);
273
        if (!empty($check)) {
274 275 276 277 278
            $query .= ', ' . $check;
        }
        $query .= ')';

        $sql[] = $query;
279 280

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

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

292
        return array_merge($sql, $defaultConstraintsSql);
293
    }
294

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

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    /**
     * 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)
    {
        if (empty($column['default']) && ! is_numeric($column['default'])) {
            throw new \InvalidArgumentException("Incomplete column definition. 'default' required.");
        }

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

330
    /**
331
     * {@inheritDoc}
332
     */
333
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
334 335
    {
        $constraint = parent::getUniqueConstraintDeclarationSQL($name, $index);
336 337 338 339 340 341 342

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

        return $constraint;
    }

    /**
343
     * {@inheritDoc}
344 345 346 347 348
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
        $constraint = parent::getCreateIndexSQL($index, $table);

Craig Mason's avatar
Craig Mason committed
349
        if ($index->isUnique() && !$index->isPrimary()) {
350 351 352 353 354 355
            $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);
        }

        return $constraint;
    }

356
    /**
357
     * {@inheritDoc}
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
     */
    protected function getCreateIndexSQLFlags(Index $index)
    {
        $type = '';
        if ($index->isUnique()) {
            $type .= 'UNIQUE ';
        }

        if ($index->hasFlag('clustered')) {
            $type .= 'CLUSTERED ';
        } else if ($index->hasFlag('nonclustered')) {
            $type .= 'NONCLUSTERED ';
        }

        return $type;
    }

375
    /**
376
     * Extend unique key constraint with required filters
377
     *
Benjamin Morel's avatar
Benjamin Morel committed
378 379
     * @param string                      $sql
     * @param \Doctrine\DBAL\Schema\Index $index
380
     *
381 382 383 384 385 386
     * @return string
     */
    private function _appendUniqueConstraintDefinition($sql, Index $index)
    {
        $fields = array();

387
        foreach ($index->getQuotedColumns($this) as $field) {
388
            $fields[] = $field . ' IS NOT NULL';
389
        }
390 391 392

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

394
    /**
395
     * {@inheritDoc}
396
     */
397
    public function getAlterTableSQL(TableDiff $diff)
398
    {
399
        $queryParts = array();
400
        $sql = array();
401
        $columnSql = array();
402

403
        /** @var \Doctrine\DBAL\Schema\Column $column */
404
        foreach ($diff->addedColumns as $column) {
405 406
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
407 408
            }

409 410 411 412 413 414 415
            $columnDef = $column->toArray();
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

            if ( ! empty($columnDef['default']) || is_numeric($columnDef['default'])) {
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
416 417
        }

418
        foreach ($diff->removedColumns as $column) {
419 420
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
421 422
            }

423
            $queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this);
424 425
        }

426
        /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
427
        foreach ($diff->changedColumns as $columnDiff) {
428 429
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
430 431
            }

432 433
            $fromColumn = $columnDiff->fromColumn;
            $fromColumnDefault = isset($fromColumn) ? $fromColumn->getDefault() : null;
434
            $column = $columnDiff->column;
435 436 437 438 439 440 441 442 443 444 445 446 447
            $columnDef = $column->toArray();
            $columnDefaultHasChanged = $columnDiff->hasChanged('default');

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

448
            $queryParts[] = 'ALTER COLUMN ' .
449 450 451 452 453 454
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

            if ($columnDefaultHasChanged && (! empty($columnDef['default']) || is_numeric($columnDef['default']))) {
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
455 456
        }

457
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
458 459
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
460 461
            }

462
            $sql[] = "sp_RENAME '". $diff->name. ".". $oldColumnName . "' , '".$column->getQuotedName($this)."', 'COLUMN'";
463 464 465 466 467 468 469 470 471 472 473 474

            $columnDef = $column->toArray();

            /**
             * Drop existing default constraint for the old column name
             * if column has default value.
             */
            if ( ! empty($columnDef['default']) || is_numeric($columnDef['default'])) {
                $queryParts[] = 'DROP CONSTRAINT ' .
                    $this->generateDefaultConstraintName($diff->name, $oldColumnName);
            }

475
            $queryParts[] = 'ALTER COLUMN ' .
476 477 478 479 480 481 482 483 484
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnDef);

            /**
             * Readd default constraint for the new column name.
             */
            if ( ! empty($columnDef['default']) || is_numeric($columnDef['default'])) {
                $columnDef['name'] = $column->getQuotedName($this);
                $queryParts[] = 'ADD' . $this->getDefaultConstraintDeclarationSQL($diff->name, $columnDef);
            }
485
        }
486

487 488 489
        $tableSql = array();

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
490
            return array_merge($tableSql, $columnSql);
491
        }
492

493 494 495
        foreach ($queryParts as $query) {
            $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
        }
496

497
        $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff));
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
498

499 500
        if ($diff->newName !== false) {
            $sql[] = "sp_RENAME '" . $diff->name . "', '" . $diff->newName . "'";
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

            /**
             * 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 " .
                "WHERE tbl.name = '" . $diff->newName . "';" .
                "EXEC sp_executesql @sql";
518 519
        }

520
        return array_merge($sql, $tableSql, $columnSql);
521
    }
522

523
    /**
524
     * {@inheritDoc}
525
     */
526
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
527
    {
528
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
529 530
    }

531
    /**
532
     * {@inheritDoc}
533
     */
534
    public function getListTablesSQL()
535
    {
536 537
        // "sysdiagrams" table must be ignored as it's internal SQL Server table for Database Diagrams
        return "SELECT name FROM sysobjects WHERE type = 'U' AND name != 'sysdiagrams' ORDER BY name";
538 539 540
    }

    /**
541
     * {@inheritDoc}
542
     */
543
    public function getListTableColumnsSQL($table, $database = null)
544
    {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        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,
                          col.collation_name AS collation
                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
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
                WHERE     obj.type = 'U'
                AND       obj.name = '$table'";
564 565 566
    }

    /**
567
     * {@inheritDoc}
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
     */
    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
                WHERE OBJECT_NAME (f.parent_object_id) = '" . $table . "'";
    }

    /**
588
     * {@inheritDoc}
589
     */
590
    public function getListTableIndexesSQL($table, $currentDatabase = null)
591
    {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        return "SELECT idx.name AS key_name,
                       col.name AS column_name,
	                   ~idx.is_unique AS non_unique,
	                   idx.is_primary_key AS [primary],
                       CASE idx.type
                           WHEN '1' THEN 'clustered'
                           WHEN '2' THEN 'nonclustered'
                           ELSE NULL
                       END AS flags
                FROM sys.tables AS tbl
                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
                WHERE tbl.name = '$table'
                ORDER BY idx.index_id ASC, idxcol.index_column_id ASC";
607
    }
608 609

    /**
610
     * {@inheritDoc}
611
     */
612
    public function getCreateViewSQL($name, $sql)
613 614 615
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
616 617

    /**
618
     * {@inheritDoc}
619
     */
620
    public function getListViewsSQL($database)
621 622 623 624
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

625
    /**
626
     * {@inheritDoc}
627 628 629
     */
    public function getDropViewSQL($name)
    {
630
        return 'DROP VIEW ' . $name;
631
    }
632 633

    /**
634
     * {@inheritDoc}
635 636 637
     */
    public function getGuidExpression()
    {
638
        return 'NEWID()';
639
    }
640 641

    /**
642
     * {@inheritDoc}
643
     */
644
    public function getLocateExpression($str, $substr, $startPos = false)
645
    {
646 647 648
        if ($startPos == false) {
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        }
649 650

        return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
651
    }
652

653
    /**
654
     * {@inheritDoc}
655
     */
656
    public function getModExpression($expression1, $expression2)
657
    {
658
        return $expression1 . ' % ' . $expression2;
659
    }
660

661
    /**
662
     * {@inheritDoc}
663
     */
664
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
665
    {
666
        if ( ! $char) {
667 668 669 670 671 672 673 674 675 676 677
            switch ($pos) {
                case self::TRIM_LEADING:
                    $trimFn = 'LTRIM';
                    break;

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

                default:
                    return 'LTRIM(RTRIM(' . $str . '))';
678 679 680 681
            }

            return $trimFn . '(' . $str . ')';
        }
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

        /** 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))';
703
    }
704

705
    /**
706
     * {@inheritDoc}
707 708
     */
    public function getConcatExpression()
709
    {
710
        $args = func_get_args();
711

712
        return '(' . implode(' + ', $args) . ')';
713
    }
714

Benjamin Morel's avatar
Benjamin Morel committed
715 716 717
    /**
     * {@inheritDoc}
     */
718
    public function getListDatabasesSQL()
719 720 721
    {
        return 'SELECT * FROM SYS.DATABASES';
    }
722

723
    /**
724
     * {@inheritDoc}
725
     */
726
    public function getSubstringExpression($value, $from, $length = null)
727
    {
728 729
        if (!is_null($length)) {
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
730
        }
731

732
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
733
    }
734

735
    /**
736
     * {@inheritDoc}
737
     */
738
    public function getLengthExpression($column)
739
    {
740
        return 'LEN(' . $column . ')';
741 742
    }

743
    /**
744
     * {@inheritDoc}
745
     */
746
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
747
    {
748
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
749
    }
750

751
    /**
752
     * {@inheritDoc}
753
     */
754
    public function getIntegerTypeDeclarationSQL(array $field)
755
    {
756
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
757 758
    }

759
    /**
760
     * {@inheritDoc}
761
     */
762
    public function getBigIntTypeDeclarationSQL(array $field)
763
    {
764
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
765 766
    }

767
    /**
768
     * {@inheritDoc}
769
     */
770
    public function getSmallIntTypeDeclarationSQL(array $field)
771
    {
772
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
773 774
    }

775
    /**
776
     * {@inheritDoc}
777
     */
778
    public function getGuidTypeDeclarationSQL(array $field)
779 780 781 782
    {
        return 'UNIQUEIDENTIFIER';
    }

783 784 785
    /**
     * {@inheritDoc}
     */
786
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
787
    {
788
        return $fixed ? ($length ? 'NCHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
789
    }
790

791 792 793
    /**
     * {@inheritDoc}
     */
794
    public function getClobTypeDeclarationSQL(array $field)
795 796 797
    {
        return 'TEXT';
    }
798

799
    /**
800
     * {@inheritDoc}
801
     */
802
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
803
    {
804
        return (!empty($columnDef['autoincrement'])) ? ' IDENTITY' : '';
805
    }
806

807
    /**
808
     * {@inheritDoc}
809
     */
810
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
811
    {
812
        return 'DATETIME';
813 814
    }

815
    /**
816
     * {@inheritDoc}
817
     */
818
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
819
    {
820
        return 'DATETIME';
821
    }
822 823

    /**
824
     * {@inheritDoc}
825
     */
826
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
827
    {
828
        return 'DATETIME';
829
    }
830

831
    /**
832
     * {@inheritDoc}
833
     */
834
    public function getBooleanTypeDeclarationSQL(array $field)
835 836 837 838
    {
        return 'BIT';
    }

839
    /**
840
     * {@inheritDoc}
841
     */
842
    protected function doModifyLimitQuery($query, $limit, $offset = null)
843
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
844
        if ($limit === null) {
Fabio B. Silva's avatar
Fabio B. Silva committed
845 846
            return $query;
        }
847

Fabio B. Silva's avatar
Fabio B. Silva committed
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        $start   = $offset + 1;
        $end     = $offset + $limit;
        $orderBy = stristr($query, 'ORDER BY');
        $query   = preg_replace('/\s+ORDER\s+BY\s+([^\)]*)/', '', $query); //Remove ORDER BY from $query
        $format  = 'SELECT * FROM (%s) AS doctrine_tbl WHERE doctrine_rownum BETWEEN %d AND %d';

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

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

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

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

            if (preg_match('/(([^\s]*)\.)?([^\.\s]*)\s*(ASC|DESC)?/i', trim($part), $matches)) {
Fabio B. Silva's avatar
Fabio B. Silva committed
870 871 872 873 874 875
                $orderbyColumns[] = array(
                    'column'    => $matches[3],
                    'hasTable'  => ( ! empty($matches[2])),
                    'sort'      => isset($matches[4]) ? $matches[4] : null,
                    'table'     => empty($matches[2]) ? '[^\.\s]*' : $matches[2]
                );
876
            }
Fabio B. Silva's avatar
Fabio B. Silva committed
877 878
        }

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

Fabio B. Silva's avatar
Fabio B. Silva committed
881 882 883
        //Find alias for each colum used in ORDER BY
        if ( ! empty($orderbyColumns)) {
            foreach ($orderbyColumns as $column) {
884

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

887
                if ($isWrapped) {
888 889
                    $overColumn = preg_match($pattern, $query, $matches)
                        ? $matches[1] : '';
890 891
                } else {
                    $overColumn = preg_match($pattern, $query, $matches)
892 893
                        ? ($column['hasTable'] ? $column['table']  . '.' : '') . $column['column']
                        : $column['column'];
894
                }
895

Fabio B. Silva's avatar
Fabio B. Silva committed
896 897 898
                if (isset($column['sort'])) {
                    $overColumn .= ' ' . $column['sort'];
                }
899

Fabio B. Silva's avatar
Fabio B. Silva committed
900 901
                $overColumns[] = $overColumn;
            }
902 903
        }

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

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

911
    /**
912
     * {@inheritDoc}
913 914 915 916 917 918
     */
    public function supportsLimitOffset()
    {
        return false;
    }

919
    /**
920
     * {@inheritDoc}
921
     */
922
    public function convertBooleans($item)
923
    {
924 925 926
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
927
                    $item[$key] = ($value) ? 1 : 0;
928 929
                }
            }
930 931
        } else if (is_bool($item) || is_numeric($item)) {
            $item = ($item) ? 1 : 0;
932
        }
933

934
        return $item;
935
    }
936 937

    /**
938
     * {@inheritDoc}
939
     */
940
    public function getCreateTemporaryTableSnippetSQL()
941
    {
942
        return "CREATE TABLE";
943
    }
944

945
    /**
946
     * {@inheritDoc}
947 948 949 950 951 952
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

953
    /**
954
     * {@inheritDoc}
955 956 957
     */
    public function getDateTimeFormatString()
    {
958 959
        return 'Y-m-d H:i:s.000';
    }
960

961
    /**
962
     * {@inheritDoc}
963
     */
964 965 966 967 968 969
    public function getDateFormatString()
    {
        return 'Y-m-d H:i:s.000';
    }

    /**
970
     * {@inheritDoc}
971
     */
972 973 974
    public function getTimeFormatString()
    {
        return 'Y-m-d H:i:s.000';
975
    }
976

977
    /**
978
     * {@inheritDoc}
979 980 981 982 983
     */
    public function getDateTimeTzFormatString()
    {
        return $this->getDateTimeFormatString();
    }
984

985
    /**
986
     * {@inheritDoc}
987
     */
988
    public function getName()
989
    {
990
        return 'mssql';
991
    }
992

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
993
    /**
994
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
995
     */
996 997
    protected function initializeDoctrineTypeMappings()
    {
998
        $this->doctrineTypeMapping = array(
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
            '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',
            'binary' => 'text',
1021
            'varbinary' => 'blob',
1022
            'image' => 'text',
1023
            'uniqueidentifier' => 'guid',
1024
        );
1025
    }
1026 1027

    /**
1028
     * {@inheritDoc}
1029 1030 1031 1032 1033 1034 1035
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
1036
     * {@inheritDoc}
1037 1038 1039 1040 1041 1042 1043
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
1044
     * {@inheritDoc}
1045 1046 1047 1048
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
1049
    }
1050 1051

    /**
1052
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1053
     */
1054
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1055
    {
Steve Müller's avatar
Steve Müller committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
        switch ($lockMode) {
            case LockMode::NONE:
                $lockClause = ' WITH (NOLOCK)';
                break;
            case LockMode::PESSIMISTIC_READ:
                $lockClause = ' WITH (HOLDLOCK, ROWLOCK)';
                break;
            case LockMode::PESSIMISTIC_WRITE:
                $lockClause = ' WITH (UPDLOCK, ROWLOCK)';
                break;
            default:
                $lockClause = '';
        }

        return $fromClause . $lockClause;
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1071 1072 1073
    }

    /**
1074
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
1075 1076 1077 1078 1079
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
1080

1081 1082 1083
    /**
     * {@inheritDoc}
     */
1084 1085
    protected function getReservedKeywordsClass()
    {
1086
        return 'Doctrine\DBAL\Platforms\Keywords\SQLServerKeywords';
1087
    }
1088 1089

    /**
1090
     * {@inheritDoc}
1091
     */
1092
    public function quoteSingleIdentifier($str)
1093
    {
1094
        return "[" . str_replace("]", "][", $str) . "]";
1095
    }
1096

1097 1098 1099
    /**
     * {@inheritDoc}
     */
1100 1101 1102 1103
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
        return 'TRUNCATE TABLE '.$tableName;
    }
1104 1105

    /**
1106
     * {@inheritDoc}
1107 1108 1109 1110 1111
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
1112 1113 1114 1115

    /**
     * {@inheritDoc}
     */
1116 1117
    public function getDefaultValueDeclarationSQL($field)
    {
1118 1119 1120 1121 1122 1123
        if ( ! isset($field['default'])) {
            return empty($field['notnull']) ? ' NULL' : '';
        }

        if ( ! isset($field['type'])) {
            return " DEFAULT '" . $field['default'] . "'";
1124
        }
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

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

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

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

        return " DEFAULT '" . $field['default'] . "'";
1139
    }
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

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

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

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

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

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

            $typeDecl = $field['type']->getSqlDeclaration($field, $this);
1171
            $columnDef = $typeDecl . $collation . $notnull . $unique . $check;
1172 1173 1174 1175
        }

        return $name . ' ' . $columnDef;
    }
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

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

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