""" 数据库管理API - 提供数据库状态查询、SQL执行、VACUUM优化等功能 兼容 SQLite / MySQL """ import os import re import tempfile import glob from flask import jsonify, request, send_from_directory from database import get_db_connection, get_all_forms, get_form_stats from db import DB_PATH, is_sqlite, is_mysql, list_table_names, get_table_columns, table_exists, get_db_size, vacuum as db_vacuum from datetime import datetime, timedelta from config import TEMPLATES_DIR # ========== 数据库统计信息 ========== def get_db_stats(): """获取数据库统计信息""" stats = { 'db_size': 0, 'tables': [], 'total_records': 0, 'file_storage': 0, 'data_storage': 0, 'forms': [] } # 获取数据库大小 stats['db_size'] = get_db_size() with get_db_connection() as conn: cursor = conn.cursor() # 获取所有表 table_names = list_table_names(conn) for table_name in table_names: # 获取表记录数 cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`") record_count = cursor.fetchone()['count'] stats['total_records'] += record_count # 获取表结构 columns = get_table_columns(conn, table_name) column_info = [{'name': c['name'], 'type': c['type']} for c in columns] stats['tables'].append({ 'name': table_name, 'record_count': record_count, 'columns': column_info }) # 获取文件存储大小 cursor.execute("SELECT COALESCE(SUM(file_size), 0) as total FROM files") file_result = cursor.fetchone() stats['file_storage'] = file_result['total'] if file_result else 0 # 获取数据存储大小(估算) cursor.execute("SELECT COALESCE(SUM(LENGTH(data)), 0) as total FROM submissions") data_result = cursor.fetchone() stats['data_storage'] = data_result['total'] if data_result else 0 # 获取每个表单的存储详情 forms = get_all_forms() for form in forms: form_id = form['id'] form_stats = get_form_stats(form_id) # 计算该表单的数据大小 with get_db_connection() as conn: cursor = conn.cursor() # 获取提交数据大小 cursor.execute("SELECT COALESCE(SUM(LENGTH(data)), 0) as total FROM submissions WHERE form_id = ?", (form_id,)) data_size = cursor.fetchone()['total'] or 0 # 获取文件大小 cursor.execute("SELECT COALESCE(SUM(file_size), 0) as total FROM files WHERE form_id = ?", (form_id,)) file_size = cursor.fetchone()['total'] or 0 stats['forms'].append({ 'id': form_id, 'title': form.get('title', '未命名表单'), 'submission_count': form_stats.get('submitted_count', 0), 'file_count': form_stats.get('file_count', 0), 'data_size': data_size, 'file_size': file_size, 'total_size': data_size + file_size }) return stats def get_table_list(): """获取表列表及结构""" tables = [] with get_db_connection() as conn: cursor = conn.cursor() table_names = list_table_names(conn) for table_name in table_names: # 获取记录数 cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`") record_count = cursor.fetchone()['count'] # 获取列信息 columns = get_table_columns(conn, table_name) tables.append({ 'name': table_name, 'record_count': record_count, 'columns': [{'name': c['name'], 'type': c['type'], 'notnull': c['notnull'], 'pk': c['pk']} for c in columns] }) return tables def execute_sql(sql): """执行SQL命令""" result = { 'success': False, 'rows': [], 'affected_rows': 0, 'execution_time': 0, 'error': None } start_time = datetime.now() try: with get_db_connection() as conn: cursor = conn.cursor() # MySQL 模式下自动转换 SQLite 风格 SQL if is_mysql(): from db import _translate_sql sql = _translate_sql(sql) # 执行SQL cursor.execute(sql) # 判断是否是查询 sql_upper = sql.strip().upper() is_query = sql_upper.startswith('SELECT') or sql_upper.startswith('PRAGMA') or sql_upper.startswith('SHOW') or sql_upper.startswith('DESCRIBE') if is_query: rows = cursor.fetchall() result['rows'] = [dict(row) for row in rows] else: result['affected_rows'] = cursor.rowcount result['success'] = True except Exception as e: result['error'] = str(e) end_time = datetime.now() result['execution_time'] = round((end_time - start_time).total_seconds() * 1000, 2) return result def browse_table(table_name, limit=50, offset=0): """浏览表数据""" result = { 'rows': [], 'total': 0, 'error': None } try: with get_db_connection() as conn: cursor = conn.cursor() # 获取总数 cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`") result['total'] = cursor.fetchone()['count'] # 获取数据 cursor.execute(f"SELECT * FROM `{table_name}` LIMIT ? OFFSET ?", (limit, offset)) rows = cursor.fetchall() result['rows'] = [dict(row) for row in rows] except Exception as e: result['error'] = str(e) return result def vacuum_database(): """执行VACUUM优化""" result = { 'success': False, 'before_size': 0, 'after_size': 0, 'freed_space': 0, 'error': None } try: # 获取优化前大小 result['before_size'] = get_db_size() # 执行优化(SQLite: VACUUM, MySQL: OPTIMIZE TABLE) db_vacuum() # 获取优化后大小 result['after_size'] = get_db_size() result['freed_space'] = max(0, result['before_size'] - result['after_size']) result['success'] = True except Exception as e: result['error'] = str(e) return result def get_temp_zip_stats(): """获取临时ZIP文件统计信息 (从文件系统temp文件夹搜索)""" stats = { 'count': 0, 'total_size': 0, 'files': [], 'earliest_expires_minutes': None, 'is_expired': False } try: temp_dir = tempfile.gettempdir() # 查找所有 form_zip_ 开头的临时ZIP文件 pattern = os.path.join(temp_dir, 'form_zip_*.zip') zip_files = glob.glob(pattern) stats['count'] = len(zip_files) now = datetime.now() earliest_expires = None for filepath in zip_files: try: filename = os.path.basename(filepath) file_size = os.path.getsize(filepath) file_mtime = datetime.fromtimestamp(os.path.getmtime(filepath)) stats['total_size'] += file_size # 从文件名解析表单ID # 格式: form_zip_{form_id}_{YYYYMMDD}_{HHMMSS}_{uuid}.zip parts = filename.replace('.zip', '').split('_') form_id = parts[2] if len(parts) >= 3 else None time_str = parts[3] + '_' + parts[4] if len(parts) >= 5 else None # 计算过期时间(临时ZIP默认30分钟过期) # 使用文件修改时间作为上传时间 uploaded_at = file_mtime expires_at = uploaded_at + timedelta(minutes=30) remaining_minutes = int((expires_at - now).total_seconds() / 60) if remaining_minutes > 0: if earliest_expires is None or remaining_minutes < earliest_expires: earliest_expires = remaining_minutes else: # 已过期 stats['is_expired'] = True file_info = { 'filename': filename, 'filepath': filepath, 'file_size': file_size, 'form_id': form_id, 'uploaded_at': uploaded_at.isoformat(), 'expires_at': expires_at.isoformat(), 'remaining_minutes': remaining_minutes } # 如果有表单ID,获取表单名称 if form_id: try: with get_db_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT title FROM forms WHERE id = ?", (form_id,)) form_row = cursor.fetchone() if form_row: file_info['form_title'] = form_row['title'] else: file_info['form_title'] = '未知表单' except: file_info['form_title'] = '未知表单' else: file_info['form_title'] = '未知表单' stats['files'].append(file_info) except Exception as e: # 跳过处理失败的文件 continue stats['earliest_expires_minutes'] = earliest_expires if not stats['is_expired'] else -1 except Exception as e: stats['error'] = str(e) return stats def cleanup_all_temp_zips(): """清理所有临时ZIP文件 (从文件系统temp文件夹删除)""" result = { 'success': False, 'deleted_count': 0, 'freed_size': 0, 'error': None, 'deleted_files': [] } try: temp_dir = tempfile.gettempdir() # 查找所有 form_zip_ 开头的临时ZIP文件 pattern = os.path.join(temp_dir, 'form_zip_*.zip') zip_files = glob.glob(pattern) total_freed = 0 deleted_count = 0 for filepath in zip_files: try: filename = os.path.basename(filepath) file_size = os.path.getsize(filepath) # 删除文件 os.remove(filepath) deleted_count += 1 total_freed += file_size result['deleted_files'].append({ 'filename': filename, 'file_size': file_size }) except Exception as e: # 跳过删除失败的文件 continue result['deleted_count'] = deleted_count result['freed_size'] = total_freed result['success'] = True except Exception as e: result['error'] = str(e) return result # ========== API路由注册 ========== def register_db_manage_routes(app, require_admin): """注册数据库管理API路由""" @app.route('/db_manage') @require_admin def db_manage_page(): """数据库管理页面""" return send_from_directory(TEMPLATES_DIR, 'db_manage.html') @app.route('/api/db/stats') @require_admin def api_db_stats(): """获取数据库统计信息""" try: stats = get_db_stats() return jsonify(stats) except Exception as e: return jsonify(error=str(e)), 500 @app.route('/api/db/tables') @require_admin def api_db_tables(): """获取表列表""" try: tables = get_table_list() return jsonify({'tables': tables}) except Exception as e: return jsonify(error=str(e)), 500 @app.route('/api/db/execute', methods=['POST']) @require_admin def api_db_execute(): """执行SQL命令""" try: data = request.get_json() sql = data.get('sql', '').strip() if not sql: return jsonify(success=False, error='SQL命令不能为空'), 400 # 禁止危险操作 dangerous_keywords = ['DROP DATABASE', 'ATTACH', 'DETACH'] for keyword in dangerous_keywords: if keyword.upper() in sql.upper(): return jsonify(success=False, error=f'禁止执行包含 {keyword} 的命令'), 403 result = execute_sql(sql) return jsonify(result) except Exception as e: return jsonify(success=False, error=str(e)), 500 @app.route('/api/db/browse') @require_admin def api_db_browse(): """浏览表数据""" try: table_name = request.args.get('table', '') limit = int(request.args.get('limit', 50)) offset = int(request.args.get('offset', 0)) if not table_name: return jsonify(error='表名不能为空'), 400 # 验证表名存在 with get_db_connection() as conn: if not table_exists(conn, table_name): return jsonify(error='表不存在'), 404 result = browse_table(table_name, limit, offset) if result['error']: return jsonify(error=result['error']), 500 return jsonify(result) except Exception as e: return jsonify(error=str(e)), 500 @app.route('/api/db/sessions') @require_admin def api_db_sessions(): """获取所有活跃会话(管理员)""" from database import get_all_active_sessions try: sessions = get_all_active_sessions() return jsonify({ 'sessions': sessions, 'count': len(sessions) }) except Exception as e: return jsonify(error=str(e)), 500 @app.route('/api/db/sessions/cleanup', methods=['POST']) @require_admin def api_cleanup_sessions(): """手动清理过期会话""" from database import cleanup_expired_sessions try: count = cleanup_expired_sessions() return jsonify({ 'success': True, 'cleaned_count': count, 'message': f'已清理 {count} 个过期会话' }) except Exception as e: return jsonify(error=str(e)), 500 @app.route('/api/db/vacuum', methods=['POST']) @require_admin def api_db_vacuum(): """执行VACUUM优化""" try: result = vacuum_database() if result['success']: return jsonify(result) else: return jsonify(result), 500 except Exception as e: return jsonify(success=False, error=str(e)), 500 @app.route('/api/db/temp-zip-stats') @require_admin def api_temp_zip_stats(): """获取临时ZIP文件统计信息""" try: stats = get_temp_zip_stats() return jsonify(stats) except Exception as e: return jsonify(success=False, error=str(e)), 500 @app.route('/api/db/temp-zip-cleanup', methods=['POST']) @require_admin def api_temp_zip_cleanup(): """清理所有临时ZIP文件""" try: result = cleanup_all_temp_zips() if result['success']: return jsonify(result) else: return jsonify(result), 500 except Exception as e: return jsonify(success=False, error=str(e)), 500