sqlite_graphrag/commands/
cleanup_orphans.rs1use crate::errors::AppError;
4use crate::output::{self, OutputFormat};
5use crate::paths::AppPaths;
6use crate::storage::connection::open_rw;
7use crate::storage::entities;
8use serde::Serialize;
9
10#[derive(clap::Args)]
11#[command(after_long_help = "EXAMPLES:\n \
12 # Remove orphan entities (no memories, no relationships) from the global namespace\n \
13 sqlite-graphrag cleanup-orphans\n\n \
14 # Preview which entities would be removed without deleting\n \
15 sqlite-graphrag cleanup-orphans --dry-run\n\n \
16 # Cleanup within a specific namespace\n \
17 sqlite-graphrag cleanup-orphans --namespace my-project --yes")]
18pub struct CleanupOrphansArgs {
20 #[arg(long)]
22 pub namespace: Option<String>,
23 #[arg(long)]
25 pub dry_run: bool,
26 #[arg(long)]
28 pub yes: bool,
29 #[arg(long, value_enum, default_value = "json")]
31 pub format: OutputFormat,
32 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
34 pub json: bool,
35 #[arg(long)]
37 pub db: Option<String>,
38}
39
40#[derive(Serialize)]
41struct CleanupResponse {
42 orphan_count: usize,
43 deleted: usize,
44 dry_run: bool,
45 namespace: Option<String>,
46 elapsed_ms: u64,
48}
49
50pub fn run(args: CleanupOrphansArgs) -> Result<(), AppError> {
52 let inicio = std::time::Instant::now();
53 let paths = AppPaths::resolve(args.db.as_deref())?;
54
55 crate::storage::connection::ensure_db_ready(&paths)?;
56
57 let mut conn = open_rw(&paths.db)?;
58
59 let orphan_ids = entities::find_orphan_entity_ids(&conn, args.namespace.as_deref())?;
60 let orphan_count = orphan_ids.len();
61
62 let deleted = if args.dry_run {
63 0
64 } else {
65 if orphan_count > 0 && !args.yes {
66 return Err(AppError::Validation(crate::i18n::validation::refuse_delete_orphans_without_yes(orphan_count)));
67 }
68 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
69 let removed = entities::delete_entities_by_ids(&tx, &orphan_ids)?;
70 tx.commit()?;
71 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
72 removed
73 };
74
75 let response = CleanupResponse {
76 orphan_count,
77 deleted,
78 dry_run: args.dry_run,
79 namespace: args.namespace.clone(),
80 elapsed_ms: inicio.elapsed().as_millis() as u64,
81 };
82
83 match args.format {
84 OutputFormat::Json => output::emit_json(&response)?,
85 OutputFormat::Text | OutputFormat::Markdown => {
86 let ns = response.namespace.as_deref().unwrap_or("<all>");
87 output::emit_text(&format!(
88 "orphans: {} found, {} deleted (dry_run={}) [{}]",
89 response.orphan_count, response.deleted, response.dry_run, ns
90 ));
91 }
92 }
93
94 Ok(())
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn cleanup_response_serializes_dry_run_true() {
103 let resp = CleanupResponse {
104 orphan_count: 5,
105 deleted: 0,
106 dry_run: true,
107 namespace: Some("global".to_string()),
108 elapsed_ms: 12,
109 };
110 let json = serde_json::to_value(&resp).expect("serialization failed");
111 assert_eq!(json["orphan_count"], 5);
112 assert_eq!(json["deleted"], 0);
113 assert_eq!(json["dry_run"], true);
114 assert_eq!(json["namespace"], "global");
115 assert!(json["elapsed_ms"].is_number());
116 }
117
118 #[test]
119 fn cleanup_response_deleted_zero_when_dry_run() {
120 let resp = CleanupResponse {
121 orphan_count: 10,
122 deleted: 0,
123 dry_run: true,
124 namespace: None,
125 elapsed_ms: 5,
126 };
127 assert_eq!(resp.deleted, 0, "dry_run must keep deleted at 0");
128 assert_eq!(resp.orphan_count, 10);
129 }
130
131 #[test]
132 fn cleanup_response_namespace_none_serializes_null() {
133 let resp = CleanupResponse {
134 orphan_count: 0,
135 deleted: 0,
136 dry_run: false,
137 namespace: None,
138 elapsed_ms: 1,
139 };
140 let json = serde_json::to_value(&resp).expect("serialization failed");
141 assert!(
142 json["namespace"].is_null(),
143 "namespace None must serialize as null"
144 );
145 }
146
147 #[test]
148 fn cleanup_response_deleted_equals_orphan_count_when_executed() {
149 let resp = CleanupResponse {
150 orphan_count: 3,
151 deleted: 3,
152 dry_run: false,
153 namespace: Some("projeto".to_string()),
154 elapsed_ms: 20,
155 };
156 assert_eq!(
157 resp.deleted, resp.orphan_count,
158 "when running without dry_run, deleted must equal orphan_count"
159 );
160 }
161}