🤖
【Alembic】マイグレーションファイルの作成と更新について
実施手順
- マイグレーションの履歴を表示する
$ alembic history dn8gzx3n9vdj -> ns1qzx2q1szv (head), add column age members table <base> -> dn8gzx3n9vdj, create members table - 現在のマイグレーションのバージョンを確認する
$ alembic current ns1qzx2q1szv (head) - マイグレーションファイルを生成する
$ alembic revision --autogenerate -m "コメント" - マイグレーションファイルを編集する
- マイグレーションファイルを反映する
$ alembic upgrade head
マイグレーションファイルの編集
テーブル
"""create teams table
Revision ID: xi7qeh4v9wsf
Revises: ns1qzx2q1szv
Create Date: 2025-08-29 11:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "xi7qeh4v9wsf"
down_revision: Union[str, None] = "ns1qzx2q1szv"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"teams",
sa.Column("id", sa.String(), primary_key=True, nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("createdAt", sa.String(), nullable=True),
sa.Column("updatedAt", sa.String(), nullable=True),
)
op.create_index(op.f("ix_teams_id"), "teams", ["id"], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
op.drop_table("teams")
カラム
"""add column_birthday_gender in members table
Revision ID: qf2prs7z2hlx
Revises: xi7qeh4v9wsf
Create Date: 2025-08-29 12:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'qf2prs7z2hlx'
down_revision: Union[str, None] = 'xi7qeh4v9wsf'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"members",
sa.Column("birthday", sa.Date(), nullable=True),
)
op.add_column(
"members",
sa.Column("gender", sa.Integer(), nullable=False), # 0:man, 1:woman, 2:other
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("members", "birthday")
op.drop_column("members", "gender")
# ### end Alembic commands ###
Discussion