Alembic for Database Migrations

Git Commit: add alembic to project
Just like GIT, Alembic is the doctor strange for Database. Let's say we add a column named "price" for the product table and its datatype is Decimal. After some days, a super smart developer changed its datatype to float. If we want to change the datatype back to decimal for greater precision, We will need to write an ALTER statement and execute it on the server. This is a very simple example, however, database changes can be massive. Things can go really bad if we execute one wrong ALTER statement.

To make things simpler, we can use Alembic to manage the migrations for us. Let's get started with Alembic. Modify the requirements.txt file to have alembic version information and do a pip install -r requirements.txt

###
alembic==1.11.1

Once Alembic is installed, we can come to the root folder where main.py file is and execute alembic init alembic

algoholic.io/
 └─core/
 └─db/
 └─requirements.txt
 └─main.py
 

This will lead to a new file named alembic.ini and a directory named alembic. There are two approaches now: First. The only thing that we want to edit in alembic.ini file is sqlalchemy.url For me its value would be postgresql://nofoobar:supersecret@localhost:5432/blogdb  where nofoobar is the database username, supersecret is the password and blogdb is the name of the database. But, this is not safe as we will commit the alembic.ini file and our database URL will be visible to the world!
Second Approach:
We can set the URL in the env.py file in a more secure manner.  env.py file is inside the alembic directory. In the env.py file, import Base from db/base.py and set the target metadata.

from alembic import context

#new
from core.config import settings  
from db.base import Base

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

#new
config.set_main_option("sqlalchemy.url",settings.DATABASE_URL)

target_metadata = Base.metadata  #find and replace target_metadata with Base.metadata

I am going to create a new file named db/base.py to keep track of all our upcoming sqlalchemy models. For now it would be as simple as:

from db.base_class import Base

Since right now we don't have any models, so alembic would be creating empty migrations files on executing : alembic revision --autogenerate -m "first commit" You can find the generated file inside alembic/versions/
 

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial