在使用 Tortoise ORM 时,可以使用 Alembic 库来进行数据库结构迁移。

首先,需要安装 Alembic 库:

pip install alembic

然后,在项目中创建一个名为'alembic' 的文件夹,用于存放迁移脚本和配置文件。

在'alembic' 文件夹中创建一个名为'env.py' 的文件,用于配置数据库连接和其他选项。例如:

from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

from app.models import *
from app.settings import DATABASE_URL  # 项目中的数据库连接配置

# 此处省略了其他的配置项

# 配置数据库连接
config = context.config
config.set_main_option('sqlalchemy.url', str(DATABASE_URL))

# 将模型添加到 context 中
target_metadata = [User.metadata, Post.metadata, Comment.metadata]
context.configure(
    url=str(DATABASE_URL),
    target_metadata=target_metadata,
    compare_type=True,
)

# 此处省略了其他的配置项

# 将模型和 metadata 传递给 alembic
def run_migrations_offline():
    '''Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.
    Calls to context.execute() here emit the given string to the
    script output.
    '''
    url = str(DATABASE_URL)
    context.configure(url=url)

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    '''Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.
    '''
    # 此处省略了其他的配置项

    engine = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool,
    )

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True,
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()

# 此处省略了其他的配置项

接下来,需要初始化 Alembic,生成一个 migration 脚本:

alembic init alembic

这将创建一个名为'alembic.ini' 的文件和一个名为'alembic/versions' 的文件夹。

在'alembic/versions' 文件夹中创建一个新的 migration 脚本:

alembic revision --autogenerate -m 'create user table'

这将创建一个新的 migration 文件,其中包含对模型的更改(例如,创建新表)的自动生成代码。可以在生成的 migration 文件中手动调整代码,以确保正确执行所需的更改。

运行迁移:

alembic upgrade head

这将应用所有未应用的迁移。可以使用其他 Alembic 命令来管理迁移历史记录、回滚迁移等。

总之,以上是使用 Alembic 库来进行数据库结构迁移的基本步骤。

FastAPI 中使用 Tortoise-ORM 进行数据库结构迁移

原文地址: https://www.cveoy.top/t/topic/nApM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录