Failed Conditions
Pull Request — master (#3512)
by David
17:16
created

SQLServerSchemaManager::listTableDetails()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 147
    public function dropDatabase($database)
30
    {
31
        try {
32 147
            parent::dropDatabase($database);
33 147
        } catch (DBALException $exception) {
34 147
            $exception = $exception->getPrevious();
35 147
            assert($exception instanceof Throwable);
36
37 147
            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 147
            if ($exception->getErrorCode() !== 3702) {
46 147
                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 158
    protected function _getPortableTableColumnDefinition($tableColumn)
67
    {
68 158
        $dbType = strtok($tableColumn['type'], '(), ');
69 158
        assert(is_string($dbType));
70
71 158
        $fixed   = null;
72 158
        $length  = (int) $tableColumn['length'];
73 158
        $default = $tableColumn['default'];
74
75 158
        if (! isset($tableColumn['name'])) {
76 29
            $tableColumn['name'] = '';
77
        }
78
79 158
        if ($default !== null) {
80 133
            $default = $this->parseDefaultExpression($default);
81
        }
82
83 158
        switch ($dbType) {
84 2
            case 'nchar':
85 2
            case 'nvarchar':
86 2
            case 'ntext':
87
                // Unicode data requires 2 bytes per character
88 129
                $length /= 2;
89 129
                break;
90 2
            case 'varchar':
91
                // TEXT type is returned as VARCHAR(MAX) with a length of -1
92 114
                if ($length === -1) {
93 114
                    $dbType = 'text';
94
                }
95 114
                break;
96
        }
97
98 158
        if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') {
99 100
            $fixed = true;
100
        }
101
102 158
        $type                   = $this->_platform->getDoctrineTypeMapping($dbType);
103 158
        $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
104 158
        $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
105
106
        $options = [
107 158
            'length'        => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
108
            'unsigned'      => false,
109 158
            'fixed'         => (bool) $fixed,
110 158
            'default'       => $default,
111 158
            'notnull'       => (bool) $tableColumn['notnull'],
112 158
            'scale'         => $tableColumn['scale'],
113 158
            'precision'     => $tableColumn['precision'],
114 158
            'autoincrement' => (bool) $tableColumn['autoincrement'],
115 158
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
116
        ];
117
118 158
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
119
120 158
        if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
121 154
            $column->setPlatformOption('collation', $tableColumn['collation']);
122
        }
123
124 158
        return $column;
125
    }
126
127 133
    private function parseDefaultExpression(string $value) : ?string
128
    {
129 133
        while (preg_match('/^\((.*)\)$/s', $value, $matches)) {
130 133
            $value = $matches[1];
131
        }
132
133 133
        if ($value === 'NULL') {
134
            return null;
135
        }
136
137 133
        if (preg_match('/^\'(.*)\'$/s', $value, $matches)) {
138 131
            $value = str_replace("''", "'", $matches[1]);
139
        }
140
141 133
        if ($value === 'getdate()') {
142 100
            return $this->_platform->getCurrentTimestampSQL();
143
        }
144
145 133
        return $value;
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151 133
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
152
    {
153 133
        $foreignKeys = [];
154
155 133
        foreach ($tableForeignKeys as $tableForeignKey) {
156 84
            if (! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
157 84
                $foreignKeys[$tableForeignKey['ForeignKey']] = [
158 84
                    'local_columns' => [$tableForeignKey['ColumnName']],
159 84
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
160 84
                    'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
161 84
                    'name' => $tableForeignKey['ForeignKey'],
162
                    'options' => [
163 84
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
164 84
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
165
                    ],
166
                ];
167
            } else {
168 54
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][]   = $tableForeignKey['ColumnName'];
169 54
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
170
            }
171
        }
172
173 133
        return parent::_getPortableTableForeignKeysList($foreignKeys);
174
    }
175
176
    /**
177
     * {@inheritdoc}
178
     */
179 133
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null)
180
    {
181 133
        foreach ($tableIndexRows as &$tableIndex) {
182 112
            $tableIndex['non_unique'] = (bool) $tableIndex['non_unique'];
183 112
            $tableIndex['primary']    = (bool) $tableIndex['primary'];
184 112
            $tableIndex['flags']      = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
185
        }
186
187 133
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193 84
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
194
    {
195 84
        return new ForeignKeyConstraint(
196 84
            $tableForeignKey['local_columns'],
197 84
            $tableForeignKey['foreign_table'],
198 84
            $tableForeignKey['foreign_columns'],
199 84
            $tableForeignKey['name'],
200 84
            $tableForeignKey['options']
201
        );
202
    }
203
204
    /**
205
     * {@inheritdoc}
206
     */
207 147
    protected function _getPortableTableDefinition($table)
208
    {
209 147
        if (isset($table['schema_name']) && $table['schema_name'] !== 'dbo') {
210 76
            return $table['schema_name'] . '.' . $table['name'];
211
        }
212
213 147
        return $table['name'];
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219 110
    protected function _getPortableDatabaseDefinition($database)
220
    {
221 110
        return $database['name'];
222
    }
223
224
    /**
225
     * {@inheritdoc}
226
     */
227 102
    protected function getPortableNamespaceDefinition(array $namespace)
228
    {
229 102
        return $namespace['name'];
230
    }
231
232
    /**
233
     * {@inheritdoc}
234
     */
235 74
    protected function _getPortableViewDefinition($view)
236
    {
237
        // @todo
238 74
        return new View($view['name'], '');
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 133
    public function listTableIndexes($table)
245
    {
246 133
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
247
248
        try {
249 133
            $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 133
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270 120
    public function alterTable(TableDiff $tableDiff)
271
    {
272 120
        if (count($tableDiff->removedColumns) > 0) {
273 120
            foreach ($tableDiff->removedColumns as $col) {
274 120
                $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
275 120
                foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
276 120
                    $this->_conn->exec(
277 120
                        sprintf(
278
                            'ALTER TABLE %s DROP CONSTRAINT %s',
279 120
                            $tableDiff->name,
280 120
                            $constraint['Name']
281
                        )
282
                    );
283
                }
284
            }
285
        }
286
287 120
        parent::alterTable($tableDiff);
288 120
    }
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 120
    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 120
            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 110
    private function closeActiveDatabaseConnections($database)
319
    {
320 110
        $database = new Identifier($database);
321
322 110
        $this->_execSql(
323 110
            sprintf(
324
                'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
325 110
                $database->getQuotedName($this->_platform)
326
            )
327
        );
328 110
    }
329
330
    /**
331
     * @param string $tableName
332
     */
333 133
    public function listTableDetails($tableName) : Table
334
    {
335 133
        $table = parent::listTableDetails($tableName);
336
337
        /** @var SQLServerPlatform $platform */
338 133
        $platform = $this->_platform;
339 133
        $sql      = $platform->getListTableMetadataSQL($tableName);
340
341 133
        $tableOptions = $this->_conn->fetchAssoc($sql);
342
343 133
        $table->addOption('comment', $tableOptions['table_comment']);
344
345 133
        return $table;
346
    }
347
}
348