Comparator.php 14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
<?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
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Schema;

/**
 * Compare to Schemas and return an instance of SchemaDiff
 *
 * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.
 * @license http://ez.no/licenses/new_bsd New BSD License
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Comparator
{
    /**
     * @param Schema $fromSchema
     * @param Schema $toSchema
     * @return SchemaDiff
     */
    static public function compareSchemas( Schema $fromSchema, Schema $toSchema )
    {
        $c = new self();
        return $c->compare($fromSchema, $toSchema);
    }

    /**
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
     *
     * The returned diferences are returned in such a way that they contain the
     * operations to change the schema stored in $fromSchema to the schema that is
     * stored in $toSchema.
     *
     * @param Schema $fromSchema
     * @param Schema $toSchema
     *
     * @return SchemaDiff
     */
58
    public function compare(Schema $fromSchema, Schema $toSchema)
59 60 61
    {
        $diff = new SchemaDiff();

62 63 64
        $foreignKeysToTable = array();

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

        /* Check if there are tables removed */
76
        foreach ( $fromSchema->getTables() AS $tableName => $table ) {
77 78 79
            if ( !$toSchema->hasTable($tableName) ) {
                $diff->removedTables[$tableName] = $table;
            }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

            // also remember all foreign keys that point to a specific table
            foreach ($table->getForeignKeys() AS $foreignKey) {
                $foreignTable = strtolower($foreignKey->getForeignTableName());
                if (!isset($foreignKeysToTable[$foreignTable])) {
                    $foreignKeysToTable[$foreignTable] = array();
                }
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
            }
        }

        foreach ($diff->removedTables AS $tableName => $table) {
            if (isset($foreignKeysToTable[$tableName])) {
                $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
            }
95 96
        }

97 98 99 100 101
        foreach ( $toSchema->getSequences() AS $sequenceName => $sequence) {
            if (!$fromSchema->hasSequence($sequenceName)) {
                $diff->newSequences[] = $sequence;
            } else {
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
102
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
103 104 105 106 107 108 109 110 111
                }
            }
        }

        foreach ($fromSchema->getSequences() AS $sequenceName => $sequence) {
            if (!$toSchema->hasSequence($sequenceName)) {
                $diff->removedSequences[] = $sequence;
            }
        }
112 113 114 115

        return $diff;
    }

116 117 118 119 120
    /**
     *
     * @param Sequence $sequence1
     * @param Sequence $sequence2
     */
121
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
122 123 124 125 126 127 128 129 130 131 132 133
    {
        if($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
            return true;
        }

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

        return false;
    }

134 135 136 137 138 139 140 141 142 143
    /**
     * Returns the difference between the tables $table1 and $table2.
     *
     * If there are no differences this method returns the boolean false.
     *
     * @param Table $table1
     * @param Table $table2
     *
     * @return bool|TableDiff
     */
144
    public function diffTable(Table $table1, Table $table2)
145 146
    {
        $changes = 0;
147
        $tableDifferences = new TableDiff($table1->getName());
148

149 150 151
        $table1Columns = $table1->getColumns();
        $table2Columns = $table2->getColumns();

152
        /* See if all the fields in table 1 exist in table 2 */
153
        foreach ( $table2Columns as $columnName => $column ) {
154
            if ( !$table1->hasColumn($columnName) ) {
155
                $tableDifferences->addedColumns[$columnName] = $column;
156 157 158 159
                $changes++;
            }
        }
        /* See if there are any removed fields in table 2 */
160
        foreach ( $table1Columns as $columnName => $column ) {
161
            if ( !$table2->hasColumn($columnName) ) {
162
                $tableDifferences->removedColumns[$columnName] = $column;
163 164 165
                $changes++;
            }
        }
166

167
        foreach ( $table1Columns as $columnName => $column ) {
168
            if ( $table2->hasColumn($columnName) ) {
169 170
                $changedProperties = $this->diffColumn( $column, $table2->getColumn($columnName) );
                if (count($changedProperties) ) {
171
                    $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
172
                    $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
173 174 175 176 177
                    $changes++;
                }
            }
        }

178
        $this->detectColumnRenamings($tableDifferences);
179

180 181 182
        $table1Indexes = $table1->getIndexes();
        $table2Indexes = $table2->getIndexes();

183 184 185 186 187 188 189 190 191 192 193 194 195
        foreach ($table2Indexes AS $index2Name => $index2Definition) {
            foreach ($table1Indexes AS $index1Name => $index1Definition) {
                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++;
                    }
                }
196 197
            }
        }
198 199

        foreach ($table1Indexes AS $index1Name => $index1Definition) {
200
            $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
201
            $changes++;
202
        }
