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

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

21
namespace Doctrine\DBAL\Platforms;
22

23 24
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\DBALException;
25
use Doctrine\DBAL\Schema\Index,
26
    Doctrine\DBAL\Schema\Table;
27 28

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

47 48 49 50
    public function getDateAddDaysExpression($date, $days)
    {
        return 'DATEADD(day, ' . $days . ', ' . $date . ')';
    }
51

52 53 54 55
    public function getDateSubDaysExpression($date, $days)
    {
        return 'DATEADD(day, -1 * ' . $days . ', ' . $date . ')';
    }
56

57 58 59 60
    public function getDateAddMonthExpression($date, $months)
    {
        return 'DATEADD(month, ' . $months . ', ' . $date . ')';
    }
61

62 63 64 65
    public function getDateSubMonthExpression($date, $months)
    {
        return 'DATEADD(month, -1 * ' . $months . ', ' . $date . ')';
    }
66

67
    /**
68 69 70
     * Whether the platform prefers identity columns for ID generation.
     * MsSql prefers "autoincrement" identity columns since sequences can only
     * be emulated with a table.
71
     *
72
     * @return boolean
73 74
     * @override
     */
75
    public function prefersIdentityColumns()
76
    {
77 78
        return true;
    }
79

80 81 82 83 84 85 86 87 88 89 90 91 92
    /**
     * Whether the platform supports identity columns.
     * MsSql supports this through AUTO_INCREMENT columns.
     *
     * @return boolean
     * @override
     */
    public function supportsIdentityColumns()
    {
        return true;
    }

    /**
93
     * Whether the platform supports releasing savepoints.
94 95 96
     *
     * @return boolean
     */
97
    public function supportsReleaseSavepoints()
98 99 100
    {
        return false;
    }
101

102 103 104 105 106 107 108 109 110 111 112
    /**
     * create a new database
     *
     * @param string $name name of the database that should be created
     * @return string
     * @override
     */
    public function getCreateDatabaseSQL($name)
    {
        return 'CREATE DATABASE ' . $name;
    }
113

114 115 116 117 118 119 120 121 122
    /**
     * drop an existing database
     *
     * @param string $name name of the database that should be dropped
     * @return string
     * @override
     */
    public function getDropDatabaseSQL($name)
    {
123 124 125 126 127 128
        return 'DROP DATABASE ' . $name;
    }

    /**
     * @override
     */
129
    public function supportsCreateDropDatabase()
130 131
    {
        return false;
132 133 134 135 136 137 138 139
    }

    /**
     * @override
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
        if ($foreignKey instanceof \Doctrine\DBAL\Schema\ForeignKeyConstraint) {
140
            $foreignKey = $foreignKey->getQuotedName($this);
141 142
        }

143
        if ($table instanceof \Doctrine\DBAL\Schema\Table) {
144
            $table = $table->getQuotedName($this);
145 146 147
        }

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

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

162 163 164 165
        if (!isset($table)) {
            return 'DROP INDEX ' . $index;
        } else {
            if ($table instanceof \Doctrine\DBAL\Schema\Table) {
166
                $table = $table->getQuotedName($this);
167 168 169
            }

            return "IF EXISTS (SELECT * FROM sysobjects WHERE name = '$index')
170
						ALTER TABLE " . $table . " DROP CONSTRAINT " . $index . "
Benjamin Eberlei's avatar
Benjamin Eberlei committed
171
					ELSE
172
						DROP INDEX " . $index . " ON " . $table;
173
        }
174
    }
175 176 177 178 179

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

189
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
190 191

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

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

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

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

        $sql[] = $query;
214 215

        if (isset($options['indexes']) && !empty($options['indexes'])) {
216 217 218 219 220 221 222 223 224 225 226 227 228
            foreach ($options['indexes'] AS $index) {
                $sql[] = $this->getCreateIndexSQL($index, $tableName);
            }
        }

        if (isset($options['foreignKeys'])) {
            foreach ((array) $options['foreignKeys'] AS $definition) {
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
            }
        }

        return $sql;
    }
229

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    /**
     * Get SQL to create an unnamed primary key constraint.
     *
     * @param Index $index
     * @param string|Table $table
     * @return string
     */
    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()) . ')';
    }

246
    /**
247 248
     * @override
     */
249
    public function getUniqueConstraintDeclarationSQL($name, Index $index)
250 251
    {
        $constraint = parent::getUniqueConstraintDeclarationSQL($name, $index);
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

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

        return $constraint;
    }

    /**
     * @override
     */
    public function getCreateIndexSQL(Index $index, $table)
    {
        $constraint = parent::getCreateIndexSQL($index, $table);

        if ($index->isUnique()) {
            $constraint = $this->_appendUniqueConstraintDefinition($constraint, $index);
        }

        return $constraint;
    }

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /**
     * @override
     */
    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;
    }

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

            $fields[] = $field . ' IS NOT NULL';
