Failed Conditions
Pull Request — develop (#3518)
by Michael
29:00 queued 25:29
created

SQLServerSchemaManager::parseDefaultExpression()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3
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\Types\Type;
10
use PDOException;
11
use Throwable;
12
use function assert;
13
use function count;
14
use function in_array;
15
use function is_string;
16
use function preg_match;
17
use function sprintf;
18
use function str_replace;
19
use function strpos;
20
use function strtok;
21
use function trim;
22
23
/**
24
 * SQL Server Schema Manager.
25
 */
26
class SQLServerSchemaManager extends AbstractSchemaManager
27
{
28
    /**
29
     * {@inheritdoc}
30
     */
31 244
    public function dropDatabase($database)
32
    {
33
        try {
34 244
            parent::dropDatabase($database);
35 244
        } catch (DBALException $exception) {
36 244
            $exception = $exception->getPrevious();
37 244
            assert($exception instanceof Throwable);
38
39 244
            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 244
            if ($exception->getCode() !== 3702) {
48 244
                throw $exception;
49
            }
50
51 188
            $this->closeActiveDatabaseConnections($database);
52
53 188
            parent::dropDatabase($database);
54
        }
55 188
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 184
    protected function _getPortableSequenceDefinition($sequence)
61
    {
62 184
        return new Sequence($sequence['name'], (int) $sequence['increment'], (int) $sequence['start_value']);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 238
    protected function _getPortableTableColumnDefinition($tableColumn)
69
    {
70 238
        $dbType = strtok($tableColumn['type'], '(), ');
71 238
        assert(is_string($dbType));
72
73 238
        $fixed   = null;
74 238
        $length  = (int) $tableColumn['length'];
75 238
        $default = $tableColumn['default'];
76
77 238
        if (! isset($tableColumn['name'])) {
78 30
            $tableColumn['name'] = '';
79
        }
80
81 238
        if ($default !== null) {
82 216
            $default = $this->parseDefaultExpression($default);
83
        }
84
85 238
        switch ($dbType) {
86
            case 'nchar':
87
            case 'nvarchar':
88
            case 'ntext':
89
                // Unicode data requires 2 bytes per character
90 204
                $length /= 2;
91 204
                break;
92
            case 'varchar':
93
                // TEXT type is returned as VARCHAR(MAX) with a length of -1
94 196
                if ($length === -1) {
95 196
                    $dbType = 'text';
96
                }
97 196
                break;
98
        }
99
100 238
        if ($dbType === 'char' || $dbType === 'nchar' || $dbType === 'binary') {
101 168
            $fixed = true;
102
        }
103
104 238
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'])
105 238
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
106
107
        $options = [
108 238
            'length'        => $length === 0 || ! in_array($type, ['text', 'string']) ? null : $length,
109
            'unsigned'      => false,
110 238
            'fixed'         => (bool) $fixed,
111 238
            'default'       => $default !== 'NULL' ? $default : null,
112 238
            'notnull'       => (bool) $tableColumn['notnull'],
113 238
            'scale'         => $tableColumn['scale'],
114 238
            'precision'     => $tableColumn['precision'],
115 238
            'autoincrement' => (bool) $tableColumn['autoincrement'],
116 238
            'comment'       => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
117
        ];
118
119 238
        $column = new Column($tableColumn['name'], Type::getType($type), $options);
120
121 238
        if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
122 226
            $column->setPlatformOption('collation', $tableColumn['collation']);
123
        }
124
125 238
        return $column;
126
    }
127
128 216
    private function parseDefaultExpression(string $value) : string
129
    {
130 216
        while (preg_match('/^\((.*)\)$/', $value, $matches)) {
131 216
            $value = trim($matches[1], "'");
132
        }
133
134 216
        if ($value === 'getdate()') {
135 200
            return $this->_platform->getCurrentTimestampSQL();
136
        }
137
138 216
        return $value;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144 216
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
145
    {
146 216
        $foreignKeys = [];
147
148 216
        foreach ($tableForeignKeys as $tableForeignKey) {
149 136
            if (! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
150 136
                $foreignKeys[$tableForeignKey['ForeignKey']] = [
151 136
                    'local_columns' => [$tableForeignKey['ColumnName']],
152 136
                    'foreign_table' => $tableForeignKey['ReferenceTableName'],
153 136
                    'foreign_columns' => [$tableForeignKey['ReferenceColumnName']],
154 136
                    'name' => $tableForeignKey['ForeignKey'],
155
                    'options' => [
156 136
                        'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
157 136
                        'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
158
                    ],
159
                ];
160
            } else {
161 76
                $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][]   = $tableForeignKey['ColumnName'];
162 76
                $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
163
            }
164
        }
165
166 216
        return parent::_getPortableTableForeignKeysList($foreignKeys);
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172 216
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
173
    {
174 216
        foreach ($tableIndexRows as &$tableIndex) {
175 192
            $tableIndex['non_unique'] = (bool) $tableIndex['non_unique'];
176 192
            $tableIndex['primary']    = (bool) $tableIndex['primary'];
177 192
            $tableIndex['flags']      = $tableIndex['flags'] ? [$tableIndex['flags']] : null;
178
        }
179
180 216
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186 136
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
187
    {
188 136
        return new ForeignKeyConstraint(
189 136
            $tableForeignKey['local_columns'],
190 136
            $tableForeignKey['foreign_table'],
191 136
            $tableForeignKey['foreign_columns'],
192 136
            $tableForeignKey['name'],
193 136
            $tableForeignKey['options']
194
        );
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200 244
    protected function _getPortableTableDefinition($table)
201
    {
202 244
        if (isset($table['schema_name']) && $table['schema_name'] !== 'dbo') {
203 120
            return $table['schema_name'] . '.' . $table['name'];
204
        }
205
206 244
        return $table['name'];
207
    }
208
209
    /**
210
     * {@inheritdoc}
211
     */
212 188
    protected function _getPortableDatabaseDefinition($database)
213
    {
214 188
        return $database['name'];
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220 172
    protected function getPortableNamespaceDefinition(array $namespace)
221
    {
222 172
        return $namespace['name'];
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228 116
    protected function _getPortableViewDefinition($view)
229
    {
230
        // @todo
231 116
        return new View($view['name'], '');
232
    }
233
234
    /**
235
     * {@inheritdoc}
236
     */
237 216
    public function listTableIndexes($table)
238
    {
239 216
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
240
241
        try {
242 216
            $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 216
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
258
    }
259
260
    /**
261
     * {@inheritdoc}
262
     */
263 208
    public function alterTable(TableDiff $tableDiff)
264
    {
265 208
        if (count($tableDiff->removedColumns) > 0) {
266 208
            foreach ($tableDiff->removedColumns as $col) {
267 208
                $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
268 208
                foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
269 208
                    $this->_conn->exec(
270 208
                        sprintf(
271
                            'ALTER TABLE %s DROP CONSTRAINT %s',
272 208
                            $tableDiff->name,
273 208
                            $constraint['Name']
274
                        )
275
                    );
276
                }
277
            }
278
        }
279
280 208
        parent::alterTable($tableDiff);
281 208
    }
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 208
    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 208
            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 188
    private function closeActiveDatabaseConnections($database)
312
    {
313 188
        $database = new Identifier($database);
314
315 188
        $this->_execSql(
316 188
            sprintf(
317
                'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
318 188
                $database->getQuotedName($this->_platform)
319
            )
320
        );
321 188
    }
322
}
323