Comparator.php 17.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

22 23
use Doctrine\DBAL\Types;

24
/**
Benjamin Morel's avatar
Benjamin Morel committed
25
 * Compares two Schemas and return an instance of SchemaDiff.
26
 *
Benjamin Morel's avatar
Benjamin Morel committed
27 28 29
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Benjamin Eberlei <kontakt@beberlei.de>
30 31 32 33
 */
class Comparator
{
    /**
Benjamin Morel's avatar
Benjamin Morel committed
34 35 36 37
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
     *
     * @return \Doctrine\DBAL\Schema\SchemaDiff
38
     */
Benjamin Morel's avatar
Benjamin Morel committed
39
    static public function compareSchemas(Schema $fromSchema, Schema $toSchema)
40 41
    {
        $c = new self();
Benjamin Morel's avatar
Benjamin Morel committed
42

43 44 45 46 47 48
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
49
     * The returned differences are returned in such a way that they contain the
50 51 52
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
Benjamin Morel's avatar
Benjamin Morel committed
53 54
     * @param \Doctrine\DBAL\Schema\Schema $fromSchema
     * @param \Doctrine\DBAL\Schema\Schema $toSchema
55
     *
Benjamin Morel's avatar
Benjamin Morel committed
56
     * @return \Doctrine\DBAL\Schema\SchemaDiff
57
     */
58
    public function compare(Schema $fromSchema, Schema $toSchema)
59 60
    {
        $diff = new SchemaDiff();
61
        $diff->fromSchema = $fromSchema;
62

63 64
        $foreignKeysToTable = array();

65 66
        foreach ($toSchema->getNamespaces() as $namespace) {
            if ( ! $fromSchema->hasNamespace($namespace)) {
Marco Pivetta's avatar
Marco Pivetta committed
67 68
                $diff->newNamespaces[$namespace] = $namespace;
            }
69 70 71 72 73 74 75
        }

        foreach ($fromSchema->getNamespaces() as $namespace) {
            if ( ! $toSchema->hasNamespace($namespace)) {
                $diff->removedNamespaces[$namespace] = $namespace;
            }
        }
Marco Pivetta's avatar
Marco Pivetta committed
76

77
        foreach ($toSchema->getTables() as $table) {
78
            $tableName = $table->getShortestName($toSchema->getName());
79
            if ( ! $fromSchema->hasTable($tableName)) {
80
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
81
            } else {
82 83
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
                if ($tableDifferences !== false) {
84 85 86 87 88 89
                    $diff->changedTables[$tableName] = $tableDifferences;
                }
            }
        }

        /* Check if there are tables removed */
90
        foreach ($fromSchema->getTables() as $table) {
91 92 93
            $tableName = $table->getShortestName($fromSchema->getName());

            $table = $fromSchema->getTable($tableName);
Steve Müller's avatar
Steve Müller committed
94
            if ( ! $toSchema->hasTable($tableName)) {
95 96
                $diff->removedTables[$tableName] = $table;
            }
97 98

            // also remember all foreign keys that point to a specific table
99
            foreach ($table->getForeignKeys() as $foreignKey) {
100 101 102 103 104 105 106 107
                $foreignTable = strtolower($foreignKey->getForeignTableName());
                if (!isset($foreignKeysToTable[$foreignTable])) {
                    $foreignKeysToTable[$foreignTable] = array();
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

108
        foreach ($diff->removedTables as $tableName => $table) {
109 110
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
111 112 113 114

                // deleting duplicated foreign keys present on both on the orphanedForeignKey
                // and the removedForeignKeys from changedTables
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
115 116 117 118 119
                    // strtolower the table name to make if compatible with getShortestName
                    $localTableName = strtolower($foreignKey->getLocalTableName());
                    if (isset($diff->changedTables[$localTableName])) {
                        foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
                            unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120 121 122
                        }
                    }
                }
123
            }
124 125
        }

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

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

144
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
145

146
            if ( ! $toSchema->hasSequence($sequenceName)) {
147 148 149
                $diff->removedSequences[] = $sequence;
            }
        }
150 151 152 153

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
154 155 156 157 158 159
    /**
     * @param \Doctrine\DBAL\Schema\Schema   $schema
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
     *
     * @return boolean
     */
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
    /**
Benjamin Morel's avatar
Benjamin Morel committed
172 173
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
174
     *
Benjamin Morel's avatar
Benjamin Morel committed
175
     * @return boolean
176
     */
177
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
178
    {
Steve Müller's avatar
Steve Müller committed
179
        if ($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
180 181 182
            return true;
        }

Steve Müller's avatar
Steve Müller committed
183
        if ($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
184 185 186 187 188 189
            return true;
        }

        return false;
    }

190 191 192 193 194
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
Benjamin Morel's avatar
Benjamin Morel committed
195 196
     * @param \Doctrine\DBAL\Schema\Table $table1
     * @param \Doctrine\DBAL\Schema\Table $table2
197
     *
Benjamin Morel's avatar
Benjamin Morel committed
198
     * @return boolean|\Doctrine\DBAL\Schema\TableDiff
199
     */
200
    public function diffTable(Table $table1, Table $table2)
201 202
    {
        $changes = 0;
203
        $tableDifferences = new TableDiff($table1->getName());
204
        $tableDifferences->fromTable = $table1;
205

206 207 208
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

Steve Müller's avatar
Steve Müller committed
209
        /* See if all the fields in table 1 exist in table 2 */
210
        foreach ($table2Columns as $columnName => $column) {
Steve Müller's avatar
Steve Müller committed
211
            if ( !$table1->hasColumn($columnName)) {
212
                $tableDifferences->addedColumns[$columnName] = $column;
213 214 215 216
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
217 218 219
        foreach ($table1Columns as $columnName => $column) {
            // See if column is removed in table 2.
            if ( ! $table2->hasColumn($columnName)) {
220
                $tableDifferences->removedColumns[$columnName] = $column;
221
                $changes++;
222
                continue;
223
            }
224

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

            if ( ! empty($changedProperties)) {
                $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
                $columnDiff->fromColumn = $column;
                $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
                $changes++;
233 234 235
            }
        }

236
        $this->detectColumnRenamings($tableDifferences);
237

238 239 240
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

241 242
        foreach ($table2Indexes as $index2Name => $index2Definition) {
            foreach ($table1Indexes as $index1Name => $index1Definition) {
243
                if ($this->diffIndex($index1Definition, $index2Definition) === false) {
244 245 246 247 248
                    if ( ! $index1Definition->isPrimary() && $index1Name != $index2Name) {
                        $tableDifferences->renamedIndexes[$index1Name] = $index2Definition;
                        $changes++;
                    }

249 250 251 252 253 254 255 256 257 258
                    unset($table1Indexes[$index1Name]);
                    unset($table2Indexes[$index2Name]);
                } else {
                    if ($index1Name == $index2Name) {
                        $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
                        unset($table1Indexes[$index1Name]);
                        unset($table2Indexes[$index2Name]);
                        $changes++;
                    }
                }
259 260
            }
        }
261

262
        foreach ($table1Indexes as $index1Name => $index1Definition) {
263
            $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
264
            $changes++;
265
        }
266

267
        foreach ($table2Indexes as $index2Name => $index2Definition) {
268 269
            $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
            $changes++;
270 271
        }

272 273 274
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

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

Benjamin Morel's avatar
Benjamin Morel committed
291
        foreach ($fromFkeys as $constraint1) {
292 293 294 295
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
296
        foreach ($toFkeys as $constraint2) {
297 298
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
299
        }
300 301 302 303

        return $changes ? $tableDifferences : false;
    }

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

323
        foreach ($renameCandidates as $candidateColumns) {
324 325
            if (count($candidateColumns) == 1) {
                list($removedColumn, $addedColumn) = $candidateColumns[0];
326 327
                $removedColumnName = strtolower($removedColumn->getName());
                $addedColumnName = strtolower($addedColumn->getName());
328

329
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
330 331 332 333
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
                    unset($tableDifferences->addedColumns[$addedColumnName]);
                    unset($tableDifferences->removedColumns[$removedColumnName]);
                }
334 335 336 337
            }
        }
    }

338
    /**
Benjamin Morel's avatar
Benjamin Morel committed
339 340 341 342
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
     *
     * @return boolean
343
     */
344
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
345
    {
346
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
347 348
            return true;
        }
349

350
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
351 352 353
            return true;
        }

354
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
355 356 357
            return true;
        }

358
        if ($key1->onUpdate() != $key2->onUpdate()) {
359 360 361
            return true;
        }

362
        if ($key1->onDelete() != $key2->onDelete()) {
363 364 365 366 367 368
            return true;
        }

