SQLServerPlatform.php 24.3 KB
Newer Older
1
<?php
2

3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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
17
 * and is licensed under the MIT license. For more information, see
18 19
 * <http://www.doctrine-project.org>.
 */
20

21
namespace Doctrine\DBAL\Platforms;
22

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
 */
38
class SQLServerPlatform extends AbstractPlatform
39
{
40 41 42
    /**
     * {@inheritDoc}
     */
43
    public function getDateDiffExpression($date1, $date2)
44 45 46
    {
        return 'DATEDIFF(day, ' . $date2 . ',' . $date1 . ')';
    }
47

48 49 50
    /**
     * {@inheritDoc}
     */
51 52 53 54
    public function getDateAddDaysExpression($date, $days)
    {
        return 'DATEADD(day, ' . $days . ', ' . $date . ')';
    }
55

56 57 58
    /**
     * {@inheritDoc}
     */
59 60 61 62
    public function getDateSubDaysExpression($date, $days)
    {
        return 'DATEADD(day, -1 * ' . $days . ', ' . $date . ')';
    }
63

64 65 66
    /**
     * {@inheritDoc}
     */
67 68 69 70
    public function getDateAddMonthExpression($date, $months)
    {
        return 'DATEADD(month, ' . $months . ', ' . $date . ')';
    }
71

72 73 74
    /**
     * {@inheritDoc}
     */
75 76 77 78
    public function getDateSubMonthExpression($date, $months)
    {
        return 'DATEADD(month, -1 * ' . $months . ', ' . $date . ')';
    }
79

80
    /**
81 82
     * {@inheritDoc}
     *
83 84
     * MsSql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
85
     */
86
    public function prefersIdentityColumns()
87
    {
88 89
        return true;
    }
90

91
    /**
92
     * {@inheritDoc}
93
     *
94
     * MsSql supports this through AUTO_INCREMENT columns.
95 96 97 98 99 100 101
     */
    public function supportsIdentityColumns()
    {
        return true;
    }

    /**
102
     * {@inheritDoc}
103
     */
104
    public function supportsReleaseSavepoints()
105 106 107
    {
        return false;
    }
108

109
    /**
110
     * {@inheritDoc}
111 112 113 114 115
     */
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }
116

117
    /**
118
     * {@inheritDoc}
119 120 121
     */
    public function getDropDatabaseSQL($name)
    {
122 123 124 125
        return 'DROP DATABASE ' . $name;
    }

    /**
126
     * {@inheritDoc}
127
     */
128
    public function supportsCreateDropDatabase()
129 130
    {
        return false;
131 132 133
    }

    /**
134
     * {@inheritDoc}
135 136 137
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
138
        if ($foreignKey instanceof ForeignKeyConstraint) {
139
            $foreignKey = $foreignKey->getQuotedName($this);
140 141
        }

142
        if ($table instanceof Table) {
143
            $table = $table->getQuotedName($this);
144 145 146
        }

        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $foreignKey;
147
    }
148 149

    /**
150
     * {@inheritDoc}
151
     */
152
    public function getDropIndexSQL($index, $table = null)
153
    {
154
        if ($index instanceof Index) {
155
            $index = $index->getQuotedName($this);
156
        } else if (!is_string($index)) {
157 158 159
            throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
        }

160 161
        if (!isset($table)) {
            return 'DROP INDEX ' . $index;
162
        }
163

164 165
        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
166
        }
