l.b.vasoya
l.b.vasoya

Reputation: 1221

How to manage sqlalchemy model migration in fastapi

I have used fastapi for project facing issue with sqlachemy model

sqlachemy create model first time but when we change in model not affect on postgres database. Overcome this problem.

like: rename is_superuser to is_admin

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("user", sa.Column("is_admin", sa.Boolean(), nullable=True))
    op.drop_column("user", "is_superuser")
    # ### end Alembic commands ###

see what's going on droping is_superuser column inted of rename

I know the tricky solution is custom adding action in migration op.alter_column('table_name','column_name',new_column_name='new column name')

How to handle model migration with sqlalchemy in fastapi because if i will make mistake in alembic migration it would be denger for me.

Is there any other package or way to handle migration with sqlalchemy

Upvotes: 7

Views: 3850

Answers (1)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11695

use case: rename column from is_superuser to is_admin in the table user

1. using alembic operations

For the above case, we can write the migration like below.

def upgrade():
    op.alter_column('user', 'is_superuser', nullable=True, new_column_name='is_admin')

Now, run the command alembic upgrade head --sql to see the actual SQL that will be applied on the databse.

ALTER TABLE user RENAME is_superuser TO is_admin;

2. using custom SQL

def upgrade():
    op.execute('ALTER TABLE user RENAME is_superuser TO is_admin;')

run command alembic upgrade head to apply the migration on the database.

Reference:

Upvotes: 1

Related Questions