├── .bandit.yml ├── .editorconfig ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── question.md └── workflows │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yml ├── pyproject.toml ├── requirements.txt ├── src └── pymongo_migrate │ ├── __init__.py │ ├── cli.py │ ├── generate.py │ ├── graph_draw.py │ ├── loader.py │ ├── migrations.py │ └── mongo_migrate.py └── tests ├── conftest.py ├── migrations ├── 20150612230153.py ├── 20181123000000_gt_500.py └── __init__.py ├── test_cli.py ├── test_generate.py ├── test_main_status.py ├── test_mongo_migrate.py └── test_mongo_migrate_generate.py /.bandit.yml: -------------------------------------------------------------------------------- 1 | targets: . 2 | skips: 3 | - B101 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | end_of_line = lf 11 | charset = utf-8 12 | 13 | [*.py] 14 | max_line_length = 88 15 | 16 | [*.{yml,yaml}] 17 | indent_size = 2 18 | 19 | [{Makefile,**.mk}] 20 | # Use tabs for indentation (Makefiles require tabs) 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: needs-triage 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Additional context** 20 | Add any other context about the problem here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Question about the project or its use. 4 | title: '' 5 | labels: question 6 | assignees: '' 7 | 8 | --- 9 | 10 | Please check closed issues and stackoverflow first to avoid duplicated work. 11 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: [main] 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: [3.8, 3.9, "3.10", 3.11] 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: make init 24 | - name: Start MongoDB 25 | uses: supercharge/mongodb-github-action@1.6.0 26 | - name: Run CI 27 | run: make ci 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # IDE 107 | .idea 108 | 109 | .ruff_cache 110 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [1.0.0] - 2023-06-30 9 | 10 | ### Added 11 | 12 | - Official support for Python 3.11 13 | - Add support for specifying database for migration while authenticating against different database #41 14 | 15 | ### Fixed 16 | 17 | - Ensure that the generate command creates files that pass mypy checks #40 18 | 19 | ### Removed 20 | 21 | - Removed support for Python 3.7 and older as they reach [End of Life](https://endoflife.date/python). 22 | 23 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | run= 2 | 3 | init: 4 | pip install -r requirements.txt 5 | 6 | format: 7 | $(run) black . 8 | $(run) ruff check --fix . 9 | $(run) mypy src 10 | $(run) bandit -c .bandit.yml -r src 11 | 12 | test: 13 | docker-compose up -d mongo 14 | $(run) pytest -vv 15 | docker-compose down 16 | 17 | check: format test 18 | @echo "Everything ok!" 19 | 20 | clean: 21 | rm -fr build dist .egg src/pymongo_migrate.egg-info 22 | 23 | publish: clean 24 | python -m pip install twine build 25 | python -m build 26 | python -m twine upload --repository testpypi dist/* 27 | python -m twine upload dist/* 28 | 29 | ci: 30 | $(run) black --check . 31 | $(run) ruff check . 32 | $(run) mypy src 33 | $(run) bandit -c .bandit.yml -r src 34 | $(run) pytest 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pymongo-migrate 2 | 3 | ![Build Status](https://github.com/stxnext/pymongo-migrate/actions/workflows/test.yml/badge.svg) 4 | [![PyPI version](https://badge.fury.io/py/pymongo-migrate.svg)](https://badge.fury.io/py/pymongo-migrate) 5 | 6 | ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pymongo-migrate.svg) 7 | 8 | Mongodb migrations using Python. 9 | 10 | Since mongodb is schema-less most of the time you can do without data migrations. 11 | Sometimes tho you want to create some new entities, or migrate old data instead adding another IF statement to your code. 12 | This is where `pymongo-migrate` comes in. 13 | 14 | ## Usage 15 | 16 | Usage: pymongo-migrate [OPTIONS] COMMAND [ARGS]... 17 | 18 | Options: 19 | --help Show this message and exit. 20 | 21 | Commands: 22 | downgrade apply necessary downgrades to reach target migration 23 | graph 24 | migrate automagically apply necessary upgrades or downgrades to reach 25 | target migration 26 | show show migrations and their status 27 | upgrade apply necessary upgrades to reach target migration 28 | 29 | 30 | The most used command will be `migrate`, which works can be called like this: 31 | 32 | $ pymongo-migrate migrate -u 'mongodb://localhost/test_db' -m tests/migrations 33 | 34 | Use `pymongo-migrate command --help` to learn more about particular command. 35 | 36 | ## Development & contributing to the project 37 | 38 | Contributions and raising Issues is welcome; standard netiquette rules apply. 39 | 40 | Use `make init` to setup the project for development. 41 | To format your code & test your changes run: 42 | 43 | make check 44 | 45 | ## Alternatives 46 | 47 | ATM there seem only two active python projects like this: 48 | * https://github.com/DoubleCiti/mongodb-migrations 49 | * https://github.com/skynyrd/cikilop 50 | 51 | So if something already existed, why then another project? 52 | 53 | Goals of this project, where at least one of them were not fulfilled by above: 54 | * tests and CI pipeline for ensuring that tool indeed works 55 | * keeping it usable both as standalone tool and as python dependency 56 | * use of modern Python version, which allows use of type annotations, dataclasses, f-strings and other goodies 57 | 58 | ## Inspiration and design 59 | 60 | Other than Alternatives mentioned above, both `alembic` and `django` were used as references when designing this tool. 61 | 62 | For now only linear revision history is supported. 63 | The support for squash migrations is planned. 64 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.5' 2 | 3 | services: 4 | mongo: 5 | image: mongo 6 | ports: 7 | - "27017:27017" 8 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "pymongo-migrate" 7 | version = "1.0.0" 8 | description = "MongoDB data migration tool in Python" 9 | license = {text="Apache Software License"} 10 | readme = "README.md" # assuming you have a README.md file 11 | requires-python = ">=3.8" 12 | keywords = ["mongo", "mongodb", "pymongo", "migrate", "migration"] 13 | classifiers = [ 14 | "License :: OSI Approved :: Apache Software License", 15 | "Operating System :: OS Independent", 16 | "Programming Language :: Python", 17 | "Programming Language :: Python :: 3", 18 | "Programming Language :: Python :: 3.8", 19 | "Programming Language :: Python :: 3.9", 20 | "Programming Language :: Python :: 3.10", 21 | "Programming Language :: Python :: 3.11", 22 | "Topic :: Software Development :: Libraries :: Python Modules", 23 | "Topic :: Database", 24 | ] 25 | 26 | dependencies = [ 27 | "pymongo>=3.7.2", 28 | "Click>=7", 29 | ] 30 | 31 | [project.urls] 32 | Homepage = "https://github.com/stxnext/pymongo-migrate" 33 | Changelog = "https://github.com/stxnext/pymongo-migrate/blob/main/CHANGELOG.md" 34 | 35 | [project.scripts] 36 | pymongo-migrate = "pymongo_migrate.cli:cli" 37 | 38 | [tool.setuptools] 39 | package-dir = {"" = "src"} 40 | include-package-data = true 41 | 42 | [tool.setuptools.packages.find] 43 | where = ["src"] 44 | exclude = ["tests"] 45 | 46 | [tool.ruff] 47 | select = ["E", "F", "I", "UP"] 48 | ignore = ["E203", "E266", "E501"] 49 | exclude = [".git", "__pycache__", ".venv", "build", "dist"] 50 | 51 | [tool.pytest.env] 52 | env_files = ".env" 53 | 54 | [tool.mypy] 55 | ignore_missing_imports = true 56 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bandit 2 | black 3 | freezegun 4 | mypy 5 | pytest 6 | ruff 7 | 8 | -e . 9 | -------------------------------------------------------------------------------- /src/pymongo_migrate/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.5.0" 2 | -------------------------------------------------------------------------------- /src/pymongo_migrate/cli.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from functools import wraps 4 | from pprint import pformat 5 | from typing import Optional 6 | 7 | import click 8 | import pymongo.monitoring 9 | 10 | from pymongo_migrate.graph_draw import dump 11 | from pymongo_migrate.mongo_migrate import MongoMigrate 12 | 13 | 14 | @click.group() 15 | def cli(): 16 | pass 17 | 18 | 19 | class CommandLogger(pymongo.monitoring.CommandListener): 20 | def __init__(self, verbose: int = 0): 21 | self.verbose = verbose 22 | 23 | def echo(self, *args, min_verbosity=1): 24 | if self.verbose >= min_verbosity: 25 | click.echo(*args) 26 | 27 | def started(self, event): 28 | self.echo(f"Command {event.command_name}#{event.request_id} STARTED") 29 | if self.verbose >= 1: 30 | self.echo(pformat(event.command), min_verbosity=1) 31 | 32 | def succeeded(self, event): 33 | self.echo( 34 | f"Command {event.command_name}#{event.request_id} SUCCEEDED in {event.duration_micros}us" 35 | ) 36 | 37 | def failed(self, event): 38 | self.echo( 39 | f"Command {event.command_name}#{event.request_id} FAILED in {event.duration_micros}us" 40 | ) 41 | 42 | 43 | def get_logger(verbose: int): 44 | logger = logging.getLogger(__name__) 45 | 46 | stream = click.get_text_stream("stdout") 47 | console_handler = logging.StreamHandler(stream=stream) 48 | log_formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") 49 | console_handler.setFormatter(log_formatter) 50 | logger.addHandler(console_handler) 51 | 52 | if verbose > 0: 53 | logger.setLevel(logging.DEBUG) 54 | else: 55 | logger.setLevel(logging.INFO) 56 | return logger 57 | 58 | 59 | def mongo_migrate_decor(f): 60 | @wraps(f) 61 | def wrap_with_client( 62 | uri, database, migrations, collection, verbose, *args, **kwargs 63 | ): 64 | mongo_migrate = MongoMigrate( 65 | client=pymongo.MongoClient( 66 | uri, event_listeners=[CommandLogger(verbose=verbose)] 67 | ), 68 | database=database, 69 | migrations_dir=migrations, 70 | migrations_collection=collection, 71 | logger=get_logger(verbose), 72 | ) 73 | return f(mongo_migrate, *args, **kwargs) 74 | 75 | return wrap_with_client 76 | 77 | 78 | def _decorate(f, *decorators): 79 | for decorator in reversed(decorators): 80 | f = decorator(f) 81 | return f 82 | 83 | 84 | def mongo_migration_options(f): 85 | return _decorate( 86 | f, 87 | click.option( 88 | "-u", 89 | "--uri", 90 | default=None, 91 | envvar="PYMONGO_MIGRATE_URI", 92 | help="mongodb URI", 93 | ), 94 | click.option( 95 | "-d", 96 | "--database", 97 | default=None, 98 | envvar="PYMONGO_MIGRATE_DATABASE", 99 | help="mongodb database on which to apply migrations", 100 | ), 101 | click.option( 102 | "-m", 103 | "--migrations", 104 | default=MongoMigrate.migrations_dir, 105 | envvar="PYMONGO_MIGRATE_MIGRATIONS", 106 | help="migration script directory", 107 | show_default=True, 108 | ), 109 | click.option( 110 | "-c", 111 | "--collection", 112 | default=MongoMigrate.migrations_collection, 113 | envvar="PYMONGO_MIGRATE_COLLECTION", 114 | help="mongodb collection used for storing migration states", 115 | show_default=True, 116 | ), 117 | click.option("-v", "--verbose", count=True), 118 | mongo_migrate_decor, 119 | ) 120 | 121 | 122 | @cli.command(short_help="show migrations and their status") 123 | @mongo_migration_options 124 | def show(mongo_migrate): 125 | name_len_max = max( 126 | (len(migration.name) for migration in mongo_migrate.get_migrations()), default=0 127 | ) 128 | 129 | migration_column_name = "Migration name".ljust(name_len_max) 130 | click.secho(f"{migration_column_name}\tApplied timestamp", fg="yellow") 131 | for migration in mongo_migrate.get_migrations(): 132 | migration_state = mongo_migrate.get_state(migration) 133 | if migration_state.applied: 134 | applied_text = click.style(migration_state.applied.isoformat(), fg="green") 135 | else: 136 | applied_text = click.style("Not applied", fg="red") 137 | click.echo(f"{migration.name.ljust(name_len_max)}\t" + applied_text) 138 | 139 | 140 | def migrate_cmd_options(f): 141 | return _decorate( 142 | f, 143 | mongo_migration_options, 144 | click.argument("migration", required=False), 145 | click.option("--fake", is_flag=True), 146 | ) 147 | 148 | 149 | @cli.command( 150 | short_help="automagically apply necessary upgrades or downgrades to reach target migration" 151 | ) 152 | @migrate_cmd_options 153 | def migrate(mongo_migrate, migration=None, fake=False): 154 | mongo_migrate.migrate(migration, fake=fake) 155 | 156 | 157 | @cli.command(short_help="apply necessary upgrades to reach target migration") 158 | @migrate_cmd_options 159 | def upgrade(mongo_migrate, migration=None, fake=False): 160 | mongo_migrate.upgrade(migration, fake=fake) 161 | 162 | 163 | @cli.command(short_help="apply necessary downgrades to reach target migration") 164 | @migrate_cmd_options 165 | def downgrade(mongo_migrate, migration, fake=False): 166 | mongo_migrate.downgrade(migration, fake=fake) 167 | 168 | 169 | @cli.command() 170 | @mongo_migration_options 171 | @click.argument("name", required=False) 172 | def generate(mongo_migrate, name: Optional[str] = None): 173 | click.echo(f"Generating new migration in {mongo_migrate.migrations_dir}") 174 | file_path = mongo_migrate.generate(name) 175 | click.echo( 176 | "Generated: " 177 | + click.style(f"{file_path.parent}{os.sep}", fg="bright_black") 178 | + click.style(file_path.stem, fg="green") 179 | + click.style(file_path.suffix, fg="bright_black") 180 | ) 181 | 182 | 183 | @cli.command() 184 | @mongo_migration_options 185 | def graph(mongo_migrate): 186 | stdout = click.get_text_stream("stdout") 187 | dump(mongo_migrate.graph, stdout) 188 | 189 | 190 | if __name__ == "__main__": 191 | cli() 192 | -------------------------------------------------------------------------------- /src/pymongo_migrate/generate.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import re 3 | from pathlib import Path 4 | from typing import List, Optional 5 | 6 | MIGRATION_MODULE_TMPL = '''\ 7 | """ 8 | {description} 9 | """ 10 | import pymongo 11 | 12 | name = {name!r} 13 | dependencies = {dependencies!r} 14 | 15 | 16 | def upgrade(db: "pymongo.database.Database"): 17 | pass 18 | 19 | 20 | def downgrade(db: "pymongo.database.Database"): 21 | pass 22 | ''' 23 | MAX_NAME_LEN = 60 24 | 25 | 26 | def slugify(text: str) -> str: 27 | text = re.sub(r"[\W_]+", "_", text) 28 | text = text.encode("ascii", errors="ignore").decode().lower() 29 | text = text.strip("_") 30 | return text 31 | 32 | 33 | def generate_migration_module( 34 | fp, 35 | name: str, 36 | description: str = "Migration description here!", 37 | dependencies: Optional[List[str]] = None, 38 | ): 39 | dependencies = dependencies or [] 40 | 41 | content = MIGRATION_MODULE_TMPL.format( 42 | name=name, description=description, dependencies=dependencies 43 | ) 44 | fp.write(content) 45 | 46 | 47 | def generate_migration_module_in_dir( 48 | migration_dir: Path, name: str = "", *args, **kwargs 49 | ) -> Path: 50 | now = datetime.datetime.utcnow() 51 | if not name: 52 | name = f"{now:%Y%m%d%H%M%S}" 53 | description = kwargs.get("description") 54 | if description: 55 | name = f"{name}_{slugify(description)}" 56 | name = name[:MAX_NAME_LEN] 57 | file_path = migration_dir / f"{name}.py" 58 | if file_path.exists(): 59 | raise FileExistsError(f"{file_path} already exists") 60 | 61 | with file_path.open("w") as f: 62 | generate_migration_module(f, name=name, *args, **kwargs) # type: ignore 63 | return file_path 64 | -------------------------------------------------------------------------------- /src/pymongo_migrate/graph_draw.py: -------------------------------------------------------------------------------- 1 | """Draw migrations graph""" 2 | 3 | from io import StringIO 4 | from typing import TextIO 5 | 6 | from pymongo_migrate.migrations import MigrationsGraph 7 | 8 | 9 | def dump(graph: MigrationsGraph, output_file: TextIO): 10 | output_file.write("// Migrations\n") 11 | output_file.write("digraph {\n") 12 | for migration in graph.migrations.values(): 13 | for dependency_name in migration.dependencies: 14 | dependency = graph.migrations[dependency_name] 15 | output_file.write(f"\t{dependency.name!r} -> {migration.name!r}\n") 16 | output_file.write("}\n") 17 | 18 | 19 | def dumps(graph: MigrationsGraph) -> str: 20 | with StringIO() as f: 21 | dump(graph, f) 22 | return f.getvalue() 23 | -------------------------------------------------------------------------------- /src/pymongo_migrate/loader.py: -------------------------------------------------------------------------------- 1 | import importlib.util 2 | from pathlib import Path 3 | from typing import Generator, cast 4 | 5 | from pymongo_migrate.migrations import MigrationModuleType, MigrationModuleWrapper 6 | 7 | 8 | def load_module_migrations( 9 | path: Path, namespace=f"{__name__}._migrations" 10 | ) -> Generator[MigrationModuleWrapper, None, None]: 11 | for module_file in path.glob("*.py"): 12 | if module_file.name.startswith("__"): 13 | continue 14 | migration_name = module_file.stem 15 | spec = importlib.util.spec_from_file_location( 16 | f"{namespace}.{migration_name}", str(module_file) 17 | ) 18 | assert spec 19 | migration_module = importlib.util.module_from_spec(spec) 20 | spec.loader.exec_module(migration_module) # type: ignore 21 | yield MigrationModuleWrapper( 22 | name=migration_name, module=cast(MigrationModuleType, migration_module) 23 | ) 24 | -------------------------------------------------------------------------------- /src/pymongo_migrate/migrations.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from collections import defaultdict 3 | from dataclasses import dataclass, field 4 | from types import ModuleType 5 | from typing import Dict, List, Optional, Set 6 | 7 | from pymongo.database import Database 8 | 9 | 10 | @dataclass 11 | class Migration: 12 | name: str 13 | dependencies: List[str] = field(default_factory=list) 14 | 15 | @property 16 | def initial(self): 17 | return not self.dependencies 18 | 19 | def upgrade(self, db: Database): 20 | raise NotImplementedError() 21 | 22 | def downgrade(self, db: Database): 23 | raise NotImplementedError() 24 | 25 | 26 | class MigrationModuleType(ModuleType): 27 | """Migration Module Type stub""" 28 | 29 | name: str 30 | dependencies: List[str] 31 | 32 | def upgrade(self, db: Database): 33 | raise NotImplementedError() 34 | 35 | def downgrade(self, db: Database): 36 | raise NotImplementedError() 37 | 38 | 39 | class MigrationModuleWrapper(Migration): 40 | """Use python module as a migration""" 41 | 42 | def __init__(self, name: str, module: MigrationModuleType): 43 | self.name = name 44 | self.module = module 45 | assert self.name == getattr(self.module, "name", name) 46 | super().__init__(name=name, dependencies=self.module.dependencies) 47 | 48 | @property 49 | def description(self): 50 | return self.module.__doc__ 51 | 52 | def upgrade(self, db: Database): 53 | self.module.upgrade(db) 54 | 55 | def downgrade(self, db: Database): 56 | self.module.downgrade(db) 57 | 58 | 59 | class MigrationsGraph: 60 | def __init__(self): 61 | self.migrations: Dict[str, Migration] = {} 62 | self.required_by: Dict[str, Set[str]] = defaultdict(set) 63 | 64 | def add_migration(self, migration: Migration): 65 | self.migrations[migration.name] = migration 66 | for required_migration_name in migration.dependencies: 67 | self.required_by[required_migration_name].add(migration.name) 68 | 69 | def get_initial(self): 70 | initial_migrations = [m for m in self.migrations.values() if m.initial] 71 | if len(initial_migrations) != 1: 72 | raise ValueError("There must be single initial migration") 73 | return initial_migrations[0] 74 | 75 | def verify(self): 76 | ordered_migration_names = [migration.name for migration in self] 77 | all_migrations = set(self.migrations.keys()) 78 | unused_migrations = all_migrations - set(ordered_migration_names) 79 | if unused_migrations: 80 | raise ValueError("Migration graph is disconnected") 81 | 82 | def __iter__(self): 83 | """ 84 | Iterate over migrations starting with initial one 85 | """ 86 | if not self.migrations: 87 | return 88 | initial_migration = self.get_initial() 89 | yield from self._get_next(initial_migration) 90 | 91 | def _get_next(self, migration): 92 | yield migration 93 | for next_migration_name in sorted(self.required_by.get(migration.name, [])): 94 | next_migration = self.migrations[next_migration_name] 95 | yield from self._get_next(next_migration) 96 | 97 | 98 | @dataclass 99 | class MigrationState: 100 | name: str 101 | applied: Optional[datetime.datetime] = None 102 | -------------------------------------------------------------------------------- /src/pymongo_migrate/mongo_migrate.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | import time 4 | from dataclasses import asdict, dataclass 5 | from pathlib import Path 6 | from typing import Iterator, Optional 7 | 8 | import pymongo 9 | from bson import CodecOptions 10 | 11 | from pymongo_migrate.generate import generate_migration_module_in_dir 12 | from pymongo_migrate.loader import load_module_migrations 13 | from pymongo_migrate.migrations import Migration, MigrationsGraph, MigrationState 14 | 15 | LOGGER = logging.getLogger(__name__) 16 | 17 | 18 | def dt(*args) -> datetime.datetime: 19 | """Create timezone-aware UTC datetime.""" 20 | if args: 21 | return datetime.datetime(*args, tzinfo=datetime.timezone.utc) # type: ignore 22 | else: 23 | return datetime.datetime.now(datetime.timezone.utc) 24 | 25 | 26 | def _serialize(obj): 27 | return asdict(obj) 28 | 29 | 30 | def _deserialize(data, cls): 31 | data = {**data} 32 | del data["_id"] 33 | return cls(**data) 34 | 35 | 36 | class _MeasureTime: 37 | """ 38 | Class to measure the time of execution of code block. 39 | usage: 40 | 41 | with MeasureTime() as mt: 42 | # code block ... 43 | print(f"Execution time: {mt.elapsed}s") 44 | """ 45 | 46 | def __init__(self): 47 | self.start = None 48 | self.stop = None 49 | 50 | @staticmethod 51 | def time() -> float: 52 | return time.time() 53 | 54 | @property 55 | def elapsed(self) -> Optional[float]: 56 | if self.start is None: 57 | return None 58 | return (self.stop or self.time()) - self.start 59 | 60 | def __enter__(self): 61 | self.start = self.time() 62 | return self 63 | 64 | def __exit__(self, exc_type, exc_val, exc_tb): 65 | self.stop = self.time() 66 | 67 | 68 | @dataclass 69 | class MongoMigrate: 70 | client: pymongo.MongoClient 71 | database: str 72 | migrations_dir: str = "./pymongo_migrations" 73 | migrations_collection: str = "pymongo_migrate" 74 | logger: logging.Logger = LOGGER 75 | 76 | def __post_init__(self): 77 | self.graph = MigrationsGraph() 78 | for migration in load_module_migrations(self.migrations_path): 79 | self.graph.add_migration(migration) 80 | self.graph.verify() 81 | 82 | @property 83 | def migrations_path(self): 84 | return Path(self.migrations_dir) 85 | 86 | @property 87 | def db(self): 88 | return self.client.get_database(self.database) 89 | 90 | @property 91 | def db_collection(self): 92 | return self.client.get_database(self.database)[ 93 | self.migrations_collection 94 | ].with_options( 95 | codec_options=CodecOptions(tz_aware=True, tzinfo=datetime.timezone.utc) 96 | ) 97 | 98 | def get_migrations(self) -> Iterator[Migration]: 99 | yield from self.graph 100 | 101 | def get_state(self, migration: Migration) -> MigrationState: 102 | data = self.db_collection.find_one({"name": migration.name}) 103 | if data: 104 | return _deserialize(data, MigrationState) 105 | return MigrationState(name=migration.name) 106 | 107 | def set_state(self, status: MigrationState): 108 | self.db_collection.replace_one( 109 | {"name": status.name}, _serialize(status), upsert=True 110 | ) 111 | 112 | def _check_for_migration( 113 | self, migration_name: Optional[str] 114 | ) -> Optional[Migration]: 115 | if migration_name is None: 116 | return None 117 | migration = self.graph.migrations.get(migration_name) 118 | if migration is None: 119 | raise ValueError(f"No such migration: {migration_name}") 120 | return migration 121 | 122 | def migrate(self, migration_name: Optional[str] = None, fake: bool = False): 123 | """ 124 | Automatically detects if upgrades or downgrades should be applied to 125 | reach target migration state. 126 | 127 | :param migration_name: 128 | target migration 129 | None if all upgrades should be applied 130 | :param fake: 131 | If True, only migration state in database will be modified and 132 | no actual migration will be run. 133 | """ 134 | if migration_name is None: 135 | self.logger.debug("Migration target not specified, assuming upgrade") 136 | self.upgrade(fake=fake) 137 | return 138 | migration = self._check_for_migration(migration_name) 139 | assert migration, "No matching migration, something went wrong" 140 | migration_state = self.get_state(migration) 141 | if migration_state.applied: 142 | self.logger.debug("Migration target already applied, assuming downgrade") 143 | self.downgrade(migration_name, fake) 144 | else: 145 | self.logger.debug("Migration target not applied, assuming upgrade") 146 | self.upgrade(migration_name, fake) 147 | 148 | def upgrade(self, migration_name: Optional[str] = None, fake: bool = False): 149 | """ 150 | Apply upgrade migrations. 151 | 152 | :param migration_name: 153 | name of migration up to which (including) upgrades should be executed 154 | None if all migrations should be run 155 | :param fake: 156 | If True, only migration state in database will be modified and 157 | no actual migration will be run. 158 | """ 159 | self._check_for_migration(migration_name) 160 | for migration in self.graph: 161 | migration_state = self.get_state(migration) 162 | if migration_state.applied: 163 | self.logger.debug( 164 | "Migration %r already applied, skipping", migration.name 165 | ) 166 | continue 167 | if fake: 168 | self.logger.info("Fake running upgrade migration %r", migration.name) 169 | else: 170 | self.logger.info("Running upgrade migration %r", migration.name) 171 | with _MeasureTime() as mt: 172 | migration.upgrade(self.db) 173 | self.logger.info( 174 | "Execution time of %r: %s seconds", migration.name, mt.elapsed 175 | ) 176 | migration_state.applied = dt() 177 | self.set_state(migration_state) 178 | if migration.name == migration_name: 179 | break 180 | 181 | def downgrade(self, migration_name: Optional[str] = None, fake: bool = False): 182 | """ 183 | Reverse migrations. 184 | 185 | :param migration_name: 186 | name of migration down to which (excluding) downgrades should be executed 187 | None if all migrations should be run 188 | :param fake: 189 | If True, only migration state in database will be modified and 190 | no actual migration will be run. 191 | """ 192 | self._check_for_migration(migration_name) 193 | for migration in reversed(list(self.get_migrations())): 194 | if migration.name == migration_name: 195 | break 196 | migration_state = self.get_state(migration) 197 | if not migration_state.applied: 198 | self.logger.debug( 199 | "Migration %r not yet applied, skipping", migration.name 200 | ) 201 | continue 202 | if fake: 203 | self.logger.info("Fake running downgrade migration %r", migration.name) 204 | else: 205 | self.logger.info("Running downgrade migration %r", migration.name) 206 | with _MeasureTime() as mt: 207 | migration.downgrade(self.db) 208 | self.logger.info( 209 | "Execution time of %r: %s seconds", migration.name, mt.elapsed 210 | ) 211 | migration_state.applied = None 212 | self.set_state(migration_state) 213 | 214 | def generate(self, name: str = "", **kwargs) -> Path: 215 | last_migration_name = None 216 | for migration in self.get_migrations(): 217 | last_migration_name = migration.name 218 | self.migrations_path.mkdir(exist_ok=True) 219 | dependencies = [last_migration_name] if last_migration_name else [] 220 | return generate_migration_module_in_dir( 221 | self.migrations_path, 222 | name=name, 223 | dependencies=dependencies, 224 | **{k: v for k, v in kwargs.items() if v is not None}, 225 | ) 226 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import random 2 | import shutil 3 | from datetime import timezone 4 | from pathlib import Path 5 | from typing import Dict 6 | 7 | import pymongo 8 | import pytest 9 | from bson import CodecOptions 10 | from pymongo_migrate.mongo_migrate import MongoMigrate 11 | 12 | TEST_DIR = Path(__file__).parent 13 | 14 | 15 | @pytest.fixture 16 | def mongo_url(): 17 | return "mongodb://localhost:27017/" 18 | 19 | 20 | @pytest.fixture 21 | def db_name(): 22 | random_id = random.randint(100, 10_000_000) # nosec 23 | return f"test_{random_id}" 24 | 25 | 26 | @pytest.fixture 27 | def db_uri(mongo_url, db_name): 28 | return f"{mongo_url}{db_name}" 29 | 30 | 31 | @pytest.fixture 32 | def db(mongo_url, db_name): 33 | client = pymongo.MongoClient(mongo_url) 34 | yield client[db_name] 35 | client.drop_database(db_name) 36 | client.close() 37 | 38 | 39 | @pytest.fixture 40 | def db_collection(db): 41 | return db.get_collection( 42 | "pymongo_migrate", 43 | codec_options=CodecOptions(tz_aware=True, tzinfo=timezone.utc), 44 | ) 45 | 46 | 47 | def _dir_contents(dir_path: Path) -> Dict[str, str]: 48 | dir_contents = {} 49 | for file_ in dir_path.iterdir(): 50 | if file_.is_file(): 51 | with file_.open() as f: 52 | dir_contents[f.name] = f.read() 53 | return dir_contents 54 | 55 | 56 | @pytest.fixture(scope="session") 57 | def migrations_dir(tmp_path_factory): 58 | original_migrations_path = TEST_DIR / "migrations" 59 | migrations_path = tmp_path_factory.mktemp("test_session") / "migrations" 60 | shutil.copytree(original_migrations_path, migrations_path) 61 | pre_contents = _dir_contents(migrations_path) 62 | yield str(migrations_path) 63 | assert pre_contents == _dir_contents( 64 | migrations_path 65 | ), "Migrations mangled during tests" 66 | 67 | 68 | @pytest.fixture 69 | def mongo_migrate(db_uri, db_name, db, migrations_dir): 70 | mm = MongoMigrate( 71 | pymongo.MongoClient(db_uri), db_name, migrations_dir=migrations_dir 72 | ) 73 | yield mm 74 | mm.client.close() 75 | 76 | 77 | @pytest.fixture() 78 | def get_db_migrations(db_collection): 79 | def getter(): 80 | return list(db_collection.find(projection={"_id": False}, sort=[("name", 1)])) 81 | 82 | return getter 83 | -------------------------------------------------------------------------------- /tests/migrations/20150612230153.py: -------------------------------------------------------------------------------- 1 | """ 2 | Initial migration 3 | 4 | Adds 1000 numbers to numbers collection. 5 | """ 6 | name = "20150612230153" 7 | dependencies = [] 8 | 9 | 10 | def upgrade(db): 11 | db.numbers_collection.insert_many([{"i": i} for i in range(1000)]) 12 | 13 | 14 | def downgrade(db): 15 | db.numbers_collection.drop() 16 | -------------------------------------------------------------------------------- /tests/migrations/20181123000000_gt_500.py: -------------------------------------------------------------------------------- 1 | """ 2 | We decided we don't like numbers <=500 anymore 3 | """ 4 | name = "20181123000000_gt_500" 5 | dependencies = ["20150612230153"] 6 | 7 | 8 | def upgrade(db): 9 | db.numbers_collection.delete_many({"i": {"$lt": 501}}) 10 | 11 | 12 | def downgrade(db): 13 | db.numbers_collection.insert_many([{"i": i} for i in range(501)]) 14 | -------------------------------------------------------------------------------- /tests/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stxnext/pymongo-migrate/e5f5f8ebc63b6ce07eccf9ce9315cfee5caade7c/tests/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | import freezegun 2 | import pytest 3 | from click.testing import CliRunner 4 | from pymongo_migrate.cli import cli 5 | 6 | 7 | @pytest.fixture 8 | def cli_runner(): 9 | return CliRunner() 10 | 11 | 12 | @pytest.fixture() 13 | def invoker(cli_runner): 14 | def invoke_wrap(*args, **kwargs): 15 | return cli_runner.invoke(cli, *args, **kwargs) 16 | 17 | return invoke_wrap 18 | 19 | 20 | def test_show(invoker, db, db_uri, migrations_dir): 21 | result = invoker( 22 | ["show", "-u", db_uri, "-m", migrations_dir], catch_exceptions=False 23 | ) 24 | 25 | assert ( 26 | result.stdout 27 | == """\ 28 | Migration name Applied timestamp 29 | 20150612230153 Not applied 30 | 20181123000000_gt_500 Not applied 31 | """ 32 | ) 33 | 34 | 35 | @freezegun.freeze_time("2019-02-03 04:05:06") 36 | def test_generate(invoker, db, db_uri, tmp_path): 37 | migrations_path = tmp_path / "migrations" 38 | result = invoker( 39 | ["generate", "-u", db_uri, "-m", str(migrations_path)], catch_exceptions=False 40 | ) 41 | filename = "20190203040506.py" 42 | assert filename in result.stdout 43 | files = {f.name: f for f in migrations_path.iterdir()} 44 | assert set(files) == {filename} 45 | with files[filename].open() as f: 46 | content = f.read() 47 | assert ( 48 | content 49 | == '''\ 50 | """ 51 | Migration description here! 52 | """ 53 | import pymongo 54 | 55 | name = '20190203040506' 56 | dependencies = [] 57 | 58 | 59 | def upgrade(db: "pymongo.database.Database"): 60 | pass 61 | 62 | 63 | def downgrade(db: "pymongo.database.Database"): 64 | pass 65 | ''' 66 | ) 67 | 68 | 69 | def test_migrate(invoker, db, db_uri, migrations_dir): 70 | result = invoker( 71 | ["migrate", "-u", db_uri, "-m", migrations_dir], catch_exceptions=False 72 | ) 73 | 74 | assert "Running upgrade migration '20150612230153'" in result.stdout 75 | 76 | 77 | def test_migrate_fake(invoker, db, db_uri, migrations_dir): 78 | result = invoker( 79 | ["migrate", "-u", db_uri, "-m", migrations_dir, "--fake"], 80 | catch_exceptions=False, 81 | ) 82 | 83 | assert "Fake running upgrade migration '20150612230153'" in result.stdout 84 | 85 | 86 | def test_migrate_verbose(invoker, db, db_uri, migrations_dir): 87 | result = invoker( 88 | ["migrate", "-u", db_uri, "-m", migrations_dir, "-vv"], catch_exceptions=False 89 | ) 90 | 91 | assert "Command update#" in result.stdout 92 | -------------------------------------------------------------------------------- /tests/test_generate.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pymongo_migrate.generate import slugify 3 | 4 | 5 | @pytest.mark.parametrize( 6 | "test_input,expected", 7 | [ 8 | ("My comment", "my_comment"), 9 | ("counting: 1, 2, 3", "counting_1_2_3"), 10 | ("wat?!", "wat"), 11 | ("mały żółwik", "may_wik"), 12 | ], 13 | ) 14 | def test_slugify(test_input, expected): 15 | assert slugify(test_input) == expected 16 | -------------------------------------------------------------------------------- /tests/test_main_status.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pymongo_migrate.migrations import Migration, MigrationState 3 | from pymongo_migrate.mongo_migrate import dt 4 | 5 | 6 | @pytest.fixture 7 | def migration(): 8 | return Migration(name="2019_test") 9 | 10 | 11 | def test_get_state_when_migration_not_applied(mongo_migrate, db, migration): 12 | assert mongo_migrate.get_state(migration) == MigrationState( 13 | name=migration.name, applied=None 14 | ) 15 | 16 | 17 | def test_get_state_when_migration_not_applied_but_in_db( 18 | mongo_migrate, db_collection, migration 19 | ): 20 | db_collection.insert_one({"name": migration.name, "applied": None}) 21 | assert mongo_migrate.get_state(migration) == MigrationState( 22 | name=migration.name, applied=None 23 | ) 24 | 25 | 26 | def test_get_state_when_migration_applied(mongo_migrate, db_collection, migration): 27 | now = dt().replace(microsecond=0) # reduced time resolution 28 | db_collection.insert_one({"name": migration.name, "applied": now}) 29 | assert mongo_migrate.get_state(migration) == MigrationState( 30 | name=migration.name, applied=now 31 | ) 32 | 33 | 34 | def test_set_state(mongo_migrate, migration, get_db_migrations): 35 | now = dt().replace(microsecond=0) # reduced time resolution 36 | mongo_migrate.set_state(MigrationState(name=migration.name, applied=now)) 37 | all_migrations = get_db_migrations() 38 | assert all_migrations == [{"name": migration.name, "applied": now}] 39 | -------------------------------------------------------------------------------- /tests/test_mongo_migrate.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from unittest.mock import Mock, patch 3 | 4 | import freezegun 5 | from pymongo_migrate.mongo_migrate import dt 6 | 7 | 8 | def test_get_migrations(mongo_migrate): 9 | assert [migration.name for migration in mongo_migrate.get_migrations()] == [ 10 | "20150612230153", 11 | "20181123000000_gt_500", 12 | ] 13 | 14 | 15 | @freezegun.freeze_time("2019-02-03 04:05:06") 16 | def test_upgrade(mongo_migrate, db, get_db_migrations): 17 | mongo_migrate.upgrade() 18 | 19 | db_migrations = get_db_migrations() 20 | assert db_migrations == [ 21 | {"applied": dt(2019, 2, 3, 4, 5, 6), "name": "20150612230153"}, 22 | {"applied": dt(2019, 2, 3, 4, 5, 6), "name": "20181123000000_gt_500"}, 23 | ] 24 | 25 | assert db.numbers_collection.count_documents({}) == 499 26 | 27 | 28 | @freezegun.freeze_time("2019-02-03 04:05:06") 29 | def test_upgrade_fake(mongo_migrate, db, get_db_migrations): 30 | mongo_migrate.upgrade(fake=True) 31 | 32 | db_migrations = get_db_migrations() 33 | assert db_migrations == [ 34 | {"applied": dt(2019, 2, 3, 4, 5, 6), "name": "20150612230153"}, 35 | {"applied": dt(2019, 2, 3, 4, 5, 6), "name": "20181123000000_gt_500"}, 36 | ] 37 | 38 | assert db.numbers_collection.count_documents({}) == 0 39 | 40 | 41 | @freezegun.freeze_time("2019-02-03 04:05:06") 42 | def test_upgrade_skip_applied(mongo_migrate, db, db_collection, get_db_migrations): 43 | db_collection.insert_one( 44 | {"applied": dt(2017, 10, 10, 10, 10, 10), "name": "20150612230153"} 45 | ) 46 | 47 | migrations = {m.name: m for m in mongo_migrate.get_migrations()} 48 | upgrade_mocks = defaultdict(Mock) 49 | 50 | def patch_upgrade(name): 51 | return patch.object(migrations[name], "upgrade", upgrade_mocks[name]) 52 | 53 | with patch_upgrade("20150612230153"), patch_upgrade("20181123000000_gt_500"): 54 | mongo_migrate.upgrade() 55 | upgrade_mocks["20150612230153"].assert_not_called() 56 | upgrade_mocks["20181123000000_gt_500"].assert_called() 57 | 58 | assert get_db_migrations() == [ 59 | {"applied": dt(2017, 10, 10, 10, 10, 10), "name": "20150612230153"}, 60 | {"applied": dt(2019, 2, 3, 4, 5, 6), "name": "20181123000000_gt_500"}, 61 | ] 62 | 63 | 64 | def test_downgrade(mongo_migrate, db, get_db_migrations): 65 | mongo_migrate.downgrade(None) 66 | db_migrations = get_db_migrations() 67 | assert db_migrations == [] 68 | assert db.list_collection_names() == [] 69 | 70 | 71 | def test_downgrade_fake(mongo_migrate, db, get_db_migrations): 72 | mongo_migrate.upgrade() 73 | mongo_migrate.downgrade(fake=True) 74 | 75 | db_migrations = get_db_migrations() 76 | assert db_migrations == [ 77 | {"applied": None, "name": "20150612230153"}, 78 | {"applied": None, "name": "20181123000000_gt_500"}, 79 | ] 80 | 81 | assert db.numbers_collection.count_documents({}) == 499 82 | 83 | 84 | def test_upgrade_n_downgrade(mongo_migrate, db, get_db_migrations): 85 | mongo_migrate.upgrade() 86 | mongo_migrate.downgrade(None) 87 | db_migrations = get_db_migrations() 88 | assert db_migrations == [ 89 | {"applied": None, "name": "20150612230153"}, 90 | {"applied": None, "name": "20181123000000_gt_500"}, 91 | ] 92 | assert db.list_collection_names() == ["pymongo_migrate"] 93 | 94 | 95 | def test_migrate(mongo_migrate): 96 | """migrate without args should work as upgrade""" 97 | with patch.object(mongo_migrate, "upgrade") as upgrade_mock: 98 | mongo_migrate.migrate() 99 | upgrade_mock.assert_called() 100 | -------------------------------------------------------------------------------- /tests/test_mongo_migrate_generate.py: -------------------------------------------------------------------------------- 1 | import freezegun 2 | import pymongo 3 | import pytest 4 | from pymongo_migrate.mongo_migrate import MongoMigrate 5 | 6 | 7 | @freezegun.freeze_time("2019-02-25 01:13:56") 8 | def test_generate(mongo_migrate, tmp_path): 9 | tmp_migrations_path = tmp_path / "test_generate_migrations" 10 | mongo_migrate.migrations_dir = str(tmp_migrations_path) 11 | filename = mongo_migrate.generate().name 12 | assert filename == "20190225011356.py" 13 | files = {f.name: f for f in tmp_migrations_path.iterdir()} 14 | assert set(files) == {filename} 15 | with files[filename].open() as f: 16 | content = f.read() 17 | assert ( 18 | content 19 | == '''\ 20 | """ 21 | Migration description here! 22 | """ 23 | import pymongo 24 | 25 | name = '20190225011356' 26 | dependencies = ['20181123000000_gt_500'] 27 | 28 | 29 | def upgrade(db: "pymongo.database.Database"): 30 | pass 31 | 32 | 33 | def downgrade(db: "pymongo.database.Database"): 34 | pass 35 | ''' 36 | ) 37 | 38 | 39 | @pytest.fixture 40 | def empty_migrations_dir(tmp_path): 41 | yield tmp_path / "migrations" 42 | 43 | 44 | @pytest.fixture 45 | def mongo_migrate_with_empty_dir(db_uri, db_name, db, empty_migrations_dir): 46 | mm = MongoMigrate( 47 | pymongo.MongoClient(db_uri), db_name, migrations_dir=str(empty_migrations_dir) 48 | ) 49 | yield mm 50 | mm.client.close() 51 | 52 | 53 | @freezegun.freeze_time("2019-02-03 04:05:06") 54 | def test_generate_initial_migration(mongo_migrate_with_empty_dir, empty_migrations_dir): 55 | mongo_migrate = mongo_migrate_with_empty_dir 56 | filename = mongo_migrate.generate().name 57 | assert filename == "20190203040506.py" 58 | files = {f.name: f for f in empty_migrations_dir.iterdir()} 59 | assert set(files) == {filename} 60 | with files[filename].open() as f: 61 | content = f.read() 62 | assert ( 63 | content 64 | == '''\ 65 | """ 66 | Migration description here! 67 | """ 68 | import pymongo 69 | 70 | name = '20190203040506' 71 | dependencies = [] 72 | 73 | 74 | def upgrade(db: "pymongo.database.Database"): 75 | pass 76 | 77 | 78 | def downgrade(db: "pymongo.database.Database"): 79 | pass 80 | ''' 81 | ) 82 | 83 | 84 | def test_generate_should_fail_when_name_collides(mongo_migrate): 85 | with pytest.raises(FileExistsError): 86 | mongo_migrate.generate("20181123000000_gt_500") 87 | --------------------------------------------------------------------------------