mirror of
https://github.com/stardrophere/InsightRadar.git
synced 2026-06-06 00:00:05 +08:00
small update
This commit is contained in:
+23
-2
@@ -1,5 +1,5 @@
|
||||
# database.py
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
# SQLite 数据库文件位置
|
||||
@@ -10,13 +10,34 @@ engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
|
||||
# ==========================================
|
||||
# 监听 SQLite 连接,注入 PRAGMA 指令
|
||||
# ==========================================
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
cursor = dbapi_connection.cursor()
|
||||
|
||||
# 1. 开启 WAL 模式:读写分离
|
||||
cursor.execute("PRAGMA journal_mode=WAL;")
|
||||
|
||||
# 2. 优化同步模式:在 WAL 模式下,NORMAL 既能保证不丢数据,又能大幅提升写入速度
|
||||
cursor.execute("PRAGMA synchronous=NORMAL;")
|
||||
|
||||
# 3. 强制开启外键约束:极其重要!SQLite 默认不检查外键,这行能保护你的多态关联不乱套
|
||||
cursor.execute("PRAGMA foreign_keys=ON;")
|
||||
|
||||
cursor.close()
|
||||
|
||||
|
||||
# 创建数据库会话工厂
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
# 依赖注入函数:每个请求过来时,给它发一个数据库连接,请求结束时自动关闭
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
db.close()
|
||||
|
||||
Reference in New Issue
Block a user