SQLServerSchemaManager.php 8.98 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * 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
Benjamin Morel's avatar
Benjamin Morel committed
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
21

22
use Doctrine\DBAL\Driver\SQLSrv\SQLSrvException;
23
use Doctrine\DBAL\Types\Type;
24

romanb's avatar
romanb committed
25
/**
Benjamin Morel's avatar
Benjamin Morel committed
26
 * SQL Server Schema Manager.
romanb's avatar
romanb committed
27
 *
28
 * @license http://www.opensource.org/licenses/mit-license.php MIT
Benjamin Morel's avatar
Benjamin Morel committed
29 30 31 32 33
 * @author  Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author  Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author  Juozas Kaziukenas <juozas@juokaz.com>
 * @author  Steve Müller <st.mueller@dzh-online.de>
 * @since   2.0
romanb's avatar
romanb committed
34
 */
35
class SQLServerSchemaManager extends AbstractSchemaManager
36
{
37 38 39 40 41 42 43 44
    /**
     * {@inheritdoc}
     */
    protected function _getPortableSequenceDefinition($sequence)
    {
        return new Sequence($sequence['name'], $sequence['increment'], $sequence['start_value']);
    }

romanb's avatar
romanb committed
45
    /**
46
     * {@inheritdoc}
romanb's avatar
romanb committed
47
     */
48
    protected function _getPortableTableColumnDefinition($tableColumn)
romanb's avatar
romanb committed
49
    {
50
        $dbType = strtok($tableColumn['type'], '(), ');
51 52 53
        $fixed = null;
        $length = (int) $tableColumn['length'];
        $default = $tableColumn['default'];
romanb's avatar
romanb committed
54

55
        if (!isset($tableColumn['name'])) {
56
            $tableColumn['name'] = '';
romanb's avatar
romanb committed
57
        }
58 59

        while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
60
            $default = trim($default2, "'");
61 62 63 64

            if ($default == 'getdate()') {
                $default = $this->_platform->getCurrentTimestampSQL();
            }
65
        }
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80
        switch ($dbType) {
            case 'nchar':
            case 'nvarchar':
            case 'ntext':
                // Unicode data requires 2 bytes per character
                $length = $length / 2;
                break;
            case 'varchar':
                // TEXT type is returned as VARCHAR(MAX) with a length of -1
                if ($length == -1) {
                    $dbType = 'text';
                }
                break;
        }
81

Steve Müller's avatar
Steve Müller committed
82 83 84 85
        if ('char' === $dbType || 'nchar' === $dbType || 'binary' === $dbType) {
            $fixed = true;
        }

86 87 88
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
89

90
        $options = array(
91 92 93 94 95 96 97
            'length'        => ($length == 0 || !in_array($type, array('text', 'string'))) ? null : $length,
            'unsigned'      => false,
            'fixed'         => (bool) $fixed,
            'default'       => $default !== 'NULL' ? $default : null,
            'notnull'       => (bool) $tableColumn['notnull'],
            'scale'         => $tableColumn['scale'],
            'precision'     => $tableColumn['precision'],
98
            'autoincrement' => (bool) $tableColumn['autoincrement'],
99
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
100
        );
101

102
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
103 104 105 106

        if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
            $column->setPlatformOption('collation', $tableColumn['collation']);
        }
107 108

        return $column;
romanb's avatar
romanb committed
109 110
    }

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    /**
     * {@inheritdoc}
     */
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
        $foreignKeys = array();

        foreach ($tableForeignKeys as $tableForeignKey) {
            if ( ! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
                $foreignKeys[$tableForeignKey['ForeignKey']] = array(
                    'local_columns' => array($tableForeignKey['ColumnName']),
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
                    'foreign_columns' => array($tableForeignKey['ReferenceColumnName']),
                    'name' => $tableForeignKey['ForeignKey'],
                    'options' => array(
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc'])
                    )
                );
            } else {
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName'];
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
            }
        }

        return parent::_getPortableTableForeignKeysList($foreignKeys);
    }

romanb's avatar
romanb committed
139
    /**
140
     * {@inheritdoc}
romanb's avatar
romanb committed
141
     */
142
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
romanb's avatar
romanb committed
143
    {
144 145 146 147
        foreach ($tableIndexRows as &$tableIndex) {
            $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique'];
            $tableIndex['primary'] = (boolean) $tableIndex['primary'];
            $tableIndex['flags'] = $tableIndex['flags'] ? array($tableIndex['flags']) : null;
148
        }
romanb's avatar
romanb committed
149

150
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
romanb's avatar
romanb committed
151 152 153
    }

    /**
154
     * {@inheritdoc}
romanb's avatar
romanb committed
155
     */
156
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
157
    {
158
        return new ForeignKeyConstraint(
159 160 161 162 163
            $tableForeignKey['local_columns'],
            $tableForeignKey['foreign_table'],
            $tableForeignKey['foreign_columns'],
            $tableForeignKey['name'],
            $tableForeignKey['options']
164
        );
romanb's avatar
romanb committed
165 166 167
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
168
     * {@inheritdoc}
romanb's avatar
romanb committed
169
     */
170
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
171
    {
172
        return $table['name'];
romanb's avatar
romanb committed
173
    }
174 175

    /**
Benjamin Morel's avatar
Benjamin Morel committed
176
     * {@inheritdoc}
177
     */
178
    protected function _getPortableDatabaseDefinition($database)
179 180 181
    {
        return $database['name'];
    }
182

183 184 185 186 187 188 189 190
    /**
     * {@inheritdoc}
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace['name'];
    }

191
    /**
Benjamin Morel's avatar
Benjamin Morel committed
192
     * {@inheritdoc}
193
     */
194
    protected function _getPortableViewDefinition($view)
195
    {
196
        // @todo
197 198
        return new View($view['name'], null);
    }
199

200
    /**
Benjamin Morel's avatar
Benjamin Morel committed
201
     * {@inheritdoc}
202 203 204 205 206 207 208
     */
    public function listTableIndexes($table)
    {
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());

        try {
            $tableIndexes = $this->_conn->fetchAll($sql);
209
        } catch (\PDOException $e) {
210 211 212 213 214
            if ($e->getCode() == "IMSSP") {
                return array();
            } else {
                throw $e;
            }
215
        } catch (SQLSrvException $e) {
216 217 218 219 220
            if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
                return array();
            } else {
                throw $e;
            }
221 222 223 224
        }

        return $this->_getPortableTableIndexesList($tableIndexes, $table);
    }
225 226

    /**
Benjamin Morel's avatar
Benjamin Morel committed
227
     * {@inheritdoc}
228 229 230
     */
    public function alterTable(TableDiff $tableDiff)
    {
Steve Müller's avatar
Steve Müller committed
231 232
        if (count($tableDiff->removedColumns) > 0) {
            foreach ($tableDiff->removedColumns as $col) {
233 234 235 236 237 238 239
                $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
                foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
                    $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']);
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
240
        parent::alterTable($tableDiff);
241 242 243
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
244 245 246 247 248 249
     * Returns the SQL to retrieve the constraints for a given column.
     *
     * @param string $table
     * @param string $column
     *
     * @return string
250 251 252 253 254 255 256 257 258 259 260
     */
    private function getColumnConstraintSQL($table, $column)
    {
        return "SELECT SysObjects.[Name]
            FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
            ON Tab.[ID] = Sysobjects.[Parent_Obj]
            INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
            INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
            WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . "
            ORDER BY Col.[Name]";
    }
261
}