1use crate::app_paths::AppPaths;
2use chrono::{DateTime, Local};
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use sha2::{Digest, Sha256};
6use std::error::Error;
7use std::fs;
8use std::path::PathBuf;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct CachedQuery {
12 pub id: u64,
13 pub query_hash: String,
14 pub query_text: String,
15 pub timestamp: DateTime<Local>,
16 pub row_count: usize,
17 pub file_path: String,
18 pub description: Option<String>,
19 pub expires_at: Option<DateTime<Local>>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct CacheMetadata {
24 pub queries: Vec<CachedQuery>,
25 pub next_id: u64,
26}
27
28pub struct QueryCache {
29 cache_dir: PathBuf,
30 metadata_path: PathBuf,
31 metadata: CacheMetadata,
32}
33
34impl QueryCache {
35 pub fn new() -> Result<Self, Box<dyn Error>> {
36 let cache_dir = AppPaths::cache_dir()?;
37 let data_dir = AppPaths::cache_data_dir()?;
38
39 fs::create_dir_all(&data_dir)?;
41
42 let metadata_path = AppPaths::cache_metadata_file()?;
43
44 let metadata = if metadata_path.exists() {
46 let content = fs::read_to_string(&metadata_path)?;
47 serde_json::from_str(&content)?
48 } else {
49 CacheMetadata {
50 queries: Vec::new(),
51 next_id: 1,
52 }
53 };
54
55 Ok(Self {
56 cache_dir,
57 metadata_path,
58 metadata,
59 })
60 }
61
62 pub fn save_query(
63 &mut self,
64 query: &str,
65 data: &[Value],
66 description: Option<String>,
67 ) -> Result<u64, Box<dyn Error>> {
68 let mut hasher = Sha256::new();
70 hasher.update(query.as_bytes());
71 let query_hash = format!("{:x}", hasher.finalize());
72
73 if let Some(existing) = self
75 .metadata
76 .queries
77 .iter()
78 .find(|q| q.query_hash == query_hash)
79 {
80 return Ok(existing.id);
81 }
82
83 let id = self.metadata.next_id;
85 let filename = format!("query_{:06}.json", id);
86 let file_path = self.cache_dir.join("data").join(&filename);
87
88 let json_data = serde_json::to_string_pretty(&data)?;
90 fs::write(&file_path, json_data)?;
91
92 let cached_query = CachedQuery {
94 id,
95 query_hash,
96 query_text: query.to_string(),
97 timestamp: Local::now(),
98 row_count: data.len(),
99 file_path: filename,
100 description,
101 expires_at: None, };
103
104 self.metadata.queries.push(cached_query);
105 self.metadata.next_id += 1;
106
107 self.save_metadata()?;
109
110 Ok(id)
111 }
112
113 pub fn load_query(&self, id: u64) -> Result<(String, Vec<Value>), Box<dyn Error>> {
114 let cached_query = self
115 .metadata
116 .queries
117 .iter()
118 .find(|q| q.id == id)
119 .ok_or(format!("Cache entry {} not found", id))?;
120
121 let file_path = self.cache_dir.join("data").join(&cached_query.file_path);
122 let json_data = fs::read_to_string(file_path)?;
123 let data: Vec<Value> = serde_json::from_str(&json_data)?;
124
125 Ok((cached_query.query_text.clone(), data))
126 }
127
128 pub fn list_cached_queries(&self) -> &[CachedQuery] {
129 &self.metadata.queries
130 }
131
132 pub fn delete_query(&mut self, id: u64) -> Result<(), Box<dyn Error>> {
133 if let Some(pos) = self.metadata.queries.iter().position(|q| q.id == id) {
134 let cached_query = self.metadata.queries.remove(pos);
135 let file_path = self.cache_dir.join("data").join(&cached_query.file_path);
136 fs::remove_file(file_path)?;
137 self.save_metadata()?;
138 }
139 Ok(())
140 }
141
142 pub fn clear_all(&mut self) -> Result<(), Box<dyn Error>> {
143 let data_dir = self.cache_dir.join("data");
145 for entry in fs::read_dir(data_dir)? {
146 let entry = entry?;
147 if entry.path().extension().map_or(false, |ext| ext == "json") {
148 fs::remove_file(entry.path())?;
149 }
150 }
151
152 self.metadata.queries.clear();
154 self.metadata.next_id = 1;
155 self.save_metadata()?;
156
157 Ok(())
158 }
159
160 pub fn get_cache_stats(&self) -> CacheStats {
161 let total_size: u64 = self
162 .metadata
163 .queries
164 .iter()
165 .filter_map(|q| {
166 let path = self.cache_dir.join("data").join(&q.file_path);
167 fs::metadata(path).ok().map(|m| m.len())
168 })
169 .sum();
170
171 let total_rows: usize = self.metadata.queries.iter().map(|q| q.row_count).sum();
172
173 CacheStats {
174 total_queries: self.metadata.queries.len(),
175 total_rows,
176 total_size_bytes: total_size,
177 oldest_entry: self
178 .metadata
179 .queries
180 .iter()
181 .min_by_key(|q| q.timestamp)
182 .map(|q| q.timestamp),
183 newest_entry: self
184 .metadata
185 .queries
186 .iter()
187 .max_by_key(|q| q.timestamp)
188 .map(|q| q.timestamp),
189 }
190 }
191
192 fn save_metadata(&self) -> Result<(), Box<dyn Error>> {
193 let json = serde_json::to_string_pretty(&self.metadata)?;
194 fs::write(&self.metadata_path, json)?;
195 Ok(())
196 }
197}
198
199#[derive(Debug)]
200pub struct CacheStats {
201 pub total_queries: usize,
202 pub total_rows: usize,
203 pub total_size_bytes: u64,
204 pub oldest_entry: Option<DateTime<Local>>,
205 pub newest_entry: Option<DateTime<Local>>,
206}
207
208impl CacheStats {
209 pub fn format_size(&self) -> String {
210 let size = self.total_size_bytes as f64;
211 if size < 1024.0 {
212 format!("{} B", size)
213 } else if size < 1024.0 * 1024.0 {
214 format!("{:.1} KB", size / 1024.0)
215 } else if size < 1024.0 * 1024.0 * 1024.0 {
216 format!("{:.1} MB", size / (1024.0 * 1024.0))
217 } else {
218 format!("{:.1} GB", size / (1024.0 * 1024.0 * 1024.0))
219 }
220 }
221}
222
223#[derive(Debug, Clone, PartialEq)]
224pub enum QueryMode {
225 Live, Cached, Hybrid, }
229
230impl Default for QueryMode {
231 fn default() -> Self {
232 QueryMode::Live
233 }
234}