2024-11-11 01:38:58 +08:00
|
|
|
// main.rs
|
2024-11-09 00:05:18 +08:00
|
|
|
mod sql;
|
|
|
|
mod config;
|
2024-11-11 01:38:58 +08:00
|
|
|
use rocket::{ get, launch, routes};
|
|
|
|
use rocket::serde::json::Json; // Added import for Json
|
2024-11-09 00:05:18 +08:00
|
|
|
use once_cell::sync::Lazy;
|
2024-11-11 01:38:58 +08:00
|
|
|
use rocket::http::Status;
|
|
|
|
use rocket::response::status;
|
|
|
|
use std::sync::Arc; // Added import for Arc and Mutex
|
|
|
|
use tokio::sync::Mutex;
|
|
|
|
use crate::sql::Database;
|
2024-11-09 00:05:18 +08:00
|
|
|
|
2024-11-11 01:38:58 +08:00
|
|
|
// 修改全局变量的类型定义
|
|
|
|
static GLOBAL_SQL: Lazy<Arc<Mutex<Option<Database>>>> = Lazy::new(|| {
|
|
|
|
Arc::new(Mutex::new(None))
|
|
|
|
});
|
2024-11-09 00:05:18 +08:00
|
|
|
|
2024-11-11 01:38:58 +08:00
|
|
|
// 修改数据库连接函数
|
|
|
|
async fn connect_database() -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let database = sql::Database::init().await?;
|
2024-11-09 00:05:18 +08:00
|
|
|
let mut lock = GLOBAL_SQL.lock().await;
|
2024-11-11 01:38:58 +08:00
|
|
|
*lock = Some(database);
|
|
|
|
Ok(())
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
|
|
|
|
2024-11-11 01:38:58 +08:00
|
|
|
async fn get_db() -> Result<Database, Box<dyn std::error::Error>> {
|
|
|
|
let lock = GLOBAL_SQL.lock().await;
|
|
|
|
match &*lock {
|
|
|
|
Some(db) => Ok(db.clone()),
|
|
|
|
None => Err("Database not initialized".into())
|
|
|
|
}
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
2024-11-11 01:38:58 +08:00
|
|
|
|
|
|
|
|
2024-11-09 00:05:18 +08:00
|
|
|
#[get("/sql")]
|
2024-11-11 01:38:58 +08:00
|
|
|
async fn ssql() -> Result<Json<Vec<std::collections::HashMap<String, String>>>, status::Custom<String>> {
|
|
|
|
let db = get_db().await.map_err(|e| {
|
|
|
|
eprintln!("Database error: {}", e);
|
|
|
|
status::Custom(Status::InternalServerError, format!("Database error: {}", e))
|
|
|
|
})?;
|
|
|
|
|
|
|
|
let query_result = db.get_db()
|
|
|
|
.query("SELECT * FROM info".to_string()) // 确保这里是正确的表名
|
|
|
|
.await
|
|
|
|
.map_err(|e| {
|
|
|
|
eprintln!("Query error: {}", e);
|
|
|
|
status::Custom(Status::InternalServerError, format!("Query error: {}", e))
|
|
|
|
})?;
|
|
|
|
|
|
|
|
Ok(Json(query_result))
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2024-11-11 01:38:58 +08:00
|
|
|
#[get("/install")]
|
|
|
|
async fn install() -> status::Custom<String> {
|
|
|
|
match connect_database().await {
|
|
|
|
Ok(_) => status::Custom(Status::Ok, "Database connected successfully".to_string()),
|
|
|
|
Err(e) => status::Custom(Status::InternalServerError, format!("Failed to connect: {}", e))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-09 00:05:18 +08:00
|
|
|
|
|
|
|
#[launch]
|
|
|
|
async fn rocket() -> _ {
|
2024-11-11 01:38:58 +08:00
|
|
|
connect_database().await.expect("Failed to connect to database");
|
2024-11-09 00:05:18 +08:00
|
|
|
rocket::build()
|
|
|
|
.mount("/api", routes![install,ssql])
|
2024-11-11 01:38:58 +08:00
|
|
|
}
|