        return false;
    }

369 370 371 372 373 374
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
Benjamin Morel's avatar
Benjamin Morel committed
375 376
     * @param \Doctrine\DBAL\Schema\Column $column1
     * @param \Doctrine\DBAL\Schema\Column $column2
377
     *
378
     * @return array
379
     */
380
    public function diffColumn(Column $column1, Column $column2)
381
    {
382 383 384
        $properties1 = $column1->toArray();
        $properties2 = $column2->toArray();

385
        $changedProperties = array();
386

387 388 389 390
        foreach (array('type', 'notnull', 'unsigned', 'autoincrement') as $property) {
            if ($properties1[$property] != $properties2[$property]) {
                $changedProperties[] = $property;
            }
391
        }
392

393
        if ($properties1['default'] != $properties2['default'] ||
394 395
            // 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.
396 397
            (null === $properties1['default'] && null !== $properties2['default']) ||
            (null === $properties2['default'] && null !== $properties1['default'])
398
        ) {
399
            $changedProperties[] = 'default';
400 401
        }

402 403 404
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
            $properties1['type'] instanceof Types\BinaryType
        ) {
405
            // check if value of length is set at all, default value assumed otherwise.
406 407
            $length1 = $properties1['length'] ?: 255;
            $length2 = $properties2['length'] ?: 255;
408
            if ($length1 != $length2) {
409
                $changedProperties[] = 'length';
410 411
            }

412
            if ($properties1['fixed'] != $properties2['fixed']) {
413
                $changedProperties[] = 'fixed';
414
            }
415 416
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
            if (($properties1['precision'] ?: 10) != ($properties2['precision'] ?: 10)) {
417
                $changedProperties[] = 'precision';
418
            }
419
            if ($properties1['scale'] != $properties2['scale']) {
420
                $changedProperties[] = 'scale';
421 422 423
            }
        }

