Skip to main content

sqlite_graphrag/commands/
rename_entity.rs

1//! Handler for the `rename-entity` CLI subcommand.
2//!
3//! Renames an entity preserving all relationships and memory bindings.
4//! Only the `name` column in `entities` and the corresponding `vec_entities`
5//! row need updating because relationships use integer FK `entity_id`.
6
7use crate::entity_type::EntityType;
8use crate::errors::AppError;
9use crate::i18n::errors_msg;
10use crate::output::{self, OutputFormat};
11use crate::paths::AppPaths;
12use crate::storage::connection::open_rw;
13use crate::storage::entities;
14use rusqlite::params;
15use serde::Serialize;
16
17#[derive(clap::Args)]
18#[command(after_long_help = "EXAMPLES:\n  \
19    # Rename an entity\n  \
20    sqlite-graphrag rename-entity --name old-name --new-name new-name\n\n  \
21    # Rename with namespace\n  \
22    sqlite-graphrag rename-entity --name auth --new-name authentication --namespace my-project")]
23pub struct RenameEntityArgs {
24    /// Current entity name to rename.
25    #[arg(long, value_name = "NAME")]
26    pub name: String,
27    /// New name for the entity.
28    #[arg(long, value_name = "NEW_NAME")]
29    pub new_name: String,
30    #[arg(long)]
31    pub namespace: Option<String>,
32    #[arg(long, value_enum, default_value = "json")]
33    pub format: OutputFormat,
34    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
35    pub json: bool,
36    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
37    pub db: Option<String>,
38}
39
40#[derive(Serialize)]
41struct RenameEntityResponse {
42    action: String,
43    old_name: String,
44    new_name: String,
45    entity_id: i64,
46    namespace: String,
47    elapsed_ms: u64,
48}
49
50pub fn run(args: RenameEntityArgs) -> Result<(), AppError> {
51    let start = std::time::Instant::now();
52    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
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    // Verify source entity exists and fetch its id and type.
60    // Normalize the lookup name to match the normalized stored names.
61    let lookup_name = crate::parsers::normalize_entity_name(&args.name);
62    let row: Option<(i64, EntityType)> = {
63        let mut stmt = conn
64            .prepare_cached("SELECT id, type FROM entities WHERE namespace = ?1 AND name = ?2")?;
65        match stmt.query_row(params![namespace, lookup_name], |r| {
66            Ok((r.get::<_, i64>(0)?, r.get::<_, EntityType>(1)?))
67        }) {
68            Ok(row) => Some(row),
69            Err(rusqlite::Error::QueryReturnedNoRows) => None,
70            Err(e) => return Err(AppError::Database(e)),
71        }
72    };
73    let (entity_id, entity_type) = row
74        .ok_or_else(|| AppError::NotFound(errors_msg::entity_not_found(&args.name, &namespace)))?;
75
76    // Validate the raw new name first (catches short ALL_CAPS NER noise),
77    // then normalize it for storage to preserve the normalized-name invariant.
78    entities::validate_entity_name(&args.new_name)?;
79    let new_name = crate::parsers::normalize_entity_name(&args.new_name);
80
81    if lookup_name == new_name {
82        return Err(AppError::Validation(
83            "source and target entity names are identical".to_string(),
84        ));
85    }
86
87    // Ensure new name is not already taken in this namespace.
88    if entities::find_entity_id(&conn, &namespace, &new_name)?.is_some() {
89        return Err(AppError::Validation(format!(
90            "entity with name '{new_name}' already exists in namespace '{namespace}'"
91        )));
92    }
93
94    // Embed the normalized new name for vec_entities replacement.
95    let embedding = crate::embedder::embed_passage_local(&paths.models, &new_name)?;
96
97    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
98    tx.execute(
99        "UPDATE entities SET name = ?1, updated_at = unixepoch() WHERE id = ?2",
100        params![new_name, entity_id],
101    )?;
102    // v1.0.76: BLOB-backed entity_embeddings table (PK = entity_id).
103    // G43: reuse the canonical writer instead of a duplicated INSERT that
104    // hardcoded dim=384 and a removed local model name; `upsert_entity_vec`
105    // records the real vector length and the CLI version as `model`.
106    entities::upsert_entity_vec(
107        &tx,
108        entity_id,
109        &namespace,
110        entity_type,
111        &embedding,
112        &new_name,
113    )?;
114    tx.commit()?;
115
116    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
117
118    let response = RenameEntityResponse {
119        action: "renamed".to_string(),
120        old_name: args.name,
121        new_name,
122        entity_id,
123        namespace: namespace.clone(),
124        elapsed_ms: start.elapsed().as_millis() as u64,
125    };
126
127    match args.format {
128        OutputFormat::Json => output::emit_json(&response)?,
129        OutputFormat::Text | OutputFormat::Markdown => {
130            output::emit_text(&format!(
131                "renamed entity: '{}' → '{}' [{}]",
132                response.old_name, response.new_name, response.namespace
133            ));
134        }
135    }
136
137    Ok(())
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn rename_entity_response_serializes_all_fields() {
146        let resp = RenameEntityResponse {
147            action: "renamed".to_string(),
148            old_name: "auth".to_string(),
149            new_name: "authentication".to_string(),
150            entity_id: 42,
151            namespace: "global".to_string(),
152            elapsed_ms: 7,
153        };
154        let json = serde_json::to_value(&resp).expect("serialization failed");
155        assert_eq!(json["action"], "renamed");
156        assert_eq!(json["old_name"], "auth");
157        assert_eq!(json["new_name"], "authentication");
158        assert_eq!(json["entity_id"], 42);
159        assert_eq!(json["namespace"], "global");
160        assert!(json["elapsed_ms"].is_number());
161    }
162
163    #[test]
164    fn rename_entity_response_action_is_renamed() {
165        let resp = RenameEntityResponse {
166            action: "renamed".to_string(),
167            old_name: "x".to_string(),
168            new_name: "y".to_string(),
169            entity_id: 1,
170            namespace: "ns".to_string(),
171            elapsed_ms: 1,
172        };
173        assert_eq!(resp.action, "renamed");
174    }
175
176    #[test]
177    fn rename_entity_response_entity_id_preserved() {
178        let resp = RenameEntityResponse {
179            action: "renamed".to_string(),
180            old_name: "old".to_string(),
181            new_name: "new".to_string(),
182            entity_id: 999,
183            namespace: "test-ns".to_string(),
184            elapsed_ms: 5,
185        };
186        let json = serde_json::to_value(&resp).expect("serialization failed");
187        assert_eq!(json["entity_id"], 999);
188    }
189
190    #[test]
191    fn rejects_rename_entity_to_same_name() {
192        use crate::errors::AppError;
193        let err = AppError::Validation("source and target entity names are identical".to_string());
194        assert_eq!(err.exit_code(), 1);
195        assert!(err.to_string().contains("identical"));
196    }
197
198    #[test]
199    fn rename_entity_response_namespace_reflected() {
200        let resp = RenameEntityResponse {
201            action: "renamed".to_string(),
202            old_name: "a".to_string(),
203            new_name: "b".to_string(),
204            entity_id: 10,
205            namespace: "my-project".to_string(),
206            elapsed_ms: 2,
207        };
208        let json = serde_json::to_value(&resp).expect("serialization failed");
209        assert_eq!(json["namespace"], "my-project");
210    }
211}