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

Comparator::isALegacyJsonComparison()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 6
nop 2
crap 6
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 strtolower;
17
18
/**
19
 * Compares two Schemas and return an instance of SchemaDiff.
20
 */
21
class Comparator
22
{
23
    /**
24
     * @return SchemaDiff
25
     */
26 1638
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27
    {
28 1638
        $c = new self();
29
30 1638
        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 2817
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44 2817
        $diff             = new SchemaDiff();
45 2817
        $diff->fromSchema = $fromSchema;
46
47 2817
        $foreignKeysToTable = [];
48
49 2817
        foreach ($toSchema->getNamespaces() as $namespace) {
50 702
            if ($fromSchema->hasNamespace($namespace)) {
51 702
                continue;
52
            }
53
54 702
            $diff->newNamespaces[$namespace] = $namespace;
55
        }
56
57 2817
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 702
            if ($toSchema->hasNamespace($namespace)) {
59 702
                continue;
60
            }
61
62 416
            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
64
65 2817
        foreach ($toSchema->getTables() as $table) {
66 2817
            $tableName = $table->getShortestName($toSchema->getName());
67 2817
            if (! $fromSchema->hasTable($tableName)) {
68 1560
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 2817
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 2817
                if ($tableDifferences !== false) {
72 2757
                    $diff->changedTables[$tableName] = $tableDifferences;
73
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78 2817
        foreach ($fromSchema->getTables() as $table) {
79 2817
            $tableName = $table->getShortestName($fromSchema->getName());
80
81 2817
            $table = $fromSchema->getTable($tableName);
82 2817
            if (! $toSchema->hasTable($tableName)) {
83 1586
                $diff->removedTables[$tableName] = $table;
84
            }
85
86
            // also remember all foreign keys that point to a specific table
87 2817
            foreach ($table->getForeignKeys() as $foreignKey) {
88 572
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 572
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 572
                    $foreignKeysToTable[$foreignTable] = [];
91
                }
92 572
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
93
            }
94
        }
95
96 2817
        foreach ($diff->removedTables as $tableName => $table) {
97 1586
            if (! isset($foreignKeysToTable[$tableName])) {
98 1586
                continue;
99
            }
100
101 572
            $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 572
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
106
                // strtolower the table name to make if compatible with getShortestName
107 572
                $localTableName = strtolower($foreignKey->getLocalTableName());
108 572
                if (! isset($diff->changedTables[$localTableName])) {
109
                    continue;
110
                }
111
112 572
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
113 572
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
114
115
                    // We check if the key is from the removed table if not we skip.
116 572
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
117 572
                        continue;
118
                    }
119 572
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120
                }
121
            }
122
        }
123
124 2817
        foreach ($toSchema->getSequences() as $sequence) {
125 1222
            $sequenceName = $sequence->getShortestName($toSchema->getName());
126 1222
            if (! $fromSchema->hasSequence($sequenceName)) {
127 1222
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
128 1222
                    $diff->newSequences[] = $sequence;
129
                }
130
            } else {
131 1066
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
132 780
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
133
                }
134
            }
135
        }
136
137 2817
        foreach ($fromSchema->getSequences() as $sequence) {
138 1248
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
139 624
                continue;
140
            }
141
142 1248
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
143
144 1248
            if ($toSchema->hasSequence($sequenceName)) {
145 1066
                continue;
146
            }
147
148 1248
            $diff->removedSequences[] = $sequence;
149
        }
150
151 2817
        return $diff;
152
    }
153
154
    /**
155
     * @param Schema   $schema
156
     * @param Sequence $sequence
157
     *
158
     * @return bool
159
     */
160 1248
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
161
    {
162 1248
        foreach ($schema->getTables() as $table) {
163 624
            if ($sequence->isAutoIncrementsFor($table)) {
164 624
                return true;
165
            }
166
        }
167
168 1248
        return false;
169
    }
170
171
    /**
172
     * @return bool
173
     */
174 2030
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
175
    {
176 2030
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
177 1274
            return true;
178
        }
179
180 2030
        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 3772
    public function diffTable(Table $table1, Table $table2)
