sqlite_graphrag/commands/
merge_entities.rs1use crate::errors::AppError;
11use crate::i18n::errors_msg;
12use crate::output::{self, OutputFormat};
13use crate::paths::AppPaths;
14use crate::storage::connection::open_rw;
15use crate::storage::entities;
16use rusqlite::params;
17use serde::Serialize;
18
19#[derive(clap::Args)]
20#[command(after_long_help = "EXAMPLES:\n \
21 # Merge two source entities into a target\n \
22 sqlite-graphrag merge-entities --names auth,authentication --into auth-service\n\n \
23 # Merge three sources into one target across a namespace\n \
24 sqlite-graphrag merge-entities --names svc-a,svc-b,old-svc --into canonical-service --namespace my-project\n\n\
25NOTE:\n \
26 --names is a comma-separated list of source entity names.\n \
27 --into is the target entity name and must already exist.\n \
28 Source entities are deleted after the merge; the target is preserved.\n \
29 Duplicate relationships (same endpoints + relation) are removed automatically.\n \
30 Run `sqlite-graphrag cleanup-orphans` afterwards if sources had no other links.")]
31pub struct MergeEntitiesArgs {
32 #[arg(long, value_delimiter = ',', value_name = "NAMES")]
34 pub names: Vec<String>,
35 #[arg(long, value_name = "TARGET")]
37 pub into: String,
38 #[arg(long)]
39 pub namespace: Option<String>,
40 #[arg(long, value_enum, default_value = "json")]
41 pub format: OutputFormat,
42 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
43 pub json: bool,
44 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
45 pub db: Option<String>,
46}
47
48#[derive(Serialize)]
49struct MergeEntitiesResponse {
50 action: String,
51 sources: Vec<String>,
52 target: String,
53 namespace: String,
54 relationships_moved: usize,
55 entities_removed: usize,
56 elapsed_ms: u64,
58}
59
60pub fn run(args: MergeEntitiesArgs) -> Result<(), AppError> {
61 let inicio = std::time::Instant::now();
62
63 if args.names.is_empty() {
64 return Err(AppError::Validation(
65 "--names must contain at least one source entity name".to_string(),
66 ));
67 }
68
69 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
70 let paths = AppPaths::resolve(args.db.as_deref())?;
71
72 crate::storage::connection::ensure_db_ready(&paths)?;
73
74 let mut conn = open_rw(&paths.db)?;
75
76 let target_id = entities::find_entity_id(&conn, &namespace, &args.into)?
78 .ok_or_else(|| AppError::NotFound(errors_msg::entity_not_found(&args.into, &namespace)))?;
79
80 let mut source_ids: Vec<i64> = Vec::with_capacity(args.names.len());
82 for name in &args.names {
83 if name == &args.into {
84 continue;
86 }
87 let id = entities::find_entity_id(&conn, &namespace, name)?
88 .ok_or_else(|| AppError::NotFound(errors_msg::entity_not_found(name, &namespace)))?;
89 if !source_ids.contains(&id) {
90 source_ids.push(id);
91 }
92 }
93
94 if source_ids.is_empty() {
95 return Err(AppError::Validation(
96 "no valid source entities to merge (all names equal the target or were duplicates)"
97 .to_string(),
98 ));
99 }
100
101 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
102
103 let mut relationships_moved: usize = 0;
104
105 for &src_id in &source_ids {
106 let moved_src = tx.execute(
108 "UPDATE relationships SET source_id = ?1 WHERE source_id = ?2",
109 params![target_id, src_id],
110 )?;
111 let moved_tgt = tx.execute(
113 "UPDATE relationships SET target_id = ?1 WHERE target_id = ?2",
114 params![target_id, src_id],
115 )?;
116 relationships_moved += moved_src + moved_tgt;
117 }
118
119 tx.execute("DELETE FROM relationships WHERE source_id = target_id", [])?;
121
122 tx.execute(
125 "DELETE FROM relationships
126 WHERE id NOT IN (
127 SELECT MIN(id)
128 FROM relationships
129 GROUP BY source_id, target_id, relation
130 )",
131 [],
132 )?;
133
134 for &src_id in &source_ids {
136 tx.execute(
137 "UPDATE memory_entities SET entity_id = ?1 WHERE entity_id = ?2",
138 params![target_id, src_id],
139 )?;
140 }
141
142 tx.execute(
144 "DELETE FROM memory_entities
145 WHERE rowid NOT IN (
146 SELECT MIN(rowid)
147 FROM memory_entities
148 GROUP BY memory_id, entity_id
149 )",
150 [],
151 )?;
152
153 let mut entities_removed: usize = 0;
155 for &src_id in &source_ids {
156 let _ = tx.execute(
157 "DELETE FROM vec_entities WHERE entity_id = ?1",
158 params![src_id],
159 );
160 let removed = tx.execute("DELETE FROM entities WHERE id = ?1", params![src_id])?;
161 entities_removed += removed;
162 }
163
164 entities::recalculate_degree(&tx, target_id)?;
166
167 tx.commit()?;
168
169 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
170
171 let processed_sources: Vec<String> = args
173 .names
174 .iter()
175 .filter(|n| n.as_str() != args.into.as_str())
176 .cloned()
177 .collect();
178
179 let response = MergeEntitiesResponse {
180 action: "merged".to_string(),
181 sources: processed_sources,
182 target: args.into.clone(),
183 namespace: namespace.clone(),
184 relationships_moved,
185 entities_removed,
186 elapsed_ms: inicio.elapsed().as_millis() as u64,
187 };
188
189 match args.format {
190 OutputFormat::Json => output::emit_json(&response)?,
191 OutputFormat::Text | OutputFormat::Markdown => {
192 output::emit_text(&format!(
193 "merged: {} sources into '{}' (relationships_moved={}, entities_removed={}) [{}]",
194 response.sources.len(),
195 response.target,
196 response.relationships_moved,
197 response.entities_removed,
198 response.namespace
199 ));
200 }
201 }
202
203 Ok(())
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn merge_entities_response_serializes_all_fields() {
212 let resp = MergeEntitiesResponse {
213 action: "merged".to_string(),
214 sources: vec!["auth".to_string(), "authentication".to_string()],
215 target: "auth-service".to_string(),
216 namespace: "global".to_string(),
217 relationships_moved: 7,
218 entities_removed: 2,
219 elapsed_ms: 15,
220 };
221 let json = serde_json::to_value(&resp).expect("serialization failed");
222 assert_eq!(json["action"], "merged");
223 assert_eq!(json["target"], "auth-service");
224 assert_eq!(json["namespace"], "global");
225 assert_eq!(json["relationships_moved"], 7);
226 assert_eq!(json["entities_removed"], 2);
227 let sources = json["sources"].as_array().expect("must be array");
228 assert_eq!(sources.len(), 2);
229 assert!(json["elapsed_ms"].is_number());
230 }
231
232 #[test]
233 fn merge_entities_response_action_is_merged() {
234 let resp = MergeEntitiesResponse {
235 action: "merged".to_string(),
236 sources: vec!["src".to_string()],
237 target: "tgt".to_string(),
238 namespace: "ns".to_string(),
239 relationships_moved: 0,
240 entities_removed: 1,
241 elapsed_ms: 0,
242 };
243 assert_eq!(resp.action, "merged");
244 }
245
246 #[test]
247 fn merge_entities_response_empty_sources_serializes() {
248 let resp = MergeEntitiesResponse {
249 action: "merged".to_string(),
250 sources: vec![],
251 target: "target".to_string(),
252 namespace: "global".to_string(),
253 relationships_moved: 0,
254 entities_removed: 0,
255 elapsed_ms: 1,
256 };
257 let json = serde_json::to_value(&resp).expect("serialization failed");
258 let sources = json["sources"].as_array().expect("must be array");
259 assert_eq!(sources.len(), 0);
260 }
261
262 #[test]
263 fn merge_entities_response_multiple_sources() {
264 let resp = MergeEntitiesResponse {
265 action: "merged".to_string(),
266 sources: vec!["a".into(), "b".into(), "c".into()],
267 target: "canonical".to_string(),
268 namespace: "proj".to_string(),
269 relationships_moved: 12,
270 entities_removed: 3,
271 elapsed_ms: 42,
272 };
273 let json = serde_json::to_value(&resp).expect("serialization failed");
274 assert_eq!(json["entities_removed"], 3);
275 let sources = json["sources"].as_array().unwrap();
276 assert_eq!(sources.len(), 3);
277 }
278}