Completed
Pull Request — develop (#3518)
by Michael
64:26
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
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27 1609
    {
28
        $c = new self();
29 1609
30
        return $c->compare($fromSchema, $toSchema);
31 1609
    }
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
    public function compare(Schema $fromSchema, Schema $toSchema)
43 3354
    {
44
        $diff             = new SchemaDiff();
45 3354
        $diff->fromSchema = $fromSchema;
46 3354
47
        $foreignKeysToTable = [];
48 3354
49
        foreach ($toSchema->getNamespaces() as $namespace) {
50 3354
            if ($fromSchema->hasNamespace($namespace)) {
51 679
                continue;
52 679
            }
53
54
            $diff->newNamespaces[$namespace] = $namespace;
55 679
        }
56
57
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 3354
            if ($toSchema->hasNamespace($namespace)) {
59 679
                continue;
60 679
            }
61
62
            $diff->removedNamespaces[$namespace] = $namespace;
63 402
        }
64
65
        foreach ($toSchema->getTables() as $table) {
66 3354
            $tableName = $table->getShortestName($toSchema->getName());
67 3342
            if (! $fromSchema->hasTable($tableName)) {
68 3342
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69 1510
            } else {
70
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 3338
                if ($tableDifferences !== false) {
72 3338
                    $diff->changedTables[$tableName] = $tableDifferences;
73 3317
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78
        foreach ($fromSchema->getTables() as $table) {
79 3354
            $tableName = $table->getShortestName($fromSchema->getName());
80 3340
81
            $table = $fromSchema->getTable($tableName);
82 3340
            if (! $toSchema->hasTable($tableName)) {
83 3340
                $diff->removedTables[$tableName] = $table;
84 1535
            }
85
86
            // also remember all foreign keys that point to a specific table
87
            foreach ($table->getForeignKeys() as $foreignKey) {
88 3340
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 554
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 554
                    $foreignKeysToTable[$foreignTable] = [];
91 554
                }
92
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
93 590
            }
94
        }
95
96
        foreach ($diff->removedTables as $tableName => $table) {
97 3354
            if (! isset($foreignKeysToTable[$tableName])) {
98 1535
                continue;
99 1531
            }
100
101
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
102 554
103
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
104
            // and the removedForeignKeys from changedTables
105
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
106 554
                // strtolower the table name to make if compatible with getShortestName
107
                $localTableName = strtolower($foreignKey->getLocalTableName());
108 554
                if (! isset($diff->changedTables[$localTableName])) {
109 554
                    continue;
110
                }
111
112
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
113 554
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
114 554
115
                    // We check if the key is from the removed table if not we skip.
116
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
117 554
                        continue;
118 552
                    }
119
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120 554
                }
121
            }
122
        }
123
124
        foreach ($toSchema->getSequences() as $sequence) {
125 3354
            $sequenceName = $sequence->getShortestName($toSchema->getName());
126 1183
            if (! $fromSchema->hasSequence($sequenceName)) {
127 1183
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
128 1181
                    $diff->newSequences[] = $sequence;
129 1181
                }
130
            } else {
131
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
132 1029
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
133 758
                }
134
            }
135
        }
136
137
        foreach ($fromSchema->getSequences() as $sequence) {
138 3354
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
139 1208
                continue;
140 602
            }
141
142
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
143 1206
144
            if ($toSchema->hasSequence($sequenceName)) {
145 1206
                continue;
146 1029
            }
147
148
            $diff->removedSequences[] = $sequence;
149 1204
        }
150
151
        return $diff;
152 3354
    }
153
154
    /**
155
     * @param Schema   $schema
156
     * @param Sequence $sequence
157
     *
158
     * @return bool
159
     */
160
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
161 1212
    {
162
        foreach ($schema->getTables() as $table) {
163 1212
            if ($sequence->isAutoIncrementsFor($table)) {
164 604
                return true;
165 604
            }
166
        }
167
168
        return false;
169 1208
    }
170
171
    /**
172
     * @return bool
173
     */
174
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
175 1537
    {
176
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
177 1537
            return true;
178 1229
        }
179
180
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
181 1535
    }
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
    public function diffTable(Table $table1, Table $table2)
