Comparator.php 16.7 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 22
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

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

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

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

61 62
        $foreignKeysToTable = array();

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

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

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

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

94
        foreach ($diff->removedTables as $tableName => $table) {
95 96
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
97 98 99 100

                // deleting duplicated foreign keys present on both on the orphanedForeignKey
                // and the removedForeignKeys from changedTables
                foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
101 102 103 104 105
                    // 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]);
106 107 108
                        }
                    }
                }
109
            }
110 111
        }

112
        foreach ($toSchema->getSequences() as $sequence) {
113
            $sequenceName = $sequence->getShortestName($toSchema->getName());
114
            if ( ! $fromSchema->hasSequence($sequenceName)) {
115 116 117
                $diff->newSequences[] = $sequence;
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
118
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
119 120 121 122
                }
            }
        }

123
        foreach ($fromSchema->getSequences() as $sequence) {
124 125 126 127
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
                continue;
            }

128
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
129

130
            if ( ! $toSchema->hasSequence($sequenceName)) {
131 132 133
                $diff->removedSequences[] = $sequence;
            }
        }
134 135 136 137

        return $diff;
    }

Benjamin Morel's avatar
Benjamin Morel committed
138 139 140 141 142 143
    /**
     * @param \Doctrine\DBAL\Schema\Schema   $schema
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
     *
     * @return boolean
     */
144 145 146 147 148 149 150 151 152 153 154
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
    {
        foreach ($schema->getTables() as $table) {
            if ($sequence->isAutoIncrementsFor($table)) {
                return true;
            }
        }

        return false;
    }

155
    /**
Benjamin Morel's avatar
Benjamin Morel committed
156 157
     * @param \Doctrine\DBAL\Schema\Sequence $sequence1
     * @param \Doctrine\DBAL\Schema\Sequence $sequence2
158
     *
Benjamin Morel's avatar
Benjamin Morel committed
159
     * @return boolean
160
     */
161
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
162 163 164 165 166 167 168 169 170 171 172 173
    {
        if($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
            return true;
        }

        if($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
            return true;
        }

        return false;
    }

174 175 176 177 178
    /**
     * 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
179 180
     * @param \Doctrine\DBAL\Schema\Table $table1
     * @param \Doctrine\DBAL\Schema\Table $table2
181
     *
Benjamin Morel's avatar
Benjamin Morel committed
182
     * @return boolean|\Doctrine\DBAL\Schema\TableDiff
183
     */
184
    public function diffTable(Table $table1, Table $table2)
185 186
    {
        $changes = 0;
187
        $tableDifferences = new TableDiff($table1->getName());
188
        $tableDifferences->fromTable = $table1;
189

190 191 192
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

193
        /* See if all the fields in table 1 exist in table 2 */
194
        foreach ( $table2Columns as $columnName => $column ) {
195
            if ( !$table1->hasColumn($columnName) ) {
196
                $tableDifferences->addedColumns[$columnName] = $column;
197 198 199 200
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
201
        foreach ( $table1Columns as $columnName => $column ) {
202
            if ( !$table2->hasColumn($columnName) ) {
203
                $tableDifferences->removedColumns[$columnName] = $column;
204 205 206
                $changes++;
            }
        }
207

208
        foreach ( $table1Columns as $columnName => $column ) {
209
            if ( $table2->hasColumn($columnName) ) {
210 211
                $changedProperties = $this->diffColumn( $column, $table2->getColumn($columnName) );
                if (count($changedProperties) ) {
212
                    $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
213
                    $columnDiff->fromColumn = $column;
214
                    $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
215 216 217 218 219
                    $changes++;
                }
            }
        }

220
        $this->detectColumnRenamings($tableDifferences);
221

222 223 224
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

225 226
        foreach ($table2Indexes as $index2Name => $index2Definition) {
            foreach ($table1Indexes as $index1Name => $index1Definition) {
227 228 229 230 231 232 233 234 235 236 237
                if ($this->diffIndex($index1Definition, $index2Definition) === false) {
                    unset($table1Indexes[$index1Name]);
                    unset($table2Indexes[$index2Name]);
                } else {
                    if ($index1Name == $index2Name) {
                        $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
                        unset($table1Indexes[$index1Name]);
                        unset($table2Indexes[$index2Name]);
                        $changes++;
                    }
                }
238 239
            }
        }
240

241
        foreach ($table1Indexes as $index1Name => $index1Definition) {
242
            $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
243
            $changes++;
244
        }
245

246
        foreach ($table2Indexes as $index2Name => $index2Definition) {
247 248
            $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
            $changes++;
249 250
        }

251 252 253
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

254 255
        foreach ($fromFkeys as $key1 => $constraint1) {
            foreach ($toFkeys as $key2 => $constraint2) {
256 257 258 259 260 261 262 263 264 265
                if($this->diffForeignKey($constraint1, $constraint2) === false) {
                    unset($fromFkeys[$key1]);
                    unset($toFkeys[$key2]);
                } else {
                    if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
                        $tableDifferences->changedForeignKeys[] = $constraint2;
                        $changes++;
                        unset($fromFkeys[$key1]);
                        unset($toFkeys[$key2]);
                    }
266 267 268 269
                }
            }
        }

Benjamin Morel's avatar
Benjamin Morel committed
270
        foreach ($fromFkeys as $constraint1) {
271 272 273 274
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

Benjamin Morel's avatar
Benjamin Morel committed
275
        foreach ($toFkeys as $constraint2) {
276 277
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
278
        }
279 280 281 282

        return $changes ? $tableDifferences : false;
    }

283 284
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
285
     * however ambiguities between different possibilities should not lead to renaming at all.
286
     *
Benjamin Morel's avatar
Benjamin Morel committed
287 288 289
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
     *
     * @return void
290 291 292 293
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
        $renameCandidates = array();
294
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
Benjamin Morel's avatar
Benjamin Morel committed
295
            foreach ($tableDifferences->removedColumns as $removedColumn) {
296
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
297
                    $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
298 299 300 301
                }
            }
        }

