firstly: thanks so much for this - it allowed me to get started with relational databases in fastapi really quickly. Thanks!!
from pydantic import BaseSettings
class Settings(BaseSettings):
db_name: str = "app"
db_user: str = "postgres"
db_password: str = "postgres"
db_host: str = "localhost"
db_port: int = 5432
def db_conn_string(self):
return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
settings = Settings()
engine = create_async_engine(settings.db_conn_string(), echo=True, future=True)
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import SQLModel
from app.settings import Settings
settings = Settings()
config = context.config
fileConfig(config.config_file_name)
target_metadata = SQLModel.metadata
def run_migrations_offline():
url = settings.db_conn_string()
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online():
connectable = create_async_engine(settings.db_conn_string(), echo=True, future=True)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
i don't know if you take PRs for this project, but for the first issue I saw some comment in the alembic github discussion that looked very similar to this code so it would probably be a big help to the community if that was fixed. If you want these suggestions in a PR instead I'd be happy to make one.