Skip to main content

sqlite_graphrag/commands/
merge_entities.rs

1//! Handler for the `merge-entities` CLI subcommand (GAP-19).
2//!
3//! Merges two or more source entities into a single target entity by:
4//!   1. Retargeting all relationships pointing at any source to the target.
5//!   2. Deduplicating relationships that become identical after the merge
6//!      (same source_id + target_id + relation).
7//!   3. Retargeting memory_entities bindings.
8//!   4. Deleting the now-empty source entity rows.
9
10use 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    /// Comma-separated list of source entity names to merge into the target.
33    #[arg(long, value_delimiter = ',', value_name = "NAMES")]
34    pub names: Vec<String>,
35    /// Target entity name. Must already exist. All source relationships are redirected here.
36    #[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    /// Total execution time in milliseconds from handler start to serialisation.
57    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    // Resolve target entity ID.
77    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    // Resolve source entity IDs (skip the target if it appears in the list).
81    let mut source_ids: Vec<i64> = Vec::with_capacity(args.names.len());
82    for name in &args.names {
83        if name == &args.into {
84            // Source equals target — skip silently to avoid self-referential merge.
85            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        // Step 1a: redirect source_id, ignoring UNIQUE conflicts.
107        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        // Step 1b: redirect target_id, ignoring UNIQUE conflicts.
116        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    // Step 2: remove self-loops introduced by the redirect (target → target).
128    tx.execute("DELETE FROM relationships WHERE source_id = target_id", [])?;
129
130    // Step 3: deduplicate relationships that now share (source, target, relation).
131    // Safety net — UPDATE OR IGNORE should have handled most duplicates above.
132    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    // Step 4: retarget memory_entities bindings.
143    for &src_id in &source_ids {
144        tx.execute(
145            "UPDATE memory_entities SET entity_id = ?1 WHERE entity_id = ?2",
146            params![target_id, src_id],
147        )?;
148    }
149
150    // Step 5: deduplicate memory_entities bindings (same memory + entity).
151    tx.execute(
152        "DELETE FROM memory_entities
153         WHERE rowid NOT IN (
154             SELECT MIN(rowid)
155             FROM memory_entities
156             GROUP BY memory_id, entity_id
157         )",
158        [],
159    )?;
160
161    // Step 6: delete source entities (vec_entities first — no FK CASCADE on vec0).
162    let mut entities_removed: usize = 0;
163    for &src_id in &source_ids {
164        let _ = tx.execute(
165            "DELETE FROM vec_entities WHERE entity_id = ?1",
166            params![src_id],
167        );
168        let removed = tx.execute("DELETE FROM entities WHERE id = ?1", params![src_id])?;
169        entities_removed += removed;
170    }
171
172    // Step 7: recalculate degree for target and all adjacent entities.
173    let adjacent_ids: Vec<i64> = {
174        let mut stmt = tx.prepare(
175            "SELECT DISTINCT CASE WHEN source_id = ?1 THEN target_id ELSE source_id END
176             FROM relationships WHERE source_id = ?1 OR target_id = ?1",
177        )?;
178        let ids: Vec<i64> = stmt
179            .query_map(params![target_id], |r| r.get(0))?
180            .collect::<Result<Vec<_>, _>>()?;
181        ids
182    };
183    entities::recalculate_degree(&tx, target_id)?;
184    for &adj_id in &adjacent_ids {
185        entities::recalculate_degree(&tx, adj_id)?;
186    }
187
188    tx.commit()?;
189
190    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
191
192    // Build the list of sources that were actually processed (excluding target duplicates).
193    let processed_sources: Vec<String> = args
194        .names
195        .iter()
196        .filter(|n| n.as_str() != args.into.as_str())
197        .cloned()
198        .collect();
199
200    let response = MergeEntitiesResponse {
201        action: "merged".to_string(),
202        sources: processed_sources,
203        target: args.into.clone(),
204        namespace: namespace.clone(),
205        relationships_moved,
206        entities_removed,
207        elapsed_ms: inicio.elapsed().as_millis() as u64,
208    };
209
210    match args.format {
211        OutputFormat::Json => output::emit_json(&response)?,
212        OutputFormat::Text | OutputFormat::Markdown => {
213            output::emit_text(&format!(
214                "merged: {} sources into '{}' (relationships_moved={}, entities_removed={}) [{}]",
215                response.sources.len(),
216                response.target,
217                response.relationships_moved,
218                response.entities_removed,
219                response.namespace
220            ));
221        }
222    }
223
224    Ok(())
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn merge_entities_response_serializes_all_fields() {
233        let resp = MergeEntitiesResponse {
234            action: "merged".to_string(),
235            sources: vec!["auth".to_string(), "authentication".to_string()],
236            target: "auth-service".to_string(),
237            namespace: "global".to_string(),
238            relationships_moved: 7,
239            entities_removed: 2,
240            elapsed_ms: 15,
241        };
242        let json = serde_json::to_value(&resp).expect("serialization failed");
243        assert_eq!(json["action"], "merged");
244        assert_eq!(json["target"], "auth-service");
245        assert_eq!(json["namespace"], "global");
246        assert_eq!(json["relationships_moved"], 7);
247        assert_eq!(json["entities_removed"], 2);
248        let sources = json["sources"].as_array().expect("must be array");
249        assert_eq!(sources.len(), 2);
250        assert!(json["elapsed_ms"].is_number());
251    }
252
253    #[test]
254    fn merge_entities_response_action_is_merged() {
255        let resp = MergeEntitiesResponse {
256            action: "merged".to_string(),
257            sources: vec!["src".to_string()],
258            target: "tgt".to_string(),
259            namespace: "ns".to_string(),
260            relationships_moved: 0,
261            entities_removed: 1,
262            elapsed_ms: 0,
263        };
264        assert_eq!(resp.action, "merged");
265    }
266
267    #[test]
268    fn merge_entities_response_empty_sources_serializes() {
269        let resp = MergeEntitiesResponse {
270            action: "merged".to_string(),
271            sources: vec![],
272            target: "target".to_string(),
273            namespace: "global".to_string(),
274            relationships_moved: 0,
275            entities_removed: 0,
276            elapsed_ms: 1,
277        };
278        let json = serde_json::to_value(&resp).expect("serialization failed");
279        let sources = json["sources"].as_array().expect("must be array");
280        assert_eq!(sources.len(), 0);
281    }
282
283    #[test]
284    fn merge_entities_response_multiple_sources() {
285        let resp = MergeEntitiesResponse {
286            action: "merged".to_string(),
287            sources: vec!["a".into(), "b".into(), "c".into()],
288            target: "canonical".to_string(),
289            namespace: "proj".to_string(),
290            relationships_moved: 12,
291            entities_removed: 3,
292            elapsed_ms: 42,
293        };
294        let json = serde_json::to_value(&resp).expect("serialization failed");
295        assert_eq!(json["entities_removed"], 3);
296        let sources = json["sources"].as_array().unwrap();
297        assert_eq!(sources.len(), 3);
298    }
299}