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?

【Python】alembicで、レコードの値を変更せずにカラム名を変更する方法

Posted at

概要

Alembicにて、レコードの値を変更せずに、カラム名を変更する方法を紹介します。

マイグレーションファイル

例えば、以下はcreated_atからcreate_dateに変更する場合のマイグレーションファイル。SQLを直接実行するパターンですね。

def upgrade() -> None:
    # カラム名を直接変更
    op.execute('ALTER TABLE sample_table CHANGE COLUMN created_at create_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP')

def downgrade() -> None:
    # カラム名を元に戻す
    op.execute('ALTER TABLE sample_table CHANGE COLUMN create_date created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP')

もしくは以下のように「追加」「更新」「削除」を行なって変更していく方法でも実現できました。

def upgrade() -> None:
    op.add_column('sample_table', sa.Column('create_date', sa.DateTime(), nullable=True))
    op.execute('UPDATE sample_table SET create_date = created_at')
    op.alter_column('sample_table', 'create_date', existing_type=mysql.DATETIME(), server_default=sa.text('now()'), nullable=False)
    op.drop_column('sample_table', 'created_at')

def downgrade() -> None:
    op.add_column('sample_table', sa.Column('created_at', sa.DateTime(), nullable=True))
    op.execute('UPDATE sample_table SET created_at = create_date')
    op.alter_column('sample_table', 'created_at', existing_type=mysql.DATETIME(), server_default=sa.text('now()'), nullable=False)
    op.drop_column('sample_table', 'create_date')

以上!

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?