Files
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

66 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
SQLite 短连接上下文管理器
========================
【功能说明】
统一「开连接 → 用完提交/回滚 → 关闭」的生命周期,杜绝连接泄漏。
【为什么需要】
Python 的 sqlite3.Connection 用在 with 里时:
with sqlite3.connect(...) as conn: # 退出时 commit/rollback,但**不 close**
...
连接对象要等 GC 才释放。后果:
- Windows:文件锁不释放 → PermissionError: [WinError 32]
- 服务端高频调用:连接数持续增长,最终耗尽句柄
测试 teardown 曾因此无法删除临时 db 文件。
【语义】与裸 `with sqlite3.connect()` **完全一致**,只多保证关闭:
- 正常退出 → commit(与 Connection.__exit__ 的成功语义相同)
- 异常退出 → rollback + 原样抛出
- 无论何种情况 → finally 中 close
【设计取舍】
用 @contextmanager 而不是包装类:调用点 `with self._connect() as conn`
的写法完全不用改,属于零侵入修复。
"""
from __future__ import annotations
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator
@contextmanager
def open_connection(
db_path: Path | str, *, timeout: float = 5.0
) -> Iterator[sqlite3.Connection]:
"""
打开一个短连接,用完自动提交/回滚并关闭。
【参数】
db_path:SQLite 文件路径
timeout:写锁冲突等待秒数(busy_timeout 同值)
【返回】yield sqlite3.Connection(row_factory 已设为 sqlite3.Row)
"""
conn = sqlite3.connect(str(db_path), timeout=timeout, check_same_thread=False)
try:
conn.row_factory = sqlite3.Row
# WAL:读写并发更友好;busy_timeout:写锁冲突时等待而非直接报错
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA busy_timeout=5000;")
yield conn
# 与 sqlite3.Connection.__exit__ 的成功语义保持一致(提交)
conn.commit()
except BaseException:
# 与 sqlite3.Connection.__exit__ 的失败语义保持一致(回滚后抛出)
try:
conn.rollback()
except Exception: # noqa: BLE001 - 回滚失败不掩盖原始异常
pass
raise
finally:
# 【本模块存在的唯一理由】确保连接一定被关闭
conn.close()