Failed Conditions
Push — master ( 30b923...92920e )
by Marco
19s queued 13s
created

SQLServerSchemaManager::dropDatabase()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 23
ccs 10
cts 11
cp 0.9091
rs 9.9
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4.0119
1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Driver\DriverException;
7
use Doctrine\DBAL\Types\Type;
8
use PDOException;
9
use Throwable;
10
use function assert;
11
use function count;
12
use function in_array;
13
use function is_string;
14
use function preg_match;
15
use function sprintf;
16
use function str_replace;
17
use function strpos;
18
use function strtok;
19
use function trim;
20
21
/**
22
 * SQL Server Schema Manager.
23
 */
24
class SQLServerSchemaManager extends AbstractSchemaManager
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29 4
    public function dropDatabase($database)
30
    {
31
        try {
32 4
            parent::dropDatabase($database);
33 4
        } catch (DBALException $exception) {
34 4
            $exception = $exception->getPrevious();
35 4
            assert($exception instanceof Throwable);
36
37 4
            if (! $exception instanceof DriverException) {
38
                throw $exception;
39
            }
40
41
            // If we have a error code 3702, the drop database operation failed
42
            // because of active connections on the database.
43
            // To force dropping the database, we first have to close all active connections
44
            // on that database and issue the drop database operation again.
45 4
            if ($exception->getErrorCode() !== 3702) {
46 4
                throw $exception;
47
            }
48
49 2
            $this->closeActiveDatabaseConnections($database);
50
51 2
            parent::dropDatabase($database);
52
        }
53 2
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 12
    protected function _getPortableSequenceDefinition($sequence)
59
    {
60 12
        return new Sequence($sequence['name'], (int) $sequence['increment'], (int) $sequence['start_value']);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 103
    protected function _getPortableTableColumnDefinition($tableColumn)
67
    {
68 103
        $dbType = strtok($tableColumn['type'], '(), ');
69 103
        assert(is_string($dbType));
70
71 103
        $fixed   = null;
72 103
        $length  = (int) $tableColumn['length'];
73 103
        $default = $tableColumn['default'];
74
75 103
        if (! isset($tableColumn['name'])) {
76 27
            $tableColumn['name'] = '';
77
        }
78
79 103
        if ($default !== null) {
80 20
            $default = $this->parseDefaultExpression($default);
81
        }
82
83 103
        switch ($dbType) {
84 103
            case 'nchar':
85 101
            case 'nvarchar':
86 99
            case 'ntext':
87
                // Unicode data requires 2 bytes per character
88 30
                $length /= 2;
89 30
                break;
90 99
            case 'varchar':
91
                // TEXT type is returned as VARCHAR(MAX) with a length of -1
92 18
                if ($length === -1) {
93 18
                    $dbType = 'text';
94
                }
95 18
                break;
96
        }
97
98 103
        if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') {
99 10
            $fixed = true;
100
        }
101
102 103
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
103 103
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
104 103
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
105
106
        $options = [
107 103
            'length'        => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
108
            'unsigned'      => false,
109 103
            'fixed'         => (bool) $fixed,
110 103
            'default'       => $default !== 'NULL' ? $default : null,
111 103
            'notnull'       => (bool) $tableColumn['notnull'],
112 103
            'scale'         => $tableColumn['scale'],
113 103
            'precision'     => $tableColumn['precision'],
114 103
            'autoincrement' => (bool) $tableColumn['autoincrement'],
115 103
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
116
        ];
117
118 103
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
119
120 103
        if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
121 63
            $column->setPlatformOption('collation', $tableColumn['collation']);
122
        }
123
124 103
        return $column;
125
    }
126
127 20
    private function parseDefaultExpression(string $value) : string
128
    {
129 20
        while (preg_match('/^\((.*)\)$/', $value, $matches)) {
130 20
            $value = trim($matches[1], "'");
131
        }
132
133 20
        if ($value === 'getdate()') {
134 2
            return $this->_platform->getCurrentTimestampSQL();
135
        }
136
137 20
        return $value;
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 54
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
144
    {
145 54
        $foreignKeys = [];
146
147 54
        foreach ($tableForeignKeys as $tableForeignKey) {
148 16
            if (! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
149 16
                $foreignKeys[$tableForeignKey['ForeignKey']] = [
150 16
                    'local_columns' => [$tableForeignKey['ColumnName']],
151 16
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
152 16
                    'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
153 16
                    'name' => $tableForeignKey['ForeignKey'],
154
                    'options' => [
155 16
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
156 16
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
157
                    ],
158
                ];
159
            } else {
160 2
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][]   = $tableForeignKey['ColumnName'];
161 2
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
162
            }
163
        }
164
165 54
        return parent::_getPortableTableForeignKeysList($foreignKeys);
166
    }
