Completed
Push — master ( 1a9812...b70610 )
by Sergei
19s queued 14s
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 4
    public function dropDatabase(string $database) : void
32
    {
33
        try {
34 4
            parent::dropDatabase($database);
35 4
        } catch (DBALException $exception) {
36 4
            $exception = $exception->getPrevious();
37 4
            assert($exception instanceof Throwable);
38
39 4
            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 4
            if ($exception->getCode() !== 3702) {
48 4
                throw $exception;
49
            }
50
51 2
            $this->closeActiveDatabaseConnections($database);
52
53 2
            parent::dropDatabase($database);
54
        }
55 2
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 12
    protected function _getPortableSequenceDefinition(array $sequence) : Sequence
61
    {
62 12
        return new Sequence($sequence['name'], (int) $sequence['increment'], (int) $sequence['start_value']);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 135
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
69
    {
70 135
        $dbType = strtok($tableColumn['type'], '(), ');
71 135
        assert(is_string($dbType));
72
73 135
        $length = (int) $tableColumn['length'];
74
75 135
        $precision = $default = null;
76
77 135
        $scale = 0;
78 135
        $fixed = false;
79
80 135
        if (! isset($tableColumn['name'])) {
81 27
            $tableColumn['name'] = '';
82
        }
83
84 135
        if ($tableColumn['scale'] !== null) {
85 135
            $scale = (int) $tableColumn['scale'];
86
        }
87
88 135
        if ($tableColumn['precision'] !== null) {
89 135
            $precision = (int) $tableColumn['precision'];
90
        }
91
92 135
        if ($tableColumn['default'] !== null) {
93 54
            $default = $this->parseDefaultExpression($tableColumn['default']);
94
        }
95
96 2
        switch ($dbType) {
97 135
            case 'nchar':
98 133
            case 'nvarchar':
99 131
            case 'ntext':
100
                // Unicode data requires 2 bytes per character
101 64
                $length /= 2;
102 64
                break;
103 131
            case 'varchar':
104
                // TEXT type is returned as VARCHAR(MAX) with a length of -1
105 14
                if ($length === -1) {
106 14
                    $dbType = 'text';
107
                }
108 14
                break;
109
        }
110
111 135
        if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') {
112 10
            $fixed = true;
113
        }
114
115 135
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'])
116 135
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
117
118
        $options = [
119 135
            'length'        => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
120 135
            'fixed'         => $fixed,
121 135
            'default'       => $default,
122 135
            'notnull'       => (bool) $tableColumn['notnull'],
123 135
            'scale'         => $scale,
124 135
            'precision'     => $precision,
125 135
            'autoincrement' => (bool) $tableColumn['autoincrement'],
126 135
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
127
        ];
128
129 135
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
130
131 135
        if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
132 93
            $column->setPlatformOption('collation', $tableColumn['collation']);
133
        }
134
135 135
        return $column;
136
    }
137
138 54
    private function parseDefaultExpression(string $value) : ?string
