refactor: database.py 添加 MySQL 连接池管理
This commit is contained in:
@@ -1,40 +1,61 @@
|
|||||||
"""SQLite 数据库操作"""
|
"""数据库操作 - 支持 MySQL"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sqlite3
|
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import date, time, datetime, timedelta
|
from datetime import date, time, datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
import mysql.connector
|
||||||
|
from mysql.connector import pooling
|
||||||
|
|
||||||
from .models import Exercise, Meal, Sleep, Weight, UserConfig, User, Reading, Invite
|
from .models import Exercise, Meal, Sleep, Weight, UserConfig, User, Reading, Invite
|
||||||
|
|
||||||
|
|
||||||
def get_db_path() -> Path:
|
# 数据库连接池(全局)
|
||||||
"""获取数据库路径(支持环境变量配置)"""
|
_connection_pool = None
|
||||||
# 优先使用环境变量
|
|
||||||
env_path = os.environ.get("VITALS_DB_PATH")
|
|
||||||
if env_path:
|
|
||||||
db_path = Path(env_path)
|
|
||||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
return db_path
|
|
||||||
|
|
||||||
# 默认路径
|
|
||||||
db_dir = Path.home() / ".vitals"
|
def get_mysql_config() -> dict:
|
||||||
db_dir.mkdir(exist_ok=True)
|
"""获取 MySQL 配置"""
|
||||||
return db_dir / "vitals.db"
|
return {
|
||||||
|
"host": os.environ.get("MYSQL_HOST", "localhost"),
|
||||||
|
"port": int(os.environ.get("MYSQL_PORT", "3306")),
|
||||||
|
"user": os.environ.get("MYSQL_USER", "vitals"),
|
||||||
|
"password": os.environ.get("MYSQL_PASSWORD", ""),
|
||||||
|
"database": os.environ.get("MYSQL_DATABASE", "vitals"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def init_connection_pool():
|
||||||
|
"""初始化数据库连接池"""
|
||||||
|
global _connection_pool
|
||||||
|
if _connection_pool is None:
|
||||||
|
config = get_mysql_config()
|
||||||
|
_connection_pool = pooling.MySQLConnectionPool(
|
||||||
|
pool_name="vitals_pool",
|
||||||
|
pool_size=5,
|
||||||
|
pool_reset_session=True,
|
||||||
|
**config
|
||||||
|
)
|
||||||
|
return _connection_pool
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def get_connection():
|
def get_connection():
|
||||||
"""获取数据库连接"""
|
"""获取数据库连接"""
|
||||||
conn = sqlite3.connect(get_db_path())
|
pool = init_connection_pool()
|
||||||
conn.row_factory = sqlite3.Row
|
conn = pool.get_connection()
|
||||||
try:
|
try:
|
||||||
yield conn
|
cursor = conn.cursor(dictionary=True)
|
||||||
|
yield conn, cursor
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
|
cursor.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user