0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ハッカソン個人備忘録㉚:FastAPIでのマイグレーションをMakefileに登録してみた記録

Posted at

はじめに

FastAPI + SQLAlchemy 構成で Alembic を使用している場合、MySQL に対するマイグレーション処理を Makefile に追加しておくと便利です。

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

ここでは docker compose を利用した開発環境において、簡単にマイグレーション操作ができるようにするためのコマンドを紹介します。

書こうと思ったきっかけ

FastAPI と SQLAlchemy を使った開発において、毎回手動で Alembic コマンドを実行するのが手間だと感じたため、Makefile に定義して効率的に操作できるようにしようと考えました。

Makefile に Alembic マイグレーション処理を追加する方法

追加する Makefile のコマンド

以下の2つのターゲットを Makefile に追記してください。

migrate:
	docker exec -it fastapi-app alembic upgrade head

makemigration:
	docker exec -it fastapi-app alembic revision --autogenerate -m "New migration"

コマンドの説明

コマンド名 内容
make migrate Alembic によるマイグレーションを実行します(最新の状態へ)
make makemigration 現在のモデルの状態を元に新しいマイグレーションファイルを自動生成します

使用例

# モデルを変更したらマイグレーションファイルを作成
make makemigration

# DBにマイグレーションを適用
make migrate

補足

  • fastapi-app は Alembic がインストールされているコンテナ名です。プロジェクトによって異なる場合は適宜変更してください。
  • alembic.inimigrations ディレクトリが適切に設定されている必要があります。

まとめ

Alembic のマイグレーション操作を Makefile に登録することで、開発時のコマンド実行が簡潔になり、作業ミスの防止や効率化に繋がります。

特にチーム開発では、共通の操作方法を提供することで、作業の統一性も保つことができます!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?