Comparator::diffColumn()   F
last analyzed

Complexity

Conditions 28
Paths 2592

Size

Total Lines 80
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 28.2486

Importance

Changes 0
Metric Value
cc 28
eloc 43
nc 2592
nop 2
dl 0
loc 80
ccs 41
cts 44
cp 0.9318
crap 28.2486
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\Types;
8
use function array_intersect_key;
9
use function array_key_exists;
10
use function array_keys;
11
use function array_map;
12
use function array_merge;
13
use function array_unique;
14
use function assert;
15
use function count;
16
use function get_class;
17
use function strtolower;
18
19
/**
20
 * Compares two Schemas and return an instance of SchemaDiff.
21
 */
22
class Comparator
23
{
24 396
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
25
    {
26 396
        $c = new self();
27
28 396
        return $c->compare($fromSchema, $toSchema);
29
    }
30
31
    /**
32
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
33
     *
34
     * The returned differences are returned in such a way that they contain the
35
     * operations to change the schema stored in $fromSchema to the schema that is
36
     * stored in $toSchema.
37
     */
38 640
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
39
    {
40 640
        $diff             = new SchemaDiff();
41 640
        $diff->fromSchema = $fromSchema;
42
43 640
        $foreignKeysToTable = [];
44
45 640
        foreach ($toSchema->getNamespaces() as $namespace) {
46 44
            if ($fromSchema->hasNamespace($namespace)) {
47 44
                continue;
48
            }
49
50 44
            $diff->newNamespaces[$namespace] = $namespace;
51
        }
52
53 640
        foreach ($fromSchema->getNamespaces() as $namespace) {
54 44
            if ($toSchema->hasNamespace($namespace)) {
55 44
                continue;
56
            }
57
58 22
            $diff->removedNamespaces[$namespace] = $namespace;
59
        }
60
61 640
        foreach ($toSchema->getTables() as $table) {
62 508
            $tableName = $table->getShortestName($toSchema->getName());
63 508
            if (! $fromSchema->hasTable($tableName)) {
64 110
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
65
            } else {
66 464
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
67 464
                if ($tableDifferences !== null) {
68 245
                    $diff->changedTables[$tableName] = $tableDifferences;
69
                }
70
            }
71
        }
72
73
        /* Check if there are tables removed */
74 640
        foreach ($fromSchema->getTables() as $table) {
75 486
            $tableName = $table->getShortestName($fromSchema->getName());
76
77 486
            $table = $fromSchema->getTable($tableName);
78 486
            if (! $toSchema->hasTable($tableName)) {
79 110
                $diff->removedTables[$tableName] = $table;
80
            }
81
82
            // also remember all foreign keys that point to a specific table
83 486
            foreach ($table->getForeignKeys() as $foreignKey) {
84 66
                $foreignTable = strtolower($foreignKey->getForeignTableName());
85 66
                if (! isset($foreignKeysToTable[$foreignTable])) {
86 66
                    $foreignKeysToTable[$foreignTable] = [];
87
                }
88
89 66
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
90
            }
91
        }
92
93 640
        foreach ($diff->removedTables as $tableName => $table) {
94 110
            if (! isset($foreignKeysToTable[$tableName])) {
95 66
                continue;
96
            }
97
98 44
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
99
100
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
101
            // and the removedForeignKeys from changedTables
102 44
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
103
                // strtolower the table name to make if compatible with getShortestName
104 44
                $localTableName = strtolower($foreignKey->getLocalTableName());
105 44
                if (! isset($diff->changedTables[$localTableName])) {
106
                    continue;
107
                }
108
109 44
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
110
                    // We check if the key is from the removed table if not we skip.
111 44
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
112 22
                        continue;
113
                    }
114
115 44
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
116
                }
117
            }
118
        }
119
120 640
        foreach ($toSchema->getSequences() as $sequence) {
121 88
            $sequenceName = $sequence->getShortestName($toSchema->getName());
122 88
            if (! $fromSchema->hasSequence($sequenceName)) {
123 66
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
124 66
                    $diff->newSequences[] = $sequence;
125
                }
126
            } else {
127 44
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
128 22
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
129
                }
130
            }
131
        }
132
133 640
        foreach ($fromSchema->getSequences() as $sequence) {
134 88
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
135 22
                continue;
136
            }
137
138 66
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
139
140 66
            if ($toSchema->hasSequence($sequenceName)) {
141 44
                continue;
142
            }
143
144 44
            $diff->removedSequences[] = $sequence;
145
        }
146
147 640
        return $diff;
148
    }
149
150 132
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
151
    {
152 132
        foreach ($schema->getTables() as $table) {
153 44
            if ($sequence->isAutoIncrementsFor($table)) {
154 44
                return true;
155
            }
156
        }
157
158 88
        return false;
159
    }
160
161 74
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
162
    {
163 74
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
164 44
            return true;
165
        }
