Completed
Pull Request — master (#3512)
by David
64:39 queued 61:17
created

SQLServerSchemaManager::getColumnConstraintSQL()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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