424 425 426 427 428
        // 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'] &&
            ! (null === $properties1['comment'] && '' === $properties2['comment']) &&
            ! (null === $properties2['comment'] && '' === $properties1['comment'])
        ) {
429 430 431
            $changedProperties[] = 'comment';
        }

432 433
        $customOptions1 = $column1->getCustomSchemaOptions();
        $customOptions2 = $column2->getCustomSchemaOptions();
434

435 436 437 438
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
            if ( ! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
                $changedProperties[] = $key;
            } elseif ($properties1[$key] !== $properties2[$key]) {
439 440 441 442
                $changedProperties[] = $key;
            }
        }

443 444 445 446
        $platformOptions1 = $column1->getPlatformOptions();
        $platformOptions2 = $column2->getPlatformOptions();

        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
447
            if ($properties1[$key] !== $properties2[$key]) {
448 449 450 451 452
                $changedProperties[] = $key;
            }
        }

        return array_unique($changedProperties);
453 454 455 456 457 458 459 460
    }

    /**
     * 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.
     *
Benjamin Morel's avatar
Benjamin Morel committed
461 462 463 464
     * @param \Doctrine\DBAL\Schema\Index $index1
     * @param \Doctrine\DBAL\Schema\Index $index2
     *
     * @return boolean
465
     */
466
    public function diffIndex(Index $index1, Index $index2)
467
    {
468 469
        if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
            return false;
470
        }
Benjamin Morel's avatar
Benjamin Morel committed
471

472
        return true;
473
    }
beberlei's avatar
beberlei committed
474
}