302
        foreach ($renameCandidates as $candidateColumns) {
303 304
            if (count($candidateColumns) == 1) {
                list($removedColumn, $addedColumn) = $candidateColumns[0];
305 306
                $removedColumnName = strtolower($removedColumn->getName());
                $addedColumnName = strtolower($addedColumn->getName());
307

308
                if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
309 310 311 312
                    $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
                    unset($tableDifferences->addedColumns[$addedColumnName]);
                    unset($tableDifferences->removedColumns[$removedColumnName]);
                }
313 314 315 316
            }
        }
    }

317
    /**
Benjamin Morel's avatar
Benjamin Morel committed
318 319 320 321
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
     *
     * @return boolean
322
     */
323
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
324
    {
325
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) != array_map('strtolower', $key2->getUnquotedLocalColumns())) {
326 327
            return true;
        }
328

329
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) != array_map('strtolower', $key2->getUnquotedForeignColumns())) {
330 331 332
            return true;
        }

333
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
334 335 336
            return true;
        }

337
        if ($key1->onUpdate() != $key2->onUpdate()) {
338 339 340
            return true;
        }

341
        if ($key1->onDelete() != $key2->onDelete()) {
342 343 344 345 346 347
            return true;
        }

        return false;
    }

348 349 350 351 352 353
    /**
     * 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
354 355
     * @param \Doctrine\DBAL\Schema\Column $column1
     * @param \Doctrine\DBAL\Schema\Column $column2
356
     *
357
     * @return array
358
     */
359
    public function diffColumn(Column $column1, Column $column2)
360
    {
361
        $changedProperties = array();
362
        if ( $column1->getType() != $column2->getType() ) {
363
            $changedProperties[] = 'type';
364 365 366
        }

        if ($column1->getNotnull() != $column2->getNotnull()) {
367
            $changedProperties[] = 'notnull';
368 369
        }

370 371 372 373 374 375 376 377 378
        $column1Default = $column1->getDefault();
        $column2Default = $column2->getDefault();

        if ($column1Default != $column2Default ||
            // 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.
            (null === $column1Default && null !== $column2Default) ||
            (null === $column2Default && null !== $column1Default)
        ) {
379
            $changedProperties[] = 'default';
380 381 382
        }

        if ($column1->getUnsigned() != $column2->getUnsigned()) {
383
            $changedProperties[] = 'unsigned';
384 385 386
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) {
387 388 389 390
            // check if value of length is set at all, default value assumed otherwise.
            $length1 = $column1->getLength() ?: 255;
            $length2 = $column2->getLength() ?: 255;
            if ($length1 != $length2) {
391
                $changedProperties[] = 'length';
392 393 394
            }

            if ($column1->getFixed() != $column2->getFixed()) {
395
                $changedProperties[] = 'fixed';
396 397 398 399
            }
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) {
400
            if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) {
401
                $changedProperties[] = 'precision';
402 403
            }
            if ($column1->getScale() != $column2->getScale()) {
404
                $changedProperties[] = 'scale';
405 406 407
            }
        }

408 409 410 411
        if ($column1->getAutoincrement() != $column2->getAutoincrement()) {
            $changedProperties[] = 'autoincrement';
        }

412 413
        // only allow to delete comment if its set to '' not to null.
        if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) {
414 415 416
            $changedProperties[] = 'comment';
        }

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        $options1 = $column1->getCustomSchemaOptions();
        $options2 = $column2->getCustomSchemaOptions();

        $commonKeys = array_keys(array_intersect_key($options1, $options2));

        foreach ($commonKeys as $key) {
            if ($options1[$key] !== $options2[$key]) {
                $changedProperties[] = $key;
            }
        }

        $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1));

        $changedProperties = array_merge($changedProperties, $diffKeys);

432
        return $changedProperties;
433 434 435 436 437 438 439 440
    }

    /**
     * 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
441 442 443 444
     * @param \Doctrine\DBAL\Schema\Index $index1
     * @param \Doctrine\DBAL\Schema\Index $index2
     *
     * @return boolean
445
     */
446
    public function diffIndex(Index $index1, Index $index2)
447
    {
448 449
        if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
            return false;
450
        }
Benjamin Morel's avatar
Benjamin Morel committed
451

452
        return true;
453
    }
beberlei's avatar
beberlei committed
454
}