SQLServerSchemaManager.php 8.56 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
 *
Benjamin Morel's avatar
Benjamin Morel committed
28 29 30 31 32 33
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @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 82

        $type = $this->_platform->getDoctrineTypeMapping($dbType);
83

84
        switch ($type) {
85
            case 'char':
86
                $fixed = true;
87
                break;
88
            case 'text':
89 90
                $fixed = false;
                break;
romanb's avatar
romanb committed
91
        }
92

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

104 105 106 107 108 109 110 111
        $platformOptions = array(
            'collate' => $tableColumn['collation'] == 'NULL' ? null : $tableColumn['collation']
        );

        $column = new Column($tableColumn['name'], Type::getType($type), $options);
        $column->setPlatformOptions($platformOptions);

        return $column;
romanb's avatar
romanb committed
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 139 140 141
    /**
     * {@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
142
    /**
143
     * {@inheritdoc}
romanb's avatar
romanb committed
144
     */
145
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
romanb's avatar
romanb committed
146
    {
147 148 149 150
        foreach ($tableIndexRows as &$tableIndex) {
            $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique'];
            $tableIndex['primary'] = (boolean) $tableIndex['primary'];
            $tableIndex['flags'] = $tableIndex['flags'] ? array($tableIndex['flags']) : null;
151
        }
romanb's avatar
romanb committed
152

153
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
romanb's avatar
romanb committed
154 155 156
    }

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

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
187
     * {@inheritdoc}
188
     */
189
    protected function _getPortableViewDefinition($view)
190
    {
191
        // @todo
192 193
        return new View($view['name'], null);
    }
194

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

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

        return $this->_getPortableTableIndexesList($tableIndexes, $table);
    }
220 221

    /**
Benjamin Morel's avatar
Benjamin Morel committed
222
     * {@inheritdoc}
223 224 225 226 227 228 229 230 231 232 233 234
     */
    public function alterTable(TableDiff $tableDiff)
    {
        if(count($tableDiff->removedColumns) > 0) {
            foreach($tableDiff->removedColumns as $col){
                $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
235
        parent::alterTable($tableDiff);
236 237 238
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
239 240 241 242 243 244
     * Returns the SQL to retrieve the constraints for a given column.
     *
     * @param string $table
     * @param string $column
     *
     * @return string
245 246 247 248 249 250 251 252 253 254 255
     */
    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]";
    }
256
}