191
    {
192 3772
        $changes                     = 0;
193 3772
        $tableDifferences            = new TableDiff($table1->getName());
194 3772
        $tableDifferences->fromTable = $table1;
195
196 3772
        $table1Columns = $table1->getColumns();
197 3772
        $table2Columns = $table2->getColumns();
198
199
        /* See if all the fields in table 1 exist in table 2 */
200 3772
        foreach ($table2Columns as $columnName => $column) {
201 3772
            if ($table1->hasColumn($columnName)) {
202 3772
                continue;
203
            }
204
205 3694
            $tableDifferences->addedColumns[$columnName] = $column;
206 3694
            $changes++;
207
        }
208
        /* See if there are any removed fields in table 2 */
209 3772
        foreach ($table1Columns as $columnName => $column) {
210
            // See if column is removed in table 2.
211 3772
            if (! $table2->hasColumn($columnName)) {
212 3512
                $tableDifferences->removedColumns[$columnName] = $column;
213 3512
                $changes++;
214 3512
                continue;
215
            }
216
217
            // See if column has changed properties in table 2.
218 3772
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
219
220 3772
            if (empty($changedProperties)) {
221 3772
                continue;
222
            }
223
224 3632
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
225 3632
            $columnDiff->fromColumn                               = $column;
226 3632
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
227 3632
            $changes++;
228
        }
229
230 3772
        $this->detectColumnRenamings($tableDifferences);
231
232 3772
        $table1Indexes = $table1->getIndexes();
233 3772
        $table2Indexes = $table2->getIndexes();
234
235
        /* See if all the indexes in table 1 exist in table 2 */
236 3772
        foreach ($table2Indexes as $indexName => $index) {
237 3730
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
238 3730
                continue;
239
            }
240
241 3640
            $tableDifferences->addedIndexes[$indexName] = $index;
242 3640
            $changes++;
243
        }
244
        /* See if there are any removed indexes in table 2 */
245 3772
        foreach ($table1Indexes as $indexName => $index) {
246
            // See if index is removed in table 2.
247 3730
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
248 3730
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
249
            ) {
250 3612
                $tableDifferences->removedIndexes[$indexName] = $index;
251 3612
                $changes++;
252 3612
                continue;
253
            }
254
255
            // See if index has changed in table 2.
256 3730
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
257 3730
            assert($table2Index instanceof Index);
258
259 3730
            if (! $this->diffIndex($index, $table2Index)) {
260 3730
                continue;
261
            }
262
263 3694
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
264 3694
            $changes++;
265
        }
266
267 3772
        $this->detectIndexRenamings($tableDifferences);
268
269 3772
        $fromFkeys = $table1->getForeignKeys();
270 3772
        $toFkeys   = $table2->getForeignKeys();
271
272 3772
        foreach ($fromFkeys as $key1 => $constraint1) {
273 3542
            foreach ($toFkeys as $key2 => $constraint2) {
274 3542
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
275 3522
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
276
                } else {
277 3512
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
278 1144
                        $tableDifferences->changedForeignKeys[] = $constraint2;
279 1144
                        $changes++;
280 1144
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
281
                    }
282
                }
283
            }
284
        }
285
286 3772
        foreach ($fromFkeys as $constraint1) {
287 3512
            $tableDifferences->removedForeignKeys[] = $constraint1;
288 3512
            $changes++;
289
        }
290
291 3772
        foreach ($toFkeys as $constraint2) {
292 3512
            $tableDifferences->addedForeignKeys[] = $constraint2;
293 3512
            $changes++;
294
        }
295
296 3772
        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 3772
    private function detectColumnRenamings(TableDiff $tableDifferences)
306
    {
307 3772
        $renameCandidates = [];
308 3772
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
309 3694
            foreach ($tableDifferences->removedColumns as $removedColumn) {
310 3512
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
311 3198
                    continue;
312
                }
313
314 3512
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
315
            }
316
        }
317
318 3772
        foreach ($renameCandidates as $candidateColumns) {
319 3512
            if (count($candidateColumns) !== 1) {
320 884
                continue;
321
            }
322
323 3512
            [$removedColumn, $addedColumn] = $candidateColumns[0];
324 3512
            $removedColumnName             = strtolower($removedColumn->getName());
325 3512
            $addedColumnName               = strtolower($addedColumn->getName());
326
327 3512
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
328 1404
                continue;
329
            }
