Failed Conditions
Pull Request — master (#3429)
by Gabriel
12:54
created

Comparator::detectColumnRenamings()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7

Importance

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

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