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

alembicで外部キーを追加するときはCONSTRAINT 名を明示した方がいい

Posted at

普通に alembic revision --autogenerate -m "add_os_version_id" でマイグレーションスクリプトを自動生成すると、 op.create_foreign_key op.drop_constraint の第一引数(CONSTRAINT名)が None となってしまう。

このスクリプトは alembic downgrade base 時に削除すべきCONSTERAINT名がわからずエラーになってしまう。

"""add_os_version_id

Revision ID: 6479768cd289
Revises: ecd9896cb55a
Create Date: 2024-01-25 11:40:11.027316

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '6479768cd289'
down_revision = 'ecd9896cb55a'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    op.add_column('devices', sa.Column('os_version_id', sa.Integer(), nullable=True))
    op.create_foreign_key(None, 'devices', 'os_versions', ['os_version_id'], ['id'], ondelete='RESTRICT')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'devices', type_='foreignkey')
    op.drop_column('devices', 'os_version_id')
    # ### end Alembic commands ###

op.create_foreign_key op.drop_constraint の第一引数(CONSTRAINT名)に何らかの値を定義してあげると、alembic downgrade base でエラーにならなくなる。

"""add_os_version_id

Revision ID: 6479768cd289
Revises: ecd9896cb55a
Create Date: 2024-01-25 11:40:11.027316

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '6479768cd289'
down_revision = 'ecd9896cb55a'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    op.add_column('devices', sa.Column('os_version_id', sa.Integer(), nullable=True))
    op.create_foreign_key("fk_devices_os_versions_id", 'devices', 'os_versions', ['os_version_id'], ['id'], ondelete='RESTRICT')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("fk_devices_os_versions_id", 'devices', type_='foreignkey')
    op.drop_column('devices', 'os_version_id')
    # ### end Alembic commands ###
1
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
1
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?