Comparator.php 18.5 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_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
     *
     * @throws SchemaException
27
     */
28
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
29 30
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
31

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

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

51
        $foreignKeysToTable = [];
52

53
        foreach ($toSchema->getNamespaces() as $namespace) {
54 55
            if ($fromSchema->hasNamespace($namespace)) {
                continue;
Marco Pivetta's avatar
Marco Pivetta committed
56
            }
57 58

            $diff->newNamespaces[$namespace] = $namespace;
59 60 61
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
62 63
            if ($toSchema->hasNamespace($namespace)) {
                continue;
64
            }
65 66

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

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

        /* Check if there are tables removed */
82
        foreach ($fromSchema->getTables() as $table) {
83 84 85
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
86
            if (! $toSchema->hasTable($tableName)) {
87 88
                $diff->removedTables[$tableName] = $table;
            }
89 90

            // also remember all foreign keys that point to a specific table
91
            foreach ($table->getForeignKeys() as $foreignKey) {
92
                $foreignTable = strtolower($foreignKey->getForeignTableName());
93
                if (! isset($foreignKeysToTable[$foreignTable])) {
94
                    $foreignKeysToTable[$foreignTable] = [];
95
                }
Grégoire Paris's avatar
Grégoire Paris committed
96

97 98 99 100
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

101
        foreach ($diff->removedTables as $tableName => $table) {
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
            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
118 119
                    assert($removedForeignKey instanceof ForeignKeyConstraint);

120 121 122
                    // We check if the key is from the removed table if not we skip.
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
                        continue;
123
                    }
Grégoire Paris's avatar
Grégoire Paris committed
124

125
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
126
                }
127
            }
128 129
        }

130
        foreach ($toSchema->getSequences() as $sequence) {
131
            $sequenceName = $sequence->getShortestName($toSchema->getName());
132 133
            if (! $fromSchema->hasSequence($sequenceName)) {
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
134 135
                    $diff->newSequences[] = $sequence;
                }
136 137
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
138
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
139 140 141 142
                }
            }
        }

143
        foreach ($fromSchema->getSequences() as $sequence) {
144 145 146 147
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

148
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
149

150 151
            if ($toSchema->hasSequence($sequenceName)) {
                continue;
152
            }
153 154

            $diff->removedSequences[] = $sequence;
155
        }
156 157 158 159

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
160
    /**
161 162
     * @param Schema   $schema
     * @param Sequence $sequence
Benjamin Morel's avatar
Benjamin Morel committed
163
     *
164
     * @return bool
Benjamin Morel's avatar
Benjamin Morel committed
165
     */
166 167 168 169 170 171 172 173 174 175 176
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

177
    /**
178
     * @return bool
179
     */
180
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
181
    {
182
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
183 184 185
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
186
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
187 188
    }

189 190 191 192 193
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
194
     * @return TableDiff|false
195 196
     *
     * @throws SchemaException
197
     */
198
    public function diffTable(Table $table1, Table $table2)
199
    {
200 201
        $changes                     = 0;
        $tableDifferences            = new TableDiff($table1->getName());
202
        $tableDifferences->fromTable = $table1;
203

204 205 206
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
207
        /* See if all the fields in table 1 exist in table 2 */
208
        foreach ($table2Columns as $columnName => $column) {
209 210
            if ($table1->hasColumn($columnName)) {
                continue;
211
            }
212 213 214

            $tableDifferences->addedColumns[$columnName] = $column;
            $changes++;
215
        }
Grégoire Paris's avatar
Grégoire Paris committed
216

217
        /* See if there are any removed fields in table 2 */
218 219
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
220
            if (! $table2->hasColumn($columnName)) {
221
                $tableDifferences->removedColumns[$columnName] = $column;
222
                $changes++;
223
                continue;
224
            }
225

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

229
            if (count($changedProperties) === 0) {
230
                continue;
231
            }
232 233 234 235 236

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

239
        $this->detectColumnRenamings($tableDifferences);
240

241 242 243
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

244 245 246 247
        /* 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;
248
            }
249

250
            $tableDifferences->addedIndexes[$indexName] = $index;
251
            $changes++;
252
        }
Grégoire Paris's avatar
Grégoire Paris committed
253

254 255 256
        /* See if there are any removed indexes in table 2 */
        foreach ($table1Indexes as $indexName => $index) {
            // See if index is removed in table 2.
257 258
            if (
                ($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
259 260 261 262 263 264
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
            ) {
                $tableDifferences->removedIndexes[$indexName] = $index;
                $changes++;
                continue;
            }
265

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

270 271
            if (! $this->diffIndex($index, $table2Index)) {
                continue;
272
            }
273 274 275

            $tableDifferences->changedIndexes[$indexName] = $table2Index;
            $changes++;
276 277
        }

278 279
        $this->detectIndexRenamings($tableDifferences);

280
        $fromFkeys = $table1->getForeignKeys();
281
        $toFkeys   = $table2->getForeignKeys();
282

283 284
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
Steve Müller's avatar
Steve Müller committed
285
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
286
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
287
                } else {
288
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
289 290
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
291
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
292
                    }
293 294 295 296
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
297
        foreach ($fromFkeys as $constraint1) {
298 299 300 301
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
302
        foreach ($toFkeys as $constraint2) {
303 304
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
305
        }
306

307
        return $changes > 0 ? $tableDifferences : false;
308 309
    }

310 311
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
312
     * however ambiguities between different possibilities should not lead to renaming at all.
313
     *
Benjamin Morel's avatar
Benjamin Morel committed
314
     * @return void
315 316 317
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
318
        $renameCandidates = [];
319
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
320
            foreach ($tableDifferences->removedColumns as $removedColumn) {
321 322
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
                    continue;
323
                }
324 325

                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
326 327 328
            }
        }

