| 27 | |
| 28 | |
| 29 | void Route_QueryDB(httplib::Server& svr) |
| 30 | { |
| 31 | svr.Post("/QueryDB/execute", [](const httplib::Request& req, httplib::Response& res) |
| 32 | { |
| 33 | json reqJson; |
| 34 | json resp; |
| 35 | |
| 36 | try |
| 37 | { |
| 38 | reqJson = json::parse(req.body); |
| 39 | } |
| 40 | catch (...) |
| 41 | { |
| 42 | resp["ret"] = -1; |
| 43 | resp["msg"] = "invalid json"; |
| 44 | res.set_content(resp.dump(), "application/json"); |
| 45 | return; |
| 46 | } |
| 47 | |
| 48 | |
| 49 | //初始化数据库管理器 |
| 50 | //OutputDebugStringA("[QueryDB] 初始化数据库管理器\n"); |
| 51 | xmgr::DatabaseMgr& g_dbMgr = xmgr::DatabaseMgr::getInstance(); |
| 52 | //OutputDebugStringA("[QueryDB] 初始化完成\n"); |
| 53 | |
| 54 | |
| 55 | std::string optDbName = reqJson.value("optDbName", ""); // MicroMsg.db |
| 56 | std::string sql = reqJson.value("SQL", ""); // 查询语句 SELECT * FROM ChatRoom LIMIT 10 |
| 57 | |
| 58 | auto result = g_dbMgr.execute(optDbName, sql); |
| 59 | |
| 60 | |
| 61 | // 使用临界区保护数据库访问 |
| 62 | /* |
| 63 | EnterCriticalSection(&g_dbMgrCriticalSection); |
| 64 | try { |
| 65 | auto start = std::chrono::high_resolution_clock::now(); |
| 66 | auto result = g_dbMgr.execute(optDbName, sql); |
| 67 | auto end = std::chrono::high_resolution_clock::now(); |
| 68 | |
| 69 | auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); |
| 70 | |
| 71 | resp["ret"] = result.value("status", 0); |
| 72 | resp["msg"] = result.value("desc", ""); |
| 73 | resp["data"] = result.value("data", json::array()); |
| 74 | resp["duration_ms"] = duration.count(); |
| 75 | |
| 76 | // 慢查询日志 |
| 77 | if (duration.count() > 1000) { |
| 78 | OutputDebugStringA(format_string("Slow query: %lldms - %s", duration.count(), sql.substr(0, 100)).c_str()); |
| 79 | } |
| 80 | |
| 81 | } |
| 82 | catch (const std::exception& e) { |
| 83 | resp["ret"] = -500; |
| 84 | resp["msg"] = std::string("Database error: ") + e.what(); |
| 85 | } |
| 86 | LeaveCriticalSection(&g_dbMgrCriticalSection); |
no test coverage detected