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