Passed
Pull Request — master (#3588)
by Andrej
11:38
created

Comparator::diffTable()   F

Complexity

Conditions 24
Paths 8640

Size

Total Lines 107
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 61
CRAP Score 24

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 61
c 1
b 0
f 0
dl 0
loc 107
ccs 61
cts 61
cp 1
rs 0
cc 24
nc 8640
nop 2
crap 24

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
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Types;
6
use function array_intersect_key;
7
use function array_key_exists;
8
use function array_keys;
9
use function array_map;
10
use function array_merge;
11
use function array_shift;
12
use function array_unique;
13
use function assert;
14
use function count;
15
use function get_class;
16
use function strtolower;
17
18
/**
19
 * Compares two Schemas and return an instance of SchemaDiff.
20
 */
21
class Comparator
22
{
23
    /**
24
     * @return SchemaDiff
25
     */
26 1627
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27
    {
28 1627
        $c = new self();
29
30 1627
        return $c->compare($fromSchema, $toSchema);
31
    }
32
33
    /**
34
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
35
     *
36
     * The returned differences are returned in such a way that they contain the
37
     * operations to change the schema stored in $fromSchema to the schema that is
38
     * stored in $toSchema.
39
     *
40
     * @return SchemaDiff
41
     */
42 3324
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44 3324
        $diff             = new SchemaDiff();
45 3324
        $diff->fromSchema = $fromSchema;
46
47 3324
        $foreignKeysToTable = [];
48
49 3324
        foreach ($toSchema->getNamespaces() as $namespace) {
50 571
            if ($fromSchema->hasNamespace($namespace)) {
51 571
                continue;
52
            }
53
54 571
            $diff->newNamespaces[$namespace] = $namespace;
55
        }
56
57 3324
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 571
            if ($toSchema->hasNamespace($namespace)) {
59 571
                continue;
60
            }
61
62 272
            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
64
65 3324
        foreach ($toSchema->getTables() as $table) {
66 3312
            $tableName = $table->getShortestName($toSchema->getName());
67 3312
            if (! $fromSchema->hasTable($tableName)) {
68 1522
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 3308
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 3308
                if ($tableDifferences !== false) {
72 3257
                    $diff->changedTables[$tableName] = $tableDifferences;
73
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78 3324
        foreach ($fromSchema->getTables() as $table) {
79 3310
            $tableName = $table->getShortestName($fromSchema->getName());
80
81 3310
            $table = $fromSchema->getTable($tableName);
82 3310
            if (! $toSchema->hasTable($tableName)) {
83 1549
                $diff->removedTables[$tableName] = $table;
84
            }
85
86
            // also remember all foreign keys that point to a specific table
87 3310
            foreach ($table->getForeignKeys() as $foreignKey) {
88 436
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 436
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 436
                    $foreignKeysToTable[$foreignTable] = [];
91
                }
92 472
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
93
            }
94
        }
95
96 3324
        foreach ($diff->removedTables as $tableName => $table) {
97 1549
            if (! isset($foreignKeysToTable[$tableName])) {
98 1545
                continue;
99
            }
100
101 436
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
102
103
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
104
            // and the removedForeignKeys from changedTables
105 436
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
106
                // strtolower the table name to make if compatible with getShortestName
107 436
                $localTableName = strtolower($foreignKey->getLocalTableName());
108 436
                if (! isset($diff->changedTables[$localTableName])) {
109
                    continue;
110
                }
111
112 436
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
113 436
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
114
115
                    // We check if the key is from the removed table if not we skip.
116 436
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
117 434
                        continue;
118
                    }
119 436
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120
                }
121
            }
122
        }
123
124 3324
        foreach ($toSchema->getSequences() as $sequence) {
125 1115
            $sequenceName = $sequence->getShortestName($toSchema->getName());
126 1115
            if (! $fromSchema->hasSequence($sequenceName)) {
127 1113
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
128 1113
                    $diff->newSequences[] = $sequence;
129
                }
130
            } else {
131 949
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
132 656
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
133
                }
134
            }
