├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── django_replace_migrations ├── __init__.py └── management │ ├── __init__.py │ └── commands │ ├── __init__.py │ └── makemigrations.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .DS_Store 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # pyenv 79 | .python-version 80 | 81 | # celery beat schedule file 82 | celerybeat-schedule 83 | 84 | # SageMath parsed files 85 | *.sage.py 86 | 87 | # Environments 88 | .env 89 | .venv 90 | env/ 91 | venv/ 92 | ENV/ 93 | env.bak/ 94 | venv.bak/ 95 | 96 | # Spyder project settings 97 | .spyderproject 98 | .spyproject 99 | 100 | # Rope project settings 101 | .ropeproject 102 | 103 | # mkdocs documentation 104 | /site 105 | 106 | # mypy 107 | .mypy_cache/ 108 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 3YOURMIND GmbH 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-replace-migrations 2 | 3 | This package is an extension to djangos `makemigrations.py`. 4 | It can be used to get rid of old migrations as an alternative to djangos `squashmigration` command. 5 | 6 | ## Reasoning 7 | 8 | In big django projects, migration files easily pile up and get an increasing problem. 9 | Django comes with the squashmigration command - however, it is hard to handle because of multiple reasons. 10 | Especially, it can not handle circular dependencies - they must be resolved [manually and with great care](https://stackoverflow.com/questions/37711402/circular-dependency-when-squashing-django-migrations). 11 | 12 | One possible solution is to: 13 | 14 | - Delete all existing migrations 15 | - Run `./manage.py makemigrations`, so that it creates new initial migrations 16 | - Run `./manage.py migrate --fake [new migrations]` or `./manage.py migrate --fake-initail` on all servers. 17 | 18 | This workflow might work fine, if you have only few (production) servers - however, it becomes hard, when you have many environments with different versions of your application. 19 | 20 | With django-replace-migrations also creates new initial migrations, but also, additionally, adds the already existing migrations to the `replace` list of the new migration 21 | (That list is used by `squashmigrations` as well). By doing that, faking migrations is not needed anymore. 22 | 23 | ## Warning 24 | 25 | The new replacing migrations will not consider any `RunPython` or `RunSQL` operations. 26 | That might be acceptable depending on your use of those operations and if you need those to prepare a fresh database. 27 | 28 | ## Installation 29 | 30 | Before you install, read the workflow below. You need to have the app installed in your project only on a specific branch temporarily. 31 | 32 | Run 33 | 34 | ``` 35 | pip install django-replace-migrations 36 | ``` 37 | 38 | and add `django_replace_migrations` to your list of installed apps. 39 | 40 | ## Simple Workflow 41 | 42 | If your apps are not depending on each other, you can use django-replace-migrations like this: 43 | 44 | ``` 45 | ./manage.py makemigratons --replace-all --name replace [app1, app2, ...] 46 | ``` 47 | 48 | Note, that you will need to [list all of your apps](https://stackoverflow.com/questions/4111244/get-a-list-of-all-installed-applications-in-django-and-their-attributes) explicitly - otherwise django will also try to replace migrations from dependencies. 49 | While `--name` could be omitted, it is highly recommended to use it so that you can easily recognize the new migrations. 50 | 51 | If for any of your apps there are not one but two or more migrations created, your apps are depending on each other (see below). 52 | 53 | You can leave your old migrations in the codebase. Old versions will continue to use the old migrations, while fresh installations will use the newly created replace migration instead. 54 | 55 | If you remove the old migrations later, you will need to update the dependencies in your other migrations and replace all occurrences of the old migration with the new replace migration. You can easily do that with try-and-error (`migrate` will fail and tell you which dependency is missing) 56 | 57 | ## Workflow for depending apps 58 | 59 | Due to the way django resolves the `replace` list, it can not handle circular dependencies within apps. To prevent an error during migration, you must delete the old migrations that you replaced. 60 | 61 | If you have your application deployed on multiple servers, you must define down to which version, you will support upgrading and only replace those migrations. 62 | 63 | Let’s assume that our current version of the application is 3.0 and we want to get rid of all migrations prior to 2.0. 64 | 65 | The workflow for this would be: 66 | 67 | - `git checkout 2.0` 68 | - create a new branch `git checkout -b 2-0-delete-migrations` 69 | - [delete all existing migrations in your apps](https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html) 70 | - commit and note the commit hash 71 | - `git checkout 2.0` 72 | - create a new branch `git checkout -b 2-0-replace-migrations` 73 | - Install `django-replace-migration` here. 74 | - run `./manage.py makemigrations --replace-all --name replace_2_0 app1, app2, ...` ([How to get all apps](https://stackoverflow.com/questions/4111244/get-a-list-of-all-installed-applications-in-django-and-their-attributes)) 75 | - commit and note the commit hash 76 | - `git checkout [your main/feature branch]` 77 | - `git cherry-pick [commit-hash from 2-0-delete-migrations]` 78 | - `git cherry-pick [commit-hash from 2-0-replace-migrations]` 79 | - Go over every migration in your app which was not replaced, and check the `dependencies` array. You need to make sure that every dependency listed was not replaced in the process, and the array is not out of date. If that's the case, then you need to specify the newest replaced migration instead. For example, in the app `A` there were two replace migrations created `0001_replace`, `0002_replace`. Migration `0026` is referencing migration `00015`, both from the app `A`, but `0015` was replaced. You need to swap `0015` with `0002_replace`. 80 | 81 | Now you have all migrations prior to 2.0 removed and replaced with new migrations. 82 | 83 | ### Consequences 84 | 85 | If your app is below 2.0 and you want to update to something after 2.0, you first need to update to 2.0 86 | 87 | - upgrading from 1.0 to 1.5 will be possible 88 | - upgrading from 2.0 to 3.0 will be possible 89 | - upgrading from 1.0 to 3.0 will be **not** possible 90 | 91 | ## `makemigration.py` compatibility 92 | 93 | This package requires deep integration into `makemigrations.py` so that I needed to copy the whole `makemigrations.py` here. Currently the version of `makemigrations.py` is copied from Django 2.1, however it is also tested with Django 3.0 and works there as well. If you encounter problems, please write what version of Django you are using. 94 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-replace-migrations/658596462a13ef92eaad1d853d99b266ff7bd814/__init__.py -------------------------------------------------------------------------------- /django_replace_migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-replace-migrations/658596462a13ef92eaad1d853d99b266ff7bd814/django_replace_migrations/__init__.py -------------------------------------------------------------------------------- /django_replace_migrations/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-replace-migrations/658596462a13ef92eaad1d853d99b266ff7bd814/django_replace_migrations/management/__init__.py -------------------------------------------------------------------------------- /django_replace_migrations/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3YOURMIND/django-replace-migrations/658596462a13ef92eaad1d853d99b266ff7bd814/django_replace_migrations/management/commands/__init__.py -------------------------------------------------------------------------------- /django_replace_migrations/management/commands/makemigrations.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from itertools import takewhile 4 | 5 | from django.apps import apps 6 | from django.conf import settings 7 | from django.core.management.base import ( 8 | BaseCommand, CommandError, no_translations, 9 | ) 10 | from django.db import DEFAULT_DB_ALIAS, connections, router 11 | from django.db.migrations import Migration 12 | from django.db.migrations.autodetector import MigrationAutodetector 13 | from django.db.migrations.loader import MigrationLoader 14 | from django.db.migrations.questioner import ( 15 | InteractiveMigrationQuestioner, MigrationQuestioner, 16 | NonInteractiveMigrationQuestioner, 17 | ) 18 | from django.db.migrations.state import ProjectState 19 | from django.db.migrations.utils import get_migration_name_timestamp 20 | from django.db.migrations.writer import MigrationWriter 21 | 22 | 23 | class Command(BaseCommand): 24 | help = "Creates new migration(s) for apps." 25 | 26 | def add_arguments(self, parser): 27 | parser.add_argument( 28 | 'args', metavar='app_label', nargs='*', 29 | help='Specify the app label(s) to create migrations for.', 30 | ) 31 | parser.add_argument( 32 | '--dry-run', action='store_true', dest='dry_run', 33 | help="Just show what migrations would be made; don't actually write them.", 34 | ) 35 | parser.add_argument( 36 | '--merge', action='store_true', dest='merge', 37 | help="Enable fixing of migration conflicts.", 38 | ) 39 | parser.add_argument( 40 | '--empty', action='store_true', dest='empty', 41 | help="Create an empty migration.", 42 | ) 43 | parser.add_argument( 44 | '--noinput', '--no-input', action='store_false', dest='interactive', 45 | help='Tells Django to NOT prompt the user for input of any kind.', 46 | ) 47 | parser.add_argument( 48 | '-n', '--name', action='store', dest='name', default=None, 49 | help="Use this name for migration file(s).", 50 | ) 51 | parser.add_argument( 52 | '--check', action='store_true', dest='check_changes', 53 | help='Exit with a non-zero status if model changes are missing migrations.', 54 | ) 55 | parser.add_argument( 56 | '--replace-all', action='store_true', dest='replace_all', 57 | help='Create fresh migrations that replaces existing ones.', 58 | ) 59 | 60 | @no_translations 61 | def handle(self, *app_labels, **options): 62 | self.verbosity = options['verbosity'] 63 | self.interactive = options['interactive'] 64 | self.dry_run = options['dry_run'] 65 | self.merge = options['merge'] 66 | self.empty = options['empty'] 67 | self.migration_name = options['name'] 68 | self.replace_all = options['replace_all'] 69 | check_changes = options['check_changes'] 70 | 71 | # Make sure the app they asked for exists 72 | app_labels = set(app_labels) 73 | bad_app_labels = set() 74 | for app_label in app_labels: 75 | try: 76 | apps.get_app_config(app_label) 77 | except LookupError: 78 | bad_app_labels.add(app_label) 79 | if bad_app_labels: 80 | for app_label in bad_app_labels: 81 | if '.' in app_label: 82 | self.stderr.write( 83 | "'%s' is not a valid app label. Did you mean '%s'?" % ( 84 | app_label, 85 | app_label.split('.')[-1], 86 | ) 87 | ) 88 | else: 89 | self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) 90 | sys.exit(2) 91 | 92 | # Load the current graph state. Pass in None for the connection so 93 | # the loader doesn't try to resolve replaced migrations from DB. 94 | loader = MigrationLoader(None, ignore_no_migrations=True) 95 | 96 | # Raise an error if any migrations are applied before their dependencies. 97 | consistency_check_labels = {config.label for config in apps.get_app_configs()} 98 | # Non-default databases are only checked if database routers used. 99 | aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS] 100 | for alias in sorted(aliases_to_check): 101 | connection = connections[alias] 102 | if (connection.settings_dict['ENGINE'] != 'django.db.backends.dummy' and any( 103 | # At least one model must be migrated to the database. 104 | router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name) 105 | for app_label in consistency_check_labels 106 | for model in apps.get_app_config(app_label).get_models() 107 | )): 108 | loader.check_consistent_history(connection) 109 | 110 | # Before anything else, see if there's conflicting apps and drop out 111 | # hard if there are any and they don't want to merge 112 | conflicts = loader.detect_conflicts() 113 | 114 | # If app_labels is specified, filter out conflicting migrations for unspecified apps 115 | if app_labels: 116 | conflicts = { 117 | app_label: conflict for app_label, conflict in conflicts.items() 118 | if app_label in app_labels 119 | } 120 | 121 | if conflicts and not self.merge: 122 | name_str = "; ".join( 123 | "%s in %s" % (", ".join(names), app) 124 | for app, names in conflicts.items() 125 | ) 126 | raise CommandError( 127 | "Conflicting migrations detected; multiple leaf nodes in the " 128 | "migration graph: (%s).\nTo fix them run " 129 | "'python manage.py makemigrations --merge'" % name_str 130 | ) 131 | 132 | # If they want to merge and there's nothing to merge, then politely exit 133 | if self.merge and not conflicts: 134 | self.stdout.write("No conflicts detected to merge.") 135 | return 136 | 137 | # If they want to merge and there is something to merge, then 138 | # divert into the merge code 139 | if self.merge and conflicts: 140 | return self.handle_merge(loader, conflicts) 141 | 142 | if self.interactive: 143 | questioner = InteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run) 144 | else: 145 | questioner = NonInteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run) 146 | 147 | if self.replace_all: 148 | replace_list = [migration for migration in loader.graph.nodes.values()] 149 | temp_nodes = loader.graph.nodes 150 | 151 | loader.graph.nodes = {k: v for (k, v) in loader.graph.nodes.items() if k[0] not in app_labels} 152 | 153 | autodetector = MigrationAutodetector( 154 | loader.project_state(), 155 | ProjectState.from_apps(apps), 156 | questioner, 157 | ) 158 | 159 | loader.graph.nodes = temp_nodes 160 | 161 | else: 162 | autodetector = MigrationAutodetector( 163 | loader.project_state(), 164 | ProjectState.from_apps(apps), 165 | questioner, 166 | ) 167 | 168 | # If they want to make an empty migration, make one for each app 169 | if self.empty: 170 | if not app_labels: 171 | raise CommandError("You must supply at least one app label when using --empty.") 172 | # Make a fake changes() result we can pass to arrange_for_graph 173 | changes = { 174 | app: [Migration("custom", app)] 175 | for app in app_labels 176 | } 177 | changes = autodetector.arrange_for_graph( 178 | changes=changes, 179 | graph=loader.graph, 180 | migration_name=self.migration_name, 181 | ) 182 | self.write_migration_files(changes) 183 | return 184 | 185 | # Detect changes 186 | changes = autodetector.changes( 187 | graph=loader.graph, 188 | trim_to_apps=app_labels or None, 189 | convert_apps=app_labels or None, 190 | migration_name=self.migration_name, 191 | ) 192 | 193 | if not changes: 194 | # No changes? Tell them. 195 | if self.verbosity >= 1: 196 | if app_labels: 197 | if len(app_labels) == 1: 198 | self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) 199 | else: 200 | self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) 201 | else: 202 | self.stdout.write("No changes detected") 203 | else: 204 | if self.replace_all: 205 | for app_label, app_migrations in changes.items(): 206 | for app_migration in app_migrations: 207 | app_migration.replaces = \ 208 | [ 209 | (migration.app_label, migration.name) 210 | for migration in replace_list 211 | if migration.app_label == app_label 212 | ] 213 | app_migration.dependencies = [dependency for dependency in app_migration.dependencies if dependency not in app_migration.replaces] 214 | 215 | self.write_migration_files(changes) 216 | if check_changes: 217 | sys.exit(1) 218 | 219 | def write_migration_files(self, changes): 220 | """ 221 | Take a changes dict and write them out as migration files. 222 | """ 223 | directory_created = {} 224 | for app_label, app_migrations in changes.items(): 225 | if self.verbosity >= 1: 226 | self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + "\n") 227 | for migration in app_migrations: 228 | # Describe the migration 229 | writer = MigrationWriter(migration) 230 | if self.verbosity >= 1: 231 | # Display a relative path if it's below the current working 232 | # directory, or an absolute path otherwise. 233 | try: 234 | migration_string = os.path.relpath(writer.path) 235 | except ValueError: 236 | migration_string = writer.path 237 | if migration_string.startswith('..'): 238 | migration_string = writer.path 239 | self.stdout.write(" %s\n" % (self.style.MIGRATE_LABEL(migration_string),)) 240 | if self.replace_all: 241 | self.stdout.write( 242 | " Replaces '%s'." % migration.replaces 243 | ) 244 | for operation in migration.operations: 245 | self.stdout.write(" - %s\n" % operation.describe()) 246 | if not self.dry_run: 247 | # Write the migrations file to the disk. 248 | migrations_directory = os.path.dirname(writer.path) 249 | if not directory_created.get(app_label): 250 | if not os.path.isdir(migrations_directory): 251 | os.mkdir(migrations_directory) 252 | init_path = os.path.join(migrations_directory, "__init__.py") 253 | if not os.path.isfile(init_path): 254 | open(init_path, "w").close() 255 | # We just do this once per app 256 | directory_created[app_label] = True 257 | migration_string = writer.as_string() 258 | with open(writer.path, "w", encoding='utf-8') as fh: 259 | fh.write(migration_string) 260 | elif self.verbosity == 3: 261 | # Alternatively, makemigrations --dry-run --verbosity 3 262 | # will output the migrations to stdout rather than saving 263 | # the file to the disk. 264 | self.stdout.write(self.style.MIGRATE_HEADING( 265 | "Full migrations file '%s':" % writer.filename) + "\n" 266 | ) 267 | self.stdout.write("%s\n" % writer.as_string()) 268 | 269 | def handle_merge(self, loader, conflicts): 270 | """ 271 | Handles merging together conflicted migrations interactively, 272 | if it's safe; otherwise, advises on how to fix it. 273 | """ 274 | if self.interactive: 275 | questioner = InteractiveMigrationQuestioner() 276 | else: 277 | questioner = MigrationQuestioner(defaults={'ask_merge': True}) 278 | 279 | for app_label, migration_names in conflicts.items(): 280 | # Grab out the migrations in question, and work out their 281 | # common ancestor. 282 | merge_migrations = [] 283 | for migration_name in migration_names: 284 | migration = loader.get_migration(app_label, migration_name) 285 | migration.ancestry = [ 286 | mig for mig in loader.graph.forwards_plan((app_label, migration_name)) 287 | if mig[0] == migration.app_label 288 | ] 289 | merge_migrations.append(migration) 290 | 291 | def all_items_equal(seq): 292 | return all(item == seq[0] for item in seq[1:]) 293 | 294 | merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations)) 295 | common_ancestor_count = sum(1 for common_ancestor_generation 296 | in takewhile(all_items_equal, merge_migrations_generations)) 297 | if not common_ancestor_count: 298 | raise ValueError("Could not find common ancestor of %s" % migration_names) 299 | # Now work out the operations along each divergent branch 300 | for migration in merge_migrations: 301 | migration.branch = migration.ancestry[common_ancestor_count:] 302 | migrations_ops = (loader.get_migration(node_app, node_name).operations 303 | for node_app, node_name in migration.branch) 304 | migration.merged_operations = sum(migrations_ops, []) 305 | # In future, this could use some of the Optimizer code 306 | # (can_optimize_through) to automatically see if they're 307 | # mergeable. For now, we always just prompt the user. 308 | if self.verbosity > 0: 309 | self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label)) 310 | for migration in merge_migrations: 311 | self.stdout.write(self.style.MIGRATE_LABEL(" Branch %s" % migration.name)) 312 | for operation in migration.merged_operations: 313 | self.stdout.write(" - %s\n" % operation.describe()) 314 | if questioner.ask_merge(app_label): 315 | # If they still want to merge it, then write out an empty 316 | # file depending on the migrations needing merging. 317 | numbers = [ 318 | MigrationAutodetector.parse_number(migration.name) 319 | for migration in merge_migrations 320 | ] 321 | try: 322 | biggest_number = max(x for x in numbers if x is not None) 323 | except ValueError: 324 | biggest_number = 1 325 | subclass = type("Migration", (Migration,), { 326 | "dependencies": [(app_label, migration.name) for migration in merge_migrations], 327 | }) 328 | migration_name = "%04i_%s" % ( 329 | biggest_number + 1, 330 | self.migration_name or ("merge_%s" % get_migration_name_timestamp()) 331 | ) 332 | new_migration = subclass(migration_name, app_label) 333 | writer = MigrationWriter(new_migration) 334 | 335 | if not self.dry_run: 336 | # Write the merge migrations file to the disk 337 | with open(writer.path, "w", encoding='utf-8') as fh: 338 | fh.write(writer.as_string()) 339 | if self.verbosity > 0: 340 | self.stdout.write("\nCreated new merge migration %s" % writer.path) 341 | elif self.verbosity == 3: 342 | # Alternatively, makemigrations --merge --dry-run --verbosity 3 343 | # will output the merge migrations to stdout rather than saving 344 | # the file to the disk. 345 | self.stdout.write(self.style.MIGRATE_HEADING( 346 | "Full merge migrations file '%s':" % writer.filename) + "\n" 347 | ) 348 | self.stdout.write("%s\n" % writer.as_string()) 349 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 3YOURMIND GmbH 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from os import path 15 | from setuptools import setup, find_packages 16 | 17 | 18 | PROJECT_DIR = path.abspath(path.dirname(__file__)) 19 | 20 | 21 | VERSION = '0.0.2' 22 | 23 | 24 | from os import path 25 | this_directory = path.abspath(path.dirname(__file__)) 26 | with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: 27 | long_description = f.read() 28 | 29 | 30 | setup( 31 | name="django-replace-migrations", 32 | version=VERSION, 33 | description="This package is an extension to djangos makemigrations.py. It can be used to get rid of old migrations as an alternative to djangos squashmigration command.", 34 | long_description=long_description, 35 | url="https://github.com/3YOURMIND/django-replace-migrations", 36 | author="3YOURMIND GmbH", 37 | license="Apache License 2.0", 38 | packages=find_packages(exclude=["tests/"]), 39 | install_requires=["django>=2.1"], 40 | extras_require={}, 41 | keywords="django migration replace squash squashmigrations database", 42 | classifiers=[ 43 | "Development Status :: 4 - Beta", 44 | "Intended Audience :: Developers", 45 | "Environment :: Web Environment", 46 | "Framework :: Django", 47 | "Framework :: Django :: 2.1", 48 | "Framework :: Django :: 2.2", 49 | "Framework :: Django :: 3.0", 50 | "Programming Language :: Python", 51 | "Programming Language :: Python :: 3", 52 | "Programming Language :: Python :: 3.5", 53 | "Programming Language :: Python :: 3.6", 54 | "Programming Language :: Python :: 3.7", 55 | ], 56 | ) 57 | --------------------------------------------------------------------------------