Skip to content

Commit be65e4a

Browse files
committed
feat: implement database migration system using Alembic, including migration scripts and utility functions for creating, upgrading, and downgrading database schemas
1 parent b8afa54 commit be65e4a

11 files changed

Lines changed: 610 additions & 13 deletions

File tree

backend/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,60 @@
1414
```
1515

1616
3. 開啟瀏覽器到 http://localhost:8000/docs,可看到 Swagger UI,並測試各 API。
17+
18+
## 修改資料庫 Schema
19+
20+
1. 修改 Models
21+
22+
編輯 `backend/app/models/models.py`
23+
24+
```python
25+
# 例如:新增一個欄位
26+
class User(SQLModel, table=True):
27+
id: Optional[int] = Field(default=None, primary_key=True)
28+
name: str
29+
email: str
30+
# 新增的欄位
31+
phone: Optional[str] = None # 新欄位
32+
```
33+
34+
2. 建立 Migration
35+
36+
```bash
37+
cd backend
38+
uv run migrate.py create "Add phone field to User table"
39+
```
40+
41+
3. 檢查生成的 Migration
42+
43+
檢查 `backend/alembic/versions/` 中新生成的檔案,確認變更正確。
44+
45+
4. 應用 Migration
46+
47+
```bash
48+
uv run migrate.py upgrade
49+
50+
docker compose down
51+
docker compose up -d
52+
```
53+
54+
## Migration 管理指令
55+
56+
```bash
57+
cd backend
58+
59+
# 建立新的 migration
60+
uv run migrate.py create "Your migration message"
61+
62+
# 應用所有 pending migrations
63+
uv run migrate.py upgrade
64+
65+
# 檢查目前的資料庫版本
66+
uv run migrate.py current
67+
68+
# 查看 migration 歷史
69+
uv run migrate.py history
70+
71+
# 回復到特定版本(謹慎使用!)
72+
uv run migrate.py downgrade <revision_id>
73+
```

backend/alembic.ini

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts.
5+
# this is typically a path given in POSIX (e.g. forward slashes)
6+
# format, relative to the token %(here)s which refers to the location of this
7+
# ini file
8+
script_location = %(here)s/alembic
9+
10+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11+
# Uncomment the line below if you want the files to be prepended with date and time
12+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13+
# for all available tokens
14+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15+
16+
# sys.path path, will be prepended to sys.path if present.
17+
# defaults to the current working directory. for multiple paths, the path separator
18+
# is defined by "path_separator" below.
19+
prepend_sys_path = .
20+
21+
22+
# timezone to use when rendering the date within the migration file
23+
# as well as the filename.
24+
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
25+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
26+
# string value is passed to ZoneInfo()
27+
# leave blank for localtime
28+
# timezone =
29+
30+
# max length of characters to apply to the "slug" field
31+
# truncate_slug_length = 40
32+
33+
# set to 'true' to run the environment during
34+
# the 'revision' command, regardless of autogenerate
35+
# revision_environment = false
36+
37+
# set to 'true' to allow .pyc and .pyo files without
38+
# a source .py file to be detected as revisions in the
39+
# versions/ directory
40+
# sourceless = false
41+
42+
# version location specification; This defaults
43+
# to <script_location>/versions. When using multiple version
44+
# directories, initial revisions must be specified with --version-path.
45+
# The path separator used here should be the separator specified by "path_separator"
46+
# below.
47+
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
48+
49+
# path_separator; This indicates what character is used to split lists of file
50+
# paths, including version_locations and prepend_sys_path within configparser
51+
# files such as alembic.ini.
52+
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
53+
# to provide os-dependent path splitting.
54+
#
55+
# Note that in order to support legacy alembic.ini files, this default does NOT
56+
# take place if path_separator is not present in alembic.ini. If this
57+
# option is omitted entirely, fallback logic is as follows:
58+
#
59+
# 1. Parsing of the version_locations option falls back to using the legacy
60+
# "version_path_separator" key, which if absent then falls back to the legacy
61+
# behavior of splitting on spaces and/or commas.
62+
# 2. Parsing of the prepend_sys_path option falls back to the legacy
63+
# behavior of splitting on spaces, commas, or colons.
64+
#
65+
# Valid values for path_separator are:
66+
#
67+
# path_separator = :
68+
# path_separator = ;
69+
# path_separator = space
70+
# path_separator = newline
71+
#
72+
# Use os.pathsep. Default configuration used for new projects.
73+
path_separator = os
74+
75+
# set to 'true' to search source files recursively
76+
# in each "version_locations" directory
77+
# new in Alembic version 1.10
78+
# recursive_version_locations = false
79+
80+
# the output encoding used when revision files
81+
# are written from script.py.mako
82+
# output_encoding = utf-8
83+
84+
# database URL. This is consumed by the user-maintained env.py script only.
85+
# other means of configuring database URLs may be customized within the env.py
86+
# file.
87+
# sqlalchemy.url = driver://user:pass@localhost/dbname
88+
# Note: Database URL will be read from environment variables in env.py
89+
90+
91+
[post_write_hooks]
92+
# post_write_hooks defines scripts or Python functions that are run
93+
# on newly generated revision scripts. See the documentation for further
94+
# detail and examples
95+
96+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
97+
# hooks = black
98+
# black.type = console_scripts
99+
# black.entrypoint = black
100+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
101+
102+
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
103+
# hooks = ruff
104+
# ruff.type = module
105+
# ruff.module = ruff
106+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
107+
108+
# Alternatively, use the exec runner to execute a binary found on your PATH
109+
# hooks = ruff
110+
# ruff.type = exec
111+
# ruff.executable = ruff
112+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
113+
114+
# Logging configuration. This is also consumed by the user-maintained
115+
# env.py script only.
116+
[loggers]
117+
keys = root,sqlalchemy,alembic
118+
119+
[handlers]
120+
keys = console
121+
122+
[formatters]
123+
keys = generic
124+
125+
[logger_root]
126+
level = WARNING
127+
handlers = console
128+
qualname =
129+
130+
[logger_sqlalchemy]
131+
level = WARNING
132+
handlers =
133+
qualname = sqlalchemy.engine
134+
135+
[logger_alembic]
136+
level = INFO
137+
handlers =
138+
qualname = alembic
139+
140+
[handler_console]
141+
class = StreamHandler
142+
args = (sys.stderr,)
143+
level = NOTSET
144+
formatter = generic
145+
146+
[formatter_generic]
147+
format = %(levelname)-5.5s [%(name)s] %(message)s
148+
datefmt = %H:%M:%S

backend/alembic/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

backend/alembic/env.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import os
2+
import sys
3+
from logging.config import fileConfig
4+
5+
from sqlalchemy import engine_from_config
6+
from sqlalchemy import pool
7+
8+
from alembic import context
9+
10+
# Add the current directory to the Python path
11+
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
12+
13+
# Import the models for autogenerate support
14+
from app.models.models import *
15+
from sqlmodel import SQLModel
16+
17+
# this is the Alembic Config object, which provides
18+
# access to the values within the .ini file in use.
19+
config = context.config
20+
21+
# Set the SQLAlchemy URL from environment variables
22+
from app.core.config import settings
23+
config.set_main_option(
24+
"sqlalchemy.url",
25+
f"postgresql+asyncpg://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}".replace("+asyncpg", "")
26+
)
27+
28+
# Interpret the config file for Python logging.
29+
# This line sets up loggers basically.
30+
if config.config_file_name is not None:
31+
fileConfig(config.config_file_name)
32+
33+
# add your model's MetaData object here
34+
# for 'autogenerate' support
35+
target_metadata = SQLModel.metadata
36+
37+
# other values from the config, defined by the needs of env.py,
38+
# can be acquired:
39+
# my_important_option = config.get_main_option("my_important_option")
40+
# ... etc.
41+
42+
43+
def run_migrations_offline() -> None:
44+
"""Run migrations in 'offline' mode.
45+
46+
This configures the context with just a URL
47+
and not an Engine, though an Engine is acceptable
48+
here as well. By skipping the Engine creation
49+
we don't even need a DBAPI to be available.
50+
51+
Calls to context.execute() here emit the given string to the
52+
script output.
53+
54+
"""
55+
url = config.get_main_option("sqlalchemy.url")
56+
context.configure(
57+
url=url,
58+
target_metadata=target_metadata,
59+
literal_binds=True,
60+
dialect_opts={"paramstyle": "named"},
61+
)
62+
63+
with context.begin_transaction():
64+
context.run_migrations()
65+
66+
67+
def run_migrations_online() -> None:
68+
"""Run migrations in 'online' mode.
69+
70+
In this scenario we need to create an Engine
71+
and associate a connection with the context.
72+
73+
"""
74+
connectable = engine_from_config(
75+
config.get_section(config.config_ini_section, {}),
76+
prefix="sqlalchemy.",
77+
poolclass=pool.NullPool,
78+
)
79+
80+
with connectable.connect() as connection:
81+
context.configure(
82+
connection=connection, target_metadata=target_metadata
83+
)
84+
85+
with context.begin_transaction():
86+
context.run_migrations()
87+
88+
89+
if context.is_offline_mode():
90+
run_migrations_offline()
91+
else:
92+
run_migrations_online()

backend/alembic/script.py.mako

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
import sqlmodel.sql.sqltypes
13+
${imports if imports else ""}
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = ${repr(up_revision)}
17+
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
18+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
19+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
20+
21+
22+
def upgrade() -> None:
23+
"""Upgrade schema."""
24+
${upgrades if upgrades else "pass"}
25+
26+
27+
def downgrade() -> None:
28+
"""Downgrade schema."""
29+
${downgrades if downgrades else "pass"}

0 commit comments

Comments
 (0)