329
        foreach ($renameCandidates as $candidateColumns) {
330 331
            if (count($candidateColumns) !== 1) {
                continue;
332
            }
333 334 335 336 337 338 339 340 341 342 343 344 345 346

            [$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]
            );
347 348 349
        }
    }

350 351 352 353 354 355 356 357
    /**
     * 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)
    {
358
        $renameCandidates = [];
359 360 361 362

        // 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) {
363 364
                if ($this->diffIndex($addedIndex, $removedIndex)) {
                    continue;
365
                }
366 367

                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
368 369 370 371 372 373 374 375
            }
        }

        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.
376 377 378 379 380 381 382 383 384 385 386
            if (count($candidateIndexes) !== 1) {
                continue;
            }

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

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

            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
                continue;
387
            }
388 389 390 391 392 393

            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
            unset(
                $tableDifferences->addedIndexes[$addedIndexName],
                $tableDifferences->removedIndexes[$removedIndexName]
            );
394 395 396
        }
    }

397
    /**
398
     * @return bool
399
     */
400
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
401
    {
402
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
403 404
            return true;
        }
405

406
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
407 408 409
            return true;
        }

410
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
411 412 413
            return true;
        }

414
        if ($key1->onUpdate() !== $key2->onUpdate()) {
415 416 417
            return true;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
418
        return $key1->onDelete() !== $key2->onDelete();
419 420
    }

421 422 423 424 425 426
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
427
     * @return string[]
428
     */
429
    public function diffColumn(Column $column1, Column $column2)
430
    {
431 432 433
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

434
        $changedProperties = [];
435

436 437 438 439 440
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
            $changedProperties[] = 'type';
        }

        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
441 442
            if ($properties1[$property] === $properties2[$property]) {
                continue;
443
            }
444 445

            $changedProperties[] = $property;
446
        }
447

448 449
        // 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.
450 451 452 453
        if (
            ($properties1['default'] === null) !== ($properties2['default'] === null)
            || $properties1['default'] != $properties2['default']
        ) {
454
            $changedProperties[] = 'default';
455 456
        }

457 458
        if (
            ($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
459 460
            $properties1['type'] instanceof Types\BinaryType
        ) {
461
            // check if value of length is set at all, default value assumed otherwise.
462 463
            $length1 = $properties1['length'] ?? 255;
            $length2 = $properties2['length'] ?? 255;
464
            if ($length1 !== $length2) {
465
                $changedProperties[] = 'length';
466 467
            }

468
            if ($properties1['fixed'] !== $properties2['fixed']) {
469
                $changedProperties[] = 'fixed';
470
            }
471
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
472
            if (($properties1['precision'] ?? 10) !== ($properties2['precision'] ?? 10)) {
473
                $changedProperties[] = 'precision';
474
            }
Grégoire Paris's avatar
Grégoire Paris committed
475

476
            if ($properties1['scale'] !== $properties2['scale']) {
477
                $changedProperties[] = 'scale';
478 479 480
            }
        }

481
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
482 483
        if (
            $properties1['comment'] !== $properties2['comment'] &&
484 485
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
486
        ) {
487 488 489
            $changedProperties[] = 'comment';
        }

490 491
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
492

493
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
494
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
495 496
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
497 498 499 500
                $changedProperties[] = $key;
            }
        }

501 502 503 504
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
505 506
            if ($properties1[$key] === $properties2[$key]) {
                continue;
507
            }
508 509

            $changedProperties[] = $key;
510 511 512
        }

        return array_unique($changedProperties);
513 514 515 516 517 518 519 520
    }

    /**
     * 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.
     *
521
     * @return bool
522
     */
523
    public function diffIndex(Index $index1, Index $index2)
524
    {
Gabriel Caruso's avatar
Gabriel Caruso committed
525
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
526
    }
beberlei's avatar
beberlei committed
527
}