167 168 169 170 171

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

    /**
175
     * {@inheritDoc}
176 177
     */
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
178
    {
179
        // @todo does other code breaks because of this?
180
        // force primary keys to be not null
181 182 183 184 185 186
        foreach ($columns as &$column) {
            if (isset($column['primary']) && $column['primary']) {
                $column['notnull'] = true;
            }
        }

187
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
188 189

        if (isset($options['uniqueConstraints']) && !empty($options['uniqueConstraints'])) {
190 191 192 193
            foreach ($options['uniqueConstraints'] as $name => $definition) {
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }
194 195

        if (isset($options['primary']) && !empty($options['primary'])) {
196 197 198 199 200
            $flags = '';
            if (isset($options['primary_index']) && $options['primary_index']->hasFlag('nonclustered')) {
                $flags = ' NONCLUSTERED';
            }
            $columnListSql .= ', PRIMARY KEY' . $flags . ' (' . implode(', ', array_unique(array_values($options['primary']))) . ')';
201 202 203 204 205
        }

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

        $check = $this->getCheckDeclarationSQL($columns);
206
        if (!empty($check)) {
207 208 209 210 211
            $query .= ', ' . $check;
        }
        $query .= ')';

        $sql[] = $query;
212 213

        if (isset($options['indexes']) && !empty($options['indexes'])) {
214
            foreach ($options['indexes'] as $index) {
215 216 217 218 219
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
            }
        }

        if (isset($options['foreignKeys'])) {
220
            foreach ((array) $options['foreignKeys'] as $definition) {
221 222 223 224 225 226
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }

        return $sql;
    }
227

228
    /**
229
     * {@inheritDoc}
230 231 232 233 234 235 236 237 238 239
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
        $flags = '';
        if ($index->hasFlag('nonclustered')) {
            $flags = ' NONCLUSTERED';
        }
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY' . $flags . ' (' . $this->getIndexFieldDeclarationListSQL($index->getColumns()) . ')';
    }

240
    /**
241
     * {@inheritDoc}
242
     */
243
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
244 245
    {
        $constraint = parent::getUniqueConstraintDeclarationSQL($name, $index);
246 247 248 249 250 251 252

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

        return $constraint;
    }

    /**
253
     * {@inheritDoc}
254 255 256 257 258
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
        $constraint = parent::getCreateIndexSQL($index, $table);

Craig Mason's avatar
Craig Mason committed
259
        if ($index->isUnique() && !$index->isPrimary()) {
260 261 262 263 264 265
            $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);
        }

        return $constraint;
    }

266
    /**
267
     * {@inheritDoc}
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
     */
    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;
    }

285
    /**
286
     * Extend unique key constraint with required filters
287 288 289
     *
     * @param string $sql
     * @param Index $index
290
     *
291 292 293 294 295
     * @return string
     */
    private function _appendUniqueConstraintDefinition($sql, Index $index)
    {
        $fields = array();
296 297 298 299
        foreach ($index->getColumns() as $field => $definition) {
            if (!is_array($definition)) {
                $field = $definition;
            }
300 301

            $fields[] = $field . ' IS NOT NULL';
302
        }
303 304 305

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

307
    /**
308
     * {@inheritDoc}
309
     */
310
    public function getAlterTableSQL(TableDiff $diff)
311
    {
312
        $queryParts = array();
313
        $sql = array();
314
        $columnSql = array();
315

316
        foreach ($diff->addedColumns as $column) {
317 318
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
319 320
            }

321
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
322 323
        }

324
        foreach ($diff->removedColumns as $column) {
325 326
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
327 328
            }

329
            $queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this);
330 331
        }

332
        foreach ($diff->changedColumns as $columnDiff) {
333 334
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
335 336
            }

337
            /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
338
            $column = $columnDiff->column;
339 340
            $queryParts[] = 'ALTER COLUMN ' .
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
341 342
        }

343
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
344 345
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
346 347
            }

348 349 350
            $sql[] = "sp_RENAME '". $diff->name. ".". $oldColumnName . "' , '".$column->getQuotedName($this)."', 'COLUMN'";
            $queryParts[] = 'ALTER COLUMN ' .
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
351
        }
352

353 354 355
        $tableSql = array();

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
356
            return array_merge($tableSql, $columnSql);
357
        }
358

359 360 361
        foreach ($queryParts as $query) {
            $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
        }
362

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

365 366 367 368
        if ($diff->newName !== false) {
            $sql[] = "sp_RENAME '" . $diff->name . "', '" . $diff->newName . "'";
        }

369
        return array_merge($sql, $tableSql, $columnSql);
370
    }
371

372
    /**
373
     * {@inheritDoc}
374
     */
375
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
376
    {
377
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
378 379
    }

380
    /**
381
     * {@inheritDoc}
382
     */
383
    public function getShowDatabasesSQL()
384
    {
385
        return 'SHOW DATABASES';
386 387 388
    }

    /**
389
     * {@inheritDoc}
390
     */
391
    public function getListTablesSQL()
392
    {
393 394
        // "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";
395 396 397
    }

    /**
398
     * {@inheritDoc}
399
     */
400
    public function getListTableColumnsSQL($table, $database = null)
401
    {
402
        return "exec sp_columns @table_name = '" . $table . "'";
403 404 405
    }

    /**
406
     * {@inheritDoc}
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
     */
    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 . "'";
    }

    /**
427
     * {@inheritDoc}
428
     */
429
    public function getListTableIndexesSQL($table, $currentDatabase = null)
430 431
    {
        return "exec sp_helpindex '" . $table . "'";
432
    }
433 434

    /**
435
     * {@inheritDoc}
436
     */
437
    public function getCreateViewSQL($name, $sql)
438 439 440
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
441 442

    /**
443
     * {@inheritDoc}
444
     */
445
    public function getListViewsSQL($database)
446 447 448 449
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

450
    /**
451
     * {@inheritDoc}
452 453 454
     */
    public function getDropViewSQL($name)
    {
455
        return 'DROP VIEW ' . $name;
456
    }
