Comparator.php 19.1 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema;

5
use Doctrine\DBAL\Types;
6 7 8 9 10 11 12
use function array_intersect_key;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_shift;
use function array_unique;
Sergei Morozov's avatar
Sergei Morozov committed
13
use function assert;
14
use function count;
15
use function get_class;
16
use function strtolower;
17

18
/**
Benjamin Morel's avatar
Benjamin Morel committed
19
 * Compares two Schemas and return an instance of SchemaDiff.
20 21 22 23
 */
class Comparator
{
    /**
24
     * @return SchemaDiff
25
     */
26
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27 28
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
29

30 31 32 33 34 35
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
36
     * The returned differences are returned in such a way that they contain the
37 38 39
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
40
     * @return SchemaDiff
41
     */
42
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44
        $diff             = new SchemaDiff();
45
        $diff->fromSchema = $fromSchema;
46

47
        $foreignKeysToTable = [];
48

49
        foreach ($toSchema->getNamespaces() as $namespace) {
50 51
            if ($fromSchema->hasNamespace($namespace)) {
                continue;
Marco Pivetta's avatar
Marco Pivetta committed
52
            }
53 54

            $diff->newNamespaces[$namespace] = $namespace;
55 56 57
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
58 59
            if ($toSchema->hasNamespace($namespace)) {
                continue;
60
            }
61 62

            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
Marco Pivetta's avatar
Marco Pivetta committed
64

65
        foreach ($toSchema->getTables() as $table) {
66
            $tableName = $table->getShortestName($toSchema->getName());
67
            if (! $fromSchema->hasTable($tableName)) {
68
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 71
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
                if ($tableDifferences !== false) {
72 73 74 75 76 77
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
78
        foreach ($fromSchema->getTables() as $table) {
79 80 81
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
82
            if (! $toSchema->hasTable($tableName)) {
83 84
                $diff->removedTables[$tableName] = $table;
            }
85 86

            // also remember all foreign keys that point to a specific table
87
            foreach ($table->getForeignKeys() as $foreignKey) {
88
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89
                if (! isset($foreignKeysToTable[$foreignTable])) {
90
                    $foreignKeysToTable[$foreignTable] = [];
91 92 93 94 95
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

96
        foreach ($diff->removedTables as $tableName => $table) {
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
            if (! isset($foreignKeysToTable[$tableName])) {
                continue;
            }

            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);

            // deleting duplicated foreign keys present on both on the orphanedForeignKey
            // and the removedForeignKeys from changedTables
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
                // strtolower the table name to make if compatible with getShortestName
                $localTableName = strtolower($foreignKey->getLocalTableName());
                if (! isset($diff->changedTables[$localTableName])) {
                    continue;
                }

                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
Sergei Morozov's avatar
Sergei Morozov committed
113 114
                    assert($removedForeignKey instanceof ForeignKeyConstraint);

115 116 117
                    // We check if the key is from the removed table if not we skip.
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
                        continue;
118
                    }
119
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120
                }
121
            }
122 123
        }

124
        foreach ($toSchema->getSequences() as $sequence) {
125
            $sequenceName = $sequence->getShortestName($toSchema->getName());
126 127
            if (! $fromSchema->hasSequence($sequenceName)) {
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
128 129
                    $diff->newSequences[] = $sequence;
                }
130 131
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
132
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
133 134 135 136
                }
            }
        }

137
        foreach ($fromSchema->getSequences() as $sequence) {
138 139 140 141
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

142
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
143

144 145
            if ($toSchema->hasSequence($sequenceName)) {
                continue;
146
            }
147 148

            $diff->removedSequences[] = $sequence;
149
        }
150 151 152 153

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
154
    /**
155 156
     * @param Schema   $schema
     * @param Sequence $sequence
Benjamin Morel's avatar
Benjamin Morel committed
157
     *
158
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
159
     */
160 161 162 163 164 165 166 167 168 169 170
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

171
    /**
172
     * @return bool
173
     */
174
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
175
    {
176
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
177 178 179
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
180
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
181 182
    }

183 184 185 186 187
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
188
     * @return TableDiff|false
189
     */
190
    public function diffTable(Table $table1, Table $table2)
191
    {
192 193
        $changes                     = 0;
        $tableDifferences            = new TableDiff($table1->getName());
194
        $tableDifferences->fromTable = $table1;
195

196 197 198
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
199
        /* See if all the fields in table 1 exist in table 2 */
200
        foreach ($table2Columns as $columnName => $column) {
201 202
            if ($table1->hasColumn($columnName)) {
                continue;
203
            }
204 205 206

            $tableDifferences->addedColumns[$columnName] = $column;
            $changes++;
207 208
        }
        /* See if there are any removed fields in table 2 */
209 210
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
211
            if (! $table2->hasColumn($columnName)) {
212
                $tableDifferences->removedColumns[$columnName] = $column;
213
                $changes++;
214
                continue;
215
            }
216

217 218 219
            // See if column has changed properties in table 2.
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));

220 221
            if (empty($changedProperties)) {
                continue;
222
            }
223 224 225 226 227

            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
            $columnDiff->fromColumn                               = $column;
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
            $changes++;
228 229
        }

