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 OR IGNORE relationships SET source_id = ?1 WHERE source_id = ?2",
109 params![target_id, src_id],
110 )?;
111 tx.execute(
112 "DELETE FROM relationships WHERE source_id = ?1",
113 params![src_id],
114 )?;
115 let moved_tgt = tx.execute(
117 "UPDATE OR IGNORE relationships SET target_id = ?1 WHERE target_id = ?2",
118 params![target_id, src_id],
119 )?;
120 tx.execute(
121 "DELETE FROM relationships WHERE target_id = ?1",
122 params![src_id],
123 )?;
124 relationships_moved += moved_src + moved_tgt;
125 }
126
127 tx.execute("DELETE FROM relationships WHERE source_id = target_id", [])?;
129
130 tx.execute(
133 "DELETE FROM relationships
134 WHERE id NOT IN (
135 SELECT MIN(id)
136 FROM relationships
137 GROUP BY source_id, target_id, relation
138 )",
139 [],
140 )?;
141
142 for &src_id in &source_ids {
147 tx.execute(
148 "UPDATE OR IGNORE memory_entities SET entity_id = ?1 WHERE entity_id = ?2",
149 params![target_id, src_id],
150 )?;
151 tx.execute(
152 "DELETE FROM memory_entities WHERE entity_id = ?1",
153 params![src_id],
154 )?;
155 }
156
157 tx.execute(
159 "DELETE FROM memory_entities
160 WHERE rowid NOT IN (
161 SELECT MIN(rowid)
162 FROM memory_entities
163 GROUP BY memory_id, entity_id
164 )",
165 [],
166 )?;
167
168 let mut entities_removed: usize = 0;
170 for &src_id in &source_ids {
171 let _ = tx.execute(
172 "DELETE FROM vec_entities WHERE entity_id = ?1",
173 params![src_id],
174 );
175 let removed = tx.execute("DELETE FROM entities WHERE id = ?1", params![src_id])?;
176 entities_removed += removed;
177 }
178
179 let adjacent_ids: Vec<i64> = {
181 let mut stmt = tx.prepare(
182 "SELECT DISTINCT CASE WHEN source_id = ?1 THEN target_id ELSE source_id END
183 FROM relationships WHERE source_id = ?1 OR target_id = ?1",
184 )?;
185 let ids: Vec<i64> = stmt
186 .query_map(params![target_id], |r| r.get(0))?
187 .collect::<Result<Vec<_>, _>>()?;
188 ids
189 };
190 entities::recalculate_degree(&tx, target_id)?;
191 for &adj_id in &adjacent_ids {
192 entities::recalculate_degree(&tx, adj_id)?;
193 }
194
195 tx.commit()?;
196
197 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
198
199 let processed_sources: Vec<String> = args
201 .names
202 .iter()
203 .filter(|n| n.as_str() != args.into.as_str())
204 .cloned()
205 .collect();
206
207 let response = MergeEntitiesResponse {
208 action: "merged".to_string(),
209 sources: processed_sources,
210 target: args.into.clone(),
211 namespace: namespace.clone(),
212 relationships_moved,
213 entities_removed,
214 elapsed_ms: inicio.elapsed().as_millis() as u64,
215 };
216
217 match args.format {
218 OutputFormat::Json => output::emit_json(&response)?,
219 OutputFormat::Text | OutputFormat::Markdown => {
220 output::emit_text(&format!(
221 "merged: {} sources into '{}' (relationships_moved={}, entities_removed={}) [{}]",
222 response.sources.len(),
223 response.target,
224 response.relationships_moved,
225 response.entities_removed,
226 response.namespace
227 ));
228 }
229 }
230
231 Ok(())
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 #[test]
239 fn merge_entities_response_serializes_all_fields() {
240 let resp = MergeEntitiesResponse {
241 action: "merged".to_string(),
242 sources: vec!["auth".to_string(), "authentication".to_string()],
243 target: "auth-service".to_string(),
244 namespace: "global".to_string(),
245 relationships_moved: 7,
246 entities_removed: 2,
247 elapsed_ms: 15,
248 };
249 let json = serde_json::to_value(&resp).expect("serialization failed");
250 assert_eq!(json["action"], "merged");
251 assert_eq!(json["target"], "auth-service");
252 assert_eq!(json["namespace"], "global");
253 assert_eq!(json["relationships_moved"], 7);
254 assert_eq!(json["entities_removed"], 2);
255 let sources = json["sources"].as_array().expect("must be array");
256 assert_eq!(sources.len(), 2);
257 assert!(json["elapsed_ms"].is_number());
258 }
259
260 #[test]
261 fn merge_entities_response_action_is_merged() {
262 let resp = MergeEntitiesResponse {
263 action: "merged".to_string(),
264 sources: vec!["src".to_string()],
265 target: "tgt".to_string(),
266 namespace: "ns".to_string(),
267 relationships_moved: 0,
268 entities_removed: 1,
269 elapsed_ms: 0,
270 };
271 assert_eq!(resp.action, "merged");
272 }
273
274 #[test]
275 fn merge_entities_response_empty_sources_serializes() {
276 let resp = MergeEntitiesResponse {
277 action: "merged".to_string(),
278 sources: vec![],
279 target: "target".to_string(),
280 namespace: "global".to_string(),
281 relationships_moved: 0,
282 entities_removed: 0,
283 elapsed_ms: 1,
284 };
285 let json = serde_json::to_value(&resp).expect("serialization failed");
286 let sources = json["sources"].as_array().expect("must be array");
287 assert_eq!(sources.len(), 0);
288 }
289
290 #[test]
291 fn merge_entities_response_with_zero_relationships_moved() {
292 let resp = MergeEntitiesResponse {
293 action: "merged".to_string(),
294 sources: vec!["src-a".to_string()],
295 target: "tgt".to_string(),
296 namespace: "global".to_string(),
297 relationships_moved: 0,
298 entities_removed: 1,
299 elapsed_ms: 5,
300 };
301 let json = serde_json::to_value(&resp).expect("serialization failed");
302 assert_eq!(json["relationships_moved"], 0);
303 assert_eq!(json["entities_removed"], 1);
304 }
305
306 #[test]
307 fn merge_entities_response_multiple_sources() {
308 let resp = MergeEntitiesResponse {
309 action: "merged".to_string(),
310 sources: vec!["a".into(), "b".into(), "c".into()],
311 target: "canonical".to_string(),
312 namespace: "proj".to_string(),
313 relationships_moved: 12,
314 entities_removed: 3,
315 elapsed_ms: 42,
316 };
317 let json = serde_json::to_value(&resp).expect("serialization failed");
318 assert_eq!(json["entities_removed"], 3);
319 let sources = json["sources"].as_array().unwrap();
320 assert_eq!(sources.len(), 3);
321 }
322}