Skip to content

Commit a886057

Browse files
committed
fix: 优化 SQLite 数据库连接配置,启用 WAL 模式提升并发性能
- 添加连接池参数(pool_size=5, max_overflow=10, pool_pre_ping) - 设置连接超时(timeout=30)并允许多线程访问(check_same_thread=False) - 通过 SQLAlchemy event 在每次连接时自动设置 PRAGMA: - journal_mode=WAL:支持读写并发,减少锁争用 - busy_timeout=30000:等待锁释放最多 30 秒 - synchronous=NORMAL:在性能与数据安全间取得平衡 - foreign_keys=ON:强制外键约束
1 parent 71ba034 commit a886057

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/web/database.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44
import shutil
55
from datetime import datetime
6-
from sqlalchemy import create_engine, text
6+
from sqlalchemy import create_engine, event, text
77
from sqlalchemy.orm import sessionmaker, DeclarativeBase
88

99
from src.web.migrations import has_pending_migrations, run_versioned_migrations
@@ -13,7 +13,29 @@
1313
DB_PATH = os.path.join(os.path.dirname(__file__), "..", "..", "data", "panwatch.db")
1414
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
1515

16-
engine = create_engine(f"sqlite:///{DB_PATH}", echo=False)
16+
engine = create_engine(
17+
f"sqlite:///{DB_PATH}",
18+
echo=False,
19+
connect_args={
20+
"timeout": 30,
21+
"check_same_thread": False,
22+
},
23+
pool_size=5,
24+
max_overflow=10,
25+
pool_pre_ping=True,
26+
)
27+
28+
29+
@event.listens_for(engine, "connect")
30+
def _set_sqlite_pragma(dbapi_conn, connection_record):
31+
cursor = dbapi_conn.cursor()
32+
cursor.execute("PRAGMA journal_mode=WAL")
33+
cursor.execute("PRAGMA busy_timeout=30000")
34+
cursor.execute("PRAGMA synchronous=NORMAL")
35+
cursor.execute("PRAGMA foreign_keys=ON")
36+
cursor.close()
37+
38+
1739
SessionLocal = sessionmaker(bind=engine)
1840

1941

0 commit comments

Comments
 (0)