Alembic是一个数据库管理工具,用于管理数据库迁移。它允许你创建、应用和撤销数据库迁移,以便在数据库结构发生变化时保持版本控制。任何有关数据库变动都需要使用这个库来进行操作。这是一个python库,版本已经记录在项目下的requirements.txt文件当中。

新增字段操作如下

在使用 Alembic 进行数据库迁移时,你需要通过 Alembic 的迁移脚本来实现对表结构的修改,同时确保原始数据不会被删除。以下是基于你的需求,使用 Alembic 添加一个新字段 usr_id 并设置默认值为 0 的详细步骤:

1. 初始化 Alembic 环

境如果你还没有初始化 Alembic,需要先在项目中初始化它:

1
alembic init alembic

这会在项目中创建一个 alembic 文件夹,其中包含 Alembic 的配置文件和迁移脚本模板。

2. 配置 Alembic

编辑 alembic.ini 文件,确保其中的 sqlalchemy.url 配置正确指向你的数据库:

1
sqlalchemy.url = mysql+pymysql://username:password@host:port/dbname

如:sqlalchemy.url = mysql+pymysql://root:123456@127.0.0.1:3306/BAIZHAN_DEV

usernamepasswordhostportdbname 替换为你的数据库连接信息。

3. 编辑 env.py

alembic/env.py 文件中,确保 target_metadata 指向你的 SQLAlchemy Base 元数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
from db.mysql_db import Base # 替换为你的 Base 模型的导入路径

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

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


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.execute context() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

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.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)

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


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

4. 更新模型定义

在你的 SQLAlchemy 模型中,新的添加字段 usr_id

1
2
3
4
5
6
7
from sqlalchemy import Column, Integer

class YourModel(Base): # 替换为你的模型类
__tablename__ = "your_table_name" # 替换为你的表名
id = Column(Integer, primary_key=True)
# 其他字段
usr_id = Column(Integer, default=0) # 新增字段

5. 生成迁移脚本

运行以下命令生成迁移脚本:

1
alembic revision --autogenerate -m "Add usr_id field"

这会根据模型的变化自动生成一个迁移脚本。

6. 检查迁移脚本

Alembic 生成的迁移脚本位于 alembic/versions 文件夹中。打开生成的脚本文件,确保内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""Add usr_id field

Revision ID: <revision_id>
Revises: <previous_revision_id>
Create Date: <create_date>

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '<revision_id>'
down_revision = '<previous_revision_id>'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('your_table_name', sa.Column('usr_id', sa.Integer(), server_default='0', nullable=False))
# ### end Alembic commands ###
# 如果有默认值server_default='0'需要自己手动添加

def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('your_table_name', 'usr_id')
# ### end Alembic commands ###

7. 应用迁移

运行以下命令将迁移应用到数据库:

1
alembic upgrade head

8. 验证结果

  • 检查数据库表结构,确认 usr_id 字段已添加。
  • 确保表中的现有数据未被删除。

注意事项

  1. 备份数据库:在执行迁移之前,建议备份数据库,以防万一出现问题。
  2. 测试迁移:在开发环境或测试环境中测试迁移脚本,确保一切正常后再应用到生产环境。
  3. 默认值处理:在迁移脚本中,server_default='0' 确保新字段在现有数据中填充默认值 0

删除字段

删除字段只需要简单修改命令即可,如下:

1
alembic revision --autogenerate -m ""

这段命令会自动生成一个空白脚本,然后手动加入删除代码,示例代码如下:

1
2
3
4
5
def upgrade():
op.drop_column('modeltest', 'content2') # 删除字段

def downgrade():
op.add_column('modeltest', sa.Column('content2', sa.Text(), nullable=True)) # 如果需要回滚,重新添加字段