166
167 52
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
168
    }
169
170
    /**
171
     * Returns the difference between the tables $table1 and $table2.
172
     *
173
     * If there are no differences this method returns null.
174
     */
175 2368
    public function diffTable(Table $table1, Table $table2) : ?TableDiff
176
    {
177 2368
        $changes                     = 0;
178 2368
        $tableDifferences            = new TableDiff($table1->getName());
179 2368
        $tableDifferences->fromTable = $table1;
180
181 2368
        $table1Columns = $table1->getColumns();
182 2368
        $table2Columns = $table2->getColumns();
183
184
        /* See if all the fields in table 1 exist in table 2 */
185 2368
        foreach ($table2Columns as $columnName => $column) {
186 2258
            if ($table1->hasColumn($columnName)) {
187 1972
                continue;
188
            }
189
190 518
            $tableDifferences->addedColumns[$columnName] = $column;
191 518
            $changes++;
192
        }
193
194
        /* See if there are any removed fields in table 2 */
195 2368
        foreach ($table1Columns as $columnName => $column) {
196
            // See if column is removed in table 2.
197 2258
            if (! $table2->hasColumn($columnName)) {
198 440
                $tableDifferences->removedColumns[$columnName] = $column;
199 440
                $changes++;
200 440
                continue;
201
            }
202
203
            // See if column has changed properties in table 2.
204 1972
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
205
206 1972
            if (count($changedProperties) === 0) {
207 1409
                continue;
208
            }
209
210 631
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
211 631
            $columnDiff->fromColumn                               = $column;
212 631
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
213 631
            $changes++;
214
        }
215
216 2368
        $this->detectColumnRenamings($tableDifferences);
217
218 2368
        $table1Indexes = $table1->getIndexes();
219 2368
        $table2Indexes = $table2->getIndexes();
220
221
        /* See if all the indexes in table 1 exist in table 2 */
222 2368
        foreach ($table2Indexes as $indexName => $index) {
223 1030
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
224 632
                continue;
225
            }
226
227 398
            $tableDifferences->addedIndexes[$indexName] = $index;
228 398
            $changes++;
229
        }
230
231
        /* See if there are any removed indexes in table 2 */
232 2368
        foreach ($table1Indexes as $indexName => $index) {
233
            // See if index is removed in table 2.
234 964
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
235 964
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
236
            ) {
237 376
                $tableDifferences->removedIndexes[$indexName] = $index;
238 376
                $changes++;
239 376
                continue;
240
            }
241
242
            // See if index has changed in table 2.
243 632
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
244 632
            assert($table2Index instanceof Index);
245
246 632
            if (! $this->diffIndex($index, $table2Index)) {
247 302
                continue;
248
            }
249
250 364
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
251 364
            $changes++;
252
        }
253
254 2368
        $this->detectIndexRenamings($tableDifferences);
255
256 2368
        $fromFkeys = $table1->getForeignKeys();
257 2368
        $toFkeys   = $table2->getForeignKeys();
258
259 2368
        foreach ($fromFkeys as $key1 => $constraint1) {
260 252
            foreach ($toFkeys as $key2 => $constraint2) {
261 164
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
262 76
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
263
                } else {
264 88
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
265 44
                        $tableDifferences->changedForeignKeys[] = $constraint2;
266 44
                        $changes++;
267 44
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
268
                    }
269
                }
270
            }
271
        }
272
273 2368
        foreach ($fromFkeys as $constraint1) {
274 132
            $tableDifferences->removedForeignKeys[] = $constraint1;
275 132
            $changes++;
276
        }
277
278 2368
        foreach ($toFkeys as $constraint2) {
279 66
            $tableDifferences->addedForeignKeys[] = $constraint2;
280 66
            $changes++;
281
        }
282
283 2368
        return $changes > 0 ? $tableDifferences : null;
284
    }
285
286
    /**
287
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
288
     * however ambiguities between different possibilities should not lead to renaming at all.
289
     */
290 2368
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
291
    {
292 2368
        $renameCandidates = [];
293 2368
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
294 518
            foreach ($tableDifferences->removedColumns as $removedColumn) {
295 352
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
296 242
                    continue;
297
                }
298
299 352
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
300
            }
301
        }
302
303 2368
        foreach ($renameCandidates as $candidateColumns) {
304 352
            if (count($candidateColumns) !== 1) {
305 22
                continue;
306
            }
307
308 330
            [$removedColumn, $addedColumn] = $candidateColumns[0];
309 330
            $removedColumnName             = strtolower($removedColumn->getName());
310 330
            $addedColumnName               = strtolower($addedColumn->getName());
311
312 330
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
313 22
                continue;
314
            }
315
316 330
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
317
            unset(
318 330
                $tableDifferences->addedColumns[$addedColumnName],
319 330
                $tableDifferences->removedColumns[$removedColumnName]
320
            );
