Failed Conditions
Push — master ( 379085...b45ed5 )
by Marco
54s queued 28s
created

Comparator::isAutoIncrementSequenceInSchema()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
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 count;
14
use function strtolower;
15
16
/**
17
 * Compares two Schemas and return an instance of SchemaDiff.
18
 *
19
 * @link   www.doctrine-project.org
20
 */
21
class Comparator
22
{
23
    /**
24
     * @return SchemaDiff
25
     */
26 323
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27
    {
28 323
        $c = new self();
29
30 323
        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 513
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44 513
        $diff             = new SchemaDiff();
45 513
        $diff->fromSchema = $fromSchema;
46
47 513
        $foreignKeysToTable = [];
48
49 513
        foreach ($toSchema->getNamespaces() as $namespace) {
50 38
            if ($fromSchema->hasNamespace($namespace)) {
51 38
                continue;
52
            }
53
54 38
            $diff->newNamespaces[$namespace] = $namespace;
55
        }
56
57 513
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 38
            if ($toSchema->hasNamespace($namespace)) {
59 38
                continue;
60
            }
61
62 19
            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
64
65 513
        foreach ($toSchema->getTables() as $table) {
66 399
            $tableName = $table->getShortestName($toSchema->getName());
67 399
            if (! $fromSchema->hasTable($tableName)) {
68 95
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 361
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 361
                if ($tableDifferences !== false) {
72 399
                    $diff->changedTables[$tableName] = $tableDifferences;
73
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78 513
        foreach ($fromSchema->getTables() as $table) {
79 380
            $tableName = $table->getShortestName($fromSchema->getName());
80
81 380
            $table = $fromSchema->getTable($tableName);
82 380
            if (! $toSchema->hasTable($tableName)) {
83 95
                $diff->removedTables[$tableName] = $table;
84
            }
85
86
            // also remember all foreign keys that point to a specific table
87 380
            foreach ($table->getForeignKeys() as $foreignKey) {
88 38
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 38
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 38
                    $foreignKeysToTable[$foreignTable] = [];
91
                }
92 380
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
93
            }
94
        }
95
96 513
        foreach ($diff->removedTables as $tableName => $table) {
97 95
            if (! isset($foreignKeysToTable[$tableName])) {
98 57
                continue;
99
            }
100
101 38
            $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 38
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
106
                // strtolower the table name to make if compatible with getShortestName
107 38
                $localTableName = strtolower($foreignKey->getLocalTableName());
108 38
                if (! isset($diff->changedTables[$localTableName])) {
109
                    continue;
110
                }
111
112 38
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
113
                    // We check if the key is from the removed table if not we skip.
114 38
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
115 19
                        continue;
116
                    }
117 38
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
118
                }
119
            }
120
        }
121
122 513
        foreach ($toSchema->getSequences() as $sequence) {
123 76
            $sequenceName = $sequence->getShortestName($toSchema->getName());
124 76
            if (! $fromSchema->hasSequence($sequenceName)) {
125 57
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
126 57
                    $diff->newSequences[] = $sequence;
127
                }
128
            } else {
129 38
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
130 76
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
131
                }
132
            }
133
        }
134
135 513
        foreach ($fromSchema->getSequences() as $sequence) {
136 76
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
137 19
                continue;
138
            }
139
140 57
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
141
142 57
            if ($toSchema->hasSequence($sequenceName)) {
143 38
                continue;
144
            }
145
146 38
            $diff->removedSequences[] = $sequence;
147
        }
148
149 513
        return $diff;
150
    }
151
152
    /**
153
     * @param Schema   $schema
154
     * @param Sequence $sequence
155
     *
156
     * @return bool
157
     */
158 114
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
159
    {
160 114
        foreach ($schema->getTables() as $table) {
161 38
            if ($sequence->isAutoIncrementsFor($table)) {
162 38
                return true;
163
            }
164
        }
165
166 76
        return false;
167
    }
168
169
    /**
170
     * @return bool
171
     */
172 66
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
173
    {
174 66
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
175 38
            return true;
176
        }
177
178 47
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
179
    }
180
181
    /**
182
     * Returns the difference between the tables $table1 and $table2.
183
     *
184
     * If there are no differences this method returns the boolean false.
185
     *
186
     * @return TableDiff|false
187
     */
188 2469
    public function diffTable(Table $table1, Table $table2)
