Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
黄南光
/
auto-restock
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Settings
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 3b6a684a
authored
Dec 02, 2026
by
黄南光
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
修改数据库校验
1 parent
0b761460
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
27 additions
and
23 deletions
CLAUDE.md
agent.md
server/app/cli.py
server/app/core/db.py
server/app/main.py
server/app/models.py
server/tests/test_system.py
CLAUDE.md
View file @
3b6a684
...
...
@@ -2,7 +2,7 @@
## 数据库变更(硬性规定,详见根目录 agent.md)
-
**任何 DDL / DML 都放进 `sql_script/v<版本号>/`,由 DBA 人工执行;程序和部署流程不允许自行修改数据库结构和数据**
(启动只做只读检查
`db.verify_schema()`
)。
-
**任何 DDL / DML 都放进 `sql_script/v<版本号>/`,由 DBA 人工执行;程序和部署流程不允许自行修改数据库结构和数据**
(启动只做只读检查
`db.verify_schema()`
:只校验版本标记,表结构和 models 的差异只告警不拦截
)。
-
改了
`server/app/models.py`
必须同步写脚本(
`python -m app.cli schema-sql`
打印差异 DDL),并升级
`__version__`
和
`db.REQUIRED_SCHEMA`
;每个版本最后是
`999_dml_schema_version.sql`
。
-
已发布的脚本不再改,追加新版本修正。
...
...
agent.md
View file @
3b6a684
...
...
@@ -7,7 +7,8 @@
2.
**程序代码和部署流程(start.sh、Dockerfile、启动钩子、CLI、定时任务)都不允许自行修改数据库结构和数据**
:
-
不允许在启动时建库、建表、同步表结构、跑迁移(
`create_all`
、alembic
`upgrade`
、
`ALTER`
之类);
-
不允许写「一次性修数据」的代码顺带在启动 / 部署时执行;
-
启动时只能做只读检查(
`server/app/core/db.py`
的
`verify_schema()`
)。
-
启动时只能做只读检查(
`server/app/core/db.py`
的
`verify_schema()`
):只有版本标记低于
`REQUIRED_SCHEMA`
才拒绝启动;
表结构和
`models.py`
的差异(索引、多 / 少字段等)只打警告,不阻止启动。
-
例外:业务运行时正常的增删改(下单、写审计、后台保存设置)和
`bootstrap.py`
在空库上建初始管理员 / 默认门店,不算数据库变更。
3.
**改了 `server/app/models.py` 就必须同时写脚本**
:
-
在开发库上运行
`python -m app.cli schema-sql`
(只打印差异 DDL,不执行),整理进新版本目录;
...
...
@@ -15,7 +16,7 @@
-
每个版本最后一个文件是
`999_dml_schema_version.sql`
,写入
`atrs_sys_config.k='db_schema'`
的版本标记;
-
同时把
`server/app/core/db.py`
的
`REQUIRED_SCHEMA`
升到这个版本。
4.
已经发布的脚本不再修改,有问题在新版本目录里追加修正脚本。
5.
部署顺序:
**先执行脚本,再发布程序**
;执行后
用
`python -m app.cli schema-check`
(只读)确认一致
。
5.
部署顺序:
**先执行脚本,再发布程序**
;执行后
可用
`python -m app.cli schema-check`
(只读)查看版本标记和表结构差异
。
6.
测试库按顺序执行
`sql_script/`
下全部脚本后再启动程序(
`server/tests/sqlscripts.py`
)。脚本和代码不一致时测试会失败,不要为了让测试通过去改测试的建库方式。
详细说明见
`sql_script/README.md`
。
...
...
server/app/cli.py
View file @
3b6a684
...
...
@@ -146,7 +146,7 @@ def main(argv: list[str] | None = None) -> int:
for
e
in
errors
:
print
(
f
"❌ {e}"
)
if
not
errors
:
print
(
f
"✅
表结构和代码一致,版本标记 {db.schema_mark()}(程序要求 {db.REQUIRED_SCHEMA})"
)
print
(
f
"✅
版本标记 {db.schema_mark()}(程序要求 {db.REQUIRED_SCHEMA})"
+
(
""
if
warns
else
",表结构和代码一致"
)
)
return
1
if
errors
else
0
elif
args
.
cmd
==
"schema-sql"
:
sql
=
db
.
schema_sql
()
...
...
server/app/core/db.py
View file @
3b6a684
...
...
@@ -106,7 +106,8 @@ def plain(row: dict | None) -> dict | None:
# ---------------- 表结构检查(只读) ----------------
# 程序不再自行修改数据库(不建库、不建表 / 改表 / 删表、不跑数据迁移)。所有 DDL / DML 都写在仓库根目录
# sql_script/<版本>/ 下,由人工按顺序执行(规则见 agent.md、sql_script/README.md)。
# 启动时 verify_schema() 只读检查:表结构和 app.models 一致、库里的版本标记不低于 REQUIRED_SCHEMA,否则拒绝启动。
# 启动时 verify_schema() 只读检查:库里的版本标记不低于 REQUIRED_SCHEMA,否则拒绝启动;
# 表结构和 app.models 的差异只打日志提醒,不阻止启动(库是 DBA 维护的,索引 / 字段细节允许和代码定义有出入)。
# 改了 app/models.py:用 `python -m app.cli schema-sql` 打印差异 DDL(只打印不执行),整理进新的 sql_script 版本目录。
TABLE_PREFIX
=
"atrs_"
SCHEMA_MARK
=
"db_schema"
# atrs_sys_config 里的一行:{"version": "x.y.z"},由各版本 sql_script 的 999 脚本写入
...
...
@@ -214,28 +215,31 @@ def schema_mark() -> str:
def
schema_problems
()
->
tuple
[
list
[
str
],
list
[
str
]]:
"""(错误, 提醒)。错误 =
缺表 / 缺字段 / 字段定义不一致 / 版本标记偏低;提醒 = 库里多出来的字段 / 表(不影响使用
)。只读。"""
"""(错误, 提醒)。错误 =
版本标记偏低;提醒 = 表结构和代码定义的差异(缺 / 多字段、索引不同等,不阻止启动
)。只读。"""
errors
:
list
[
str
]
=
[]
mark
=
schema_mark
()
if
_version_tuple
(
mark
)
<
_version_tuple
(
REQUIRED_SCHEMA
):
errors
.
append
(
f
"库里的表结构版本是 {mark or '(没有)'},程序要求 {REQUIRED_SCHEMA}:"
f
"请 DBA 按顺序执行 sql_script/ 下 {mark or '全部'} 之后各版本目录里的脚本"
f
"(到 v{REQUIRED_SCHEMA} 为止)"
)
pending
=
schema_diff
()
drops
=
[
p
for
p
in
pending
if
p
.
startswith
((
"删字段"
,
"删表"
))]
if
len
(
pending
)
>
len
(
drops
):
errors
.
append
(
"表结构和代码不一致:"
+
";"
.
join
(
p
for
p
in
pending
if
p
not
in
drops
)
+
f
"(请执行 sql_script/v{REQUIRED_SCHEMA}/ 下的脚本;开发人员可用 python -m app.cli schema-sql 查看差异 DDL)"
)
warns
=
[
"库里有代码已不再使用的字段 / 表(程序不会删除,需要的话由 DBA 写脚本处理):"
+
";"
.
join
(
drops
)]
if
drops
else
[]
warns
:
list
[
str
]
=
[]
try
:
pending
=
schema_diff
()
except
Exception
as
e
:
# noqa: BLE001 比对失败也不影响启动
warns
.
append
(
f
"表结构比对失败(不影响启动):{e}"
)
pending
=
[]
if
pending
:
warns
.
append
(
"表结构和代码定义有差异(不影响启动;需要的话由 DBA 写脚本处理,"
"开发人员可用 python -m app.cli schema-sql 查看差异 DDL):"
+
";"
.
join
(
pending
))
return
errors
,
warns
def
verify_schema
()
->
None
:
"""启动检查(只读,不改库):
不一致就抛 SchemaError 拒绝启动
。"""
"""启动检查(只读,不改库):
版本标记偏低就抛 SchemaError 拒绝启动;表结构差异只打警告
。"""
errors
,
warns
=
schema_problems
()
for
w
in
warns
:
_log
()
.
warning
(
w
)
if
errors
:
for
e
in
errors
:
_log
()
.
error
(
e
)
raise
SchemaError
(
"数据库
表结构和程序版本不一致
,已拒绝启动:"
+
";"
.
join
(
errors
))
raise
SchemaError
(
"数据库
版本标记低于程序要求
,已拒绝启动:"
+
";"
.
join
(
errors
))
server/app/main.py
View file @
3b6a684
...
...
@@ -48,7 +48,7 @@ def startup_info() -> str:
@asynccontextmanager
async
def
lifespan
(
app
:
FastAPI
):
db
.
init_engine
()
await
asyncio
.
to_thread
(
db
.
verify_schema
)
# 只读检查:
表结构 / 版本标记不对就拒绝启动
(改库走 sql_script)
await
asyncio
.
to_thread
(
db
.
verify_schema
)
# 只读检查:
版本标记偏低就拒绝启动,表结构差异只告警
(改库走 sql_script)
bootstrap
.
run
()
events
.
start
()
edge
.
mark_started
()
...
...
server/app/models.py
View file @
3b6a684
...
...
@@ -131,7 +131,7 @@ devices_t = Table(
tasks_t
=
Table
(
"atrs_edge_task"
,
md
,
Column
(
"id"
,
String
(
32
),
primary_key
=
True
,
comment
=
"任务ID(主键,32 位十六进制)"
),
Column
(
"store_id"
,
Integer
,
nullable
=
False
,
index
=
True
,
comment
=
"门店ID"
),
Column
(
"store_id"
,
Integer
,
nullable
=
False
,
comment
=
"门店ID"
),
Column
(
"device_id"
,
Integer
,
comment
=
"领取任务的设备ID(atrs_edge_device.id,领取前为空)"
),
Column
(
"feature"
,
String
(
40
),
comment
=
"发起任务的业务功能(sys = 系统自身)"
),
Column
(
"type"
,
String
(
60
),
nullable
=
False
,
comment
=
"任务类型:sys.check 自检 / restock.outbound 零件出库明细 / restock.quote 查库存·主数据·全国仓 / restock.so_sync 近期 SO 单同步 / restock.create_po 建采购单 / restock.screenshot_po 截图 / restock.export_history 历史导出 …"
),
...
...
server/tests/test_system.py
View file @
3b6a684
...
...
@@ -550,7 +550,7 @@ def test_selfcheck_schema_and_stale_texts(client, kit, capsys):
from
app
import
cli
from
app.models
import
texts_t
assert
db
.
schema_mark
()
==
db
.
REQUIRED_SCHEMA
assert
db
.
schema_problems
()
==
([],
[])
assert
db
.
schema_problems
()
[
0
]
==
[]
db
.
q
(
texts_t
.
insert
()
.
values
(
key
=
"restock.msg_po_done"
,
content
=
"👉 没问题请 {{ owner }} @我 回「确认提交」"
,
updated_by
=
"test"
,
updated_at
=
db
.
now
()))
db
.
q
(
texts_t
.
insert
()
.
values
(
key
=
"restock.msg_confirm_not_owner"
,
content
=
"只有发起人本人能确认"
,
...
...
@@ -565,8 +565,8 @@ def test_selfcheck_schema_and_stale_texts(client, kit, capsys):
def
test_startup_only_checks_schema_never_changes_it
(
client
):
"""程序不改库:
库和代码不一致 / 版本标记偏低 → verify_schema 拒绝启动(只读,库保持原样)
;
schema-sql 只打印差异 DDL
;多出来的字段只提醒、不删
。"""
"""程序不改库:
表结构和代码不一致只提醒、不拒绝启动,也不自动补 / 删字段;版本标记偏低 → 拒绝启动
;
schema-sql 只打印差异 DDL。"""
from
sqlalchemy
import
inspect
,
text
from
app.models
import
settings_t
...
...
@@ -575,13 +575,12 @@ def test_startup_only_checks_schema_never_changes_it(client):
c
.
execute
(
text
(
"ALTER TABLE atrs_im_target DROP COLUMN contact_name"
))
c
.
execute
(
text
(
"ALTER TABLE atrs_restock_plan ADD COLUMN said_time VARCHAR(20) NULL COMMENT '旧字段'"
))
try
:
with
pytest
.
raises
(
db
.
SchemaError
)
as
ei
:
db
.
verify_schema
()
assert
"加字段 atrs_im_target.contact_name"
in
str
(
ei
.
value
)
db
.
verify_schema
()
# 结构差异不阻止启动
cols
=
{
c
[
"name"
]
for
c
in
inspect
(
db
.
engine
())
.
get_columns
(
"atrs_im_target"
)}
assert
"contact_name"
not
in
cols
# 没有自动补字段
errors
,
warns
=
db
.
schema_problems
()
assert
any
(
"said_time"
in
w
for
w
in
warns
)
and
not
any
(
"said_time"
in
e
for
e
in
errors
)
assert
not
errors
assert
any
(
"said_time"
in
w
for
w
in
warns
)
and
any
(
"加字段 atrs_im_target.contact_name"
in
w
for
w
in
warns
)
sql
=
db
.
schema_sql
()
assert
"ALTER TABLE atrs_im_target ADD COLUMN contact_name"
in
sql
and
"said_time"
in
sql
finally
:
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment