Completed
Push — master ( 5dd66e...5b5c2c )
by Marco
114:19 queued 111:15
created

lib/Doctrine/DBAL/Schema/Comparator.php (1 issue)

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
     */
25 1609
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
26
    {
27 1609
        $c = new self();
28
29 1609
        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
     */
41 3115
    public function compare(Schema $fromSchema, Schema $toSchema)
42
    {
43 3115
        $diff             = new SchemaDiff();
44 3115
        $diff->fromSchema = $fromSchema;
45
46 3115
        $foreignKeysToTable = [];
47
48 3115
        foreach ($toSchema->getNamespaces() as $namespace) {
49 679
            if ($fromSchema->hasNamespace($namespace)) {
50 679
                continue;
51
            }
52
53 679
            $diff->newNamespaces[$namespace] = $namespace;
54
        }
55
56 3115
        foreach ($fromSchema->getNamespaces() as $namespace) {
57 679
            if ($toSchema->hasNamespace($namespace)) {
58 679
                continue;
59
            }
60
61 402
            $diff->removedNamespaces[$namespace] = $namespace;
62
        }
63
64 3115
        foreach ($toSchema->getTables() as $table) {
65 3103
            $tableName = $table->getShortestName($toSchema->getName());
66 3103
            if (! $fromSchema->hasTable($tableName)) {
67 1510
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
68
            } else {
69 3099
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
70 3099
                if ($tableDifferences !== false) {
71 3048
                    $diff->changedTables[$tableName] = $tableDifferences;
72
                }
73
            }
74
        }
75
76
        /* Check if there are tables removed */
77 3115
        foreach ($fromSchema->getTables() as $table) {
78 3101
            $tableName = $table->getShortestName($fromSchema->getName());
79
80 3101
            $table = $fromSchema->getTable($tableName);
81 3101
            if (! $toSchema->hasTable($tableName)) {
82 1535
                $diff->removedTables[$tableName] = $table;
83
            }
84
85
            // also remember all foreign keys that point to a specific table
86 3101
            foreach ($table->getForeignKeys() as $foreignKey) {
87 554
                $foreignTable = strtolower($foreignKey->getForeignTableName());
88 554
                if (! isset($foreignKeysToTable[$foreignTable])) {
89 554
                    $foreignKeysToTable[$foreignTable] = [];
90
                }
91 590
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
92
            }
93
        }
94
95 3115
        foreach ($diff->removedTables as $tableName => $table) {
96 1535
            if (! isset($foreignKeysToTable[$tableName])) {
97 1531
                continue;
98
            }
99
100 554
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
101
102
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
103
            // and the removedForeignKeys from changedTables
104 554
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
105
                // strtolower the table name to make if compatible with getShortestName
106 554
                $localTableName = strtolower($foreignKey->getLocalTableName());
107 554
                if (! isset($diff->changedTables[$localTableName])) {
108
                    continue;
109
                }
110
111 554
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
112 554
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
113
114
                    // We check if the key is from the removed table if not we skip.
115 554
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
116 552
                        continue;
117
                    }
118 554
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
119
                }
120
            }
121
        }
122
123 3115
        foreach ($toSchema->getSequences() as $sequence) {
124 1183
            $sequenceName = $sequence->getShortestName($toSchema->getName());
125 1183
            if (! $fromSchema->hasSequence($sequenceName)) {
126 1181
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
127 1181
                    $diff->newSequences[] = $sequence;
128
                }
129
            } else {
130 1029
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
131 758
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
132
                }
133
            }
134
        }
135
136 3115
        foreach ($fromSchema->getSequences() as $sequence) {
137 1208
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
138 602
                continue;
139
            }
140
141 1206
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
142
143 1206
            if ($toSchema->hasSequence($sequenceName)) {
144 1029
                continue;
145
            }
146
147 1204
            $diff->removedSequences[] = $sequence;
148
        }
149
150 3115
        return $diff;
151
    }
152
153
    /**
154
     * @param Schema   $schema
155
     * @param Sequence $sequence
156
     *
157
     * @return bool
158
     */
159 1212
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
160
    {
161 1212
        foreach ($schema->getTables() as $table) {
162 604
            if ($sequence->isAutoIncrementsFor($table)) {
163 604
                return true;
164
            }
165
        }
166
167 1208
        return false;
168
    }
169
170
    /**
171
     * @return bool
172
     */
173 2086
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
174
    {
175 2086
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
176 1229
            return true;
177
        }
178
179 2084
        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
     *
187
     * @return TableDiff|false
188
     */
189 4458
    public function diffTable(Table $table1, Table $table2)