135
        }
136
137 3324
        foreach ($fromSchema->getSequences() as $sequence) {
138 1142
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
139 488
                continue;
140
            }
141
142 1140
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
143
144 1140
            if ($toSchema->hasSequence($sequenceName)) {
145 949
                continue;
146
            }
147
148 1138
            $diff->removedSequences[] = $sequence;
149
        }
150
151 3324
        return $diff;
152
    }
153
154
    /**
155
     * @param Schema   $schema
156
     * @param Sequence $sequence
157
     *
158
     * @return bool
159
     */
160 1146
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
161
    {
162 1146
        foreach ($schema->getTables() as $table) {
163 490
            if ($sequence->isAutoIncrementsFor($table)) {
164 490
                return true;
165
            }
166
        }
167
168 1142
        return false;
169
    }
170
171
    /**
172
     * @return bool
173
     */
174 2040
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
175
    {
176 2040
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
177 1165
            return true;
178
        }
179
180 2038
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
181
    }
182
183
    /**
184
     * Returns the difference between the tables $table1 and $table2.
185
     *
186
     * If there are no differences this method returns the boolean false.
187
     *
188
     * @return TableDiff|false
189
     */
190 4671
    public function diffTable(Table $table1, Table $table2)
191
    {
192 4671
        $changes                     = 0;
193 4671
        $tableDifferences            = new TableDiff($table1->getName());
194 4671
        $tableDifferences->fromTable = $table1;
195
196 4671
        $table1Columns = $table1->getColumns();
197 4671
        $table2Columns = $table2->getColumns();
198
199
        /* See if all the fields in table 1 exist in table 2 */
200 4671
        foreach ($table2Columns as $columnName => $column) {
201 4661
            if ($table1->hasColumn($columnName)) {
202 4619
                continue;
203
            }
204
205 4373
            $tableDifferences->addedColumns[$columnName] = $column;
206 4373
            $changes++;
207
        }
208
        /* See if there are any removed fields in table 2 */
209 4671
        foreach ($table1Columns as $columnName => $column) {
210
            // See if column is removed in table 2.
211 4661
            if (! $table2->hasColumn($columnName)) {
212 4165
                $tableDifferences->removedColumns[$columnName] = $column;
213 4165
                $changes++;
214 4165
                continue;
215
            }
216
217
            // See if column has changed properties in table 2.
218 4619
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
219
220 4619
            if (empty($changedProperties)) {
221 4553
                continue;
222
            }
223
224 4360
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
225 4360
            $columnDiff->fromColumn                               = $column;
226 4360
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
227 4360
            $changes++;
228
        }
229
230 4671
        $this->detectColumnRenamings($tableDifferences);
231
232 4671
        $table1Indexes = $table1->getIndexes();
233 4671
        $table2Indexes = $table2->getIndexes();
234
235
        /* See if all the indexes in table 1 exist in table 2 */
236 4671
        foreach ($table2Indexes as $indexName => $index) {
237 4460
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
238 4426
                continue;
239
            }
240
241 4286
            $tableDifferences->addedIndexes[$indexName] = $index;
242 4286
            $changes++;
243
        }
244
        /* See if there are any removed indexes in table 2 */
245 4671
        foreach ($table1Indexes as $indexName => $index) {
246
            // See if index is removed in table 2.
247 4454
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
248 4454
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
249
            ) {
250 4257
                $tableDifferences->removedIndexes[$indexName] = $index;
251 4257
                $changes++;
252 4257
                continue;
253
            }
254
255
            // See if index has changed in table 2.
256 4426
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
257 4426
            assert($table2Index instanceof Index);
258
259 4426
            if (! $this->diffIndex($index, $table2Index)) {
260 4396
                continue;
261
            }
262
263 4340
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
264 4340
            $changes++;
