You don't need to change alembic.ini
to set up a database connection.
Alembic will derive database connection uri from settings.yaml
(or any yaml which you specify in SETTINGS_PATH
environment variable).
Example of settings.yaml
:
db_uri: "postgresql+asyncpg://postgres:postgres@localhost:5432/postgres"
You don't need to separate the database connection setup between your async application and the alembic - just use same async driver.
You don't need to manually check and delete empty auto-migrations.
You don't need to run ruff format after each migration, because alembic will do it for you.
You don't need to remember the migration sequence, now the files are sorted by time and human-readable.
- Clone files from this gist to your project.
- Add ruff to your project.
- Setup alembic folder:
mkdir -p alembic/versions
mv script.py.mako alembic/
mv env.py alembic/
mv ALEMBIC.md alembic/README.md
touch alembic/versions/.gitkeep
- Make sure the sqlalchemy metadata is imported correctly.
alembic/env.py
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from src.database.models.db import Base # noqa: E402
target_metadata = Base.metadata
### Read yaml settings
`alembic/env.py`
```python3
app_settings_path = os.getenv("SETTINGS_PATH", "settings.yaml")
app_settings = safe_load(Path(app_settings_path).read_text())
# get database uri from settings.yaml
config.set_main_option("sqlalchemy.url", app_settings["db_uri"])
alembic/env.py
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
alembic.ini
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
file_template = _%%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d_%%(minute).2d_%%(slug)s
alembic.ini
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
hooks = ruff
ruff.type = exec
ruff.executable = poetry
ruff.options = run ruff format REVISION_SCRIPT_FILENAME
alembic/env.py
def process_revision_directives(context, revision, directives):
if config.cmd_opts.autogenerate:
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
print("No changes in schema detected.")
MIT License
Copyright (c) 2024 Ruslan Belkov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.