230
        $this->detectColumnRenamings($tableDifferences);
231

232 233 234
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

235 236 237 238
        /* See if all the indexes in table 1 exist in table 2 */
        foreach ($table2Indexes as $indexName => $index) {
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
                continue;
239
            }
240

241
            $tableDifferences->addedIndexes[$indexName] = $index;
242
            $changes++;
243
        }
244 245 246 247 248 249 250 251 252 253
        /* See if there are any removed indexes in table 2 */
        foreach ($table1Indexes as $indexName => $index) {
            // See if index is removed in table 2.
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
            ) {
                $tableDifferences->removedIndexes[$indexName] = $index;
                $changes++;
                continue;
            }
254

255 256
            // See if index has changed in table 2.
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
Sergei Morozov's avatar
Sergei Morozov committed
257
            assert($table2Index instanceof Index);
258

259 260
            if (! $this->diffIndex($index, $table2Index)) {
                continue;
261
            }
262 263 264

            $tableDifferences->changedIndexes[$indexName] = $table2Index;
            $changes++;
265 266
        }

267 268
        $this->detectIndexRenamings($tableDifferences);

269
        $fromFkeys = $table1->getForeignKeys();
270
        $toFkeys   = $table2->getForeignKeys();
271

272 273
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
Steve Müller's avatar
Steve Müller committed
274
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
275
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
276
                } else {
277
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
278 279
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
280
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
281
                    }
282 283 284 285
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
286
        foreach ($fromFkeys as $constraint1) {
287 288 289 290
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
291
        foreach ($toFkeys as $constraint2) {
292 293
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
294
        }
295 296 297 298

        return $changes ? $tableDifferences : false;
    }

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
     *
Benjamin Morel's avatar
Benjamin Morel committed
303
     * @return void
304 305 306
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
307
        $renameCandidates = [];
308
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
309
            foreach ($tableDifferences->removedColumns as $removedColumn) {
310 311
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
                    continue;
312
                }
313 314

                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
315 316 317
            }
        }

318
        foreach ($renameCandidates as $candidateColumns) {
319 320
            if (count($candidateColumns) !== 1) {
                continue;
321
            }
322 323 324 325 326 327 328 329 330 331 332 333 334 335

            [$removedColumn, $addedColumn] = $candidateColumns[0];
            $removedColumnName             = strtolower($removedColumn->getName());
            $addedColumnName               = strtolower($addedColumn->getName());

            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
                continue;
            }

            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
            unset(
                $tableDifferences->addedColumns[$addedColumnName],
                $tableDifferences->removedColumns[$removedColumnName]
            );
336 337 338
        }
    }