189
    {
190 2469
        $changes                     = 0;
191 2469
        $tableDifferences            = new TableDiff($table1->getName());
192 2469
        $tableDifferences->fromTable = $table1;
193
194 2469
        $table1Columns = $table1->getColumns();
195 2469
        $table2Columns = $table2->getColumns();
196
197
        /* See if all the fields in table 1 exist in table 2 */
198 2469
        foreach ($table2Columns as $columnName => $column) {
199 2374
            if ($table1->hasColumn($columnName)) {
200 1975
                continue;
201
            }
202
203 588
            $tableDifferences->addedColumns[$columnName] = $column;
204 588
            $changes++;
205
        }
206
        /* See if there are any removed fields in table 2 */
207 2469
        foreach ($table1Columns as $columnName => $column) {
208
            // See if column is removed in table 2.
209 2374
            if (! $table2->hasColumn($columnName)) {
210 588
                $tableDifferences->removedColumns[$columnName] = $column;
211 588
                $changes++;
212 588
                continue;
213
            }
214
215
            // See if column has changed properties in table 2.
216 1975
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
217
218 1975
            if (empty($changedProperties)) {
219 1392
                continue;
220
            }
221
222 812
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
223 812
            $columnDiff->fromColumn                               = $column;
224 812
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
225 812
            $changes++;
226
        }
227
228 2469
        $this->detectColumnRenamings($tableDifferences);
229
230 2469
        $table1Indexes = $table1->getIndexes();
231 2469
        $table2Indexes = $table2->getIndexes();
232
233
        /* See if all the indexes in table 1 exist in table 2 */
234 2469
        foreach ($table2Indexes as $indexName => $index) {
235 920
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
236 582
                continue;
237
            }
238
239 338
            $tableDifferences->addedIndexes[$indexName] = $index;
240 338
            $changes++;
241
        }
242
        /* See if there are any removed indexes in table 2 */
243 2469
        foreach ($table1Indexes as $indexName => $index) {
244
            // See if index is removed in table 2.
245 863
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
246 863
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
247
            ) {
248 376
                $tableDifferences->removedIndexes[$indexName] = $index;
249 376
                $changes++;
250 376
                continue;
251
            }
252
253
            // See if index has changed in table 2.
254 582
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
255
256 582
            if (! $this->diffIndex($index, $table2Index)) {
0 ignored issues
show
Bug introduced by
It seems like $table2Index can also be of type null; however, parameter $index2 of Doctrine\DBAL\Schema\Comparator::diffIndex() does only seem to accept Doctrine\DBAL\Schema\Index, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

256
            if (! $this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
257 297
                continue;
258
            }
259
260 303
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
261 303
            $changes++;
262
        }
263
264 2469
        $this->detectIndexRenamings($tableDifferences);
265
266 2469
        $fromFkeys = $table1->getForeignKeys();
267 2469
        $toFkeys   = $table2->getForeignKeys();
268
269 2469
        foreach ($fromFkeys as $key1 => $constraint1) {
270 251
            foreach ($toFkeys as $key2 => $constraint2) {
271 118
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
272 43
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
273
                } else {
274 75
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
275 38
                        $tableDifferences->changedForeignKeys[] = $constraint2;
276 38
                        $changes++;
277 251
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
278
                    }
279
                }
280
            }
281
        }
282
283 2469
        foreach ($fromFkeys as $constraint1) {
284 170
            $tableDifferences->removedForeignKeys[] = $constraint1;
285 170
            $changes++;
286
        }
287
288 2469
        foreach ($toFkeys as $constraint2) {
289 56
            $tableDifferences->addedForeignKeys[] = $constraint2;
290 56
            $changes++;
291
        }
292
293 2469
        return $changes ? $tableDifferences : false;
294
    }
295
296
    /**
297
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
298
     * however ambiguities between different possibilities should not lead to renaming at all.
299
     *
300
     * @return void
301
     */
302 2469
    private function detectColumnRenamings(TableDiff $tableDifferences)
303
    {
304 2469
        $renameCandidates = [];
305 2469
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
306 588
            foreach ($tableDifferences->removedColumns as $removedColumn) {
307 455
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
308 361
                    continue;
309
                }
310
311 588
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
312
            }
313
        }
314
315 2469
        foreach ($renameCandidates as $candidateColumns) {
316 455
            if (count($candidateColumns) !== 1) {
317 19
                continue;
318
            }
319
320 436
            [$removedColumn, $addedColumn] = $candidateColumns[0];
321 436
            $removedColumnName             = strtolower($removedColumn->getName());
322 436
            $addedColumnName               = strtolower($addedColumn->getName());
323
324 436
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
325 19
                continue;
326
            }
327
328 436
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
329
            unset(
330 436
                $tableDifferences->addedColumns[$addedColumnName],
331 436
                $tableDifferences->removedColumns[$removedColumnName]
332
            );
333
        }
334 2469
    }
335
336
    /**
337
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
338
     * however ambiguities between different possibilities should not lead to renaming at all.
339
     *
340
     * @return void
341
     */
342 2469
    private function detectIndexRenamings(TableDiff $tableDifferences)