190
    {
191 4458
        $changes                     = 0;
192 4458
        $tableDifferences            = new TableDiff($table1->getName());
193 4458
        $tableDifferences->fromTable = $table1;
194
195 4458
        $table1Columns = $table1->getColumns();
196 4458
        $table2Columns = $table2->getColumns();
197
198
        /* See if all the fields in table 1 exist in table 2 */
199 4458
        foreach ($table2Columns as $columnName => $column) {
200 4448
            if ($table1->hasColumn($columnName)) {
201 4406
                continue;
202
            }
203
204 4160
            $tableDifferences->addedColumns[$columnName] = $column;
205 4160
            $changes++;
206
        }
207
        /* See if there are any removed fields in table 2 */
208 4458
        foreach ($table1Columns as $columnName => $column) {
209
            // See if column is removed in table 2.
210 4448
            if (! $table2->hasColumn($columnName)) {
211 3978
                $tableDifferences->removedColumns[$columnName] = $column;
212 3978
                $changes++;
213 3978
                continue;
214
            }
215
216
            // See if column has changed properties in table 2.
217 4406
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
218
219 4406
            if (empty($changedProperties)) {
220 4340
                continue;
221
            }
222
223 4161
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
224 4161
            $columnDiff->fromColumn                               = $column;
225 4161
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
226 4161
            $changes++;
227
        }
228
229 4458
        $this->detectColumnRenamings($tableDifferences);
230
231 4458
        $table1Indexes = $table1->getIndexes();
232 4458
        $table2Indexes = $table2->getIndexes();
233
234
        /* See if all the indexes in table 1 exist in table 2 */
235 4458
        foreach ($table2Indexes as $indexName => $index) {
236 4247
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
237 4213
                continue;
238
            }
239
240 4079
            $tableDifferences->addedIndexes[$indexName] = $index;
241 4079
            $changes++;
242
        }
243
        /* See if there are any removed indexes in table 2 */
244 4458
        foreach ($table1Indexes as $indexName => $index) {
245
            // See if index is removed in table 2.
246 4241
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
247 4241
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
248
            ) {
249 4054
                $tableDifferences->removedIndexes[$indexName] = $index;
250 4054
                $changes++;
251 4054
                continue;
252
            }
253
254
            // See if index has changed in table 2.
255 4213
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
256 4213
            assert($table2Index instanceof Index);
257
258 4213
            if (! $this->diffIndex($index, $table2Index)) {
259 4183
                continue;
260
            }
261
262 4127
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
263 4127
            $changes++;
264
        }
265
266 4458
        $this->detectIndexRenamings($tableDifferences);
267
268 4458
        $fromFkeys = $table1->getForeignKeys();
269 4458
        $toFkeys   = $table2->getForeignKeys();
270
271 4458
        foreach ($fromFkeys as $key1 => $constraint1) {
272 3941
            foreach ($toFkeys as $key2 => $constraint2) {
273 3865
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
274 3834
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
275
                } else {
276 3826
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
277 1104
                        $tableDifferences->changedForeignKeys[] = $constraint2;
278 1104
                        $changes++;
279 1126
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
280
                    }
281
                }
282
            }
283
        }
284
285 4458
        foreach ($fromFkeys as $constraint1) {
286 3898
            $tableDifferences->removedForeignKeys[] = $constraint1;
287 3898
            $changes++;
288
        }
289
290 4458
        foreach ($toFkeys as $constraint2) {
291 3826
            $tableDifferences->addedForeignKeys[] = $constraint2;
292 3826
            $changes++;
293
        }
294
295 4458
        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
     * however ambiguities between different possibilities should not lead to renaming at all.
301
     *
302
     * @return void
303
     */
304 4458
    private function detectColumnRenamings(TableDiff $tableDifferences)
305
    {
306 4458
        $renameCandidates = [];
307 4458
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
308 4160
            foreach ($tableDifferences->removedColumns as $removedColumn) {
309 3964
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
310 3588
                    continue;
311
                }
312
313 3978
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
314
            }
315
        }
316
317 4458
        foreach ($renameCandidates as $candidateColumns) {
318 3964
            if (count($candidateColumns) !== 1) {
319 852
                continue;
320
            }
321
322 3962
            [$removedColumn, $addedColumn] = $candidateColumns[0];
323 3962
            $removedColumnName             = strtolower($removedColumn->getName());
324 3962
            $addedColumnName               = strtolower($addedColumn->getName());
325
326 3962
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
327 1352
                continue;
328
            }
329
330 3962
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
331
            unset(
332 3962
                $tableDifferences->addedColumns[$addedColumnName],
333 3962
                $tableDifferences->removedColumns[$removedColumnName]
334
            );
335
        }
336 4458
    }
