from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
import hashlib
import json
import os
import shutil
import sqlite3
import subprocess
import sys
FIRST = "coast001"
SECOND = "coast002"
INIT = "Flask-Migrate initializes an actual revision directory"
PLAN = "Autogenerate produces two reviewed migration candidates"
UPGRADE = "Upgrade and database default preserve prior blog rows"
HISTORY = "Flask-Migrate current history and schema check"
DOWN = "Batch downgrade keeps rows but loses removed values"
REPLAY = "Re-upgrade recreates defaults instead of lost data"
CREATE = "create_all skips altering the existing table"
def check(name, operation, inputs, expected, actual):
assert expected == actual, (name, expected, actual)
return dict(name=name, operation=operation, input=inputs, expected=expected, actual=actual)
def exercise(root):
shutil.copyfile(Path(__file__).with_name("migration_app.py"), root/"migration_app.py")
def run(args, stage):
process = subprocess.run([sys.executable,"-B",*args], cwd=root,
env=dict(os.environ,COAST_SCHEMA=stage), capture_output=True,encoding="utf8",timeout=20)
assert process.returncode == 0, (args,process.stdout,process.stderr)
return process.stdout + process.stderr
def db(*args, stage="1"):
return run(["-m","flask","--app","migration_app:create_app","db",*args],stage)
def read(*queries):
with closing(sqlite3.connect(root/"coast-revisions.sqlite")) as con:
return [[list(row) for row in con.execute(query)] for query in queries]
db("init")
directory = root/"migrations"
cases = [check(INIT, "Run the Flask CLI and inspect generated files", "db init",
[True,True,True],[(directory/p).exists() for p in ("env.py","script.py.mako","versions")])]
db("migrate","--rev-id",FIRST,"-m","coast blog tables")
first, = (directory/"versions").glob(f"{FIRST}_*.py")
initial = first.read_bytes()
db("upgrade",FIRST)
with closing(sqlite3.connect(root/"coast-revisions.sqlite")) as con, con:
con.execute("INSERT INTO category VALUES (1,'coast')")
con.execute("INSERT INTO post VALUES (1,'tide notebook',1)")
run(["-c","from migration_app import create_app,db; app=create_app(); ctx=app.app_context(); ctx.push(); db.create_all(); ctx.pop()"],"2")
columns = "select name from pragma_table_info('post') order by cid"
entries = "select id,title,read_count from post order by id"
revision = "select version_num from alembic_version"
cases.append(check(CREATE, "Call create_all with v2 on a real v1 table", "new column on existing table",
[[["id"],["title"],["category_id"]],[[FIRST]]],read(columns,revision)))
db("migrate","--rev-id",SECOND,"-m","read counter",stage="2")
second, = (directory/"versions").glob(f"{SECOND}_*.py")
change = second.read_bytes()
digests = {p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (first,second)}
cases.append(check(PLAN, "Read both generated scripts before applying",
digests,[True]*7,[b"create_table('category'" in initial,b"create_table('post'" in initial,
b"drop_table('post'" in initial,b"batch_alter_table('post'" in change,b"add_column" in change,
b"server_default" in change,b"drop_column('read_count')" in change]))
db("upgrade","head",stage="2")
with closing(sqlite3.connect(root/"coast-revisions.sqlite")) as con, con:
con.execute("INSERT INTO post (id,title,category_id) VALUES (2,'late reading',1)")
con.execute("UPDATE post SET read_count=7 WHERE id=1")
cases.append(check(UPGRADE, "Upgrade SQLite, use the default on INSERT, then update an old row",
["upgrade head","INSERT without read_count","update to 7"],
[[[1,"tide notebook",7],[2,"late reading",0]],[[SECOND]]],read(entries,revision)))
current = db("current",stage="2")
history = db("history",stage="2")
checked = db("check",stage="2")
cases.append(check(HISTORY, "Read both CLI reports and check metadata parity",
["current","history","check"],[True,True,True,True],
[SECOND in current,FIRST in history,SECOND in history,"No new upgrade operations" in checked]))
db("downgrade","--","-1",stage="2")
cases.append(check(DOWN, "Apply the generated downgrade in SQLite batch mode",
"downgrade -- -1",[[["id"],["title"],["category_id"]],[[FIRST]],[[1,"tide notebook"],[2,"late reading"]]],
read(columns,revision,"select id,title from post order by id")))
db("upgrade","head",stage="2")
cases.append(check(REPLAY, "Recreate the removed column from version history",
"upgrade head again",[[[1,"tide notebook",0],[2,"late reading",0]],[[SECOND]]],read(entries,revision)))
return {"cases":cases,"generated_revision_sha256":digests}
if __name__ == "__main__":
with TemporaryDirectory(prefix="mbsky-flask-migrate-") as work:
print(json.dumps(exercise(Path(work)),ensure_ascii=False))
本例需在 Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLite 3.53.1、Flask-Migrate 4.1.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLite 3.53.1、Flask-Migrate 4.1.0
入口文件:projects/flask-coast-search-migrate/migration_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
migration_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLite 3.53.1、Flask-Migrate 4.1.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202611a482.zip
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202611a486.zip