Failed Conditions
Push — 2.10.x ( db5afa...61a6b9 )
by Grégoire
27s queued 15s
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

Importance

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