457 458

    /**
459
     * {@inheritDoc}
460
     */
461
    public function getRegexpExpression()
462
    {
463
        return 'RLIKE';
464 465 466
    }

    /**
467
     * {@inheritDoc}
468 469 470
     */
    public function getGuidExpression()
    {
471
        return 'UUID()';
472
    }
473 474

    /**
475
     * {@inheritDoc}
476
     */
477
    public function getLocateExpression($str, $substr, $startPos = false)
478
    {
479 480 481
        if ($startPos == false) {
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        }
482 483

        return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
484
    }
485

486
    /**
487
     * {@inheritDoc}
488
     */
489
    public function getModExpression($expression1, $expression2)
490
    {
491
        return $expression1 . ' % ' . $expression2;
492
    }
493

494
    /**
495
     * {@inheritDoc}
496
     */
497
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
498
    {
499
        if ( ! $char) {
500 501 502 503 504 505 506 507 508 509 510
            switch ($pos) {
                case self::TRIM_LEADING:
                    $trimFn = 'LTRIM';
                    break;

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

                default:
                    return 'LTRIM(RTRIM(' . $str . '))';
511 512 513 514
            }

            return $trimFn . '(' . $str . ')';
        }
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

        /** 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))';
536
    }
537

538
    /**
539
     * {@inheritDoc}
540 541
     */
    public function getConcatExpression()
542
    {
543
        $args = func_get_args();
544

545
        return '(' . implode(' + ', $args) . ')';
546
    }
547 548

    public function getListDatabasesSQL()
549 550 551
    {
        return 'SELECT * FROM SYS.DATABASES';
    }
552

553
    /**
554
     * {@inheritDoc}
555
     */
556
    public function getSubstringExpression($value, $from, $length = null)
557
    {
558 559
        if (!is_null($length)) {
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $length . ')';
560
        }
561

562
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
563
    }
564

565
    /**
566
     * {@inheritDoc}
567
     */
568
    public function getLengthExpression($column)
569
    {
570
        return 'LEN(' . $column . ')';
571 572
    }

573
    /**
574
     * {@inheritDoc}
575
     */
576
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
577
    {
578
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
579
    }
580

581
    /**
582
     * {@inheritDoc}
583
     */
584
    public function getIntegerTypeDeclarationSQL(array $field)
585
    {
586
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
587 588
    }

589
    /**
590
     * {@inheritDoc}
591
     */
592
    public function getBigIntTypeDeclarationSQL(array $field)
593
    {
594
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
595 596
    }

597
    /**
598
     * {@inheritDoc}
599
     */
600
    public function getSmallIntTypeDeclarationSQL(array $field)
601
    {
602
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
603 604
    }

605
    /**
606
     * {@inheritDoc}
607
     */
608
    public function getGuidTypeDeclarationSQL(array $field)
609 610 611 612
    {
        return 'UNIQUEIDENTIFIER';
    }

613 614 615
    /**
     * {@inheritDoc}
     */
616
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
617
    {
618
        return $fixed ? ($length ? 'NCHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
619
    }
620

621 622 623
    /**
     * {@inheritDoc}
     */
624
    public function getClobTypeDeclarationSQL(array $field)
625 626 627
    {
        return 'TEXT';
    }
628

629
    /**
630
     * {@inheritDoc}
631
     */
632
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
633
    {
634
        return (!empty($columnDef['autoincrement'])) ? ' IDENTITY' : '';
635
    }
636

637
    /**
638
     * {@inheritDoc}
639
     */
640
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
641
    {
642
        return 'DATETIME';
643 644
    }

645
    /**
646
     * {@inheritDoc}
647
     */
648
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
649
    {
650
        return 'DATETIME';
651
    }
652 653

    /**
654
     * {@inheritDoc}
655
     */
656
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
657
    {
658
        return 'DATETIME';
659
    }
660

661
    /**
662
     * {@inheritDoc}
663
     */
664
    public function getBooleanTypeDeclarationSQL(array $field)
665 666 667 668
    {
        return 'BIT';
    }

669
    /**
670
     * {@inheritDoc}
671 672 673
     *
     * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
     */
674
    protected function doModifyLimitQuery($query, $limit, $offset = null)
675 676
    {
        if ($limit > 0) {
677
            if ($offset == 0) {
678
                $query = preg_replace('/^(SELECT\s(DISTINCT\s)?)/i', '\1TOP ' . $limit . ' ', $query);
679 680
            } else {
                $orderby = stristr($query, 'ORDER BY');
681

682
                if ( ! $orderby) {
683 684 685
                    $over = 'ORDER BY (SELECT 0)';
                } else {
                    $over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby);
686 687
                }

688 689
                // Remove ORDER BY clause from $query
                $query = preg_replace('/\s+ORDER BY(.*)/', '', $query);
690
                $query = preg_replace('/\sFROM/i', ", ROW_NUMBER() OVER ($over) AS doctrine_rownum FROM", $query);
691

692
                $start = $offset + 1;
693
                $end = $offset + $limit;
694

695
                $query = "SELECT * FROM ($query) AS doctrine_tbl WHERE doctrine_rownum BETWEEN $start AND $end";
696 697 698 699 700
            }
        }

        return $query;
    }
701

702
    /**
703
     * {@inheritDoc}
704 705 706 707 708 709
     */
    public function supportsLimitOffset()
    {
        return false;
    }

710
    /**
711
     * {@inheritDoc}
712
     */
713
    public function convertBooleans($item)
714
    {
715 716 717
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
718
                    $item[$key] = ($value) ? 1 : 0;
719 720
                }
            }