191 3948
    {
192
        $changes                     = 0;
193 3948
        $tableDifferences            = new TableDiff($table1->getName());
194 3948
        $tableDifferences->fromTable = $table1;
195 3948
196
        $table1Columns = $table1->getColumns();
197 3948
        $table2Columns = $table2->getColumns();
198 3948
199
        /* See if all the fields in table 1 exist in table 2 */
200
        foreach ($table2Columns as $columnName => $column) {
201 3948
            if ($table1->hasColumn($columnName)) {
202 3938
                continue;
203 3908
            }
204
205
            $tableDifferences->addedColumns[$columnName] = $column;
206 3715
            $changes++;
207 3715
        }
208
        /* See if there are any removed fields in table 2 */
209
        foreach ($table1Columns as $columnName => $column) {
210 3948
            // See if column is removed in table 2.
211
            if (! $table2->hasColumn($columnName)) {
212 3938
                $tableDifferences->removedColumns[$columnName] = $column;
213 3451
                $changes++;
214 3451
                continue;
215 3451
            }
216
217
            // See if column has changed properties in table 2.
218
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
219 3908
220
            if (empty($changedProperties)) {
221 3908
                continue;
222 3860
            }
223
224
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
225 3646
            $columnDiff->fromColumn                               = $column;
226 3646
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
227 3646
            $changes++;
228 3646
        }
229
230
        $this->detectColumnRenamings($tableDifferences);
231 3948
232
        $table1Indexes = $table1->getIndexes();
233 3948
        $table2Indexes = $table2->getIndexes();
234 3948
235
        /* See if all the indexes in table 1 exist in table 2 */
236
        foreach ($table2Indexes as $indexName => $index) {
237 3948
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
238 3792
                continue;
239 3758
            }
240
241
            $tableDifferences->addedIndexes[$indexName] = $index;
242 3634
            $changes++;
243 3634
        }
244
        /* See if there are any removed indexes in table 2 */
245
        foreach ($table1Indexes as $indexName => $index) {
246 3948
            // See if index is removed in table 2.
247
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
248 3786
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
249 3786
            ) {
250
                $tableDifferences->removedIndexes[$indexName] = $index;
251 3593
                $changes++;
252 3593
                continue;
253 3593
            }
254
255
            // See if index has changed in table 2.
256
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
257 3758
            assert($table2Index instanceof Index);
258 3758
259
            if (! $this->diffIndex($index, $table2Index)) {
260 3758
                continue;
261 3728
            }
262
263
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
264 3694
            $changes++;
265 3694
        }
266
267
        $this->detectIndexRenamings($tableDifferences);
268 3948
269
        $fromFkeys = $table1->getForeignKeys();
270 3948
        $toFkeys   = $table2->getForeignKeys();
271 3948
272
        foreach ($fromFkeys as $key1 => $constraint1) {
273 3948
            foreach ($toFkeys as $key2 => $constraint2) {
274 3411
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
275 3358
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
276 3324
                } else {
277
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
278 3334
                        $tableDifferences->changedForeignKeys[] = $constraint2;
279 1104
                        $changes++;
280 1104
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
281 1122
                    }
282
                }
283
            }
284
        }
285
286
        foreach ($fromFkeys as $constraint1) {
287 3948
            $tableDifferences->removedForeignKeys[] = $constraint1;
288 3383
            $changes++;
289 3383
        }
290
291
        foreach ($toFkeys as $constraint2) {
292 3948
            $tableDifferences->addedForeignKeys[] = $constraint2;
293 3334
            $changes++;
294 3334
        }
295
296
        return $changes ? $tableDifferences : false;
297 3948
    }
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
    private function detectColumnRenamings(TableDiff $tableDifferences)
306 3948
    {
307
        $renameCandidates = [];
308 3948
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
309 3948
            foreach ($tableDifferences->removedColumns as $removedColumn) {
310 3715
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
311 3441
                    continue;
312 3101
                }
313
314
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
315 3455
            }
316
        }
317
318
        foreach ($renameCandidates as $candidateColumns) {
319 3948
            if (count($candidateColumns) !== 1) {
320 3441
                continue;
321 852
            }
322
323
            [$removedColumn, $addedColumn] = $candidateColumns[0];
324 3439
            $removedColumnName             = strtolower($removedColumn->getName());
325 3439
            $addedColumnName               = strtolower($addedColumn->getName());
326 3439
327
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
328 3439
                continue;
329 1352
            }
330
331
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
332 3439
            unset(
333
                $tableDifferences->addedColumns[$addedColumnName],
334 3439
                $tableDifferences->removedColumns[$removedColumnName]
335 3439
            );
