diff --git a/src/search_db/mod.rs b/src/search_db/mod.rs index 7753324..1cd80ec 100644 --- a/src/search_db/mod.rs +++ b/src/search_db/mod.rs @@ -38,16 +38,24 @@ pub struct SearchDb { impl SearchDb { pub async fn new(db_path: &str) -> Result { - if let Some(parent) = std::path::Path::new(db_path).parent() { + // 确保父目录存在 + let path = std::path::Path::new(db_path); + if let Some(parent) = path.parent() { if !parent.exists() { std::fs::create_dir_all(parent)?; } } - if !std::path::Path::new(db_path).exists() { - std::fs::File::create(db_path)?; - } - let url = format!("sqlite:{}", db_path.replace('\\', "/")); + // 转换为绝对路径并创建文件(如果不存在) + let abs_path = std::fs::canonicalize(db_path) + .unwrap_or_else(|_| { + // canonicalize 要求文件存在,所以先创建再转换 + std::fs::File::create(db_path).ok(); + std::fs::canonicalize(db_path).unwrap_or_else(|_| path.to_path_buf()) + }); + + // 使用 sqlite:/// 前缀 + 绝对路径,避免相对路径解析错误 + let url = format!("sqlite:///{}", abs_path.to_string_lossy().replace('\\', "/")); let pool = SqlitePoolOptions::new() .max_connections(2)