139
    {
140 54
        while (preg_match('/^\((.*)\)$/s', $value, $matches)) {
141 54
            $value = $matches[1];
142
        }
143
144 54
        if ($value === 'NULL') {
145
            return null;
146
        }
147
148 54
        if (preg_match('/^\'(.*)\'$/s', $value, $matches)) {
149 52
            $value = str_replace("''", "'", $matches[1]);
150
        }
151
152 54
        if ($value === 'getdate()') {
153 4
            return $this->_platform->getCurrentTimestampSQL();
154
        }
155
156 54
        return $value;
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162 86
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
163
    {
164 86
        $foreignKeys = [];
165
166 86
        foreach ($tableForeignKeys as $tableForeignKey) {
167 16
            if (! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
168 16
                $foreignKeys[$tableForeignKey['ForeignKey']] = [
169 16
                    'local_columns' => [$tableForeignKey['ColumnName']],
170 16
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
171 16
                    'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
172 16
                    'name' => $tableForeignKey['ForeignKey'],
173
                    'options' => [
174 16
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
175 16
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
176
                    ],
177
                ];
178
            } else {
179 2
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][]   = $tableForeignKey['ColumnName'];
180 2
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
181
            }
182
        }
183
184 86
        return parent::_getPortableTableForeignKeysList($foreignKeys);
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190 92
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
191
    {
192 92
        foreach ($tableIndexRows as &$tableIndex) {
193 34
            $tableIndex['non_unique'] = (bool) $tableIndex['non_unique'];
194 34
            $tableIndex['primary']    = (bool) $tableIndex['primary'];
195 34
            $tableIndex['flags']      = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
196
        }
197
198 92
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
199
    }
200
201
    /**
202
     * {@inheritdoc}
203
     */
204 16
    protected function _getPortableTableForeignKeyDefinition(array $tableForeignKey) : ForeignKeyConstraint
205
    {
206 16
        return new ForeignKeyConstraint(
207 16
            $tableForeignKey['local_columns'],
208 16
            $tableForeignKey['foreign_table'],
209 16
            $tableForeignKey['foreign_columns'],
210 16
            $tableForeignKey['name'],
211 16
            $tableForeignKey['options']
212
        );
213
    }
214
215
    /**
216
     * {@inheritdoc}
217
     */
218 22
    protected function _getPortableTableDefinition(array $table) : string
219
    {
220 22
        if (isset($table['schema_name']) && $table['schema_name'] !== 'dbo') {
221 2
            return $table['schema_name'] . '.' . $table['name'];
222
        }
223
224 22
        return $table['name'];
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     */
230 4
    protected function _getPortableDatabaseDefinition(array $database) : string
231
    {
232 4
        return $database['name'];
233
    }
234
235
    /**
236
     * {@inheritdoc}
237
     */
238 4
    protected function getPortableNamespaceDefinition(array $namespace) : string
239
    {
240 4
        return $namespace['name'];
241
    }
242
243
    /**
244
     * {@inheritdoc}
245
     */
246 2
    protected function _getPortableViewDefinition(array $view) : View
247
    {
248
        // @todo
249 2
        return new View($view['name'], '');
250
    }
251
252
    /**
253
     * {@inheritdoc}
254
     */
255 92
    public function listTableIndexes(string $table) : array
256
    {
257 92
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
258
259
        try {
260 92
            $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 92
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
276
    }
277
278
    /**
279
     * {@inheritdoc}
280
     */
281 36
    public function alterTable(TableDiff $tableDiff) : void
282
    {
283 36
        if (count($tableDiff->removedColumns) > 0) {
284 6
            foreach ($tableDiff->removedColumns as $col) {
285 6
                $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
286 6
                foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
287 4
                    $this->_conn->exec(
288 4
                        sprintf(
289
                            'ALTER TABLE %s DROP CONSTRAINT %s',
290 4
                            $tableDiff->name,
291 4
                            $constraint['Name']
292
                        )
293
                    );
294
                }
295
            }
296
        }
297
298 36
        parent::alterTable($tableDiff);
299 36
    }
300
301
    /**
302
     * Returns the SQL to retrieve the constraints for a given column.
303
     */
304 6
    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 6
            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 2
    private function closeActiveDatabaseConnections(string $database) : void
321
    {
322 2
        $database = new Identifier($database);
323
324 2
        $this->_execSql(
325 2
            sprintf(
326
                'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
327 2
                $database->getQuotedName($this->_platform)
328
            )
329
        );
330 2
    }
331
332 80
    public function listTableDetails(string $tableName) : Table
333
    {
334 80
        $table = parent::listTableDetails($tableName);
335
336
        /** @var SQLServerPlatform $platform */
337 80
        $platform = $this->_platform;
338 80
        $sql      = $platform->getListTableMetadataSQL($tableName);
339
340 80
        $tableOptions = $this->_conn->fetchAssoc($sql);
341
342 80
        if ($tableOptions !== false) {
343 2
            $table->addOption('comment', $tableOptions['table_comment']);
344
        }
345
346 80
        return $table;
347
    }
348
}
349