307
        }
308 309 310

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

312
    /**
313
     * @override
314
     */
315
    public function getAlterTableSQL(TableDiff $diff)
316
    {
317
        $queryParts = array();
318
        $sql = array();
319
        $columnSql = array();
320

321
        if ($diff->newName !== false) {
322
            $queryParts[] = 'RENAME TO ' . $diff->newName;
323 324
        }

325
        foreach ($diff->addedColumns AS $fieldName => $column) {
326 327
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
328 329
            }

330
            $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
331 332
        }

333
        foreach ($diff->removedColumns AS $column) {
334 335
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
336 337
            }

338
            $queryParts[] = 'DROP COLUMN ' . $column->getQuotedName($this);
339 340
        }

341
        foreach ($diff->changedColumns AS $columnDiff) {
342 343
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
344 345
            }

346 347
            /* @var $columnDiff Doctrine\DBAL\Schema\ColumnDiff */
            $column = $columnDiff->column;
348 349
            $queryParts[] = 'ALTER COLUMN ' .
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
350 351
        }

352
        foreach ($diff->renamedColumns AS $oldColumnName => $column) {
353 354
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
355 356
            }

357 358 359
            $sql[] = "sp_RENAME '". $diff->name. ".". $oldColumnName . "' , '".$column->getQuotedName($this)."', 'COLUMN'";
            $queryParts[] = 'ALTER COLUMN ' .
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
360
        }
361

362 363 364
        $tableSql = array();

        if ($this->onSchemaAlterTable($diff, $tableSql)) {
365
            return array_merge($tableSql, $columnSql);
366
        }
367

368 369 370
        foreach ($queryParts as $query) {
            $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
        }
371

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

374
        return array_merge($sql, $tableSql, $columnSql);
375
    }
376

377 378 379
    /**
     * @override
     */
380
    public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
381
    {
382
        return 'INSERT INTO ' . $quotedTableName . ' DEFAULT VALUES';
383 384
    }

385 386 387
    /**
     * @override
     */
388
    public function getShowDatabasesSQL()
389
    {
390
        return 'SHOW DATABASES';
391 392 393 394 395
    }

    /**
     * @override
     */
396
    public function getListTablesSQL()
397
    {
398 399
        // "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";
400 401 402 403 404
    }

    /**
     * @override
     */
405
    public function getListTableColumnsSQL($table, $database = null)
406
    {
407
        return "exec sp_columns @table_name = '" . $table . "'";
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    }

    /**
     * @override
     */
    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 . "'";
    }

    /**
     * @override
     */
434
    public function getListTableIndexesSQL($table, $currentDatabase = null)
435 436
    {
        return "exec sp_helpindex '" . $table . "'";
437
    }
438 439

    /**
440 441
     * @override
     */
442
    public function getCreateViewSQL($name, $sql)
443 444 445
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }
446 447

    /**
448 449
     * @override
     */
450
    public function getListViewsSQL($database)
451 452 453 454
    {
        return "SELECT name FROM sysobjects WHERE type = 'V' ORDER BY name";
    }

455
    /**
456 457 458 459
     * @override
     */
    public function getDropViewSQL($name)
    {
460
        return 'DROP VIEW ' . $name;
461
    }
462 463

    /**
464
     * Returns the regular expression operator.
465
     *
466
     * @return string
467 468
     * @override
     */
469
    public function getRegexpExpression()
470
    {
471
        return 'RLIKE';
472 473 474 475 476 477 478 479 480 481
    }

    /**
     * Returns global unique identifier
     *
     * @return string to get global unique identifier
     * @override
     */
    public function getGuidExpression()
    {
482
        return 'UUID()';
483
    }
484 485 486 487

    /**
     * @override
     */
488
    public function getLocateExpression($str, $substr, $startPos = false)
489
    {
490 491 492
        if ($startPos == false) {
            return 'CHARINDEX(' . $substr . ', ' . $str . ')';
        } else {
493
            return 'CHARINDEX(' . $substr . ', ' . $str . ', ' . $startPos . ')';
494
        }
495
    }
496

497 498 499
    /**
     * @override
     */
500
    public function getModExpression($expression1, $expression2)
501
    {
502
        return $expression1 . ' % ' . $expression2;
503
    }
504

505 506 507
    /**
     * @override
     */