337
338
    /**
339
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
340
     * however ambiguities between different possibilities should not lead to renaming at all.
341
     *
342
     * @return void
343
     */
344 4458
    private function detectIndexRenamings(TableDiff $tableDifferences)
345
    {
346 4458
        $renameCandidates = [];
347
348
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
349 4458
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
350 4079
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
351 4032
                if ($this->diffIndex($addedIndex, $removedIndex)) {
352 3846
                    continue;
353
                }
354
355 3823
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
356
            }
357
        }
358
359 4458
        foreach ($renameCandidates as $candidateIndexes) {
360
            // If the current rename candidate contains exactly one semantically equal index,
361
            // 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 3797
            if (count($candidateIndexes) !== 1) {
365 802
                continue;
366
            }
367
368 3795
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
369
370 3795
            $removedIndexName = strtolower($removedIndex->getName());
371 3795
            $addedIndexName   = strtolower($addedIndex->getName());
372
373 3795
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
374
                continue;
375
            }
376
377 3795
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
378
            unset(
379 3795
                $tableDifferences->addedIndexes[$addedIndexName],
380 3795
                $tableDifferences->removedIndexes[$removedIndexName]
381
            );
382
        }
383 4458
    }
384
385
    /**
386
     * @return bool
387
     */
388 3871
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
389
    {
390 3871
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
391 3782
            return true;
392
        }
393
394 3850
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
395
            return true;
396
        }
397
398 3850
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
399 1077
            return true;
400
        }
401
402 3848
        if ($key1->onUpdate() !== $key2->onUpdate()) {
403 1102
            return true;
404
        }
405
406 3840
        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
     * boolean false.
414
     *
415
     * @return string[]
416
     */
417 4492
    public function diffColumn(Column $column1, Column $column2)
418
    {
419 4492
        $properties1 = $column1->toArray();
420 4492
        $properties2 = $column2->toArray();
421
422 4492
        $changedProperties = [];
423
424 4492
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
425 4492
            if ($properties1[$property] === $properties2[$property]) {
426 4492
                continue;
427
            }
428
429 3814
            $changedProperties[] = $property;
430
        }
431
432
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
433 4492
        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 3620
            array_shift($changedProperties);
435
436 3620
            $changedProperties[] = 'comment';
437
        }
438
439
        // 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 4492
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
442 4492
            || $properties1['default'] != $properties2['default']) {
443 3968
            $changedProperties[] = 'default';
444
        }
445
446 4492
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
447 4492
            $properties1['type'] instanceof Types\BinaryType
448
        ) {
449
            // check if value of length is set at all, default value assumed otherwise.
450 4209
            $length1 = $properties1['length'] ?: 255;
451 4209
            $length2 = $properties2['length'] ?: 255;
452 4209
            if ($length1 !== $length2) {
453 3332
                $changedProperties[] = 'length';
454
            }
455
456 4209
            if ($properties1['fixed'] !== $properties2['fixed']) {
457 4209
                $changedProperties[] = 'fixed';
458
            }
459 4456
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
460 3955
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
461
                $changedProperties[] = 'precision';
462
            }
463 3955
            if ($properties1['scale'] !== $properties2['scale']) {
464
                $changedProperties[] = 'scale';
465
            }
466
        }
467
468
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
469 4492
        if ($properties1['comment'] !== $properties2['comment'] &&
470 4492
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
471 4492
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
472
        ) {
473 3949
            $changedProperties[] = 'comment';
474
        }
475
476 4492
        $customOptions1 = $column1->getCustomSchemaOptions();
477 4492
        $customOptions2 = $column2->getCustomSchemaOptions();
478
479 4492
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
480 1379
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
481 1377
                $changedProperties[] = $key;
482 1379
            } elseif ($properties1[$key] !== $properties2[$key]) {
483 4
                $changedProperties[] = $key;
484
            }
485
        }
486
487 4492
        $platformOptions1 = $column1->getPlatformOptions();
488 4492
        $platformOptions2 = $column2->getPlatformOptions();
489
490 4492
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
491 2570
            if ($properties1[$key] === $properties2[$key]) {
492 2570
                continue;
493
            }
494
495 2460
            $changedProperties[] = $key;
496
        }
497
498 4492
        return array_unique($changedProperties);
499
    }
500
501
    /**
502
     * TODO: kill with fire on v3.0
503
     *
504
     * @deprecated
505
     */
506 4492
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
507
    {
508 4492
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
509 4488
            return false;
510
        }
511
512 3647
        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
513 3647
            || ( ! $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
     * differences or false in case there are no differences.
521
     *
522
     * @return bool
523
     */
524 4229
    public function diffIndex(Index $index1, Index $index2)
525
    {
526 4229
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
527
    }
528
}
529