Comparator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. * Compares two Schemas and return an instance of SchemaDiff.
  22. *
  23. * @link www.doctrine-project.org
  24. * @since 2.0
  25. * @author Benjamin Eberlei <kontakt@beberlei.de>
  26. */
  27. class Comparator
  28. {
  29. /**
  30. * @param \Doctrine\DBAL\Schema\Schema $fromSchema
  31. * @param \Doctrine\DBAL\Schema\Schema $toSchema
  32. *
  33. * @return \Doctrine\DBAL\Schema\SchemaDiff
  34. */
  35. static public function compareSchemas(Schema $fromSchema, Schema $toSchema)
  36. {
  37. $c = new self();
  38. return $c->compare($fromSchema, $toSchema);
  39. }
  40. /**
  41. * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
  42. *
  43. * The returned differences are returned in such a way that they contain the
  44. * operations to change the schema stored in $fromSchema to the schema that is
  45. * stored in $toSchema.
  46. *
  47. * @param \Doctrine\DBAL\Schema\Schema $fromSchema
  48. * @param \Doctrine\DBAL\Schema\Schema $toSchema
  49. *
  50. * @return \Doctrine\DBAL\Schema\SchemaDiff
  51. */
  52. public function compare(Schema $fromSchema, Schema $toSchema)
  53. {
  54. $diff = new SchemaDiff();
  55. $diff->fromSchema = $fromSchema;
  56. $foreignKeysToTable = array();
  57. foreach ( $toSchema->getTables() as $table ) {
  58. $tableName = $table->getShortestName($toSchema->getName());
  59. if ( ! $fromSchema->hasTable($tableName)) {
  60. $diff->newTables[$tableName] = $toSchema->getTable($tableName);
  61. } else {
  62. $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
  63. if ($tableDifferences !== false) {
  64. $diff->changedTables[$tableName] = $tableDifferences;
  65. }
  66. }
  67. }
  68. /* Check if there are tables removed */
  69. foreach ($fromSchema->getTables() as $table) {
  70. $tableName = $table->getShortestName($fromSchema->getName());
  71. $table = $fromSchema->getTable($tableName);
  72. if ( ! $toSchema->hasTable($tableName) ) {
  73. $diff->removedTables[$tableName] = $table;
  74. }
  75. // also remember all foreign keys that point to a specific table
  76. foreach ($table->getForeignKeys() as $foreignKey) {
  77. $foreignTable = strtolower($foreignKey->getForeignTableName());
  78. if (!isset($foreignKeysToTable[$foreignTable])) {
  79. $foreignKeysToTable[$foreignTable] = array();
  80. }
  81. $foreignKeysToTable[$foreignTable][] = $foreignKey;
  82. }
  83. }
  84. foreach ($diff->removedTables as $tableName => $table) {
  85. if (isset($foreignKeysToTable[$tableName])) {
  86. $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
  87. // deleting duplicated foreign keys present on both on the orphanedForeignKey
  88. // and the removedForeignKeys from changedTables
  89. foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
  90. // strtolower the table name to make if compatible with getShortestName
  91. $localTableName = strtolower($foreignKey->getLocalTableName());
  92. if (isset($diff->changedTables[$localTableName])) {
  93. foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
  94. unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
  95. }
  96. }
  97. }
  98. }
  99. }
  100. foreach ($toSchema->getSequences() as $sequence) {
  101. $sequenceName = $sequence->getShortestName($toSchema->getName());
  102. if ( ! $fromSchema->hasSequence($sequenceName)) {
  103. $diff->newSequences[] = $sequence;
  104. } else {
  105. if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
  106. $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
  107. }
  108. }
  109. }
  110. foreach ($fromSchema->getSequences() as $sequence) {
  111. if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
  112. continue;
  113. }
  114. $sequenceName = $sequence->getShortestName($fromSchema->getName());
  115. if ( ! $toSchema->hasSequence($sequenceName)) {
  116. $diff->removedSequences[] = $sequence;
  117. }
  118. }
  119. return $diff;
  120. }
  121. /**
  122. * @param \Doctrine\DBAL\Schema\Schema $schema
  123. * @param \Doctrine\DBAL\Schema\Sequence $sequence
  124. *
  125. * @return boolean
  126. */
  127. private function isAutoIncrementSequenceInSchema($schema, $sequence)
  128. {
  129. foreach ($schema->getTables() as $table) {
  130. if ($sequence->isAutoIncrementsFor($table)) {
  131. return true;
  132. }
  133. }
  134. return false;
  135. }
  136. /**
  137. * @param \Doctrine\DBAL\Schema\Sequence $sequence1
  138. * @param \Doctrine\DBAL\Schema\Sequence $sequence2
  139. *
  140. * @return boolean
  141. */
  142. public function diffSequence(Sequence $sequence1, Sequence $sequence2)
  143. {
  144. if($sequence1->getAllocationSize() != $sequence2->getAllocationSize()) {
  145. return true;
  146. }
  147. if($sequence1->getInitialValue() != $sequence2->getInitialValue()) {
  148. return true;
  149. }
  150. return false;
  151. }
  152. /**
  153. * Returns the difference between the tables $table1 and $table2.
  154. *
  155. * If there are no differences this method returns the boolean false.
  156. *
  157. * @param \Doctrine\DBAL\Schema\Table $table1
  158. * @param \Doctrine\DBAL\Schema\Table $table2
  159. *
  160. * @return boolean|\Doctrine\DBAL\Schema\TableDiff
  161. */
  162. public function diffTable(Table $table1, Table $table2)
  163. {
  164. $changes = 0;
  165. $tableDifferences = new TableDiff($table1->getName());
  166. $tableDifferences->fromTable = $table1;
  167. $table1Columns = $table1->getColumns();
  168. $table2Columns = $table2->getColumns();
  169. /* See if all the fields in table 1 exist in table 2 */
  170. foreach ( $table2Columns as $columnName => $column ) {
  171. if ( !$table1->hasColumn($columnName) ) {
  172. $tableDifferences->addedColumns[$columnName] = $column;
  173. $changes++;
  174. }
  175. }
  176. /* See if there are any removed fields in table 2 */
  177. foreach ( $table1Columns as $columnName => $column ) {
  178. if ( !$table2->hasColumn($columnName) ) {
  179. $tableDifferences->removedColumns[$columnName] = $column;
  180. $changes++;
  181. }
  182. }
  183. foreach ( $table1Columns as $columnName => $column ) {
  184. if ( $table2->hasColumn($columnName) ) {
  185. $changedProperties = $this->diffColumn( $column, $table2->getColumn($columnName) );
  186. if (count($changedProperties) ) {
  187. $columnDiff = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
  188. $columnDiff->fromColumn = $column;
  189. $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
  190. $changes++;
  191. }
  192. }
  193. }
  194. $this->detectColumnRenamings($tableDifferences);
  195. $table1Indexes = $table1->getIndexes();
  196. $table2Indexes = $table2->getIndexes();
  197. foreach ($table2Indexes as $index2Name => $index2Definition) {
  198. foreach ($table1Indexes as $index1Name => $index1Definition) {
  199. if ($this->diffIndex($index1Definition, $index2Definition) === false) {
  200. unset($table1Indexes[$index1Name]);
  201. unset($table2Indexes[$index2Name]);
  202. } else {
  203. if ($index1Name == $index2Name) {
  204. $tableDifferences->changedIndexes[$index2Name] = $table2Indexes[$index2Name];
  205. unset($table1Indexes[$index1Name]);
  206. unset($table2Indexes[$index2Name]);
  207. $changes++;
  208. }
  209. }
  210. }
  211. }
  212. foreach ($table1Indexes as $index1Name => $index1Definition) {
  213. $tableDifferences->removedIndexes[$index1Name] = $index1Definition;
  214. $changes++;
  215. }
  216. foreach ($table2Indexes as $index2Name => $index2Definition) {
  217. $tableDifferences->addedIndexes[$index2Name] = $index2Definition;
  218. $changes++;
  219. }
  220. $fromFkeys = $table1->getForeignKeys();
  221. $toFkeys = $table2->getForeignKeys();
  222. foreach ($fromFkeys as $key1 => $constraint1) {
  223. foreach ($toFkeys as $key2 => $constraint2) {
  224. if($this->diffForeignKey($constraint1, $constraint2) === false) {
  225. unset($fromFkeys[$key1]);
  226. unset($toFkeys[$key2]);
  227. } else {
  228. if (strtolower($constraint1->getName()) == strtolower($constraint2->getName())) {
  229. $tableDifferences->changedForeignKeys[] = $constraint2;
  230. $changes++;
  231. unset($fromFkeys[$key1]);
  232. unset($toFkeys[$key2]);
  233. }
  234. }
  235. }
  236. }
  237. foreach ($fromFkeys as $constraint1) {
  238. $tableDifferences->removedForeignKeys[] = $constraint1;
  239. $changes++;
  240. }
  241. foreach ($toFkeys as $constraint2) {
  242. $tableDifferences->addedForeignKeys[] = $constraint2;
  243. $changes++;
  244. }
  245. return $changes ? $tableDifferences : false;
  246. }
  247. /**
  248. * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
  249. * however ambiguities between different possibilities should not lead to renaming at all.
  250. *
  251. * @param \Doctrine\DBAL\Schema\TableDiff $tableDifferences
  252. *
  253. * @return void
  254. */
  255. private function detectColumnRenamings(TableDiff $tableDifferences)
  256. {
  257. $renameCandidates = array();
  258. foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
  259. foreach ($tableDifferences->removedColumns as $removedColumn) {
  260. if (count($this->diffColumn($addedColumn, $removedColumn)) == 0) {
  261. $renameCandidates[$addedColumn->getName()][] = array($removedColumn, $addedColumn, $addedColumnName);
  262. }
  263. }
  264. }
  265. foreach ($renameCandidates as $candidateColumns) {
  266. if (count($candidateColumns) == 1) {
  267. list($removedColumn, $addedColumn) = $candidateColumns[0];
  268. $removedColumnName = strtolower($removedColumn->getName());
  269. $addedColumnName = strtolower($addedColumn->getName());
  270. if ( ! isset($tableDifferences->renamedColumns[$removedColumnName])) {
  271. $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
  272. unset($tableDifferences->addedColumns[$addedColumnName]);
  273. unset($tableDifferences->removedColumns[$removedColumnName]);
  274. }
  275. }
  276. }
  277. }
  278. /**
  279. * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key1
  280. * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $key2
  281. *
  282. * @return boolean
  283. */
  284. public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
  285. {
  286. if (array_map('strtolower', $key1->getLocalColumns()) != array_map('strtolower', $key2->getLocalColumns())) {
  287. return true;
  288. }
  289. if (array_map('strtolower', $key1->getForeignColumns()) != array_map('strtolower', $key2->getForeignColumns())) {
  290. return true;
  291. }
  292. if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
  293. return true;
  294. }
  295. if ($key1->onUpdate() != $key2->onUpdate()) {
  296. return true;
  297. }
  298. if ($key1->onDelete() != $key2->onDelete()) {
  299. return true;
  300. }
  301. return false;
  302. }
  303. /**
  304. * Returns the difference between the fields $field1 and $field2.
  305. *
  306. * If there are differences this method returns $field2, otherwise the
  307. * boolean false.
  308. *
  309. * @param \Doctrine\DBAL\Schema\Column $column1
  310. * @param \Doctrine\DBAL\Schema\Column $column2
  311. *
  312. * @return array
  313. */
  314. public function diffColumn(Column $column1, Column $column2)
  315. {
  316. $changedProperties = array();
  317. if ( $column1->getType() != $column2->getType() ) {
  318. $changedProperties[] = 'type';
  319. }
  320. if ($column1->getNotnull() != $column2->getNotnull()) {
  321. $changedProperties[] = 'notnull';
  322. }
  323. if ($column1->getDefault() != $column2->getDefault()) {
  324. $changedProperties[] = 'default';
  325. }
  326. if ($column1->getUnsigned() != $column2->getUnsigned()) {
  327. $changedProperties[] = 'unsigned';
  328. }
  329. if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) {
  330. // check if value of length is set at all, default value assumed otherwise.
  331. $length1 = $column1->getLength() ?: 255;
  332. $length2 = $column2->getLength() ?: 255;
  333. if ($length1 != $length2) {
  334. $changedProperties[] = 'length';
  335. }
  336. if ($column1->getFixed() != $column2->getFixed()) {
  337. $changedProperties[] = 'fixed';
  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. if ($column1->getAutoincrement() != $column2->getAutoincrement()) {
  349. $changedProperties[] = 'autoincrement';
  350. }
  351. // only allow to delete comment if its set to '' not to null.
  352. if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) {
  353. $changedProperties[] = 'comment';
  354. }
  355. $options1 = $column1->getCustomSchemaOptions();
  356. $options2 = $column2->getCustomSchemaOptions();
  357. $commonKeys = array_keys(array_intersect_key($options1, $options2));
  358. foreach ($commonKeys as $key) {
  359. if ($options1[$key] !== $options2[$key]) {
  360. $changedProperties[] = $key;
  361. }
  362. }
  363. $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1));
  364. $changedProperties = array_merge($changedProperties, $diffKeys);
  365. return $changedProperties;
  366. }
  367. /**
  368. * Finds the difference between the indexes $index1 and $index2.
  369. *
  370. * Compares $index1 with $index2 and returns $index2 if there are any
  371. * differences or false in case there are no differences.
  372. *
  373. * @param \Doctrine\DBAL\Schema\Index $index1
  374. * @param \Doctrine\DBAL\Schema\Index $index2
  375. *
  376. * @return boolean
  377. */
  378. public function diffIndex(Index $index1, Index $index2)
  379. {
  380. if ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1)) {
  381. return false;
  382. }
  383. return true;
  384. }
  385. }