321
        }
322 2368
    }
323
324
    /**
325
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
326
     * however ambiguities between different possibilities should not lead to renaming at all.
327
     */
328 2368
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
329
    {
330 2368
        $renameCandidates = [];
331
332
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
333 2368
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
334 398
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
335 188
                if ($this->diffIndex($addedIndex, $removedIndex)) {
336 100
                    continue;
337
                }
338
339 88
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
340
            }
341
        }
342
343 2368
        foreach ($renameCandidates as $candidateIndexes) {
344
            // If the current rename candidate contains exactly one semantically equal index,
345
            // we can safely rename it.
346
            // Otherwise it is unclear if a rename action is really intended,
347
            // therefore we let those ambiguous indexes be added/dropped.
348 88
            if (count($candidateIndexes) !== 1) {
349 22
                continue;
350
            }
351
352 66
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
353
354 66
            $removedIndexName = strtolower($removedIndex->getName());
355 66
            $addedIndexName   = strtolower($addedIndex->getName());
356
357 66
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
358
                continue;
359
            }
360
361 66
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
362
            unset(
363 66
                $tableDifferences->addedIndexes[$addedIndexName],
364 66
                $tableDifferences->removedIndexes[$removedIndexName]
365
            );
366
        }
367 2368
    }
368
369 230
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
370
    {
371 230
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
372 44
            return true;
373
        }
374
375 186
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
376
            return true;
377
        }
378
379 186
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
380 22
            return true;
381
        }
382
383 164
        if ($key1->onUpdate() !== $key2->onUpdate()) {
384 22
            return true;
385
        }
386
387 142
        return $key1->onDelete() !== $key2->onDelete();
388
    }
389
390
    /**
391
     * Returns the difference between the fields $field1 and $field2.
392
     *
393
     * If there are differences this method returns $field2, otherwise the
394
     * boolean false.
395
     *
396
     * @return array<int, string>
397
     */
398 2676
    public function diffColumn(Column $column1, Column $column2) : array
399
    {
400 2676
        $properties1 = $column1->toArray();
401 2676
        $properties2 = $column2->toArray();
402
403 2676
        $changedProperties = [];
404
405 2676
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
406 168
            $changedProperties[] = 'type';
407
        }
408
409 2676
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
410 2676
            if ($properties1[$property] === $properties2[$property]) {
411 2676
                continue;
412
            }
413
414 81
            $changedProperties[] = $property;
415
        }
416
417
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
418
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
419 2676
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
420 2676
            || $properties1['default'] != $properties2['default']) {
421 96
            $changedProperties[] = 'default';
422
        }
423
424 2676
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
425 2676
            $properties1['type'] instanceof Types\BinaryType
426
        ) {
427 567
            if ((isset($properties1['length']) !== isset($properties2['length']))
428 545
                || (isset($properties1['length']) && isset($properties2['length'])
429 567
                    && $properties1['length'] !== $properties2['length'])
430
            ) {
431 199
                $changedProperties[] = 'length';
432
            }
433
434 567
            if ($properties1['fixed'] !== $properties2['fixed']) {
435 567
                $changedProperties[] = 'fixed';
436
            }
437 2334
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
438 43
            if (($properties1['precision'] ?? 10) !== ($properties2['precision'] ?? 10)) {
439
                $changedProperties[] = 'precision';
440
            }
441
442 43
            if ($properties1['scale'] !== $properties2['scale']) {
443
                $changedProperties[] = 'scale';
444
            }
445
        }
446
447
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
448 2676
        if ($properties1['comment'] !== $properties2['comment'] &&
449 2676
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
450 2676
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
451
        ) {
452 572
            $changedProperties[] = 'comment';
453
        }
454
455 2676
        $customOptions1 = $column1->getCustomSchemaOptions();
456 2676
        $customOptions2 = $column2->getCustomSchemaOptions();
457
458 2676
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
459 44
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
460 22
                $changedProperties[] = $key;
461 44
            } elseif ($properties1[$key] !== $properties2[$key]) {
462
                $changedProperties[] = $key;
463
            }
464
        }
465
466 2676
        $platformOptions1 = $column1->getPlatformOptions();
467 2676
        $platformOptions2 = $column2->getPlatformOptions();
468
469 2676
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
470 80
            if ($properties1[$key] === $properties2[$key]) {
471 56
                continue;
472
            }
473
474 46
            $changedProperties[] = $key;
475
        }
476
477 2676
        return array_unique($changedProperties);
478
    }
479
480
    /**
481
     * Finds the difference between the indexes $index1 and $index2.
482
     *
483
     * Compares $index1 with $index2 and returns $index2 if there are any
484
     * differences or false in case there are no differences.
485
     */
486 820
    public function diffIndex(Index $index1, Index $index2) : bool
487
    {
488 820
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
489
    }
490
}
491