Passed
Pull Request — 2.11.x (#3971)
by Grégoire
03:18
created

closeActiveDatabaseConnections()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0046

Importance

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