1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SQLAlchemy×Alembicでマイグレーション

Posted at

はじめに

よくFastAPIのマイグレーションしようとしたときに、接続先を
sqlalchemy.url = mysql+pymysql://root:root-password@host:port/database
こんな感じにすると非同期とか考えなくていいらしく正常に行くが、
接続先を下のような感じにすると、asyncが~とかawait~がとか怒られうまくいかない。
mysql+asyncmy://root:root-password@host:port/database

日本語で検索しても今回のようにasyncmyの場合の情報が出てこなかったので参考までにどうぞ・・・

流れ

※ライブラリのインストール後の流れになります。。。

alembic init migrations

上記コマンドを対象のapp直下で実行(場所はどこでもいいはず・・・)
すると下のような感じになります。

app
├── migrations
│   ├── versions
│   ├── env.py
│   ├── README
│   └── script.py.mako
└── alembic.ini

そうしたら、env.pyを修正してコマンドを実行したらOK

コード

env.py
import asyncio
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlalchemy.ext.asyncio import AsyncEngine

config = context.config
config.set_main_option("sqlalchemy.url", "mysql+asyncmy://root:root-password@host:port/database")

fileConfig(config.config_file_name)

# ここに作成したModelクラスをimport
# from models.manager import Sample

target_metadata = Base.metadata

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 = AsyncEngine(
        engine_from_config(
            config.get_section(config.config_ini_section),
            prefix="sqlalchemy.",
            poolclass=pool.NullPool,
            future=True,
        )
    )
    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)

    await connectable.dispose()

if context.is_offline_mode():
    run_migrations_offline()
else:
    asyncio.run(run_migrations_online())

実行コマンド

※今回はDockerで環境構築しているので、コンテナ内に入って実行

docker compose exec {app名} alembic revision --autogenerate -m "create tables"
docker compose exec {app名} alembic upgrade head
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?