167
168
    /**
169
     * {@inheritdoc}
170
     */
171 60
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null)
172
    {
173 60
        foreach ($tableIndexRows as &$tableIndex) {
174 34
            $tableIndex['non_unique'] = (bool) $tableIndex['non_unique'];
175 34
            $tableIndex['primary']    = (bool) $tableIndex['primary'];
176 34
            $tableIndex['flags']      = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
177
        }
178
179 60
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185 16
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
186
    {
187 16
        return new ForeignKeyConstraint(
188 16
            $tableForeignKey['local_columns'],
189 16
            $tableForeignKey['foreign_table'],
190 16
            $tableForeignKey['foreign_columns'],
191 16
            $tableForeignKey['name'],
192 16
            $tableForeignKey['options']
193
        );
194
    }
195
196
    /**
197
     * {@inheritdoc}
198
     */
199 134
    protected function _getPortableTableDefinition($table)
200
    {
201 134
        if (isset($table['schema_name']) && $table['schema_name'] !== 'dbo') {
202 2
            return $table['schema_name'] . '.' . $table['name'];
203
        }
204
205 134
        return $table['name'];
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211 4
    protected function _getPortableDatabaseDefinition($database)
212
    {
213 4
        return $database['name'];
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219 4
    protected function getPortableNamespaceDefinition(array $namespace)
220
    {
221 4
        return $namespace['name'];
222
    }
223
224
    /**
225
     * {@inheritdoc}
226
     */
227 2
    protected function _getPortableViewDefinition($view)
228
    {
229
        // @todo
230 2
        return new View($view['name'], '');
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236 60
    public function listTableIndexes($table)
237
    {
238 60
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
239
240
        try {
241 60
            $tableIndexes = $this->_conn->fetchAll($sql);
242
        } catch (PDOException $e) {
243
            if ($e->getCode() === 'IMSSP') {
244
                return [];
245
            }
246
247
            throw $e;
248
        } catch (DBALException $e) {
249
            if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
250
                return [];
251
            }
252
253
            throw $e;
254
        }
255
256 60
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262 36
    public function alterTable(TableDiff $tableDiff)
263
    {
264 36
        if (count($tableDiff->removedColumns) > 0) {
265 8
            foreach ($tableDiff->removedColumns as $col) {
266 8
                $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
267 8
                foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
268 4
                    $this->_conn->exec(
269 4
                        sprintf(
270 4
                            'ALTER TABLE %s DROP CONSTRAINT %s',
271 4
                            $tableDiff->name,
272 4
                            $constraint['Name']
273
                        )
274
                    );
275
                }
276
            }
277
        }
278
279 36
        parent::alterTable($tableDiff);
280 36
    }
281
282
    /**
283
     * Returns the SQL to retrieve the constraints for a given column.
284
     *
285
     * @param string $table
286
     * @param string $column
287
     *
288
     * @return string
289
     */
290 8
    private function getColumnConstraintSQL($table, $column)
291
    {
292
        return "SELECT SysObjects.[Name]
293
            FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
294
            ON Tab.[ID] = Sysobjects.[Parent_Obj]
295
            INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
296
            INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
297 8
            WHERE Col.[Name] = " . $this->_conn->quote($column) . ' AND Tab.[Name] = ' . $this->_conn->quote($table) . '
298
            ORDER BY Col.[Name]';
299
    }
300
301
    /**
302
     * Closes currently active connections on the given database.
303
     *
304
     * This is useful to force DROP DATABASE operations which could fail because of active connections.
305
     *
306
     * @param string $database The name of the database to close currently active connections for.
307
     *
308
     * @return void
309
     */
310 2
    private function closeActiveDatabaseConnections($database)
311
    {
312 2
        $database = new Identifier($database);
313
314 2
        $this->_execSql(
315 2
            sprintf(
316 2
                'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
317 2
                $database->getQuotedName($this->_platform)
318
            )
319
        );
320 2
    }
321
}
322