alembic使用教程

Alembic 是一个用于 Python 数据库迁移和版本控制的工具。它与 SQLAlchemy(一个流行的 Python ORM 库)紧密集成,共同为 Python 应用程序提供数据库管理和迁移支持。

1. 安装

uv add alembic
# 或者pip install alembic

2.初始化

# alembic init 包名
alembic init alembic

项目中多出alembic目录

  • alembic.ini: Alembic 的主配置文件。
  • env.py: Alembic 运行时环境的 Python 脚本,用于配置 SQLAlchemy 引擎和元数据。
  • script.py.mako: 迁移脚本的模板文件。
  • versions/: 存放所有迁移脚本的目录。

3.修改相关配置

3.1 修改alembic.ini

修改数据库连接即:sqlalchemy.url =

3.2 修改env.py文件

修改target_metadata = None

# 1. 找到model文件里的模型基类代码,类似如下:
class Base(DeclarativeBase):
    """Declarative base for all ORM models."""
# env.py修改示例,包含同步和异步,如果只有同步,只需要删除异步相关的代码,下面需要修改的地方,都标注了

"""Alembic migration environment (async).

Uses the application's ``Settings`` for the database URL and SQLAlchemy
metadata from ``app.core.database.Base`` so migrations stay in sync with
the ORM models.
"""
from __future__ import annotations

import asyncio
from logging.config import fileConfig

from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config

# 需要导入model文件里的基类
from model import Base

config = context.config


config = context.config

if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# 需要修改
target_metadata = Base.metadata


def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode (emit SQL without a DB connection)."""
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        compare_type=True,
    )
    with context.begin_transaction():
        context.run_migrations()


def do_run_migrations(connection: Connection) -> None:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True,
    )
    with context.begin_transaction():
        context.run_migrations()


async def run_async_migrations() -> None:
    """Create an async engine and run migrations within its transaction."""
    connectable = async_engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )
    async with connectable.connect() as connection:
        await connection.run_sync(do_run_migrations)
    await connectable.dispose()


def run_migrations_online() -> None:
    """Run migrations in 'online' mode with an async connection."""
    asyncio.run(run_async_migrations())


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

4.生成迁移脚本

# alembic revision: 创建一个新的数据库迁移脚本。
#      --autogenerate: 自动检测你的 SQLAlchemy 模型与数据库当前状态的差异,并生成相应的升级/降级 SQL 语句。
#      -m "Create initial tables": 为这个迁移脚本添加一个描述性消息,方便你理解其目的。

alembic revision --autogenerate -m "Create initial tables"

  

执行以上命令会在versions里生成对应的迁移脚本

5. 执行数据库的迁移

alembic upgrade head

  

6.逻辑流程图

    1. 初始化 Alembic 项目
      ↓
    2. 配置env.py (离线迁移,加载 ORM 模型, 建立连接)
      ↓
    3. 定义 SQLAlchemy Base 和 ORM 模型
      ↓
    4. ORM 模型发生变化?
      ├─ 是 (模型与数据库结构不一致)
      │ ↓
      │ 5. 生成迁移文件 (alembic revision --autogenerate)
      │ (Alembic 比较 ORM 模型定义 与 MySQL 数据库实际结构)
      │ ↓
      │ 6. 人工检查并修改迁移文件 (确保 upgrade/downgrade 逻辑正确)
      │ ↓
      │ 7. 执行迁移 (alembic upgrade head)
      │ (Alembic 读取迁移文件, 更新 MySQL 数据库结构, 并更新 alembic_version 表)
      │ ↓
      └─ 否 (模型与数据库结构一致)
      ↓
      (无需迁移)
      ↓
    5. 应用程序启动 & 与更新后的 MySQL 数据库交互

7.常用命令

命令作用
alembic init alembic 初始化
alembic revision --autogenerate -m "msg" 自动生成迁移
alembic revision -m "msg" 手动迁移脚本
alembic upgrade head 升级到最新
alembic downgrade -1 回滚上一个
alembic current 当前版本
alembic history 迁移历史
alembic heads 查看 head
alembic stamp rev 打版本标记,不执行 SQL
alembic merge heads 合并多分支

  

 

posted @ 2026-12-03 15:44  NAVYSUMMER  阅读(4)  评论(0)    收藏  举报
交流群 编程书籍