SQLServerSchemaManager.php 10.5 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 23
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\DriverException;
24
use Doctrine\DBAL\Types\Type;
25

romanb's avatar
romanb committed
26
/**
Benjamin Morel's avatar
Benjamin Morel committed
27
 * SQL Server Schema Manager.
romanb's avatar
romanb committed
28
 *
29
 * @license http://www.opensource.org/licenses/mit-license.php MIT
Benjamin Morel's avatar
Benjamin Morel committed
30 31 32 33 34
 * @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
35
 */
36
class SQLServerSchemaManager extends AbstractSchemaManager
37
{
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
    {
        try {
            parent::dropDatabase($database);
        } catch (DBALException $exception) {
            $exception = $exception->getPrevious();

            if (! $exception instanceof DriverException) {
                throw $exception;
            }

            // If we have a error code 3702, the drop database operation failed
            // because of active connections on the database.
            // To force dropping the database, we first have to close all active connections
            // on that database and issue the drop database operation again.
            if ($exception->getErrorCode() !== 3702) {
                throw $exception;
            }

            $this->closeActiveDatabaseConnections($database);

            parent::dropDatabase($database);
        }
    }

66 67 68 69 70 71 72 73
    /**
     * {@inheritdoc}
     */
    protected function _getPortableSequenceDefinition($sequence)
    {
        return new Sequence($sequence['name'], $sequence['increment'], $sequence['start_value']);
    }

romanb's avatar
romanb committed
74
    /**
75
     * {@inheritdoc}
romanb's avatar
romanb committed
76
     */
77
    protected function _getPortableTableColumnDefinition($tableColumn)
romanb's avatar
romanb committed
78
    {
79
        $dbType = strtok($tableColumn['type'], '(), ');
80 81 82
        $fixed = null;
        $length = (int) $tableColumn['length'];
        $default = $tableColumn['default'];
romanb's avatar
romanb committed
83

84
        if (!isset($tableColumn['name'])) {
85
            $tableColumn['name'] = '';
romanb's avatar
romanb committed
86
        }
87 88

        while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
89
            $default = trim($default2, "'");
90 91 92 93

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

96 97 98 99 100 101 102 103 104 105 106 107 108 109
        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;
        }
110

Steve Müller's avatar
Steve Müller committed
111 112 113 114
        if ('char' === $dbType || 'nchar' === $dbType || 'binary' === $dbType) {
            $fixed = true;
        }

115 116 117
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
118

119 120
        $options = [
            'length'        => ($length == 0 || !in_array($type, ['text', 'string'])) ? null : $length,
121 122 123 124 125 126
            'unsigned'      => false,
            'fixed'         => (bool) $fixed,
            'default'       => $default !== 'NULL' ? $default : null,
            'notnull'       => (bool) $tableColumn['notnull'],
            'scale'         => $tableColumn['scale'],
            'precision'     => $tableColumn['precision'],
127
            'autoincrement' => (bool) $tableColumn['autoincrement'],
128
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
129
        ];
130

131
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
132 133 134 135

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

        return $column;
romanb's avatar
romanb committed
138 139
    }

140 141 142 143 144
    /**
     * {@inheritdoc}
     */
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
145
        $foreignKeys = [];
146 147 148

        foreach ($tableForeignKeys as $tableForeignKey) {
            if ( ! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
149 150
                $foreignKeys[$tableForeignKey['ForeignKey']] = [
                    'local_columns' => [$tableForeignKey['ColumnName']],
151
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
152
                    'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
153
                    'name' => $tableForeignKey['ForeignKey'],
154
                    'options' => [
155 156
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc'])
157 158
                    ]
                ];
159 160 161 162 163 164 165 166 167
            } else {
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName'];
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
            }
        }

        return parent::_getPortableTableForeignKeysList($foreignKeys);
    }

romanb's avatar
romanb committed
168
    /**
169
     * {@inheritdoc}
romanb's avatar
romanb committed
170
     */
171
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
romanb's avatar
romanb committed
172
    {
173 174 175
        foreach ($tableIndexRows as &$tableIndex) {
            $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique'];
            $tableIndex['primary'] = (boolean) $tableIndex['primary'];
176
            $tableIndex['flags'] = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
177
        }
romanb's avatar
romanb committed
178

179
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
romanb's avatar
romanb committed
180 181 182
    }

    /**
183
     * {@inheritdoc}
romanb's avatar
romanb committed
184
     */
185
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
romanb's avatar
romanb committed
186
    {
187
        return new ForeignKeyConstraint(
188 189 190 191 192
            $tableForeignKey['local_columns'],
            $tableForeignKey['foreign_table'],
            $tableForeignKey['foreign_columns'],
            $tableForeignKey['name'],
            $tableForeignKey['options']
193
        );
romanb's avatar
romanb committed
194 195 196
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
197
     * {@inheritdoc}
romanb's avatar
romanb committed
198
     */
199
    protected function _getPortableTableDefinition($table)
romanb's avatar
romanb committed
200
    {
201
        return $table['name'];
romanb's avatar
romanb committed
202
    }
203 204

    /**
Benjamin Morel's avatar
Benjamin Morel committed
205
     * {@inheritdoc}
206
     */
207
    protected function _getPortableDatabaseDefinition($database)
208 209 210
    {
        return $database['name'];
    }
211

212 213 214 215 216 217 218 219
    /**
     * {@inheritdoc}
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace['name'];
    }

220
    /**
Benjamin Morel's avatar
Benjamin Morel committed
221
     * {@inheritdoc}
222
     */
223
    protected function _getPortableViewDefinition($view)
224
    {
225
        // @todo
226 227
        return new View($view['name'], null);
    }
228

229
    /**
Benjamin Morel's avatar
Benjamin Morel committed
230
     * {@inheritdoc}
231 232 233 234 235 236 237
     */
    public function listTableIndexes($table)
    {
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());

        try {
            $tableIndexes = $this->_conn->fetchAll($sql);
238
        } catch (\PDOException $e) {
239
            if ($e->getCode() == "IMSSP") {
240
                return [];
241 242 243
            } else {
                throw $e;
            }
244
        } catch (DBALException $e) {
245
            if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
246
                return [];
247 248 249
            } else {
                throw $e;
            }
250 251 252 253
        }

        return $this->_getPortableTableIndexesList($tableIndexes, $table);
    }
254 255

    /**
Benjamin Morel's avatar
Benjamin Morel committed
256
     * {@inheritdoc}
257 258 259
     */
    public function alterTable(TableDiff $tableDiff)
    {
Steve Müller's avatar
Steve Müller committed
260 261
        if (count($tableDiff->removedColumns) > 0) {
            foreach ($tableDiff->removedColumns as $col) {
262 263 264 265 266 267 268
                $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
269
        parent::alterTable($tableDiff);
270 271 272
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
273 274 275 276 277 278
     * Returns the SQL to retrieve the constraints for a given column.
     *
     * @param string $table
     * @param string $column
     *
     * @return string
279 280 281 282 283 284 285 286 287 288 289
     */
    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]";
    }
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    /**
     * Closes currently active connections on the given database.
     *
     * This is useful to force DROP DATABASE operations which could fail because of active connections.
     *
     * @param string $database The name of the database to close currently active connections for.
     *
     * @return void
     */
    private function closeActiveDatabaseConnections($database)
    {
        $database = new Identifier($database);

        $this->_execSql(
            sprintf(
                'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
                $database->getQuotedName($this->_platform)
            )
        );
    }
311
}