265
        }
266
267 4671
        $this->detectIndexRenamings($tableDifferences);
268
269 4671
        $fromFkeys = $table1->getForeignKeys();
270 4671
        $toFkeys   = $table2->getForeignKeys();
271
272 4671
        foreach ($fromFkeys as $key1 => $constraint1) {
273 4128
            foreach ($toFkeys as $key2 => $constraint2) {
274 4050
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
275 4017
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
276
                } else {
277 4011
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
278 1030
                        $tableDifferences->changedForeignKeys[] = $constraint2;
279 1030
                        $changes++;
280 1052
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
281
                    }
282
                }
283
            }
284
        }
285
286 4671
        foreach ($fromFkeys as $constraint1) {
287 4085
            $tableDifferences->removedForeignKeys[] = $constraint1;
288 4085
            $changes++;
289
        }
290
291 4671
        foreach ($toFkeys as $constraint2) {
292 4011
            $tableDifferences->addedForeignKeys[] = $constraint2;
293 4011
            $changes++;
294
        }
295
296 4671
        return $changes ? $tableDifferences : false;
297
    }
298
299
    /**
300
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
301
     * however ambiguities between different possibilities should not lead to renaming at all.
302
     *
303
     * @return void
304
     */
305 4671
    private function detectColumnRenamings(TableDiff $tableDifferences)
306
    {
307 4671
        $renameCandidates = [];
308 4671
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
309 4373
            foreach ($tableDifferences->removedColumns as $removedColumn) {
310 4151
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
311 3764
                    continue;
312
                }
313
314 4165
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
315
            }
316
        }
317
318 4671
        foreach ($renameCandidates as $candidateColumns) {
319 4151
            if (count($candidateColumns) !== 1) {
320 758
                continue;
321
            }
322
323 4149
            [$removedColumn, $addedColumn] = $candidateColumns[0];
324 4149
            $removedColumnName             = strtolower($removedColumn->getName());
325 4149
            $addedColumnName               = strtolower($addedColumn->getName());
326
327 4149
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
328 1298
                continue;
329
            }
330
331 4149
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
332
            unset(
333 4149
                $tableDifferences->addedColumns[$addedColumnName],
334 4149
                $tableDifferences->removedColumns[$removedColumnName]
335
            );
336
        }
337 4671
    }
338
339
    /**
340
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
341
     * however ambiguities between different possibilities should not lead to renaming at all.
342
     *
343
     * @return void
344
     */
345 4671
    private function detectIndexRenamings(TableDiff $tableDifferences)
346
    {
347 4671
        $renameCandidates = [];
348
349
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
350 4671
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
351 4286
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
352 4235
                if ($this->diffIndex($addedIndex, $removedIndex)) {
353 4045
                    continue;
354
                }
355
356 4006
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
357
            }
358
        }
359
360 4671
        foreach ($renameCandidates as $candidateIndexes) {
361
            // If the current rename candidate contains exactly one semantically equal index,
362
            // we can safely rename it.
363
            // Otherwise it is unclear if a rename action is really intended,
364
            // therefore we let those ambiguous indexes be added/dropped.
365 3980
            if (count($candidateIndexes) !== 1) {
366 704
                continue;
367
            }
368
369 3978
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
370
371 3978
            $removedIndexName = strtolower($removedIndex->getName());
372 3978
            $addedIndexName   = strtolower($addedIndex->getName());
373
374 3978
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
375
                continue;
376
            }
377
378 3978
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
379
            unset(
380 3978
                $tableDifferences->addedIndexes[$addedIndexName],
381 3978
                $tableDifferences->removedIndexes[$removedIndexName]
382
            );
383
        }
384 4671
    }
385
386
    /**
387
     * @return bool
388
     */
389 4056
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390
    {
391 4056
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 3973
            return true;
393
        }
394
395 4033
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396
            return true;
397
        }
398
399 4033
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
400 1001
            return true;
