fix: commit template upload atomically

This commit is contained in:
zwt13703
2026-07-01 21:50:38 +08:00
parent 1ff0fdf602
commit 28f87fbb62
3 changed files with 34 additions and 6 deletions
+3 -2
View File
@@ -34,8 +34,9 @@ def upload_template(
try:
stored_path, content = store_template_file(file)
blocks = parse_document(content)
template = create_template_record(db, name=name, file_path=stored_path, type=type)
save_template_blocks(db, template.id, blocks)
template = create_template_record(db, name=name, file_path=stored_path, type=type, commit=False)
save_template_blocks(db, template.id, blocks, commit=False)
db.commit()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
+21 -4
View File
@@ -46,16 +46,30 @@ def store_template_file(file: UploadFile) -> tuple[str, bytes]:
return stored_path, content
def create_template_record(db: Session, name: str, file_path: str, type: str = "report") -> Template:
def create_template_record(
db: Session,
name: str,
file_path: str,
type: str = "report",
commit: bool = True,
) -> Template:
"""创建模板记录"""
tmpl = Template(name=name, type=type, original_file_path=file_path)
db.add(tmpl)
db.commit()
if commit:
db.commit()
else:
db.flush()
db.refresh(tmpl)
return tmpl
def save_template_blocks(db: Session, template_id: int, blocks: list[dict]) -> list[TemplateBlock]:
def save_template_blocks(
db: Session,
template_id: int,
blocks: list[dict],
commit: bool = True,
) -> list[TemplateBlock]:
"""批量保存解析出的模板区域。"""
records = [
TemplateBlock(
@@ -74,5 +88,8 @@ def save_template_blocks(db: Session, template_id: int, blocks: list[dict]) -> l
]
db.add_all(records)
db.commit()
if commit:
db.commit()
else:
db.flush()
return records
+10
View File
@@ -189,3 +189,13 @@
6. 上传成功后刷新模板列表并跳转编辑页。
7. 执行后端路由检查和前端生产构建验证。
- **执行结果**: 模板中心已具备模板列表展示、失败重试和进入标注页能力。
## 会话 ID: 20260701-upload-transaction
- [2026-07-01 21:50:22]
- **执行原因**: 继续增强后端上传链路可靠性,避免模板记录和 block 记录出现部分提交。
- **执行过程**:
1.`create_template_record` 增加可选 `commit` 参数,支持在外层事务中只 `flush`
2.`save_template_blocks` 增加可选 `commit` 参数,支持在外层事务中只 `flush`
3. 调整模板上传接口,将 template 创建和 blocks 批量保存放入同一事务后统一 `commit`
4. 执行 Python 语法检查和上传路由注册检查。
- **执行结果**: 模板上传的数据库写入已统一事务提交,降低半成功数据残留风险。