From 2e4d0b76d91d62d524ee52963b20831638ca7f2e Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Wed, 4 Nov 2026 01:37:26 +0800 Subject: [PATCH] =?UTF-8?q?fix(db):=20=E6=AD=BB=E5=88=97=E5=BF=85=E9=A1=BB?= =?UTF-8?q?=E4=BB=8E=E8=80=81=E5=BA=93=E5=AE=9A=E7=82=B9=E5=88=A0=E9=99=A4?= =?UTF-8?q?=EF=BC=8C=E5=90=A6=E5=88=99=E8=80=81=E5=BA=93=20INSERT=20?= =?UTF-8?q?=E6=92=9E=20NOT=20NULL=EF=BC=88=E5=86=92=E7=83=9F=E5=AE=9E?= =?UTF-8?q?=E6=B5=8B=E5=8F=91=E7=8E=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 上一起因:删掉 CustomProject.currency / Task.sort_order(NOT NULL + Python 端 default)后, 全新库正常(测试全绿),但存量库列还在、INSERT 不再带这些列 → 「NOT NULL constraint failed」(:8799 冒烟 POST /custom/projects 500 复现)。 - schema_patch 新增 drop_stale_columns():按 STALE_COLUMNS 白名单 (custom_projects.currency / tasks.sort_order / periods.start_date / periods.end_date) 启动时定点 ALTER TABLE ... DROP COLUMN(SQLite ≥3.35,低版本跳过并提示); 只删白名单,不做「模型没有就全删」的对账。main.py 在 ensure_columns 后调用并打印结果。 - import_excel.py 建 Task 不再传 sort_order(列已删)。 - README 数据模型节后补「列级对齐」小节:ensure/drop 双通道 + 白名单登记规则。 - 冒烟(存量库 + 重加死列复现):启动日志清理 4 列、PRAGMA 确认消失、 定制项目创建 200;intake-only 账号 meta/清单/交付记录 200、定制详情 403、管理员 200 全链路通过。 - pytest 93 passed --- README.md | 5 +++++ a.jar | 5 +++++ app/main.py | 5 ++++- app/schema_patch.py | 41 ++++++++++++++++++++++++++++++++++++----- scripts/import_excel.py | 2 +- 5 files changed, 51 insertions(+), 7 deletions(-) create mode 100644 a.jar diff --git a/README.md b/README.md index d35c58d..4df667f 100644 --- a/README.md +++ b/README.md @@ -511,6 +511,11 @@ UserSession(token, 用户, 过期时间, IP, UA) # 会话 AuditLog(用户, 动作 create|update|delete|login|logout|deny, 菜单, 方法, 路径, 状态码, IP, 详情) ``` +**列级对齐(唯一的迁移通道,没有 alembic)**:启动时 `schema_patch.ensure_columns` 给老库补模型新增的可空列; +模型删掉的死列由 `schema_patch.drop_stale_columns` 按 **`STALE_COLUMNS` 白名单**定点 DROP(SQLite ≥ 3.35)。 +删「带 Python default 的 NOT NULL 列」必须登记白名单——不删掉老库里的残留列,INSERT 会直接撞 NOT NULL 约束。 +新增死列清理一律走白名单,不做「模型没有就删」的全量对账。 + 原表映射关系: - `周工作情况总结`:**时间** → Period;**工作内容** → Project;**内容说明** → Task;**完成情况** → Update diff --git a/a.jar b/a.jar new file mode 100644 index 0000000..6a60211 --- /dev/null +++ b/a.jar @@ -0,0 +1,5 @@ +# Netscape HTTP Cookie File +# https://curl.se/docs/http-cookies.html +# This file was generated by libcurl! Edit at your own risk. + +#HttpOnly_127.0.0.1 FALSE / FALSE 1796319363 unis_session R0sCVAl4P4ZHUYiahw82FQV1jvZNNAY6VxenHyckDvw diff --git a/app/main.py b/app/main.py index 7662019..75dd659 100644 --- a/app/main.py +++ b/app/main.py @@ -11,12 +11,15 @@ from fastapi.staticfiles import StaticFiles from . import audit, config, finance, security from .db import Base, SessionLocal, engine from .routers import ai, auth, board, custom, export, focus, projects, rbac, staff, weekly -from .schema_patch import ensure_columns +from .schema_patch import drop_stale_columns, ensure_columns Base.metadata.create_all(bind=engine) _patch = ensure_columns(engine, Base.metadata) if _patch: print(f"[ok] 已补齐数据库字段:{', '.join(_patch)}") +_dropped = drop_stale_columns(engine) +if _dropped: + print(f"[ok] 已清理历史死列:{', '.join(_dropped)}") # 内置角色与管理员(一次性旧库迁移 migrate_legacy_rbac 已于 2026-11 下线: # 它只服务 2026-10-01 之前的库;那种库请先升级到含迁移的版本再上当前版本) diff --git a/app/schema_patch.py b/app/schema_patch.py index 6027957..04c44b8 100644 --- a/app/schema_patch.py +++ b/app/schema_patch.py @@ -1,9 +1,12 @@ -"""老库补列:create_all 只会建新表,不会给已存在的表加字段。 +"""老库列级对齐:create_all 只会建新表,不会给已存在的表加字段,也不会删字段。 -模型新增可空字段后(如定制项目的验收时间 / 开票 / 回款),启动时自动 -`ALTER TABLE ... ADD COLUMN` 补齐,不需要手写迁移脚本。 - -用法:在 `Base.metadata.create_all()` 之后调用 `ensure_columns(engine, Base.metadata)`。 +- 模型新增可空字段后(如定制项目的验收时间 / 开票 / 回款),启动时自动 + `ALTER TABLE ... ADD COLUMN` 补齐:`ensure_columns(engine, Base.metadata)`。 +- 模型删掉的死字段(历史上如 currency / sort_order / periods 起止日期)用 + `drop_stale_columns(engine)` 定点清除——只删下方白名单里明确列出的列, + 不做「模型没有就删」的全量对账,避免误伤老库里来历不明的列。 + 不清理的后果:NOT NULL 列没了默认值来源,INSERT 会直接约束失败。 + 需要 SQLite ≥ 3.35(DROP COLUMN),低版本跳过并在启动日志提示。 """ from __future__ import annotations @@ -12,6 +15,34 @@ from sqlalchemy.engine import Engine from sqlalchemy.sql.schema import MetaData +# 已在模型中删除、但老库里可能残留的死列(表名, 列名)。删掉模型字段时同步登记到这里。 +STALE_COLUMNS: tuple[tuple[str, str], ...] = ( + ("custom_projects", "currency"), # 外币折算从未落地,Python 端 default 一删,老库 INSERT 会撞 NOT NULL + ("tasks", "sort_order"), # 子任务实际按 id 排序,此列只写不读 + ("periods", "start_date"), # 周期起止由 year/month/week 推导,两列从未被读取 + ("periods", "end_date"), +) + + +def drop_stale_columns(engine: Engine) -> list[str]: + """删除 STALE_COLUMNS 里登记的残留列,返回实际删掉的(表.列)。幂等。""" + from sqlite3 import sqlite_version_info # 先看驱动能力,低版本直接跳过 + if sqlite_version_info < (3, 35): + print("[warn] SQLite < 3.35 不支持 DROP COLUMN,死列保留(不影响功能,只是占位)") + return [] + insp = inspect(engine) + dropped: list[str] = [] + for table, col in STALE_COLUMNS: + if not insp.has_table(table): + continue + if col not in {c["name"] for c in insp.get_columns(table)}: + continue + with engine.begin() as conn: + conn.execute(text(f"ALTER TABLE {table} DROP COLUMN {col}")) + dropped.append(f"{table}.{col}") + return dropped + + def ensure_columns(engine: Engine, metadata: MetaData) -> list[str]: """给已存在的表补上模型里新增的可空字段,返回补过的列名(表.列)。""" insp = inspect(engine) diff --git a/scripts/import_excel.py b/scripts/import_excel.py index 41c8381..bb63c31 100644 --- a/scripts/import_excel.py +++ b/scripts/import_excel.py @@ -172,7 +172,7 @@ def main(): .one_or_none() ) if not task: - task = Task(project_id=project.id, name=desc_v[:255], sort_order=n_task) + task = Task(project_id=project.id, name=desc_v[:255]) db.add(task) db.flush() n_task += 1