343
    {
344 2469
        $renameCandidates = [];
345
346
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
347 2469
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
348 338
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
349 159
                if ($this->diffIndex($addedIndex, $removedIndex)) {
350 84
                    continue;
351
                }
352
353 338
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
354
            }
355
        }
356
357 2469
        foreach ($renameCandidates as $candidateIndexes) {
358
            // If the current rename candidate contains exactly one semantically equal index,
359
            // we can safely rename it.
360
            // Otherwise it is unclear if a rename action is really intended,
361
            // therefore we let those ambiguous indexes be added/dropped.
362 75
            if (count($candidateIndexes) !== 1) {
363 19
                continue;
364
            }
365
366 56
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
367
368 56
            $removedIndexName = strtolower($removedIndex->getName());
369 56
            $addedIndexName   = strtolower($addedIndex->getName());
370
371 56
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
372
                continue;
373
            }
374
375 56
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
376
            unset(
377 56
                $tableDifferences->addedIndexes[$addedIndexName],
378 56
                $tableDifferences->removedIndexes[$removedIndexName]
379
            );
380
        }
381 2469
    }
382
383
    /**
384
     * @return bool
385
     */
386 175
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
387
    {
388 175
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
389 37
            return true;
390
        }
391
392 138
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
393
            return true;
394
        }
395
396 138
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
397 19
            return true;
398
        }
399
400 119
        if ($key1->onUpdate() !== $key2->onUpdate()) {
401 19
            return true;
402
        }
403
404 100
        return $key1->onDelete() !== $key2->onDelete();
405
    }
406
407
    /**
408
     * Returns the difference between the fields $field1 and $field2.
409
     *
410
     * If there are differences this method returns $field2, otherwise the
411
     * boolean false.
412
     *
413
     * @return string[]
414
     */
415 2792
    public function diffColumn(Column $column1, Column $column2)
416
    {
417 2792
        $properties1 = $column1->toArray();
418 2792
        $properties2 = $column2->toArray();
419
420 2792
        $changedProperties = [];
421
422 2792
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
423 2792
            if ($properties1[$property] === $properties2[$property]) {
424 2792
                continue;
425
            }
426
427 255
            $changedProperties[] = $property;
428
        }
429
430
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
431 2792
        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

431
        if (/** @scrutinizer ignore-deprecated */ $this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
Loading history...
432 35
            array_shift($changedProperties);
433
434 35
            $changedProperties[] = 'comment';
435
        }
436
437 2792
        if ($properties1['default'] !== $properties2['default'] ||
438
            // Null values need to be checked additionally as they tell whether to create or drop a default value.
439
            // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
440 2729
            ($properties1['default'] === null && $properties2['default'] !== null) ||
441 2792
            ($properties2['default'] === null && $properties1['default'] !== null)
442
        ) {
443 82
            $changedProperties[] = 'default';
444
        }
445
446 2792
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
447 2792
            $properties1['type'] instanceof Types\BinaryType
448
        ) {
449
            // check if value of length is set at all, default value assumed otherwise.
450 590
            $length1 = $properties1['length'] ?: 255;
451 590
            $length2 = $properties2['length'] ?: 255;
452 590
            if ($length1 !== $length2) {
453 286
                $changedProperties[] = 'length';
454
            }
455
456 590
            if ($properties1['fixed'] !== $properties2['fixed']) {
457 590
                $changedProperties[] = 'fixed';
458
            }
459 2450
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
460 37
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
461
                $changedProperties[] = 'precision';
462
            }
463 37
            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 2792
        if ($properties1['comment'] !== $properties2['comment'] &&
470 2792
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
471 2792
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
472
        ) {
473 893
            $changedProperties[] = 'comment';
474
        }
475
476 2792
        $customOptions1 = $column1->getCustomSchemaOptions();
477 2792
        $customOptions2 = $column2->getCustomSchemaOptions();
478
479 2792
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
480 38
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
481 19
                $changedProperties[] = $key;
482 38
            } elseif ($properties1[$key] !== $properties2[$key]) {
483 38
                $changedProperties[] = $key;
484
            }
485
        }
486
487 2792
        $platformOptions1 = $column1->getPlatformOptions();
488 2792
        $platformOptions2 = $column2->getPlatformOptions();
489
490 2792
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
491 38
            if ($properties1[$key] === $properties2[$key]) {
492 38
                continue;
493
            }
494
495 19
            $changedProperties[] = $key;
496
        }
497
498 2792
        return array_unique($changedProperties);
499
    }
500
501
    /**
502
     * TODO: kill with fire on v3.0
503
     *
504
     * @deprecated
505
     */
506 2792
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
507
    {
508 2792
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
509 2730
            return false;
510
        }
511
512 62
        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
513 62
            || ( ! $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 741
    public function diffIndex(Index $index1, Index $index2)
525
    {
526 741
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
527
    }
528
}
529