初版:上传接口(从线上实例导出,适配容器端口)
This commit is contained in:
@@ -0,0 +1,394 @@
|
||||
"""
|
||||
统一数据库管理器
|
||||
读取 config.yml,根据配置返回对应数据库的连接。
|
||||
切换数据库只需修改 config.yml 中的 type 字段。
|
||||
|
||||
核心设计:
|
||||
- get_db_connection() 返回的连接,其 cursor 自动适配 SQL 方言差异
|
||||
- 调用方(database.py 等)继续写 SQLite 风格的 SQL(? 占位符、INSERT OR REPLACE 等)
|
||||
- MySQL 模式下,游标包装层自动将 SQL 转换为 MySQL 兼容语法
|
||||
- 因此 database.py 的 85+ 处 cursor.execute 无需任何修改
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import yaml
|
||||
from contextlib import contextmanager
|
||||
|
||||
from config import BASE_DIR, DATA_DIR
|
||||
|
||||
|
||||
# ========== 读取配置 ==========
|
||||
|
||||
_config_path = os.path.join(BASE_DIR, 'config.yml')
|
||||
|
||||
|
||||
def _load_db_config():
|
||||
"""从 config.yml 加载数据库配置,文件不存在时使用默认值"""
|
||||
if not os.path.exists(_config_path):
|
||||
return {
|
||||
'database': {
|
||||
'type': 'sqlite',
|
||||
'sqlite': {'path': os.path.join(DATA_DIR, 'app.db')},
|
||||
'mysql': {}
|
||||
}
|
||||
}
|
||||
with open(_config_path, 'r', encoding='utf-8') as f:
|
||||
cfg = yaml.safe_load(f) or {}
|
||||
if 'database' not in cfg:
|
||||
cfg['database'] = {'type': 'sqlite'}
|
||||
return cfg
|
||||
|
||||
|
||||
_db_config = _load_db_config()
|
||||
_db_section = _db_config.get('database', {})
|
||||
|
||||
# 数据库类型:sqlite / mysql
|
||||
DB_TYPE = _db_section.get('type', 'sqlite')
|
||||
|
||||
# SQLite 路径(相对路径自动转换为绝对路径)
|
||||
_sqlite_path = _db_section.get('sqlite', {}).get('path', 'data/app.db')
|
||||
if not os.path.isabs(_sqlite_path):
|
||||
_sqlite_path = os.path.join(BASE_DIR, _sqlite_path)
|
||||
DB_PATH = _sqlite_path
|
||||
|
||||
# MySQL 连接参数
|
||||
_mysql_cfg = _db_section.get('mysql', {})
|
||||
MYSQL_CONFIG = {
|
||||
'host': _mysql_cfg.get('host', 'localhost'),
|
||||
'port': int(_mysql_cfg.get('port', 3306)),
|
||||
'user': _mysql_cfg.get('user', 'root'),
|
||||
'password': _mysql_cfg.get('password', ''),
|
||||
'database': _mysql_cfg.get('database', 'form_system'),
|
||||
'charset': _mysql_cfg.get('charset', 'utf8mb4'),
|
||||
'blob_type': _mysql_cfg.get('blob_type', 'LONGBLOB'),
|
||||
'max_allowed_packet': int(_mysql_cfg.get('max_allowed_packet', 0)),
|
||||
}
|
||||
|
||||
|
||||
# ========== SQL 方言转换 ==========
|
||||
|
||||
def _translate_sql(sql):
|
||||
"""
|
||||
将 SQLite 风格 SQL 转换为 MySQL 兼容语法。
|
||||
仅在 MySQL 模式下调用;SQLite 模式下原样返回。
|
||||
|
||||
转换规则:
|
||||
1. ? 占位符 → %s
|
||||
2. INSERT OR REPLACE INTO → REPLACE INTO
|
||||
3. INTEGER PRIMARY KEY AUTOINCREMENT → INTEGER PRIMARY KEY AUTO_INCREMENT
|
||||
4. CREATE TABLE IF NOT EXISTS → 保持不变(MySQL 也支持)
|
||||
5. BLOB 类型 → LONGBLOB(MySQL 的 BLOB 只有 64KB,LONGBLOB 可达 4GB)
|
||||
"""
|
||||
# 1. 参数占位符 ? → %s
|
||||
# 注意:只转换独立的 ?,不碰字符串字面量内的问号
|
||||
# 简单方案:按 ? 出现的位置逐个替换(SQL 中的 ? 一定是参数占位符)
|
||||
sql = sql.replace('?', '%s')
|
||||
|
||||
# 2. INSERT OR REPLACE INTO → REPLACE INTO
|
||||
sql = re.sub(
|
||||
r'INSERT\s+OR\s+REPLACE\s+INTO',
|
||||
'REPLACE INTO',
|
||||
sql,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
# 3. AUTOINCREMENT → AUTO_INCREMENT
|
||||
sql = re.sub(
|
||||
r'\bAUTOINCREMENT\b',
|
||||
'AUTO_INCREMENT',
|
||||
sql,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
# 4. BLOB → 配置的 blob_type(默认 LONGBLOB)
|
||||
sql = re.sub(
|
||||
r'\bBLOB\b',
|
||||
MYSQL_CONFIG['blob_type'],
|
||||
sql,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
return sql
|
||||
|
||||
|
||||
# ========== 游标包装层 ==========
|
||||
|
||||
class _MySQLCursorWrapper:
|
||||
"""
|
||||
包装 MySQL 游标,自动将 SQLite 风格 SQL 转换为 MySQL 语法。
|
||||
对调用方完全透明,行为与 sqlite3.Cursor 一致。
|
||||
"""
|
||||
|
||||
def __init__(self, cursor):
|
||||
self._cursor = cursor
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
translated = _translate_sql(sql)
|
||||
if params is not None:
|
||||
return self._cursor.execute(translated, params)
|
||||
return self._cursor.execute(translated)
|
||||
|
||||
def executemany(self, sql, params_seq):
|
||||
translated = _translate_sql(sql)
|
||||
return self._cursor.executemany(translated, params_seq)
|
||||
|
||||
def fetchone(self):
|
||||
return self._cursor.fetchone()
|
||||
|
||||
def fetchall(self):
|
||||
return self._cursor.fetchall()
|
||||
|
||||
def fetchmany(self, size=None):
|
||||
if size is not None:
|
||||
return self._cursor.fetchmany(size)
|
||||
return self._cursor.fetchmany()
|
||||
|
||||
@property
|
||||
def rowcount(self):
|
||||
return self._cursor.rowcount
|
||||
|
||||
@property
|
||||
def lastrowid(self):
|
||||
return self._cursor.lastrowid
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return self._cursor.description
|
||||
|
||||
def close(self):
|
||||
return self._cursor.close()
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._cursor)
|
||||
|
||||
def __getattr__(self, name):
|
||||
"""透明代理其他属性"""
|
||||
return getattr(self._cursor, name)
|
||||
|
||||
|
||||
class _MySQLConnectionWrapper:
|
||||
"""
|
||||
包装 MySQL 连接,使 cursor() 返回包装后的游标。
|
||||
commit / rollback / close 直接代理。
|
||||
"""
|
||||
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
|
||||
def cursor(self):
|
||||
return _MySQLCursorWrapper(self._conn.cursor())
|
||||
|
||||
def commit(self):
|
||||
return self._conn.commit()
|
||||
|
||||
def rollback(self):
|
||||
return self._conn.rollback()
|
||||
|
||||
def close(self):
|
||||
return self._conn.close()
|
||||
|
||||
def __getattr__(self, name):
|
||||
"""透明代理其他属性"""
|
||||
return getattr(self._conn, name)
|
||||
|
||||
|
||||
# ========== 统一连接管理 ==========
|
||||
|
||||
@contextmanager
|
||||
def get_db_connection():
|
||||
"""
|
||||
获取数据库连接上下文管理器。
|
||||
根据 config.yml 的 type 字段自动选择 SQLite 或 MySQL。
|
||||
返回的连接对象具有统一的接口:
|
||||
- cursor().execute() 接受 SQLite 风格 SQL(? 占位符、INSERT OR REPLACE 等)
|
||||
- MySQL 模式下自动转换为 MySQL 兼容语法
|
||||
- row_factory 返回 dict-like 行(SQLite 用 Row,MySQL 用 DictCursor)
|
||||
- commit / rollback / close 行为一致
|
||||
"""
|
||||
if DB_TYPE == 'sqlite':
|
||||
import sqlite3
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
raise e
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
elif DB_TYPE == 'mysql':
|
||||
try:
|
||||
import pymysql
|
||||
except ImportError:
|
||||
raise RuntimeError("MySQL 模式需要安装 pymysql:pip install pymysql")
|
||||
|
||||
conn = pymysql.connect(
|
||||
host=MYSQL_CONFIG['host'],
|
||||
port=MYSQL_CONFIG['port'],
|
||||
user=MYSQL_CONFIG['user'],
|
||||
password=MYSQL_CONFIG['password'],
|
||||
database=MYSQL_CONFIG['database'],
|
||||
charset=MYSQL_CONFIG['charset'],
|
||||
cursorclass=pymysql.cursors.DictCursor
|
||||
)
|
||||
try:
|
||||
yield _MySQLConnectionWrapper(conn)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
raise e
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
else:
|
||||
raise ValueError(f"不支持的数据库类型: {DB_TYPE}(可选值: sqlite / mysql)")
|
||||
|
||||
|
||||
def is_sqlite():
|
||||
"""当前是否为 SQLite 模式"""
|
||||
return DB_TYPE == 'sqlite'
|
||||
|
||||
|
||||
def is_mysql():
|
||||
"""当前是否为 MySQL 模式"""
|
||||
return DB_TYPE == 'mysql'
|
||||
|
||||
|
||||
# ========== 跨数据库辅助函数 ==========
|
||||
|
||||
def list_table_names(conn):
|
||||
"""获取所有表名(兼容 SQLite / MySQL)"""
|
||||
cursor = conn.cursor()
|
||||
if is_sqlite():
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||
return [row['name'] for row in cursor.fetchall()]
|
||||
else:
|
||||
cursor.execute("""
|
||||
SELECT TABLE_NAME as name
|
||||
FROM information_schema.tables
|
||||
WHERE TABLE_SCHEMA = %s AND TABLE_TYPE = 'BASE TABLE'
|
||||
ORDER BY TABLE_NAME
|
||||
""", (MYSQL_CONFIG['database'],))
|
||||
return [row['name'] for row in cursor.fetchall()]
|
||||
|
||||
|
||||
def table_exists(conn, table_name):
|
||||
"""检查表是否存在(兼容 SQLite / MySQL)"""
|
||||
cursor = conn.cursor()
|
||||
if is_sqlite():
|
||||
cursor.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name = ?",
|
||||
(table_name,)
|
||||
)
|
||||
return cursor.fetchone() is not None
|
||||
else:
|
||||
cursor.execute("""
|
||||
SELECT TABLE_NAME
|
||||
FROM information_schema.tables
|
||||
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
|
||||
""", (MYSQL_CONFIG['database'], table_name))
|
||||
return cursor.fetchone() is not None
|
||||
|
||||
|
||||
def get_table_columns(conn, table_name):
|
||||
"""
|
||||
获取表的列信息(兼容 SQLite / MySQL)
|
||||
返回列表,每项为 dict: {name, type, notnull, pk, dflt}
|
||||
"""
|
||||
cursor = conn.cursor()
|
||||
if is_sqlite():
|
||||
cursor.execute(f"PRAGMA table_info({table_name})")
|
||||
return [
|
||||
{
|
||||
'name': row['name'],
|
||||
'type': row['type'],
|
||||
'notnull': row['notnull'],
|
||||
'pk': row['pk'],
|
||||
'dflt': row['dflt_value']
|
||||
}
|
||||
for row in cursor.fetchall()
|
||||
]
|
||||
else:
|
||||
cursor.execute("""
|
||||
SELECT COLUMN_NAME as name, DATA_TYPE as type,
|
||||
(IS_NULLABLE = 'NO') as notnull,
|
||||
(COLUMN_KEY = 'PRI') as pk,
|
||||
COLUMN_DEFAULT as dflt
|
||||
FROM information_schema.columns
|
||||
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
|
||||
ORDER BY ORDINAL_POSITION
|
||||
""", (MYSQL_CONFIG['database'], table_name))
|
||||
return [
|
||||
{
|
||||
'name': row['name'],
|
||||
'type': row['type'],
|
||||
'notnull': 1 if row['notnull'] else 0,
|
||||
'pk': 1 if row['pk'] else 0,
|
||||
'dflt': row['dflt']
|
||||
}
|
||||
for row in cursor.fetchall()
|
||||
]
|
||||
|
||||
|
||||
def get_db_size():
|
||||
"""
|
||||
获取数据库文件大小(字节)。
|
||||
SQLite:返回 .db 文件大小
|
||||
MySQL:返回该数据库所有表的总数据大小
|
||||
"""
|
||||
if is_sqlite():
|
||||
if os.path.exists(DB_PATH):
|
||||
return os.path.getsize(DB_PATH)
|
||||
return 0
|
||||
else:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT COALESCE(SUM(data_length + index_length), 0) as size
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = %s
|
||||
""", (MYSQL_CONFIG['database'],))
|
||||
row = cursor.fetchone()
|
||||
return row['size'] if row else 0
|
||||
|
||||
|
||||
def vacuum():
|
||||
"""执行数据库优化(SQLite: VACUUM, MySQL: OPTIMIZE TABLE)"""
|
||||
if is_sqlite():
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('VACUUM')
|
||||
else:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
tables = list_table_names(conn)
|
||||
for table_name in tables:
|
||||
cursor.execute(f"OPTIMIZE TABLE `{table_name}`")
|
||||
|
||||
|
||||
def init_mysql_session_vars():
|
||||
"""
|
||||
MySQL 启动时配置会话级变量。
|
||||
- SET GLOBAL max_allowed_packet:提升单条 SQL 最大尺寸(需 SUPER 权限)
|
||||
- SET SESSION max_allowed_packet:当前连接生效
|
||||
如果用户权限不足或 max_allowed_packet=0(未配置),跳过。
|
||||
"""
|
||||
if not is_mysql():
|
||||
return
|
||||
if MYSQL_CONFIG['max_allowed_packet'] <= 0:
|
||||
return
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
val = MYSQL_CONFIG['max_allowed_packet']
|
||||
try:
|
||||
cursor.execute(f"SET GLOBAL max_allowed_packet = {val}")
|
||||
print(f"✅ MySQL max_allowed_packet 全局已设为 {val} ({val // 1024 // 1024}MB)")
|
||||
except Exception as e:
|
||||
print(f"⚠️ 设置 GLOBAL max_allowed_packet 失败(可能权限不足,仅设置 SESSION 级): {e}")
|
||||
cursor.execute(f"SET SESSION max_allowed_packet = {val}")
|
||||
print(f"✅ MySQL max_allowed_packet 会话级已设为 {val} ({val // 1024 // 1024}MB)")
|
||||
except Exception as e:
|
||||
print(f"⚠️ MySQL 会话变量配置失败: {e}")
|
||||
Reference in New Issue
Block a user