Comparator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. /**
  21. * Compare to Schemas and return an instance of SchemaDiff
  22. *
  23. * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.
  24. * @license http://ez.no/licenses/new_bsd New BSD License
  25. *
  26. * @link www.doctrine-project.org
  27. * @since 2.0
  28. * @version $Revision$
  29. * @author Benjamin Eberlei <kontakt@beberlei.de>
  30. */
  31. class Comparator
  32. {
  33. /**
  34. * @param Schema $fromSchema
  35. * @param Schema $toSchema
  36. * @return SchemaDiff
  37. */
  38. static public function compareSchemas( Schema $fromSchema, Schema $toSchema )
  39. {
  40. $c = new self();
  41. return $c->compare($fromSchema, $toSchema);
  42. }
  43. /**
  44. * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
  45. *
  46. * The returned differences are returned in such a way that they contain the
  47. * operations to change the schema stored in $fromSchema to the schema that is
  48. * stored in $toSchema.
  49. *
  50. * @param Schema $fromSchema
  51. * @param Schema $toSchema
  52. *
  53. * @return SchemaDiff
  54. */
  55. public function compare(Schema $fromSchema, Schema $toSchema)
  56. {
  57. $diff = new SchemaDiff();
  58. $foreignKeysToTable = array();
  59. foreach ( $toSchema->getTables() as $table ) {
  60. $tableName = $table->getShortestName($toSchema->getName());
  61. if ( ! $fromSchema->hasTable($tableName)) {
  62. $diff->newTables[$tableName] = $toSchema->getTable($tableName);
  63. } else {
  64. $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
  65. if ($tableDifferences !== false) {
  66. $diff->changedTables[$tableName] = $tableDifferences;
  67. }
  68. }
  69. }
  70. /* Check if there are tables removed */
  71. foreach ($fromSchema->getTables() as $table) {
  72. $tableName = $table->getShortestName($fromSchema->getName());
  73. $table = $fromSchema->getTable($tableName);
  74. if ( ! $toSchema->hasTable($tableName) ) {
  75. $diff->removedTables[$tableName] = $table;
  76. }
  77. // also remember all foreign keys that point to a specific table
  78. foreach ($table->getForeignKeys() as $foreignKey) {
  79. $foreignTable = strtolower($foreignKey->getForeignTableName());
  80. if (!isset($foreignKeysToTable[$foreignTable])) {
  81. $foreignKeysToTable[$foreignTable] = array();
  82. }
  83. $foreignKeysToTable[$foreignTable][] = $foreignKey;
  84. }
  85. }
  86. foreach ($diff->removedTables as $tableName => $table) {
  87. if (isset($foreignKeysToTable[$tableName])) {
  88. $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
  89. // deleting duplicated foreign keys present on both on the orphanedForeignKey
  90. // and the removedForeignKeys from changedTables
  91. foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
  92. // strtolower the table name to make if compatible with getShortestName
  93. $localTableName = strtolower($foreignKey->getLocalTableName());
  94. if (isset($diff->changedTables[$localTableName])) {
  95. foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
  96. unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
  97. }
  98. }
  99. }
  100. }
  101. }
  102. foreach ($toSchema->getSequences() as $sequence) {
  103. $sequenceName = $sequence->getShortestName($toSchema->getName());
  104. if ( ! $fromSchema->hasSequence($sequenceName)) {
  105. $diff->newSequences[] = $sequence;
  106. } else {
  107. if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
  108. $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
  109. }
  110. }
  111. }
  112. foreach ($fromSchema->getSequences() as $sequence) {
  113. if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
  114. continue;
  115. }
  116. $sequenceName = $sequence->getShortestName($fromSchema->getName());
  117. if ( ! $toSchema->hasSequence($sequenceName)) {
  118. $diff->removedSequences[] = $sequence;
  119. }
  120. }
  121. return $diff;
  122. }
  123. private function isAutoIncrementSequenceInSchema($schema, $sequence)
  124. {
  125. foreach ($schema->getTables() as $table) {
  126. if ($sequence->isAutoIncrementsFor($table)) {
  127. return true;
  128. }
  129. }
  130. return false;
  131. }
  132. /**
  133. *
  134. * @param Sequence $sequence1
  135. * @param Sequence $sequence2
  136. */
  137. public function diffSequence(Sequence $sequence1, Sequence $sequence2)
  138. {
  139. if($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
  140. return true;
  141. }
  142. if($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
  143. return true;
  144. }
  145. return false;
  146. }
  147. /**
  148. * Returns the difference between the tables $table1 and $table2.
  149. *
  150. * If there are no differences this method returns the boolean false.
  151. *
  152. * @param Table $table1
  153. * @param Table $table2
  154. *
  155. * @return bool|TableDiff
  156. */
  157. public function diffTable(Table $table1, Table $table2)
  158. {
  159. $changes = 0;
  160. $tableDifferences = new TableDiff($table1->getName());
  161. $table1Columns = $table1->getColumns();
  162. $table2Columns = $table2->getColumns();
  163. /* See if all the fields in table 1 exist in table 2 */
  164. foreach ( $table2Columns as $columnName => $column ) {
  165. if ( !$table1->hasColumn($columnName) ) {
  166. $tableDifferences->addedColumns[$columnName] = $column;
  167. $changes++;
  168. }
  169. }
  170. /* See if there are any removed fields in table 2 */
  171. foreach ( $table1Columns as $columnName => $column ) {
  172. if ( !$table2->hasColumn($columnName) ) {
  173. $tableDifferences->removedColumns[$columnName] = $column;
  174. $changes++;
  175. }
  176. }
  177. foreach ( $table1Columns as $columnName => $column ) {
  178. if ( $table2->hasColumn($columnName) ) {
  179. $changedProperties = $this->diffColumn( $column, $table2->getColumn($columnName) );
  180. if (count($changedProperties) ) {
  181. $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
  182. $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
  183. $changes++;
  184. }
  185. }
  186. }
  187. $this->detectColumnRenamings($tableDifferences);
  188. $table1Indexes = $table1->getIndexes();
  189. $table2Indexes = $table2->getIndexes();
  190. foreach ($table2Indexes as $index2Name => $index2Definition) {
  191. foreach ($table1Indexes as $index1Name => $index1Definition) {
  192. if ($this->diffIndex($index1Definition, $index2Definition) === false) {
  193. unset($table1Indexes[$index1Name]);
  194. unset($table2Indexes[$index2Name]);
  195. } else {
  196. if ($index1Name == $index2Name) {
  197. $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
  198. unset($table1Indexes[$index1Name]);
  199. unset($table2Indexes[$index2Name]);
  200. $changes++;
  201. }
  202. }
  203. }
  204. }
  205. foreach ($table1Indexes as $index1Name => $index1Definition) {
  206. $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
  207. $changes++;
  208. }
  209. foreach ($table2Indexes as $index2Name => $index2Definition) {
  210. $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
  211. $changes++;
  212. }
  213. $fromFkeys = $table1->getForeignKeys();
  214. $toFkeys = $table2->getForeignKeys();
  215. foreach ($fromFkeys as $key1 => $constraint1) {
  216. foreach ($toFkeys as $key2 => $constraint2) {
  217. if($this->diffForeignKey($constraint1, $constraint2) === false) {
  218. unset($fromFkeys[$key1]);
  219. unset($toFkeys[$key2]);
  220. } else {
  221. if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
  222. $tableDifferences->changedForeignKeys[] = $constraint2;
  223. $changes++;
  224. unset($fromFkeys[$key1]);
  225. unset($toFkeys[$key2]);
  226. }
  227. }
  228. }
  229. }
  230. foreach ($fromFkeys as $key1 => $constraint1) {
  231. $tableDifferences->removedForeignKeys[] = $constraint1;
  232. $changes++;
  233. }
  234. foreach ($toFkeys as $key2 => $constraint2) {
  235. $tableDifferences->addedForeignKeys[] = $constraint2;
  236. $changes++;
  237. }
  238. return $changes ? $tableDifferences : false;
  239. }
  240. /**
  241. * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
  242. * however ambiguities between different possibilities should not lead to renaming at all.
  243. *
  244. * @param TableDiff $tableDifferences
  245. */
  246. private function detectColumnRenamings(TableDiff $tableDifferences)
  247. {
  248. $renameCandidates = array();
  249. foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
  250. foreach ($tableDifferences->removedColumns as $removedColumnName => $removedColumn) {
  251. if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
  252. $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
  253. }
  254. }
  255. }
  256. foreach ($renameCandidates as $candidateColumns) {
  257. if (count($candidateColumns) == 1) {
  258. list($removedColumn, $addedColumn) = $candidateColumns[0];
  259. $removedColumnName = strtolower($removedColumn->getName());
  260. $addedColumnName = strtolower($addedColumn->getName());
  261. if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
  262. $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
  263. unset($tableDifferences->addedColumns[$addedColumnName]);
  264. unset($tableDifferences->removedColumns[$removedColumnName]);
  265. }
  266. }
  267. }
  268. }
  269. /**
  270. * @param ForeignKeyConstraint $key1
  271. * @param ForeignKeyConstraint $key2
  272. * @return bool
  273. */
  274. public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
  275. {
  276. if (array_map('strtolower', $key1->getLocalColumns()) != array_map('strtolower', $key2->getLocalColumns())) {
  277. return true;
  278. }
  279. if (array_map('strtolower', $key1->getForeignColumns()) != array_map('strtolower', $key2->getForeignColumns())) {
  280. return true;
  281. }
  282. if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
  283. return true;
  284. }
  285. if ($key1->onUpdate() != $key2->onUpdate()) {
  286. return true;
  287. }
  288. if ($key1->onDelete() != $key2->onDelete()) {
  289. return true;
  290. }
  291. return false;
  292. }
  293. /**
  294. * Returns the difference between the fields $field1 and $field2.
  295. *
  296. * If there are differences this method returns $field2, otherwise the
  297. * boolean false.
  298. *
  299. * @param Column $column1
  300. * @param Column $column2
  301. *
  302. * @return array
  303. */
  304. public function diffColumn(Column $column1, Column $column2)
  305. {
  306. $changedProperties = array();
  307. if ( $column1->getType() != $column2->getType() ) {
  308. $changedProperties[] = 'type';
  309. }
  310. if ($column1->getNotnull() != $column2->getNotnull()) {
  311. $changedProperties[] = 'notnull';
  312. }
  313. if ($column1->getDefault() != $column2->getDefault()) {
  314. $changedProperties[] = 'default';
  315. }
  316. if ($column1->getUnsigned() != $column2->getUnsigned()) {
  317. $changedProperties[] = 'unsigned';
  318. }
  319. if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) {
  320. // check if value of length is set at all, default value assumed otherwise.
  321. $length1 = $column1->getLength() ?: 255;
  322. $length2 = $column2->getLength() ?: 255;
  323. if ($length1 != $length2) {
  324. $changedProperties[] = 'length';
  325. }
  326. if ($column1->getFixed() != $column2->getFixed()) {
  327. $changedProperties[] = 'fixed';
  328. }
  329. }
  330. if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) {
  331. if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) {
  332. $changedProperties[] = 'precision';
  333. }
  334. if ($column1->getScale() != $column2->getScale()) {
  335. $changedProperties[] = 'scale';
  336. }
  337. }
  338. if ($column1->getAutoincrement() != $column2->getAutoincrement()) {
  339. $changedProperties[] = 'autoincrement';
  340. }
  341. // only allow to delete comment if its set to '' not to null.
  342. if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) {
  343. $changedProperties[] = 'comment';
  344. }
  345. $options1 = $column1->getCustomSchemaOptions();
  346. $options2 = $column2->getCustomSchemaOptions();
  347. $commonKeys = array_keys(array_intersect_key($options1, $options2));
  348. foreach ($commonKeys as $key) {
  349. if ($options1[$key] !== $options2[$key]) {
  350. $changedProperties[] = $key;
  351. }
  352. }
  353. $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1));
  354. $changedProperties = array_merge($changedProperties, $diffKeys);
  355. return $changedProperties;
  356. }
  357. /**
  358. * Finds the difference between the indexes $index1 and $index2.
  359. *
  360. * Compares $index1 with $index2 and returns $index2 if there are any
  361. * differences or false in case there are no differences.
  362. *
  363. * @param Index $index1
  364. * @param Index $index2
  365. * @return bool
  366. */
  367. public function diffIndex(Index $index1, Index $index2)
  368. {
  369. if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
  370. return false;
  371. }
  372. return true;
  373. }
  374. }