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