from contextlib import closing
from hashlib import sha256
from pathlib import Path
from tempfile import TemporaryDirectory
import json
import os
import shutil
import sqlite3
import subprocess
import sys
ROOT = Path(__file__).resolve().parent
FIRST, SECOND = "01_base", "02_read_count"
reports = []
def check(name, data, operation, expected, actual):
assert actual == expected,(name,actual,expected)
reports.append(dict(name=name,input=data,operation=operation,expected=expected,actual=actual))
def invoke(root, args, stage="1"):
result=subprocess.run([sys.executable,"-B","-s",*args],cwd=root,
env=dict(os.environ,MBSKY_MIGRATION_STAGE=stage),capture_output=True,encoding="utf8",timeout=18)
assert result.returncode==0,(args,result.stdout,result.stderr)
return result.stdout
def migrate(root,*args,stage="1"):
return invoke(root,["-m","alembic","-c","alembic.ini",*args],stage)
def rows(path,query):
with closing(sqlite3.connect(path)) as db:
return [list(row) for row in db.execute(query)]
def exercise(root):
for name in ("alembic.ini","schema.py"):
shutil.copyfile(ROOT/name,root/name)
probe=("from sqlalchemy import create_engine; from schema import Base; "
"e=create_engine('sqlite:///create-only.sqlite'); Base.metadata.create_all(e); e.dispose()")
invoke(root,["-c",probe],stage="1")
invoke(root,["-c",probe],stage="2")
columns=rows(root/"create-only.sqlite","SELECT name FROM pragma_table_info('posts') ORDER BY cid")
check("create_all leaves existing columns unchanged",["model 1","model 2"],
"Apply create_all on the same database with two model versions.",
[["id"],["title"],["category_id"]],columns)
migrate(root,"init","migrations")
expected=["env.py","script.py.mako","versions"]
actual=[name for name in expected if (root/"migrations"/name).exists()]
check("Alembic initializes the directory", "alembic init migrations",
"Execute official CLI and inspect environment, template and version directory.",expected,actual)
shutil.copyfile(ROOT/"lab_env.py",root/"migrations/env.py")
db_path=root/"shore-migration.sqlite"
revisions=root/"migrations/versions"
migrate(root,"revision","--autogenerate","--rev-id",FIRST,"-m","initial tables")
first=next(revisions.glob(f"{FIRST}_*.py"))
assert "op.create_table" in first.read_text(encoding="utf8")
migrate(root,"upgrade",FIRST)
check("specific revision creates tables", FIRST,
"Autogenerate, inspect candidate, upgrade to explicit revision and query SQLite.",
[["alembic_version"],["categories"],["posts"]],rows(db_path,"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"))
with closing(sqlite3.connect(db_path)) as db:
with db:
db.execute("INSERT INTO categories (id,name) VALUES (1,'shore')")
db.execute("INSERT INTO posts (id,title,category_id) VALUES (1,'kept row',1)")
migrate(root,"revision","--autogenerate","--rev-id",SECOND,"-m","reading counter",stage="2")
second=next(revisions.glob(f"{SECOND}_*.py"))
candidate=second.read_text(encoding="utf8")
assert "add_column" in candidate and "read_count" in candidate and "drop_column" in candidate
migrate(root,"upgrade","head",stage="2")
check("head adds counter to existing rows", "upgrade head after model change",
"Inspect new column values on old and new records, and the active revision.",
[["kept row",0],[SECOND]],rows(db_path,"SELECT title,read_count FROM posts")+rows(db_path,"SELECT version_num FROM alembic_version"))
with closing(sqlite3.connect(db_path)) as db:
with db:
db.execute("INSERT INTO posts (id,title,category_id) VALUES (2,'new row',1)")
db.execute("UPDATE posts SET read_count=7 WHERE id=1")
check("database default and changed counts", "INSERT without count and UPDATE to 7",
"Read both rows from a separate SQLite connection.",
[[1,7],[2,0]],rows(db_path,"SELECT id,read_count FROM posts ORDER BY id"))
migrate(root,"downgrade","-1",stage="2")
check("downgrade retains titles and removes counter", "downgrade -1",
"Observe prior revision, remaining columns and existing rows.",
[[[FIRST]],[["id"],["title"],["category_id"]],[[1,"kept row"],[2,"new row"]]],
[rows(db_path,"SELECT version_num FROM alembic_version"),
rows(db_path,"SELECT name FROM pragma_table_info('posts') ORDER BY cid"),
rows(db_path,"SELECT id,title FROM posts ORDER BY id")])
migrate(root,"upgrade","head",stage="2")
check("reupgrade does not restore lost counts", "upgrade after downgrade",
"Verify the recreated column uses its default rather than restoring former values.",
[[1,0],[2,0]],rows(db_path,"SELECT id,read_count FROM posts ORDER BY id"))
return {path.name:sha256(path.read_bytes()).hexdigest() for path in (first,second)}
if __name__=="__main__":
with TemporaryDirectory(prefix="shore-alembic-") as work:
revisions=exercise(Path(work))
print(json.dumps(dict(cases=reports,revisions=revisions),ensure_ascii=False))
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-blog-query-migration/migration/exercise_migration.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
exercise_migration.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a499.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip