Completed
Pull Request — develop (#3518)
by Michael
105:06 queued 40:05
created

Comparator::isALegacyJsonComparison()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6

Importance

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