721 722
        } else if (is_bool($item) || is_numeric($item)) {
            $item = ($item) ? 1 : 0;
723
        }
724

725
        return $item;
726
    }
727 728

    /**
729
     * {@inheritDoc}
730
     */
731
    public function getCreateTemporaryTableSnippetSQL()
732
    {
733
        return "CREATE TABLE";
734
    }
735

736
    /**
737
     * {@inheritDoc}
738 739 740 741 742 743
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

744
    /**
745
     * {@inheritDoc}
746 747 748
     */
    public function getDateTimeFormatString()
    {
749 750
        return 'Y-m-d H:i:s.000';
    }
751

752
    /**
753
     * {@inheritDoc}
754
     */
755 756 757 758 759 760
    public function getDateFormatString()
    {
        return 'Y-m-d H:i:s.000';
    }

    /**
761
     * {@inheritDoc}
762
     */
763 764 765
    public function getTimeFormatString()
    {
        return 'Y-m-d H:i:s.000';
766
    }
767

768
    /**
769
     * {@inheritDoc}
770 771 772 773 774
     */
    public function getDateTimeTzFormatString()
    {
        return $this->getDateTimeFormatString();
    }
775

776
    /**
777
     * {@inheritDoc}
778
     */
779
    public function getName()
780
    {
781
        return 'mssql';
782
    }
783

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
784
    /**
785
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
786
     */
787 788
    protected function initializeDoctrineTypeMappings()
    {
789
        $this->doctrineTypeMapping = array(
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
            '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',
            'datetimeoffset' => 'datetimetz',
            'smalldatetime' => 'datetime',
            'datetime' => 'datetime',
            'char' => 'string',
            'varchar' => 'string',
            'text' => 'text',
            'nchar' => 'string',
            'nvarchar' => 'string',
            'ntext' => 'text',
            'binary' => 'text',
813
            'varbinary' => 'blob',
814
            'image' => 'text',
815
            'uniqueidentifier' => 'guid',
816
        );
817
    }
818 819

    /**
820
     * {@inheritDoc}
821 822 823 824 825 826 827
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
828
     * {@inheritDoc}
829 830 831 832 833 834 835
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
836
     * {@inheritDoc}
837 838 839 840
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
841
    }
842 843

    /**
844
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
845
     */
846
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
847
    {
848 849
        // @todo coorect
        if ($lockMode == \Doctrine\DBAL\LockMode::PESSIMISTIC_READ) {
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
850
            return $fromClause . ' WITH (tablockx)';
851 852 853
        }

        if ($lockMode == \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) {
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
854 855
            return $fromClause . ' WITH (tablockx)';
        }
856 857

        return $fromClause;
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
858 859 860
    }

    /**
861
     * {@inheritDoc}
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
862 863 864 865 866
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
867

868 869 870
    /**
     * {@inheritDoc}
     */
871 872 873 874
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\MsSQLKeywords';
    }
875 876

    /**
877
     * {@inheritDoc}
878
     */
879
    public function quoteSingleIdentifier($str)
880
    {
881
        return "[" . str_replace("]", "][", $str) . "]";
882
    }
883

884 885 886
    /**
     * {@inheritDoc}
     */
887 888 889 890
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
        return 'TRUNCATE TABLE '.$tableName;
    }
891 892

    /**
893
     * {@inheritDoc}
894 895 896 897 898
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
899 900 901 902

    /**
     * {@inheritDoc}
     */
903 904
    public function getDefaultValueDeclarationSQL($field)
    {
905 906 907 908 909 910
        if ( ! isset($field['default'])) {
            return empty($field['notnull']) ? ' NULL' : '';
        }

        if ( ! isset($field['type'])) {
            return " DEFAULT '" . $field['default'] . "'";
911
        }
912 913 914 915 916 917 918 919 920 921 922 923 924 925

        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'] . "'";
926
    }
927
}