203 204 205 206

        foreach ($table2Indexes AS $index2Name => $index2Definition) {
            $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
            $changes++;
207 208
        }

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        $fromFkeys = $table1->getForeignKeys();
        $toFkeys = $table2->getForeignKeys();

        foreach ($fromFkeys AS $key1 => $constraint1) {
            foreach ($toFkeys AS $key2 => $constraint2) {
                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]);
                    }
224 225 226 227
                }
            }
        }

228 229 230 231 232 233 234 235
        foreach ($fromFkeys AS $key1 => $constraint1) {
            $tableDifferences->removedForeignKeys[] = $constraint1;
            $changes++;
        }

        foreach ($toFkeys AS $key2 => $constraint2) {
            $tableDifferences->addedForeignKeys[] = $constraint2;
            $changes++;
236
        }
237 238 239 240

        return $changes ? $tableDifferences : false;
    }

241 242 243
    /**
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
     * however ambiguouties between different possibilites should not lead to renaming at all.
244
     *
245 246 247 248 249 250 251 252
     * @param TableDiff $tableDifferences
     */
    private function detectColumnRenamings(TableDiff $tableDifferences)
    {
        $renameCandidates = array();
        foreach ($tableDifferences->addedColumns AS $addedColumnName => $addedColumn) {
            foreach ($tableDifferences->removedColumns AS $removedColumnName => $removedColumn) {
                if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
253
                    $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
254 255 256 257 258 259 260
                }
            }
        }

        foreach ($renameCandidates AS $candidate => $candidateColumns) {
            if (count($candidateColumns) == 1) {
                list($removedColumn, $addedColumn) = $candidateColumns[0];
261 262
                $removedColumnName = strtolower($removedColumn->getName());
                $addedColumnName = strtolower($addedColumn->getName());
263

264
                $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
265 266 267 268 269 270
                unset($tableDifferences->addedColumns[$addedColumnName]);
                unset($tableDifferences->removedColumns[$removedColumnName]);
            }
        }
    }

271 272 273 274 275
    /**
     * @param ForeignKeyConstraint $key1
     * @param ForeignKeyConstraint $key2
     * @return bool
     */
276
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
277
    {
278
        if (array_map('strtolower', $key1->getLocalColumns()) != array_map('strtolower', $key2->getLocalColumns())) {
279 280
            return true;
        }
281

282
        if (array_map('strtolower', $key1->getForeignColumns()) != array_map('strtolower', $key2->getForeignColumns())) {
283 284 285
            return true;
        }

286
        if ($key1->onUpdate() != $key2->onUpdate()) {
287 288 289
            return true;
        }

290
        if ($key1->onDelete() != $key2->onDelete()) {
291 292 293 294 295 296
            return true;
        }

        return false;
    }

297 298 299 300 301 302 303 304 305
    /**
     * Returns the difference between the fields $field1 and $field2.
     *
     * If there are differences this method returns $field2, otherwise the
     * boolean false.
     *
     * @param Column $column1
     * @param Column $column2
     *
306
     * @return array
307
     */
308
    public function diffColumn(Column $column1, Column $column2)
309
    {
310
        $changedProperties = array();
311
        if ( $column1->getType() != $column2->getType() ) {
312
            $changedProperties[] = 'type';
313 314 315
        }

        if ($column1->getNotnull() != $column2->getNotnull()) {
316
            $changedProperties[] = 'notnull';
317 318 319
        }

        if ($column1->getDefault() != $column2->getDefault()) {
320
            $changedProperties[] = 'default';
321 322 323
        }

        if ($column1->getUnsigned() != $column2->getUnsigned()) {
324
            $changedProperties[] = 'unsigned';
325 326 327
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) {
328 329 330 331
            // check if value of length is set at all, default value assumed otherwise.
            $length1 = $column1->getLength() ?: 255;
            $length2 = $column2->getLength() ?: 255;
            if ($length1 != $length2) {
332
                $changedProperties[] = 'length';
333 334 335
            }

            if ($column1->getFixed() != $column2->getFixed()) {
336
                $changedProperties[] = 'fixed';
337 338 339 340
            }
        }

        if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) {
341
            if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) {
342
                $changedProperties[] = 'precision';
343 344
            }
            if ($column1->getScale() != $column2->getScale()) {
345
                $changedProperties[] = 'scale';
346 347 348
            }
        }

349 350 351 352
        if ($column1->getAutoincrement() != $column2->getAutoincrement()) {
            $changedProperties[] = 'autoincrement';
        }

353 354
        // only allow to delete comment if its set to '' not to null.
        if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) {
355 356 357
            $changedProperties[] = 'comment';
        }

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        $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);

373
        return $changedProperties;
374 375 376 377 378 379 380 381 382 383
    }

    /**
     * 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.
     *
     * @param Index $index1
     * @param Index $index2
384
     * @return bool
385
     */
386
    public function diffIndex(Index $index1, Index $index2)
387
    {
388 389
        if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
            return false;
390
        }
391
        return true;
392
    }
beberlei's avatar
beberlei committed
393
}