401
        }
402
403 4031
        if ($key1->onUpdate() !== $key2->onUpdate()) {
404 1028
            return true;
405
        }
406
407 4023
        return $key1->onDelete() !== $key2->onDelete();
408
    }
409
410
    /**
411
     * Returns the difference between the fields $field1 and $field2.
412
     *
413
     * If there are differences this method returns $field2, otherwise the
414
     * boolean false.
415
     *
416
     * @return string[]
417
     */
418 4709
    public function diffColumn(Column $column1, Column $column2)
419
    {
420 4709
        $properties1 = $column1->toArray();
421 4709
        $properties2 = $column2->toArray();
422
423 4709
        $changedProperties = [];
424
425 4709
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
426 3956
            $changedProperties[] = 'type';
427
        }
428
429 4709
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
430 4709
            if ($properties1[$property] === $properties2[$property]) {
431 4709
                continue;
432
            }
433
434 2702
            $changedProperties[] = $property;
435
        }
436
437
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
438 4709
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\Schema\Com...ALegacyJsonComparison() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

438
        if (/** @scrutinizer ignore-deprecated */ $this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
Loading history...
439 3803
            array_shift($changedProperties);
440
441 3803
            $changedProperties[] = 'comment';
442
        }
443
444
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
445
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
446 4709
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
447 4709
            || $properties1['default'] != $properties2['default']) {
448 4167
            $changedProperties[] = 'default';
449
        }
450
451 4709
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
452 4709
            $properties1['type'] instanceof Types\BinaryType
453
        ) {
454
            // check if value of length is set at all, default value assumed otherwise.
455 4422
            $length1 = $properties1['length'] ?: 255;
456 4422
            $length2 = $properties2['length'] ?: 255;
457 4422
            if ($length1 !== $length2) {
458 3488
                $changedProperties[] = 'length';
459
            }
460
461 4422
            if ($properties1['fixed'] !== $properties2['fixed']) {
462 4422
                $changedProperties[] = 'fixed';
463
            }
464 4673
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
465 4144
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
466
                $changedProperties[] = 'precision';
467
            }
468 4144
            if ($properties1['scale'] !== $properties2['scale']) {
469
                $changedProperties[] = 'scale';
470
            }
471
        }
472
473
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
474 4709
        if ($properties1['comment'] !== $properties2['comment'] &&
475 4709
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
476 4709
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
477
        ) {
478 4130
            $changedProperties[] = 'comment';
479
        }
480
481 4709
        $customOptions1 = $column1->getCustomSchemaOptions();
482 4709
        $customOptions2 = $column2->getCustomSchemaOptions();
483
484 4709
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
485 1327
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
486 1325
                $changedProperties[] = $key;
487 1327
            } elseif ($properties1[$key] !== $properties2[$key]) {
488 4
                $changedProperties[] = $key;
489
            }
490
        }
491
492 4709
        $platformOptions1 = $column1->getPlatformOptions();
493 4709
        $platformOptions2 = $column2->getPlatformOptions();
494
495 4709
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
496 2757
            if ($properties1[$key] === $properties2[$key]) {
497 2757
                continue;
498
            }
499
500 2631
            $changedProperties[] = $key;
501
        }
502
503 4709
        return array_unique($changedProperties);
504
    }
505
506
    /**
507
     * TODO: kill with fire on v3.0
508
     *
509
     * @deprecated
510
     */
511 4709
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
512
    {
513 4709
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
514 4705
            return false;
515
        }
516
517 3832
        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
518 3832
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
519
    }
520
521
    /**
522
     * Finds the difference between the indexes $index1 and $index2.
523
     *
524
     * Compares $index1 with $index2 and returns $index2 if there are any
525
     * differences or false in case there are no differences.
526
     *
527
     * @return bool
528
     */
529 4442
    public function diffIndex(Index $index1, Index $index2)
530
    {
531 4442
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
532
    }
533
}
534