sqlite_graphrag/commands/
rename.rs1use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::output::JsonOutputFormat;
7use crate::paths::AppPaths;
8use crate::storage::connection::open_rw;
9use crate::storage::{memories, versions};
10use serde::Serialize;
11
12#[derive(clap::Args)]
13#[command(after_long_help = "EXAMPLES:\n \
14 # Rename using two positional arguments (NAME NEW)\n \
15 sqlite-graphrag rename onboarding welcome-guide\n\n \
16 # Rename using the positional NAME + --new-name flag\n \
17 sqlite-graphrag rename onboarding --new-name welcome-guide\n\n \
18 # Rename using the named flag form\n \
19 sqlite-graphrag rename --name onboarding --new-name welcome-guide\n\n \
20 # Rename within a specific namespace\n \
21 sqlite-graphrag rename onboarding welcome-guide --namespace my-project")]
22pub struct RenameArgs {
24 #[arg(
26 value_name = "NAME",
27 conflicts_with = "name",
28 help = "Current memory name to rename; alternative to --name/--old"
29 )]
30 pub name_positional: Option<String>,
31 #[arg(long, alias = "old", alias = "from")]
33 pub name: Option<String>,
34 #[arg(
36 value_name = "NEW",
37 conflicts_with = "new_name",
38 help = "New memory name; alternative to --new-name/--new/--to"
39 )]
40 pub new_name_positional: Option<String>,
41 #[arg(long, alias = "new", alias = "to")]
43 pub new_name: Option<String>,
44 #[arg(
45 long,
46 help = "Namespace (flag / XDG namespace.default / global)"
47 )]
48 pub namespace: Option<String>,
50 #[arg(
52 long,
53 value_name = "EPOCH_OR_RFC3339",
54 value_parser = crate::parsers::parse_expected_updated_at,
55 long_help = "Optimistic lock: reject if updated_at does not match. \
56Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
57 )]
58 pub expected_updated_at: Option<i64>,
59 #[arg(long, value_name = "UUID")]
61 pub session_id: Option<String>,
62 #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
64 pub format: JsonOutputFormat,
65 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
67 pub json: bool,
68 #[arg(long)]
70 pub db: Option<String>,
71}
72
73#[derive(Serialize)]
74struct RenameResponse {
75 memory_id: i64,
76 name: String,
77 action: &'static str,
78 version: i64,
79 #[serde(skip_serializing_if = "Option::is_none")]
81 ghost_purged: Option<bool>,
82 elapsed_ms: u64,
84}
85
86pub fn run(args: RenameArgs) -> Result<(), AppError> {
88 let inicio = std::time::Instant::now();
89 let _ = args.format;
90 tracing::debug!(target: "rename", old = ?args.name, new = ?args.new_name, "renaming memory");
91 use crate::constants::*;
92
93 let name = args.name_positional.or(args.name).ok_or_else(|| {
95 AppError::Validation(crate::i18n::validation::name_required_positional_or_flag())
96 })?;
97 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
98
99 let raw_new_name = args.new_name.or(args.new_name_positional).ok_or_else(|| {
100 AppError::Validation(
101 "new name required: pass as positional <NEW> or via --new-name/--new/--to".to_string(),
102 )
103 })?;
104
105 let normalized_new_name = {
107 let lower = raw_new_name.to_lowercase().replace(['_', ' '], "-");
108 let trimmed = lower.trim_matches('-').to_string();
109 if trimmed != raw_new_name {
110 tracing::warn!(target: "rename",
111 original = %raw_new_name,
112 normalized = %trimmed,
113 "new_name auto-normalized to kebab-case"
114 );
115 }
116 trimmed
117 };
118
119 if normalized_new_name == name {
120 return Err(AppError::Validation(
121 "source and target names are identical".to_string(),
122 ));
123 }
124
125 if normalized_new_name.starts_with("__") {
126 return Err(AppError::Validation(
127 crate::i18n::validation::reserved_name(),
128 ));
129 }
130
131 if normalized_new_name.is_empty() || normalized_new_name.len() > MAX_MEMORY_NAME_LEN {
132 return Err(AppError::Validation(
133 crate::i18n::validation::new_name_length(MAX_MEMORY_NAME_LEN),
134 ));
135 }
136
137 {
138 let slug_re = crate::constants::name_slug_regex();
139 if !slug_re.is_match(&normalized_new_name) {
140 return Err(AppError::Validation(
141 crate::i18n::validation::new_name_kebab(&normalized_new_name),
142 ));
143 }
144 }
145
146 let paths = AppPaths::resolve(args.db.as_deref())?;
147 crate::storage::connection::ensure_db_ready(&paths)?;
148 let mut conn = open_rw(&paths.db)?;
149
150 let (memory_id, current_updated_at, _) = memories::find_by_name(&conn, &namespace, &name)?
151 .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
152
153 if let Some(expected) = args.expected_updated_at {
154 if expected != current_updated_at {
155 return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
156 expected,
157 current_updated_at,
158 )));
159 }
160 }
161
162 let row = memories::read_by_name(&conn, &namespace, &name)?
163 .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory not found before rename")))?;
164
165 let memory_type = row.memory_type.clone();
166 let description = row.description.clone();
167 let body = row.body.clone();
168 let metadata = row.metadata.clone();
169
170 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
171
172 let mut ghost_purged: Option<bool> = None;
174 if let Some((ghost_id, is_deleted)) =
175 memories::find_by_name_any_state(&tx, &namespace, &normalized_new_name)?
176 {
177 if is_deleted {
178 tracing::info!(target: "rename",
179 ghost_id,
180 name = %normalized_new_name,
181 "auto-purging soft-deleted ghost to free target name for rename"
182 );
183 tx.execute(
184 "DELETE FROM memory_versions WHERE memory_id = ?1",
185 rusqlite::params![ghost_id],
186 )?;
187 tx.execute(
188 "DELETE FROM memory_chunks WHERE memory_id = ?1",
189 rusqlite::params![ghost_id],
190 )?;
191 tx.execute(
192 "DELETE FROM memory_entities WHERE memory_id = ?1",
193 rusqlite::params![ghost_id],
194 )?;
195 tx.execute(
196 "DELETE FROM vec_memories WHERE memory_id = ?1",
197 rusqlite::params![ghost_id],
198 )?;
199 tx.execute(
200 "DELETE FROM memories WHERE id = ?1",
201 rusqlite::params![ghost_id],
202 )?;
203 ghost_purged = Some(true);
204 } else if ghost_id != memory_id {
205 return Err(AppError::Duplicate(format!(
206 "target name '{normalized_new_name}' is already occupied by active memory id {ghost_id}"
207 )));
208 }
209 }
210
211 let affected = if let Some(ts) = args.expected_updated_at {
212 tx.execute(
213 "UPDATE memories SET name=?2 WHERE id=?1 AND updated_at=?3 AND deleted_at IS NULL",
214 rusqlite::params![memory_id, normalized_new_name, ts],
215 )?
216 } else {
217 tx.execute(
218 "UPDATE memories SET name=?2 WHERE id=?1 AND deleted_at IS NULL",
219 rusqlite::params![memory_id, normalized_new_name],
220 )?
221 };
222
223 if affected == 0 {
224 return Err(AppError::Conflict(
225 "optimistic lock conflict: memory was modified by another process".to_string(),
226 ));
227 }
228
229 let next_v = versions::next_version(&tx, memory_id)?;
230
231 versions::insert_version(
232 &tx,
233 memory_id,
234 next_v,
235 &normalized_new_name,
236 &memory_type,
237 &description,
238 &body,
239 &metadata,
240 None,
241 "rename",
242 )?;
243
244 memories::sync_fts_after_update(
245 &tx,
246 memory_id,
247 &name,
248 &description,
249 &body,
250 &normalized_new_name,
251 &description,
252 &body,
253 )?;
254
255 tx.commit()?;
256
257 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
258
259 output::emit_json(&RenameResponse {
260 memory_id,
261 name: normalized_new_name,
262 action: "renamed",
263 version: next_v,
264 ghost_purged,
265 elapsed_ms: inicio.elapsed().as_millis() as u64,
266 })?;
267
268 Ok(())
269}
270
271#[cfg(test)]
272mod tests {
273 use crate::storage::memories::{insert, NewMemory};
274 use tempfile::TempDir;
275
276 fn setup_db() -> (TempDir, rusqlite::Connection) {
277 crate::storage::connection::register_vec_extension();
278 let dir = TempDir::new().unwrap();
279 let db_path = dir.path().join("test.db");
280 let mut conn = rusqlite::Connection::open(&db_path).unwrap();
281 crate::migrations::runner().run(&mut conn).unwrap();
282 (dir, conn)
283 }
284
285 fn new_memory(name: &str) -> NewMemory {
286 NewMemory {
287 namespace: "global".to_string(),
288 name: name.to_string(),
289 memory_type: "user".to_string(),
290 description: "desc".to_string(),
291 body: "corpo".to_string(),
292 body_hash: format!("hash-{name}"),
293 session_id: None,
294 source: "agent".to_string(),
295 metadata: serde_json::json!({}),
296 }
297 }
298
299 #[test]
300 fn rejects_new_name_with_double_underscore_prefix() {
301 use crate::errors::AppError;
302 let (_dir, conn) = setup_db();
303 insert(&conn, &new_memory("mem-teste")).unwrap();
304 drop(conn);
305
306 let err = AppError::Validation(
307 "names and namespaces starting with __ are reserved for internal use".to_string(),
308 );
309 assert!(err.to_string().contains("__"));
310 assert_eq!(err.exit_code(), 1);
311 }
312
313 #[test]
314 fn rejects_rename_to_same_name() {
315 use crate::errors::AppError;
316 let err = AppError::Validation(crate::i18n::validation::source_target_names_identical());
317 assert_eq!(err.exit_code(), 1);
318 assert!(err.to_string().contains("identical"));
319 }
320
321 #[test]
322 fn optimistic_lock_conflict_returns_exit_3() {
323 use crate::errors::AppError;
324 let err = AppError::Conflict(
325 "optimistic lock conflict: expected updated_at=100, but current is 200".to_string(),
326 );
327 assert_eq!(err.exit_code(), 3);
328 }
329}