"""数据库初始化与连接管理""" import sqlite3 import os from config import DB_PATH def get_db(): """获取数据库连接(FastAPI 依赖注入用)""" conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") try: yield conn finally: conn.close() def get_db_conn(): """获取数据库连接(直接调用)""" conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") return conn def init_db(): """初始化数据库,创建所有表""" conn = get_db_conn() cursor = conn.cursor() # ====== 年度版本表 ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS risk_versions ( id INTEGER PRIMARY KEY AUTOINCREMENT, year INTEGER NOT NULL UNIQUE, version_name TEXT NOT NULL, description TEXT DEFAULT '', status TEXT DEFAULT '编辑中', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 风险清单表 ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS risk_items ( id INTEGER PRIMARY KEY AUTOINCREMENT, version_id INTEGER NOT NULL, risk_code TEXT NOT NULL, department TEXT NOT NULL, risk_no TEXT NOT NULL, risk_desc TEXT NOT NULL, is_economic TEXT DEFAULT '否', in_responsibility TEXT DEFAULT '是', has_regulation TEXT DEFAULT '是', probability_score REAL DEFAULT 1, impact_score REAL DEFAULT 1, risk_total_score REAL DEFAULT 1, framework TEXT DEFAULT '', risk_level TEXT DEFAULT '低风险', risk_type TEXT DEFAULT '运营', control_flow_no TEXT DEFAULT '', target_category TEXT DEFAULT '', target_content TEXT DEFAULT '', coso_erm_category TEXT DEFAULT '', indicator TEXT DEFAULT '', formula TEXT DEFAULT '', formula_attr TEXT DEFAULT '调查获取', low_risk_threshold TEXT DEFAULT '0.95', mid_risk_threshold TEXT DEFAULT '0.85', high_risk_threshold TEXT DEFAULT '0.75', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (version_id) REFERENCES risk_versions(id) ON DELETE CASCADE, UNIQUE(version_id, risk_code) ) """) # ====== 调查任务表(按科室+年度) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS survey_tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, version_id INTEGER NOT NULL, department TEXT NOT NULL DEFAULT '', task_name TEXT NOT NULL, status TEXT DEFAULT '待下发', respondent_count INTEGER DEFAULT 0, response_count INTEGER DEFAULT 0, audit_status TEXT DEFAULT '待提交', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (version_id) REFERENCES risk_versions(id) ON DELETE CASCADE ) """) # ====== 调查结果表(含选项+审核状态) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS survey_responses ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, risk_item_id INTEGER NOT NULL, risk_no TEXT DEFAULT '', risk_desc TEXT DEFAULT '', department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', respondent TEXT DEFAULT '', status TEXT DEFAULT '待审核', audit_remark TEXT DEFAULT '', submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, audited_at TIMESTAMP DEFAULT NULL, FOREIGN KEY (task_id) REFERENCES survey_tasks(id) ON DELETE CASCADE, FOREIGN KEY (risk_item_id) REFERENCES risk_items(id) ON DELETE CASCADE ) """) # ====== 自动迁移旧表:检测是否需要重建 ====== cursor.execute("PRAGMA table_info(survey_tasks)") task_cols = [r[1] for r in cursor.fetchall()] if "department" not in task_cols: cursor.execute("DROP TABLE IF EXISTS survey_responses") cursor.execute("DROP TABLE survey_tasks") cursor.execute(""" CREATE TABLE survey_tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, version_id INTEGER NOT NULL, department TEXT NOT NULL DEFAULT '', task_name TEXT NOT NULL, status TEXT DEFAULT '待下发', respondent_count INTEGER DEFAULT 0, response_count INTEGER DEFAULT 0, audit_status TEXT DEFAULT '待提交', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (version_id) REFERENCES risk_versions(id) ON DELETE CASCADE ) """) cursor.execute(""" CREATE TABLE survey_responses ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, risk_item_id INTEGER NOT NULL, risk_no TEXT DEFAULT '', risk_desc TEXT DEFAULT '', department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', respondent TEXT DEFAULT '', status TEXT DEFAULT '待审核', audit_remark TEXT DEFAULT '', submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, audited_at TIMESTAMP DEFAULT NULL, FOREIGN KEY (task_id) REFERENCES survey_tasks(id) ON DELETE CASCADE, FOREIGN KEY (risk_item_id) REFERENCES risk_items(id) ON DELETE CASCADE ) """) print("survey_tasks / survey_responses 表已迁移为新结构") # ====== 客观指标计算结果表 ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS objective_results ( id INTEGER PRIMARY KEY AUTOINCREMENT, risk_item_id INTEGER NOT NULL, version_id INTEGER NOT NULL, indicator_value REAL DEFAULT 0, calc_source TEXT DEFAULT '手动录入', calc_detail TEXT DEFAULT '', calc_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (risk_item_id) REFERENCES risk_items(id) ON DELETE CASCADE, FOREIGN KEY (version_id) REFERENCES risk_versions(id) ON DELETE CASCADE ) """) # ====== 综合风险评估结果表 ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS risk_assessments ( id INTEGER PRIMARY KEY AUTOINCREMENT, risk_item_id INTEGER NOT NULL, version_id INTEGER NOT NULL, subjective_score REAL DEFAULT 0, objective_score REAL DEFAULT 0, combined_score REAL DEFAULT 0, final_risk_level TEXT DEFAULT '', assessment_detail TEXT DEFAULT '', assessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (risk_item_id) REFERENCES risk_items(id) ON DELETE CASCADE, FOREIGN KEY (version_id) REFERENCES risk_versions(id) ON DELETE CASCADE ) """) # ====== 风险点唯一值表(基础表,风险编号为主键) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS risk_unique_points ( risk_no TEXT PRIMARY KEY, risk_desc TEXT NOT NULL, business_level TEXT DEFAULT '', business_framework TEXT DEFAULT '', level_code TEXT DEFAULT '', risk_number INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 科室表(基础表) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS departments ( id INTEGER PRIMARY KEY AUTOINCREMENT, dept_code TEXT NOT NULL UNIQUE, dept_name TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 目标分类表(基础表) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS target_categories ( id INTEGER PRIMARY KEY AUTOINCREMENT, cat_code TEXT NOT NULL UNIQUE, cat_name TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== COSO-ERM目标类别表(基础表) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS coso_erm_categories ( id INTEGER PRIMARY KEY AUTOINCREMENT, coso_code TEXT NOT NULL UNIQUE, coso_name TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 自动迁移:如果旧表有 framework 列则删除重建 ====== cursor.execute("PRAGMA table_info(risk_unique_points)") cols = [r[1] for r in cursor.fetchall()] if "framework" in cols and "business_level" not in cols: cursor.execute("DROP TABLE risk_unique_points") cursor.execute(""" CREATE TABLE risk_unique_points ( risk_no TEXT PRIMARY KEY, risk_desc TEXT NOT NULL, business_level TEXT DEFAULT '', business_framework TEXT DEFAULT '', level_code TEXT DEFAULT '', risk_number INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) print("risk_unique_points 表已迁移为新结构") # ====== AI风险分析待审核表 ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS ai_risk_candidates ( id INTEGER PRIMARY KEY AUTOINCREMENT, risk_desc TEXT NOT NULL, suggested_business_level TEXT DEFAULT '', suggested_business_framework TEXT DEFAULT '', suggested_level_code TEXT DEFAULT '', source_material TEXT DEFAULT '', ai_analysis TEXT DEFAULT '', similarity_score REAL DEFAULT 0, matched_risk_no TEXT DEFAULT '', status TEXT DEFAULT '待审核', audit_remark TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, audited_at TIMESTAMP DEFAULT NULL ) """) # ====== 检查报告表(记录每次上传的检查报告) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS inspection_reports ( id INTEGER PRIMARY KEY AUTOINCREMENT, year INTEGER NOT NULL, report_name TEXT NOT NULL, report_date TEXT DEFAULT '', batch_no TEXT NOT NULL, source_file TEXT DEFAULT '', total_identified INTEGER DEFAULT 0, new_risks INTEGER DEFAULT 0, existing_matches INTEGER DEFAULT 0, status TEXT DEFAULT '已完成', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 检查风险数据表(与调查表数据结构一致 + 报告元数据) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS inspection_risk_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, year INTEGER NOT NULL, report_id INTEGER, risk_no TEXT DEFAULT '', risk_desc TEXT DEFAULT '', department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', batch_no TEXT DEFAULT '', report_name TEXT DEFAULT '', report_date TEXT DEFAULT '', status TEXT DEFAULT '已入库', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 检查风险候选表(AI分析后待审核) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS inspection_risk_candidates ( id INTEGER PRIMARY KEY AUTOINCREMENT, report_id INTEGER, year INTEGER NOT NULL, risk_no TEXT DEFAULT '', risk_desc TEXT NOT NULL, department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', is_new INTEGER DEFAULT 1, matched_risk_no TEXT DEFAULT '', match_reason TEXT DEFAULT '', ai_analysis TEXT DEFAULT '', source_material TEXT DEFAULT '', status TEXT DEFAULT '待审核', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 合并风险数据表(调查数据 + 检查数据合并去重) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS merged_risk_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, version_id INTEGER NOT NULL, year INTEGER, risk_no TEXT DEFAULT '', risk_desc TEXT DEFAULT '', department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', data_source TEXT DEFAULT '', has_duplicate INTEGER DEFAULT 0, duplicate_group_id INTEGER DEFAULT 0, is_selected INTEGER DEFAULT 0, merge_status TEXT DEFAULT 'unique', survey_response_id INTEGER, inspection_data_id INTEGER, risk_item_id INTEGER, survey_respondent TEXT DEFAULT '', inspection_report_name TEXT DEFAULT '', subjective_score REAL DEFAULT 0, combined_score REAL DEFAULT 0, final_risk_level TEXT DEFAULT '', assessment_detail TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 检查数据汇总表(按风险点分组汇总后) ====== cursor.execute(""" CREATE TABLE IF NOT EXISTS inspection_aggregated ( id INTEGER PRIMARY KEY AUTOINCREMENT, year INTEGER NOT NULL, risk_no TEXT DEFAULT '', risk_desc TEXT DEFAULT '', department TEXT DEFAULT '', is_economic TEXT DEFAULT '否', survey_choice TEXT DEFAULT '', occurrence_count INTEGER DEFAULT 0, occurrence_amount REAL DEFAULT 0, remark TEXT DEFAULT '', source_reports TEXT DEFAULT '', source_record_count INTEGER DEFAULT 0, source_record_ids TEXT DEFAULT '', subjective_score REAL DEFAULT 0, combined_score REAL DEFAULT 0, final_risk_level TEXT DEFAULT '', assessment_detail TEXT DEFAULT '', aggregated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # ====== 自动初始化:从 risk_items 提取唯一值填充三张基础表 ====== _auto_populate_base_tables(cursor) # ====== 自动补充 merged_risk_data 表的汇总来源字段 ====== cursor.execute("PRAGMA table_info(merged_risk_data)") existing_cols = {row[1] for row in cursor.fetchall()} new_cols = { "source_record_count": "INTEGER DEFAULT 1", "source_record_ids": "TEXT DEFAULT ''", } for col, col_type in new_cols.items(): if col not in existing_cols: cursor.execute(f"ALTER TABLE merged_risk_data ADD COLUMN {col} {col_type}") print(f" merged_risk_data 表已添加字段: {col}") conn.commit() conn.close() print("数据库初始化完成") def _auto_populate_base_tables(cursor): """从 risk_items 表提取唯一值,自动填充科室表、目标分类表、COSO-ERM目标类别表""" # 科室 cursor.execute("SELECT COUNT(*) as c FROM departments") if cursor.fetchone()["c"] == 0: cursor.execute("SELECT DISTINCT department FROM risk_items WHERE department != '' AND department IS NOT NULL ORDER BY department") depts = [r["department"] for r in cursor.fetchall()] for i, dept in enumerate(depts, 1): code = f"DEPT-{i:03d}" cursor.execute("INSERT INTO departments (dept_code, dept_name) VALUES (?, ?)", (code, dept)) if depts: print(f"科室表自动填充 {len(depts)} 条记录") # 目标分类 cursor.execute("SELECT COUNT(*) as c FROM target_categories") if cursor.fetchone()["c"] == 0: cursor.execute("SELECT DISTINCT target_category FROM risk_items WHERE target_category != '' AND target_category IS NOT NULL ORDER BY target_category") cats = [r["target_category"] for r in cursor.fetchall()] for i, cat in enumerate(cats, 1): code = f"TC-{i:03d}" cursor.execute("INSERT INTO target_categories (cat_code, cat_name) VALUES (?, ?)", (code, cat)) if cats: print(f"目标分类表自动填充 {len(cats)} 条记录") # COSO-ERM目标类别 cursor.execute("SELECT COUNT(*) as c FROM coso_erm_categories") if cursor.fetchone()["c"] == 0: cursor.execute("SELECT DISTINCT coso_erm_category FROM risk_items WHERE coso_erm_category != '' AND coso_erm_category IS NOT NULL ORDER BY coso_erm_category") cosos = [r["coso_erm_category"] for r in cursor.fetchall()] for i, coso in enumerate(cosos, 1): code = f"COSO-{i:03d}" cursor.execute("INSERT INTO coso_erm_categories (coso_code, coso_name) VALUES (?, ?)", (code, coso)) if cosos: print(f"COSO-ERM目标类别表自动填充 {len(cosos)} 条记录") if __name__ == "__main__": init_db()