Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Alembic Database Migrations

Alembic Database Migrations

In this chapter you'll learn to manage database schema changes with Alembic and understand how it compares to Django Migration and Flask-Migrate.


Why do you need a migration tool?

Base.metadata.create_all() also has a fatal flaw: it only creates a table if it doesn't exist, and changes to existing table structures aren't synced automatically.

Alembic is SQLAlchemy's official migration tool; Django's makemigrations/migrate and Flask's Flask-Migrate are both based on Alembic's design under the hood.


Installation and initialization



(venv) $ pip install alembic

(venv) $ alembic init alembic

Creating directory alembic/... done

Generated directory structure:



alembic/

├── versions/          # 迁移脚本存放目录

├── env.py             # 迁移环境配置(需手动修改!)

└── script.py.mako     # 迁移脚本模板

alembic.ini            # Alembic 配置文件


Configure env.py to connect to your models

This is the key step—Alembic doesn't know where your SQLAlchemy models are by default.

Example

File path: alembic/env.py (modify the key parts)

import

sys

from

pathlib

import

Path

Add the project root to sys.path (so you can import your own modules)

sys

.

path

.

insert

(

0

,

str

(

Path

(

file

)

.

resolve

(

)

.

parent

.

parent

)

)

from

database

import

Base

,

engine

from

models

import

Category

,

Post  

Import all models to ensure Base.metadata includes them

target_metadata must be set to the models' metadata

target_metadata

=

Base.

metadata

Also modify alembic.ini the database connection in the file:



# File path: alembic.ini

sqlalchemy.url = sqlite:///./blog.db


The three-step migration process

Step Command Purpose Compared with Django
Initialization alembic init alembic Create the migration environment (only once) —
Generation alembic revision --autogenerate -m "description" Detect model changes and generate migration scripts makemigrations
Executing alembic upgrade head Execute all unapplied migrations migrate

Generate and run the migration



(venv) $ alembic revision --autogenerate -m "初始化 Post 和 Category 模型"

INFO  [alembic.autogenerate] Detected added table 'categories'

INFO  [alembic.autogenerate] Detected added table 'posts'

Generating alembic/versions/xxxx_initial.py ... done



(venv) $ alembic upgrade head

INFO  [alembic.runtime.migration] Running upgrade -> xxxx, 初始化


Hands-on: adding a read_count field

Example

File path: add to the Post class in models.py

class

Post

(

Base

)

:

   

... existing fields ...

    read_count

=

Column

(

Integer

,

default

=

0

)

 

Read count



(venv) $ alembic revision --autogenerate -m "Post 新增 read_count 字段"

(venv) $ alembic upgrade head

Rollback



(venv) $ alembic downgrade -1        # 回退到上一个版本

alembic upgrade head The head represents the latest version. You can also specify a specific version number:alembic upgrade xxxx(version ID).


Comparison of migration tools across the three frameworks

Operation Django Flask(Flask-Migrate) FastAPI(Alembic)
Initialization No need to flask db init alembic init alembic
Generate migration makemigrations flask db migrate -m "description" alembic revision --autogenerate -m "description"
Run migration migrate flask db upgrade alembic upgrade head
Rollback migrate app 0001 flask db downgrade alembic downgrade -1
Degree of Automation Highest Medium Requires manual configuration of env.py

Chapter Summary

In this chapter you mastered the complete Alembic workflow: alembic init for initialization, configuring env.py to connect models, revision --autogenerate to generate migrations, upgrade head to apply, and downgrade to roll back.

Alembic has more configuration steps than Django/Flask's migration tools, but it's lower-level and more flexible.

Next chapter preview: as articles accumulate, you need search and pagination. The next chapter implements combined keyword search and offset/limit-based pagination.