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