Skip to main content

sqlite_graphrag/commands/
rename.rs

1use crate::errors::AppError;
2use crate::i18n::erros;
3use crate::output;
4use crate::output::JsonOutputFormat;
5use crate::paths::AppPaths;
6use crate::storage::connection::open_rw;
7use crate::storage::{memories, versions};
8use serde::Serialize;
9
10#[derive(clap::Args)]
11pub struct RenameArgs {
12    /// Nome atual da memória. Aceita alias `--old` para compatibilidade com doc bilíngue.
13    #[arg(long, alias = "old")]
14    pub name: String,
15    /// Novo nome da memória. Aceita alias `--new` para compatibilidade com doc bilíngue.
16    #[arg(long, alias = "new")]
17    pub new_name: String,
18    #[arg(long, default_value = "global")]
19    pub namespace: Option<String>,
20    /// Optimistic locking: rejeitar se updated_at atual não bater (exit 3).
21    #[arg(
22        long,
23        value_name = "EPOCH_OR_RFC3339",
24        value_parser = crate::parsers::parse_expected_updated_at,
25        long_help = "Optimistic lock: reject if updated_at does not match. \
26Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
27    )]
28    pub expected_updated_at: Option<i64>,
29    /// Session ID opcional para rastrear origem da mudança.
30    #[arg(long, value_name = "UUID")]
31    pub session_id: Option<String>,
32    /// Formato da saída.
33    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
34    pub format: JsonOutputFormat,
35    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
36    pub json: bool,
37    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
38    pub db: Option<String>,
39}
40
41#[derive(Serialize)]
42struct RenameResponse {
43    memory_id: i64,
44    name: String,
45    action: &'static str,
46    version: i64,
47    /// Tempo total de execução em milissegundos desde início do handler até serialização.
48    elapsed_ms: u64,
49}
50
51pub fn run(args: RenameArgs) -> Result<(), AppError> {
52    let inicio = std::time::Instant::now();
53    let _ = args.format;
54    use crate::constants::*;
55
56    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
57
58    if args.new_name.starts_with("__") {
59        return Err(AppError::Validation(
60            crate::i18n::validacao::nome_reservado(),
61        ));
62    }
63
64    if args.new_name.is_empty() || args.new_name.len() > MAX_MEMORY_NAME_LEN {
65        return Err(AppError::Validation(
66            crate::i18n::validacao::novo_nome_comprimento(MAX_MEMORY_NAME_LEN),
67        ));
68    }
69
70    {
71        let slug_re = regex::Regex::new(crate::constants::NAME_SLUG_REGEX)
72            .map_err(|e| AppError::Internal(anyhow::anyhow!("regex: {e}")))?;
73        if !slug_re.is_match(&args.new_name) {
74            return Err(AppError::Validation(
75                crate::i18n::validacao::novo_nome_kebab(&args.new_name),
76            ));
77        }
78    }
79
80    let paths = AppPaths::resolve(args.db.as_deref())?;
81    let mut conn = open_rw(&paths.db)?;
82
83    let (memory_id, current_updated_at, _) = memories::find_by_name(&conn, &namespace, &args.name)?
84        .ok_or_else(|| AppError::NotFound(erros::memoria_nao_encontrada(&args.name, &namespace)))?;
85
86    if let Some(expected) = args.expected_updated_at {
87        if expected != current_updated_at {
88            return Err(AppError::Conflict(erros::conflito_optimistic_lock(
89                expected,
90                current_updated_at,
91            )));
92        }
93    }
94
95    let row = memories::read_by_name(&conn, &namespace, &args.name)?
96        .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory not found before rename")))?;
97
98    let memory_type = row.memory_type.clone();
99    let description = row.description.clone();
100    let body = row.body.clone();
101    let metadata = row.metadata.clone();
102
103    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
104
105    let affected = if let Some(ts) = args.expected_updated_at {
106        tx.execute(
107            "UPDATE memories SET name=?2 WHERE id=?1 AND updated_at=?3 AND deleted_at IS NULL",
108            rusqlite::params![memory_id, args.new_name, ts],
109        )?
110    } else {
111        tx.execute(
112            "UPDATE memories SET name=?2 WHERE id=?1 AND deleted_at IS NULL",
113            rusqlite::params![memory_id, args.new_name],
114        )?
115    };
116
117    if affected == 0 {
118        return Err(AppError::Conflict(
119            "optimistic lock conflict: memory was modified by another process".to_string(),
120        ));
121    }
122
123    let next_v = versions::next_version(&tx, memory_id)?;
124
125    versions::insert_version(
126        &tx,
127        memory_id,
128        next_v,
129        &args.new_name,
130        &memory_type,
131        &description,
132        &body,
133        &metadata,
134        None,
135        "rename",
136    )?;
137
138    tx.commit()?;
139
140    output::emit_json(&RenameResponse {
141        memory_id,
142        name: args.new_name,
143        action: "renamed",
144        version: next_v,
145        elapsed_ms: inicio.elapsed().as_millis() as u64,
146    })?;
147
148    Ok(())
149}
150
151#[cfg(test)]
152mod testes {
153    use crate::storage::memories::{insert, NewMemory};
154    use tempfile::TempDir;
155
156    fn setup_db() -> (TempDir, rusqlite::Connection) {
157        crate::storage::connection::register_vec_extension();
158        let dir = TempDir::new().unwrap();
159        let db_path = dir.path().join("test.db");
160        let mut conn = rusqlite::Connection::open(&db_path).unwrap();
161        crate::migrations::runner().run(&mut conn).unwrap();
162        (dir, conn)
163    }
164
165    fn nova_memoria(name: &str) -> NewMemory {
166        NewMemory {
167            namespace: "global".to_string(),
168            name: name.to_string(),
169            memory_type: "user".to_string(),
170            description: "desc".to_string(),
171            body: "corpo".to_string(),
172            body_hash: format!("hash-{name}"),
173            session_id: None,
174            source: "agent".to_string(),
175            metadata: serde_json::json!({}),
176        }
177    }
178
179    #[test]
180    fn rejeita_new_name_com_prefixo_duplo_underscore() {
181        use crate::errors::AppError;
182        let (_dir, conn) = setup_db();
183        insert(&conn, &nova_memoria("mem-teste")).unwrap();
184        drop(conn);
185
186        let err = AppError::Validation(
187            "names and namespaces starting with __ are reserved for internal use".to_string(),
188        );
189        assert!(err.to_string().contains("__"));
190        assert_eq!(err.exit_code(), 1);
191    }
192
193    #[test]
194    fn optimistic_lock_conflict_retorna_exit_3() {
195        use crate::errors::AppError;
196        let err = AppError::Conflict(
197            "optimistic lock conflict: expected updated_at=100, but current is 200".to_string(),
198        );
199        assert_eq!(err.exit_code(), 3);
200    }
201}