330
331 3512
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
332
            unset(
333 3512
                $tableDifferences->addedColumns[$addedColumnName],
334 3512
                $tableDifferences->removedColumns[$removedColumnName]
335
            );
336
        }
337 3772
    }
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 3772
    private function detectIndexRenamings(TableDiff $tableDifferences)
346
    {
347 3772
        $renameCandidates = [];
348
349
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
350 3772
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
351 3640
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
352 3612
                if ($this->diffIndex($addedIndex, $removedIndex)) {
353 3443
                    continue;
354
                }
355
356 3486
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
357
            }
358
        }
359
360 3772
        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 3486
            if (count($candidateIndexes) !== 1) {
366 832
                continue;
367
            }
368
369 3486
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
370
371 3486
            $removedIndexName = strtolower($removedIndex->getName());
372 3486
            $addedIndexName   = strtolower($addedIndex->getName());
373
374 3486
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
375
                continue;
376
            }
377
378 3486
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
379
            unset(
380 3486
                $tableDifferences->addedIndexes[$addedIndexName],
381 3486
                $tableDifferences->removedIndexes[$removedIndexName]
382
            );
383
        }
384 3772
    }
385
386
    /**
387
     * @return bool
388
     */
389 3542
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390
    {
391 3542
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 3512
            return true;
393
        }
394
395 3522
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396
            return true;
397
        }
398
399 3522
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
400 1118
            return true;
401
        }
402
403 3522
        if ($key1->onUpdate() !== $key2->onUpdate()) {
404 1144
            return true;
405
        }
406
407 3522
        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 3772
    public function diffColumn(Column $column1, Column $column2)
419
    {
420 3772
        $properties1 = $column1->toArray();
421 3772
        $properties2 = $column2->toArray();
422
423 3772
        $changedProperties = [];
424
425 3772
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
426 3772
            if ($properties1[$property] === $properties2[$property]) {
427 3772
                continue;
428
            }
429
430 2589
            $changedProperties[] = $property;
431
        }
432
433
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
434
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
435 3772
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
436 3772
            || $properties1['default'] != $properties2['default']) {
437 3540
            $changedProperties[] = 'default';
438
        }
439
440 3772
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
441 3772
            $properties1['type'] instanceof Types\BinaryType
442
        ) {
443
            // check if value of length is set at all, default value assumed otherwise.
444 3730
            $length1 = $properties1['length'] ?: 255;
445 3730
            $length2 = $properties2['length'] ?: 255;
446 3730
            if ($length1 !== $length2) {
447 2938
                $changedProperties[] = 'length';
448
            }
449
450 3730
            if ($properties1['fixed'] !== $properties2['fixed']) {
451 3730
                $changedProperties[] = 'fixed';
452
            }
453 3772
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
454 3538
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
455
                $changedProperties[] = 'precision';
456
            }
457 3538
            if ($properties1['scale'] !== $properties2['scale']) {
458
                $changedProperties[] = 'scale';
459
            }
460
        }
461
462
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
463 3772
        if ($properties1['comment'] !== $properties2['comment'] &&
464 3772
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
465 3772
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
466
        ) {
467 3434
            $changedProperties[] = 'comment';
468
        }
469
470 3772
        $customOptions1 = $column1->getCustomSchemaOptions();
471 3772
        $customOptions2 = $column2->getCustomSchemaOptions();
472
473 3772
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
474 1430
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
475 1430
                $changedProperties[] = $key;
476 1430
            } elseif ($properties1[$key] !== $properties2[$key]) {
477
                $changedProperties[] = $key;
478
            }
479
        }
480
481 3772
        $platformOptions1 = $column1->getPlatformOptions();
482 3772
        $platformOptions2 = $column2->getPlatformOptions();
483
484 3772
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
485 2277
            if ($properties1[$key] === $properties2[$key]) {
486 2277
                continue;
487
            }
488
489 2169
            $changedProperties[] = $key;
490
        }
491
492 3772
        return array_unique($changedProperties);
493
    }
494
495
    /**
496
     * Finds the difference between the indexes $index1 and $index2.
497
     *
498
     * Compares $index1 with $index2 and returns $index2 if there are any
499
     * differences or false in case there are no differences.
500
     *
501
     * @return bool
502
     */
503 3730
    public function diffIndex(Index $index1, Index $index2)
504
    {
505 3730
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
506
    }
507
}
508