336
        }
337
    }
338 3948
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
    private function detectIndexRenamings(TableDiff $tableDifferences)
346 3948
    {
347
        $renameCandidates = [];
348 3948
349
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
350
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
351 3948
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
352 3634
                if ($this->diffIndex($addedIndex, $removedIndex)) {
353 3575
                    continue;
354 3498
                }
355
356
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
357 3331
            }
358
        }
359
360
        foreach ($renameCandidates as $candidateIndexes) {
361 3948
            // 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
            if (count($candidateIndexes) !== 1) {
366 3305
                continue;
367 802
            }
368
369
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
370 3303
371
            $removedIndexName = strtolower($removedIndex->getName());
372 3303
            $addedIndexName   = strtolower($addedIndex->getName());
373 3303
374
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
375 3303
                continue;
376
            }
377
378
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
379 3303
            unset(
380
                $tableDifferences->addedIndexes[$addedIndexName],
381 3303
                $tableDifferences->removedIndexes[$removedIndexName]
382 3303
            );
383
        }
384
    }
385 3948
386
    /**
387
     * @return bool
388
     */
389
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390 3364
    {
391
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 3364
            return true;
393 3290
        }
394
395
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396 3340
            return true;
397
        }
398
399
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
400 3340
            return true;
401 1077
        }
402
403
        if ($key1->onUpdate() !== $key2->onUpdate()) {
404 3338
            return true;
405 1102
        }
406
407
        return $key1->onDelete() !== $key2->onDelete();
408 3330
    }
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
    public function diffColumn(Column $column1, Column $column2)
419 3982
    {
420
        $properties1 = $column1->toArray();
421 3982
        $properties2 = $column2->toArray();
422 3982
423
        $changedProperties = [];
424 3982
425
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
426 3982
            if ($properties1[$property] === $properties2[$property]) {
427 3982
                continue;
428 3982
            }
429
430
            $changedProperties[] = $property;
431 3260
        }
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 3982
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
436 3142
            || $properties1['default'] != $properties2['default']) {
437
            $changedProperties[] = 'default';
438 3142
        }
439
440
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
441
            $properties1['type'] instanceof Types\BinaryType
442
        ) {
443 3982
            // check if value of length is set at all, default value assumed otherwise.
444 3982
            $length1 = $properties1['length'] ?: 255;
445 3505
            $length2 = $properties2['length'] ?: 255;
446
            if ($length1 !== $length2) {
447
                $changedProperties[] = 'length';
448 3982
            }
449 3982
450
            if ($properties1['fixed'] !== $properties2['fixed']) {
451
                $changedProperties[] = 'fixed';
452 3750
            }
453 3750
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
454 3750
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
455 2849
                $changedProperties[] = 'precision';
456
            }
457
            if ($properties1['scale'] !== $properties2['scale']) {
458 3750
                $changedProperties[] = 'scale';
459 3750
            }
460
        }
461 3950
462 3444
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
463
        if ($properties1['comment'] !== $properties2['comment'] &&
464
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
465 3444
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
466
        ) {
467
            $changedProperties[] = 'comment';
468
        }
469
470
        $customOptions1 = $column1->getCustomSchemaOptions();
471 3982
        $customOptions2 = $column2->getCustomSchemaOptions();
472 3982
473 3982
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
474
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
475 3416
                $changedProperties[] = $key;
476
            } elseif ($properties1[$key] !== $properties2[$key]) {
477
                $changedProperties[] = $key;
478 3982
            }
479 3982
        }
480
481 3982
        $platformOptions1 = $column1->getPlatformOptions();
482 1379
        $platformOptions2 = $column2->getPlatformOptions();
483 1377
484 1379
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
485 4
            if ($properties1[$key] === $properties2[$key]) {
486
                continue;
487
            }
488
489 3982
            $changedProperties[] = $key;
490 3982
        }
491
492 3982
        return array_unique($changedProperties);
493 3079
    }
494 3079
495
    /**
496
     * Finds the difference between the indexes $index1 and $index2.
497 2921
     *
498
     * Compares $index1 with $index2 and returns $index2 if there are any
499
     * differences or false in case there are no differences.
500 3982
     *
501
     * @return bool
502
     */
503
    public function diffIndex(Index $index1, Index $index2)
504
    {
505
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
506
    }
507
}
508