339 340 341 342 343 344 345 346
    /**
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
     * however ambiguities between different possibilities should not lead to renaming at all.
     *
     * @return void
     */
    private function detectIndexRenamings(TableDiff $tableDifferences)
    {
347
        $renameCandidates = [];
348 349 350 351

        // Gather possible rename candidates by comparing each added and removed index based on semantics.
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
352 353
                if ($this->diffIndex($addedIndex, $removedIndex)) {
                    continue;
354
                }
355 356

                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
357 358 359 360 361 362 363 364
            }
        }

        foreach ($renameCandidates as $candidateIndexes) {
            // If the current rename candidate contains exactly one semantically equal index,
            // we can safely rename it.
            // Otherwise it is unclear if a rename action is really intended,
            // therefore we let those ambiguous indexes be added/dropped.
365 366 367 368 369 370 371 372 373 374 375
            if (count($candidateIndexes) !== 1) {
                continue;
            }

            [$removedIndex, $addedIndex] = $candidateIndexes[0];

            $removedIndexName = strtolower($removedIndex->getName());
            $addedIndexName   = strtolower($addedIndex->getName());

            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
                continue;
376
            }
377 378 379 380 381 382

            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
            unset(
                $tableDifferences->addedIndexes[$addedIndexName],
                $tableDifferences->removedIndexes[$removedIndexName]
            );
383 384 385
        }
    }

386
    /**
387
     * @return bool
388
     */
389
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390
    {
391
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 393
            return true;
        }
394

395
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396 397 398
            return true;
        }

399
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
400 401 402
            return true;
        }

403
        if ($key1->onUpdate() !== $key2->onUpdate()) {
404 405 406
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
407
        return $key1->onDelete() !== $key2->onDelete();
408 409
    }

410 411 412 413 414 415
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
416
     * @return string[]
417
     */
418
    public function diffColumn(Column $column1, Column $column2)
419
    {
420 421 422
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

423
        $changedProperties = [];
424

425 426 427 428 429
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
            $changedProperties[] = 'type';
        }

        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
430 431
            if ($properties1[$property] === $properties2[$property]) {
                continue;
432
            }
433 434

            $changedProperties[] = $property;
435
        }
436

437 438 439 440 441 442 443
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
            array_shift($changedProperties);

            $changedProperties[] = 'comment';
        }

444 445 446
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
447
            || $properties1['default'] != $properties2['default']) {
448
            $changedProperties[] = 'default';
449 450
        }

451 452 453
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
            $properties1['type'] instanceof Types\BinaryType
        ) {
454
            // check if value of length is set at all, default value assumed otherwise.
455 456
            $length1 = $properties1['length'] ?: 255;
            $length2 = $properties2['length'] ?: 255;
457
            if ($length1 !== $length2) {
458
                $changedProperties[] = 'length';
459 460
            }

461
            if ($properties1['fixed'] !== $properties2['fixed']) {
462
                $changedProperties[] = 'fixed';
463
            }
464
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
465
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
466
                $changedProperties[] = 'precision';
467
            }
468
            if ($properties1['scale'] !== $properties2['scale']) {
469
                $changedProperties[] = 'scale';
470 471 472
            }
        }

473 474
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
        if ($properties1['comment'] !== $properties2['comment'] &&
475 476
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
477
        ) {
478 479 480
            $changedProperties[] = 'comment';
        }

481 482
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
483

484
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
485
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
486 487
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
488 489 490 491
                $changedProperties[] = $key;
            }
        }

492 493 494 495
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
496 497
            if ($properties1[$key] === $properties2[$key]) {
                continue;
498
            }
499 500

            $changedProperties[] = $key;
501 502 503
        }

        return array_unique($changedProperties);
504 505
    }

506 507 508 509 510 511 512
    /**
     * TODO: kill with fire on v3.0
     *
     * @deprecated
     */
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
    {
513
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
514 515 516 517 518 519 520
            return false;
        }

        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
    }

521 522 523 524 525 526
    /**
     * Finds the difference between the indexes $index1 and $index2.
     *
     * Compares $index1 with $index2 and returns $index2 if there are any
     * differences or false in case there are no differences.
     *
527
     * @return bool
528
     */
529
    public function diffIndex(Index $index1, Index $index2)
530
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
531
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
532
    }
beberlei's avatar
beberlei committed
533
}