1use crate::parser::SqlDialect;
10use anyhow::{Context, Result};
11use sha2::{Digest, Sha256};
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
18pub struct CacheEntry {
19 pub dump_path: String,
21 pub cache_key: String,
23 pub dump_size: u64,
25 pub dump_mtime: u64,
27 pub cache_size: u64,
29 pub created_at: u64,
31 pub table_count: usize,
33 pub row_count: u64,
35 #[serde(default)]
37 pub tables: Option<Vec<String>>,
38}
39
40#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
42pub struct CacheIndex {
43 pub entries: Vec<CacheEntry>,
44}
45
46pub struct CacheManager {
48 cache_dir: PathBuf,
49}
50
51fn wal_path(db_path: &Path) -> PathBuf {
53 let mut os = db_path.as_os_str().to_os_string();
54 os.push(".wal");
55 PathBuf::from(os)
56}
57
58fn mtime_secs(metadata: &fs::Metadata) -> u64 {
59 metadata
60 .modified()
61 .unwrap_or(SystemTime::UNIX_EPOCH)
62 .duration_since(SystemTime::UNIX_EPOCH)
63 .map(|d| d.as_secs())
64 .unwrap_or(0)
65}
66
67fn normalize_tables(tables: Option<&[String]>) -> String {
70 match tables {
71 None => "all".to_string(),
72 Some(tables) => {
73 let mut names: Vec<String> = tables.iter().map(|t| t.to_ascii_lowercase()).collect();
74 names.sort();
75 names.dedup();
76 names.join(",")
77 }
78 }
79}
80
81impl CacheManager {
82 pub fn new() -> Result<Self> {
84 let cache_dir = Self::default_cache_dir()?;
85 fs::create_dir_all(&cache_dir).context("Failed to create cache directory")?;
86 Ok(Self { cache_dir })
87 }
88
89 pub fn with_dir(cache_dir: PathBuf) -> Result<Self> {
91 fs::create_dir_all(&cache_dir).context("Failed to create cache directory")?;
92 Ok(Self { cache_dir })
93 }
94
95 pub fn default_cache_dir() -> Result<PathBuf> {
97 if let Some(dir) = std::env::var_os("SQL_SPLITTER_CACHE_DIR").filter(|d| !d.is_empty()) {
98 return Ok(PathBuf::from(dir));
99 }
100
101 let cache_base = dirs::cache_dir()
102 .or_else(|| dirs::home_dir().map(|h| h.join(".cache")))
103 .context("Could not determine cache directory")?;
104
105 Ok(cache_base.join("sql-splitter").join("duckdb"))
106 }
107
108 pub fn compute_cache_key(
110 dump_path: &Path,
111 tables: Option<&[String]>,
112 dialect: Option<SqlDialect>,
113 ) -> Result<String> {
114 let canonical = dump_path
115 .canonicalize()
116 .with_context(|| format!("Failed to canonicalize path: {}", dump_path.display()))?;
117
118 let metadata = fs::metadata(&canonical)
119 .with_context(|| format!("Failed to read metadata: {}", dump_path.display()))?;
120
121 let dialect = dialect.map_or_else(|| "auto".to_string(), |d| d.to_string());
122 let key_input = format!(
123 "{}:{}:{}:{}:{}",
124 canonical.display(),
125 metadata.len(),
126 mtime_secs(&metadata),
127 normalize_tables(tables),
128 dialect
129 );
130
131 let mut hasher = Sha256::new();
132 hasher.update(key_input.as_bytes());
133 let hash = hasher.finalize();
134
135 Ok(hex::encode(&hash[..16])) }
137
138 pub fn cache_path(&self, cache_key: &str) -> PathBuf {
140 self.cache_dir.join(format!("{}.duckdb", cache_key))
141 }
142
143 pub fn partial_path(&self, cache_key: &str) -> PathBuf {
145 self.cache_dir.join(format!("{}.duckdb.partial", cache_key))
146 }
147
148 pub fn has_valid_cache(
153 &self,
154 dump_path: &Path,
155 tables: Option<&[String]>,
156 dialect: Option<SqlDialect>,
157 ) -> Result<bool> {
158 let cache_key = Self::compute_cache_key(dump_path, tables, dialect)?;
159 Ok(self.cache_path(&cache_key).exists())
160 }
161
162 pub fn get_cache(
164 &self,
165 dump_path: &Path,
166 tables: Option<&[String]>,
167 dialect: Option<SqlDialect>,
168 ) -> Result<Option<PathBuf>> {
169 if self.has_valid_cache(dump_path, tables, dialect)? {
170 let cache_key = Self::compute_cache_key(dump_path, tables, dialect)?;
171 Ok(Some(self.cache_path(&cache_key)))
172 } else {
173 Ok(None)
174 }
175 }
176
177 pub fn discard_partial(&self, cache_key: &str) -> Result<()> {
179 let partial = self.partial_path(cache_key);
180 if partial.exists() {
181 fs::remove_file(&partial).context("Failed to remove partial cache file")?;
182 }
183 let wal = wal_path(&partial);
184 if wal.exists() {
185 fs::remove_file(&wal)?;
186 }
187 Ok(())
188 }
189
190 pub fn commit_cache(
194 &self,
195 dump_path: &Path,
196 cache_key: &str,
197 tables: Vec<String>,
198 row_count: u64,
199 ) -> Result<PathBuf> {
200 let partial = self.partial_path(cache_key);
201 let cache_path = self.cache_path(cache_key);
202
203 if !partial.exists() {
204 anyhow::bail!("No staged cache file to commit: {}", partial.display());
205 }
206
207 if cache_path.exists() {
209 fs::remove_file(&cache_path).context("Failed to remove old cache file")?;
210 }
211 let old_wal = wal_path(&cache_path);
212 if old_wal.exists() {
213 let _ = fs::remove_file(&old_wal);
214 }
215
216 fs::rename(&partial, &cache_path).context("Failed to move cache file into place")?;
217 let partial_wal = wal_path(&partial);
218 if partial_wal.exists() {
219 let _ = fs::remove_file(&partial_wal);
220 }
221
222 let canonical = dump_path
223 .canonicalize()
224 .with_context(|| format!("Failed to canonicalize path: {}", dump_path.display()))?;
225 let metadata = fs::metadata(&canonical)?;
226 let dump_mtime = mtime_secs(&metadata);
227 let dump_path_str = canonical.display().to_string();
228
229 let mut index = self.load_index()?;
230
231 let stale_keys: Vec<String> = index
233 .entries
234 .iter()
235 .filter(|e| {
236 e.dump_path == dump_path_str
237 && (e.dump_size != metadata.len() || e.dump_mtime != dump_mtime)
238 })
239 .map(|e| e.cache_key.clone())
240 .collect();
241 for key in &stale_keys {
242 let path = self.cache_path(key);
243 let _ = fs::remove_file(&path);
244 let _ = fs::remove_file(wal_path(&path));
245 }
246 index
247 .entries
248 .retain(|e| e.cache_key != cache_key && !stale_keys.contains(&e.cache_key));
249
250 index.entries.push(CacheEntry {
251 dump_path: dump_path_str,
252 cache_key: cache_key.to_string(),
253 dump_size: metadata.len(),
254 dump_mtime,
255 cache_size: fs::metadata(&cache_path).map(|m| m.len()).unwrap_or(0),
256 created_at: SystemTime::now()
257 .duration_since(SystemTime::UNIX_EPOCH)
258 .map(|d| d.as_secs())
259 .unwrap_or(0),
260 table_count: tables.len(),
261 row_count,
262 tables: Some(tables),
263 });
264
265 self.save_index(&index)?;
266 Ok(cache_path)
267 }
268
269 pub fn load_index(&self) -> Result<CacheIndex> {
272 let index_path = self.cache_dir.join("index.json");
273
274 if !index_path.exists() {
275 return Ok(CacheIndex::default());
276 }
277
278 let content = fs::read_to_string(&index_path).context("Failed to read cache index")?;
279 Ok(serde_json::from_str(&content).unwrap_or_else(|e| {
280 eprintln!(
281 "Warning: cache index {} is corrupt ({}); treating it as empty",
282 index_path.display(),
283 e
284 );
285 CacheIndex::default()
286 }))
287 }
288
289 fn save_index(&self, index: &CacheIndex) -> Result<()> {
291 let index_path = self.cache_dir.join("index.json");
292 let tmp_path = self.cache_dir.join("index.json.tmp");
293 let content =
294 serde_json::to_string_pretty(index).context("Failed to serialize cache index")?;
295 fs::write(&tmp_path, content).context("Failed to write cache index")?;
296 fs::rename(&tmp_path, &index_path).context("Failed to replace cache index")?;
297 Ok(())
298 }
299
300 pub fn list_entries(&self) -> Result<Vec<CacheEntry>> {
302 let index = self.load_index()?;
303 Ok(index.entries)
304 }
305
306 pub fn remove_cache(&self, cache_key: &str) -> Result<()> {
308 let cache_path = self.cache_path(cache_key);
309
310 if cache_path.exists() {
311 fs::remove_file(&cache_path).context("Failed to remove cache file")?;
312 }
313
314 let wal = wal_path(&cache_path);
316 if wal.exists() {
317 fs::remove_file(&wal)?;
318 }
319 self.discard_partial(cache_key)?;
320
321 let mut index = self.load_index()?;
323 index.entries.retain(|e| e.cache_key != cache_key);
324 self.save_index(&index)?;
325
326 Ok(())
327 }
328
329 pub fn clear_all(&self) -> Result<usize> {
336 let mut count = 0;
337
338 for entry in fs::read_dir(&self.cache_dir).context("Failed to read cache directory")? {
339 let path = entry?.path();
340 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
341 if name.ends_with(".duckdb") {
342 count += 1;
343 }
344 if name.ends_with(".duckdb") || name.ends_with(".wal") || name.ends_with(".partial") {
345 fs::remove_file(&path)
346 .with_context(|| format!("Failed to remove {}", path.display()))?;
347 }
348 }
349
350 self.save_index(&CacheIndex::default())?;
351 Ok(count)
352 }
353
354 pub fn total_size(&self) -> Result<u64> {
356 let entries = self.list_entries()?;
357 Ok(entries.iter().map(|e| e.cache_size).sum())
358 }
359
360 pub fn cache_dir(&self) -> &Path {
362 &self.cache_dir
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369 use tempfile::TempDir;
370
371 fn setup_test_cache() -> (CacheManager, TempDir) {
372 let temp_dir = TempDir::new().unwrap();
373 let cache_manager = CacheManager::with_dir(temp_dir.path().to_path_buf()).unwrap();
374 (cache_manager, temp_dir)
375 }
376
377 fn strings(names: &[&str]) -> Vec<String> {
378 names.iter().map(|s| s.to_string()).collect()
379 }
380
381 #[test]
382 fn test_cache_key_computation() {
383 let temp_dir = TempDir::new().unwrap();
384 let test_file = temp_dir.path().join("test.sql");
385 fs::write(&test_file, "SELECT 1;").unwrap();
386
387 let key1 = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
388 let key2 = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
389
390 assert_eq!(key1, key2);
391 assert_eq!(key1.len(), 32); }
393
394 #[test]
395 fn test_cache_key_changes_with_content() {
396 let temp_dir = TempDir::new().unwrap();
397 let test_file = temp_dir.path().join("test.sql");
398
399 fs::write(&test_file, "SELECT 1;").unwrap();
400 let key1 = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
401
402 fs::write(&test_file, "SELECT 2; -- with extra content to change size").unwrap();
404 let key2 = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
405
406 assert_ne!(key1, key2);
408 }
409
410 #[test]
411 fn test_cache_key_includes_tables() {
412 let temp_dir = TempDir::new().unwrap();
413 let test_file = temp_dir.path().join("test.sql");
414 fs::write(&test_file, "SELECT 1;").unwrap();
415
416 let all = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
417 let users =
418 CacheManager::compute_cache_key(&test_file, Some(&strings(&["users"])), None).unwrap();
419 let both =
420 CacheManager::compute_cache_key(&test_file, Some(&strings(&["users", "orders"])), None)
421 .unwrap();
422
423 assert_ne!(all, users);
424 assert_ne!(all, both);
425 assert_ne!(users, both);
426 }
427
428 #[test]
429 fn test_cache_key_normalizes_tables() {
430 let temp_dir = TempDir::new().unwrap();
431 let test_file = temp_dir.path().join("test.sql");
432 fs::write(&test_file, "SELECT 1;").unwrap();
433
434 let messy = CacheManager::compute_cache_key(
435 &test_file,
436 Some(&strings(&["Orders", "users", "USERS"])),
437 None,
438 )
439 .unwrap();
440 let clean =
441 CacheManager::compute_cache_key(&test_file, Some(&strings(&["orders", "users"])), None)
442 .unwrap();
443
444 assert_eq!(messy, clean);
445 }
446
447 #[test]
448 fn test_cache_key_includes_dialect() {
449 let temp_dir = TempDir::new().unwrap();
450 let test_file = temp_dir.path().join("test.sql");
451 fs::write(&test_file, "SELECT 1;").unwrap();
452
453 let auto = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
454 let mysql =
455 CacheManager::compute_cache_key(&test_file, None, Some(SqlDialect::MySql)).unwrap();
456
457 assert_ne!(auto, mysql);
458 }
459
460 #[test]
461 fn test_cache_path() {
462 let (cache_manager, _temp_dir) = setup_test_cache();
463 let cache_path = cache_manager.cache_path("abc123");
464 assert!(cache_path.to_string_lossy().ends_with("abc123.duckdb"));
465 }
466
467 #[test]
468 fn test_has_valid_cache_when_missing() {
469 let (cache_manager, temp_dir) = setup_test_cache();
470 let test_file = temp_dir.path().join("test.sql");
471 fs::write(&test_file, "SELECT 1;").unwrap();
472
473 assert!(!cache_manager
474 .has_valid_cache(&test_file, None, None)
475 .unwrap());
476 }
477
478 #[test]
479 fn test_partial_is_not_a_valid_cache() {
480 let (cache_manager, temp_dir) = setup_test_cache();
481 let test_file = temp_dir.path().join("test.sql");
482 fs::write(&test_file, "SELECT 1;").unwrap();
483
484 let key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
485 fs::write(cache_manager.partial_path(&key), b"garbage").unwrap();
486
487 assert!(!cache_manager
488 .has_valid_cache(&test_file, None, None)
489 .unwrap());
490 assert!(cache_manager
491 .get_cache(&test_file, None, None)
492 .unwrap()
493 .is_none());
494 }
495
496 #[test]
497 fn test_commit_cache_renames_and_records_size() {
498 let (cache_manager, temp_dir) = setup_test_cache();
499 let test_file = temp_dir.path().join("test.sql");
500 fs::write(&test_file, "SELECT 1;").unwrap();
501
502 let key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
503 fs::write(cache_manager.partial_path(&key), b"fake database contents").unwrap();
504
505 let cache_path = cache_manager
506 .commit_cache(&test_file, &key, strings(&["users"]), 42)
507 .unwrap();
508
509 assert!(cache_path.exists());
510 assert!(!cache_manager.partial_path(&key).exists());
511
512 let entries = cache_manager.list_entries().unwrap();
513 assert_eq!(entries.len(), 1);
514 assert!(entries[0].cache_size > 0);
515 assert_eq!(entries[0].tables, Some(strings(&["users"])));
516 assert_eq!(entries[0].table_count, 1);
517 assert_eq!(entries[0].row_count, 42);
518 }
519
520 #[test]
521 fn test_commit_without_partial_leaves_index_intact() {
522 let (cache_manager, temp_dir) = setup_test_cache();
523 let test_file = temp_dir.path().join("test.sql");
524 fs::write(&test_file, "SELECT 1;").unwrap();
525
526 let key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
527 fs::write(cache_manager.partial_path(&key), b"data").unwrap();
528 cache_manager
529 .commit_cache(&test_file, &key, strings(&["users"]), 1)
530 .unwrap();
531
532 let result = cache_manager.commit_cache(&test_file, "deadbeef", strings(&["x"]), 1);
534 assert!(result.is_err());
535 assert_eq!(cache_manager.list_entries().unwrap().len(), 1);
536 }
537
538 #[test]
539 fn test_two_table_sets_coexist() {
540 let (cache_manager, temp_dir) = setup_test_cache();
541 let test_file = temp_dir.path().join("test.sql");
542 fs::write(&test_file, "SELECT 1;").unwrap();
543
544 let key1 =
545 CacheManager::compute_cache_key(&test_file, Some(&strings(&["users"])), None).unwrap();
546 let key2 = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
547 assert_ne!(key1, key2);
548
549 fs::write(cache_manager.partial_path(&key1), b"one").unwrap();
550 cache_manager
551 .commit_cache(&test_file, &key1, strings(&["users"]), 1)
552 .unwrap();
553 fs::write(cache_manager.partial_path(&key2), b"two").unwrap();
554 cache_manager
555 .commit_cache(&test_file, &key2, strings(&["users", "orders"]), 2)
556 .unwrap();
557
558 assert!(cache_manager.cache_path(&key1).exists());
559 assert!(cache_manager.cache_path(&key2).exists());
560 assert_eq!(cache_manager.list_entries().unwrap().len(), 2);
561 }
562
563 #[test]
564 fn test_gc_deletes_caches_of_changed_dump() {
565 let (cache_manager, temp_dir) = setup_test_cache();
566 let test_file = temp_dir.path().join("test.sql");
567 fs::write(&test_file, "SELECT 1;").unwrap();
568
569 let old_key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
570 fs::write(cache_manager.partial_path(&old_key), b"v1").unwrap();
571 cache_manager
572 .commit_cache(&test_file, &old_key, strings(&["users"]), 1)
573 .unwrap();
574
575 fs::write(&test_file, "SELECT 2; -- different size now").unwrap();
577 let new_key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
578 assert_ne!(old_key, new_key);
579 fs::write(cache_manager.partial_path(&new_key), b"v2").unwrap();
580 cache_manager
581 .commit_cache(&test_file, &new_key, strings(&["users"]), 2)
582 .unwrap();
583
584 assert!(!cache_manager.cache_path(&old_key).exists());
585 let entries = cache_manager.list_entries().unwrap();
586 assert_eq!(entries.len(), 1);
587 assert_eq!(entries[0].cache_key, new_key);
588 }
589
590 #[test]
591 fn test_corrupt_index_recovers_as_empty() {
592 let (cache_manager, temp_dir) = setup_test_cache();
593 fs::write(temp_dir.path().join("index.json"), "{broken json").unwrap();
594
595 let index = cache_manager.load_index().unwrap();
596 assert!(index.entries.is_empty());
597
598 let test_file = temp_dir.path().join("test.sql");
600 fs::write(&test_file, "SELECT 1;").unwrap();
601 let key = CacheManager::compute_cache_key(&test_file, None, None).unwrap();
602 fs::write(cache_manager.partial_path(&key), b"data").unwrap();
603 cache_manager
604 .commit_cache(&test_file, &key, strings(&["users"]), 1)
605 .unwrap();
606 assert_eq!(cache_manager.list_entries().unwrap().len(), 1);
607 }
608
609 #[test]
610 fn test_index_old_format_parses_with_unknown_tables() {
611 let (cache_manager, temp_dir) = setup_test_cache();
612 let old_entry = r#"{"entries":[{"dump_path":"/tmp/a.sql","cache_key":"abc","dump_size":1,"dump_mtime":2,"cache_size":3,"created_at":4,"table_count":5,"row_count":6}]}"#;
613 fs::write(temp_dir.path().join("index.json"), old_entry).unwrap();
614
615 let entries = cache_manager.list_entries().unwrap();
616 assert_eq!(entries.len(), 1);
617 assert_eq!(entries[0].tables, None);
618 }
619
620 #[test]
621 fn test_clear_all_sweeps_directory() {
622 let (cache_manager, temp_dir) = setup_test_cache();
623 fs::write(temp_dir.path().join("aa.duckdb"), b"x").unwrap();
624 fs::write(temp_dir.path().join("aa.duckdb.wal"), b"x").unwrap();
625 fs::write(temp_dir.path().join("bb.duckdb.partial"), b"x").unwrap();
626 fs::write(temp_dir.path().join("index.json"), "{broken").unwrap();
627
628 let count = cache_manager.clear_all().unwrap();
629 assert_eq!(count, 1);
630 assert!(!temp_dir.path().join("aa.duckdb").exists());
631 assert!(!temp_dir.path().join("aa.duckdb.wal").exists());
632 assert!(!temp_dir.path().join("bb.duckdb.partial").exists());
633 assert!(cache_manager.list_entries().unwrap().is_empty());
634 }
635
636 #[test]
637 fn test_list_entries_empty() {
638 let (cache_manager, _temp_dir) = setup_test_cache();
639 let entries = cache_manager.list_entries().unwrap();
640 assert!(entries.is_empty());
641 }
642
643 #[test]
644 fn test_total_size_empty() {
645 let (cache_manager, _temp_dir) = setup_test_cache();
646 assert_eq!(cache_manager.total_size().unwrap(), 0);
647 }
648}