508
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
509
    {
510
        $trimFn = '';
511

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        if (!$char) {
            if ($pos == self::TRIM_LEADING) {
                $trimFn = 'LTRIM';
            } else if ($pos == self::TRIM_TRAILING) {
                $trimFn = 'RTRIM';
            } else {
                return 'LTRIM(RTRIM(' . $str . '))';
            }

            return $trimFn . '(' . $str . ')';
        } else {
            /** 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)';
            } else if ($pos == self::TRIM_TRAILING) {
                return 'reverse(stuff(reverse(' . $str . '), 1, patindex(' . $pattern . ', reverse(' . $str . ')) - 1, null))';
            } else {
                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))';
            }
        }
542
    }
543

544 545 546 547
    /**
     * @override
     */
    public function getConcatExpression()
548
    {
549 550
        $args = func_get_args();
        return '(' . implode(' + ', $args) . ')';
551
    }
552 553

    public function getListDatabasesSQL()
554 555 556
    {
        return 'SELECT * FROM SYS.DATABASES';
    }
557

558
    /**
559 560
     * @override
     */
561
    public function getSubstringExpression($value, $from, $len = null)
562
    {
563
        if (!is_null($len)) {
564 565 566
            return 'SUBSTRING(' . $value . ', ' . $from . ', ' . $len . ')';
        }
        return 'SUBSTRING(' . $value . ', ' . $from . ', LEN(' . $value . ') - ' . $from . ' + 1)';
567
    }
568

569 570 571
    /**
     * @override
     */
572
    public function getLengthExpression($column)
573
    {
574
        return 'LEN(' . $column . ')';
575 576
    }

577 578 579
    /**
     * @override
     */
580
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
581
    {
582
        return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
583
    }
584

585 586
    /**
     * @override
587
     */
588
    public function getIntegerTypeDeclarationSQL(array $field)
589
    {
590
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
591 592
    }

593
    /**
594
     * @override
595
     */
596
    public function getBigIntTypeDeclarationSQL(array $field)
597
    {
598
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
599 600
    }

601 602
    /**
     * @override
603
     */
604
    public function getSmallIntTypeDeclarationSQL(array $field)
605
    {
606
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
607 608
    }

609 610 611 612 613 614 615 616 617 618 619
    /**
     * Decleration for a UNIQUEIDENTIFIER (GUID) field in SQL Server
     *
     * @param array $field
     * @return string
     */
    public function getGuidTypeDeclartionSQL(array $field)
    {
        return 'UNIQUEIDENTIFIER';
    }

620
    /** @override */
621
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
622
    {
623
        return $fixed ? ($length ? 'NCHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'NVARCHAR(' . $length . ')' : 'NVARCHAR(255)');
624
    }
625

626
    /** @override */
627
    public function getClobTypeDeclarationSQL(array $field)
628 629 630
    {
        return 'TEXT';
    }
631

632 633
    /**
     * @override
634
     */
635
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
636 637
    {
        $autoinc = '';
638
        if (!empty($columnDef['autoincrement'])) {
639
            $autoinc = ' IDENTITY';
640 641 642 643 644
        }
        $unsigned = (isset($columnDef['unsigned']) && $columnDef['unsigned']) ? ' UNSIGNED' : '';

        return $unsigned . $autoinc;
    }
645

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

654 655 656
    /**
     * @override
     */
657
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
658
    {
659
        return 'DATETIME';
660
    }
661 662 663 664

    /**
     * @override
     */
665
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
666
    {
667
        return 'DATETIME';
668
    }
669

670 671 672
    /**
     * @override
     */
673
    public function getBooleanTypeDeclarationSQL(array $field)
674 675 676 677
    {
        return 'BIT';
    }

678 679 680 681
    /**
     * Adds an adapter-specific LIMIT clause to the SELECT statement.
     *
     * @param string $query
682 683
     * @param integer $limit
     * @param integer $offset
684 685 686
     * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
     * @return string
     */
687
    protected function doModifyLimitQuery($query, $limit, $offset = null)
688 689
    {
        if ($limit > 0) {
690
            if ($offset == 0) {
691
                $query = preg_replace('/^(SELECT\s(DISTINCT\s)?)/i', '\1TOP ' . $limit . ' ', $query);
692 693
            } else {
                $orderby = stristr($query, 'ORDER BY');
694

695 696 697 698
                if (!$orderby) {
                    $over = 'ORDER BY (SELECT 0)';
                } else {
                    $over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby);
699 700
                }

701 702
                // Remove ORDER BY clause from $query
                $query = preg_replace('/\s+ORDER BY(.*)/', '', $query);
AaronDDM's avatar
AaronDDM committed
703
                $query = preg_replace('/^SELECT\s/', '', $query);
704

705
                $start = $offset + 1;
706
                $end = $offset + $limit;
707

AaronDDM's avatar
AaronDDM committed
708
                $query = "SELECT * FROM (SELECT ROW_NUMBER() OVER ($over) AS \"doctrine_rownum\", $query) AS doctrine_tbl WHERE \"doctrine_rownum\" BETWEEN $start AND $end";
709 710 711 712 713
            }
        }

        return $query;
    }
714

715 716 717 718 719 720 721 722
    /**
     * @override
     */
    public function supportsLimitOffset()
    {
        return false;
    }

723
    /**
724
     * @override
725
     */
726
    public function convertBooleans($item)
727
    {
728 729 730
        if (is_array($item)) {
            foreach ($item as $key => $value) {
                if (is_bool($value) || is_numeric($item)) {
731
                    $item[$key] = ($value) ? 1 : 0;
732 733 734
                }
            }
        } else {
735
            if (is_bool($item) || is_numeric($item)) {
736
                $item = ($item) ? 1 : 0;
737
            }
738 739
        }
        return $item;
740
    }
741 742

    /**
743
     * @override
744
     */
745
    public function getCreateTemporaryTableSnippetSQL()
746
    {
747
        return "CREATE TABLE";
748
    }
749

750 751 752 753 754 755 756 757
    /**
     * @override
     */
    public function getTemporaryTableName($tableName)
    {
        return '#' . $tableName;
    }

758
    /**
759 760 761 762
     * @override
     */
    public function getDateTimeFormatString()
    {
763 764
        return 'Y-m-d H:i:s.000';
    }
765

766 767
    /**
     * @override
768
     */
769 770 771 772 773 774 775
    public function getDateFormatString()
    {
        return 'Y-m-d H:i:s.000';
    }

    /**
     * @override
776
     */
777 778 779
    public function getTimeFormatString()
    {
        return 'Y-m-d H:i:s.000';
780
    }
781

782 783 784 785 786 787 788
    /**
     * @override
     */
    public function getDateTimeTzFormatString()
    {
        return $this->getDateTimeFormatString();
    }
789

790
    /**
791 792
     * Get the platform name for this instance
     *
793 794
     * @return string
     */
795
    public function getName()
796
    {
797
        return 'mssql';
798
    }
799

Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
800 801 802
    /**
     * @override
     */
803 804
    protected function initializeDoctrineTypeMappings()
    {
805
        $this->doctrineTypeMapping = array(
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
            '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',
829
            'varbinary' => 'blob',
830
            'image' => 'text',
831
            'uniqueidentifier' => 'guid',
832
        );
833
    }
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865

    /**
     * Generate SQL to create a new savepoint
     *
     * @param string $savepoint
     * @return string
     */
    public function createSavePoint($savepoint)
    {
        return 'SAVE TRANSACTION ' . $savepoint;
    }

    /**
     * Generate SQL to release a savepoint
     *
     * @param string $savepoint
     * @return string
     */
    public function releaseSavePoint($savepoint)
    {
        return '';
    }

    /**
     * Generate SQL to rollback a savepoint
     *
     * @param string $savepoint
     * @return string
     */
    public function rollbackSavePoint($savepoint)
    {
        return 'ROLLBACK TRANSACTION ' . $savepoint;
866
    }
867 868

    /**
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
869 870
     * @override
     */
871
    public function appendLockHint($fromClause, $lockMode)
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
872
    {
873 874
        // @todo coorect
        if ($lockMode == \Doctrine\DBAL\LockMode::PESSIMISTIC_READ) {
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
875 876 877
            return $fromClause . ' WITH (tablockx)';
        } else if ($lockMode == \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) {
            return $fromClause . ' WITH (tablockx)';
878 879
        } else {
            return $fromClause;
Juozas Kaziukenas's avatar
Juozas Kaziukenas committed
880 881 882 883 884 885 886 887 888 889
        }
    }

    /**
     * @override
     */
    public function getForUpdateSQL()
    {
        return ' ';
    }
890

891 892 893 894
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\MsSQLKeywords';
    }
895 896

    /**
897
     * {@inheritDoc}
898
     */
899
    public function quoteSingleIdentifier($str)
900
    {
901
        return "[" . str_replace("]", "][", $str) . "]";
902
    }
903

904 905 906 907
    public function getTruncateTableSQL($tableName, $cascade = false)
    {
        return 'TRUNCATE TABLE '.$tableName;
    }
908 909 910 911 912 913 914 915

    /**
     * Gets the SQL Snippet used to declare a BLOB column type.
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'VARBINARY(MAX)';
    }
916
}