SQLServerSchemaManager.php 8.96 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
romanb's avatar
romanb committed
17 18 19
 * <http://www.phpdoctrine.org>.
 */

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

22
use Doctrine\DBAL\Events;
23
use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
24
use Doctrine\DBAL\Driver\SQLSrv\SQLSrvException;
25

romanb's avatar
romanb committed
26
/**
27
 * SQL Server Schema Manager
romanb's avatar
romanb committed
28 29 30 31
 *
 * @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)
32
 * @author      Juozas Kaziukenas <juozas@juokaz.com>
romanb's avatar
romanb committed
33 34
 * @since       2.0
 */
35
class SQLServerSchemaManager extends AbstractSchemaManager
36
{
romanb's avatar
romanb committed
37
    /**
38
     * @override
romanb's avatar
romanb committed
39
     */
40
    protected function _getPortableTableColumnDefinition($tableColumn)
romanb's avatar
romanb committed
41
    {
42 43
        $dbType = strtolower($tableColumn['TYPE_NAME']);

44
        $autoincrement = false;
45 46
        if (stripos($dbType, 'identity')) {
            $dbType = trim(str_ireplace('identity', '', $dbType));
47
            $autoincrement = true;
romanb's avatar
romanb committed
48 49
        }

50 51
        $type = array();
        $unsigned = $fixed = null;
romanb's avatar
romanb committed
52

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

57 58
        $default = $tableColumn['COLUMN_DEF'];

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

        $length = (int) $tableColumn['LENGTH'];

        $type = $this->_platform->getDoctrineTypeMapping($dbType);
66
        switch ($type) {
67 68 69 70 71 72
            case 'char':
                if ($tableColumn['LENGTH'] == '1') {
                    $type = 'boolean';
                    if (preg_match('/^(is|has)/', $tableColumn['name'])) {
                        $type = array_reverse($type);
                    }
romanb's avatar
romanb committed
73
                }
74
                $fixed = true;
75
                break;
76
            case 'text':
77 78
                $fixed = false;
                break;
romanb's avatar
romanb committed
79
        }
80 81 82 83
        switch ($dbType) {
            case 'nchar':
            case 'nvarchar':
            case 'ntext':
84 85 86
                // Unicode data requires 2 bytes per character
                $length = $length / 2;
                break;
87
        }
88

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

100
        return new Column($tableColumn['COLUMN_NAME'], \Doctrine\DBAL\Types\Type::getType($type), $options);
romanb's avatar
romanb committed
101 102 103
    }

    /**
104
     * @override
romanb's avatar
romanb committed
105
     */
106
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
romanb's avatar
romanb committed
107
    {
108
        // TODO: Remove code duplication with AbstractSchemaManager;
109
        $result = array();
110
        foreach ($tableIndexRows as $tableIndex) {
111
            $indexName = $keyName = $tableIndex['index_name'];
112
            if (strpos($tableIndex['index_description'], 'primary key') !== false) {
113
                $keyName = 'primary';
romanb's avatar
romanb committed
114
            }
115
            $keyName = strtolower($keyName);
romanb's avatar
romanb committed
116

117 118 119 120 121 122 123
            $flags = array();
            if (strpos($tableIndex['index_description'], 'clustered') !== false) {
                $flags[] = 'clustered';
            } else if (strpos($tableIndex['index_description'], 'nonclustered') !== false) {
                $flags[] = 'nonclustered';
            }

124 125 126 127 128
            $result[$keyName] = array(
                'name' => $indexName,
                'columns' => explode(', ', $tableIndex['index_keys']),
                'unique' => strpos($tableIndex['index_description'], 'unique') !== false,
                'primary' => strpos($tableIndex['index_description'], 'primary key') !== false,
129
                'flags' => $flags,
romanb's avatar
romanb committed
130 131 132
            );
        }

133 134
        $eventManager = $this->_platform->getEventManager();

135
        $indexes = array();
136
        foreach ($result as $indexKey => $data) {
137 138 139 140 141 142 143 144 145 146 147
            $index = null;
            $defaultPrevented = false;

            if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
                $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
                $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
                $index = $eventArgs->getIndex();
            }

148
            if ( ! $defaultPrevented) {
149 150 151 152 153 154
                $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary']);
            }

            if ($index) {
                $indexes[$indexKey] = $index;
            }
155
        }
romanb's avatar
romanb committed
156

157
        return $indexes;
romanb's avatar
romanb committed
158 159 160
    }

    /**
161
     * @override
romanb's avatar
romanb committed
162
     */
163
    public function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
164
    {
165
        return new ForeignKeyConstraint(
166 167 168 169 170 171 172 173
                (array) $tableForeignKey['ColumnName'],
                $tableForeignKey['ReferenceTableName'],
                (array) $tableForeignKey['ReferenceColumnName'],
                $tableForeignKey['ForeignKey'],
                array(
                    'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
                    'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
                )
174
        );
romanb's avatar
romanb committed
175 176 177
    }

    /**
178
     * @override
romanb's avatar
romanb committed
179
     */
180
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
181
    {
182
        return $table['name'];
romanb's avatar
romanb committed
183
    }
184 185

    /**
186 187
     * @override
     */
188
    protected function _getPortableDatabaseDefinition($database)
189 190 191
    {
        return $database['name'];
    }
192 193

    /**
194 195
     * @override
     */
196
    protected function _getPortableViewDefinition($view)
197
    {
198
        // @todo
199 200
        return new View($view['name'], null);
    }
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    /**
     * List the indexes for a given table returning an array of Index instances.
     *
     * Keys of the portable indexes list are all lower-cased.
     *
     * @param string $table The name of the table
     * @return Index[] $tableIndexes
     */
    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;
            }
222 223 224 225 226 227
        } catch(SQLSrvException $e) {
            if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
                return array();
            } else {
                throw $e;
            }
228 229 230 231
        }

        return $this->_getPortableTableIndexesList($tableIndexes, $table);
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

    /**
     * @override
     */
    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']);
                }
            }
        }

        return parent::alterTable($tableDiff);
    }

    /**
     * This function retrieves the constraints for a given column.
     */
    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]";
    }
263
}