sqlite_graphrag/commands/
edit.rs1use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::paths::AppPaths;
7use crate::storage::connection::open_rw;
8use crate::storage::{memories, versions};
9use serde::Serialize;
10
11#[derive(clap::Args)]
12#[command(after_long_help = "EXAMPLES:\n \
13 # Edit body inline\n \
14 sqlite-graphrag edit onboarding --body \"updated content\"\n\n \
15 # Edit body from a file\n \
16 sqlite-graphrag edit onboarding --body-file ./updated.md\n\n \
17 # Edit body from stdin (pipe)\n \
18 cat updated.md | sqlite-graphrag edit onboarding --body-stdin\n\n \
19 # Update only the description\n \
20 sqlite-graphrag edit onboarding --description \"new short description\"")]
21pub struct EditArgs {
22 #[arg(
24 value_name = "NAME",
25 conflicts_with = "name",
26 help = "Memory name to edit; alternative to --name"
27 )]
28 pub name_positional: Option<String>,
29 #[arg(long)]
31 pub name: Option<String>,
32 #[arg(long, conflicts_with_all = ["body_file", "body_stdin"])]
34 pub body: Option<String>,
35 #[arg(long, conflicts_with_all = ["body", "body_stdin"])]
37 pub body_file: Option<std::path::PathBuf>,
38 #[arg(long, conflicts_with_all = ["body", "body_file"])]
40 pub body_stdin: bool,
41 #[arg(long)]
43 pub description: Option<String>,
44 #[arg(
45 long,
46 value_name = "EPOCH_OR_RFC3339",
47 value_parser = crate::parsers::parse_expected_updated_at,
48 long_help = "Optimistic lock: reject if updated_at does not match. \
49Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
50 )]
51 pub expected_updated_at: Option<i64>,
52 #[arg(long, default_value = "global")]
53 pub namespace: Option<String>,
54 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
55 pub json: bool,
56 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
57 pub db: Option<String>,
58}
59
60#[derive(Serialize)]
61struct EditResponse {
62 memory_id: i64,
63 name: String,
64 action: String,
65 version: i64,
66 elapsed_ms: u64,
68}
69
70pub fn run(args: EditArgs) -> Result<(), AppError> {
71 use crate::constants::*;
72
73 let inicio = std::time::Instant::now();
74 let name = args.name_positional.or(args.name).ok_or_else(|| {
76 AppError::Validation("name required: pass as positional argument or via --name".to_string())
77 })?;
78 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
79
80 let paths = AppPaths::resolve(args.db.as_deref())?;
81 crate::storage::connection::ensure_db_ready(&paths)?;
82 let mut conn = open_rw(&paths.db)?;
83
84 let (memory_id, current_updated_at, _current_version) =
85 memories::find_by_name(&conn, &namespace, &name)?
86 .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
87
88 if let Some(expected) = args.expected_updated_at {
89 if expected != current_updated_at {
90 return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
91 expected,
92 current_updated_at,
93 )));
94 }
95 }
96
97 let mut raw_body: Option<String> = None;
98 if args.body.is_some() || args.body_file.is_some() || args.body_stdin {
99 let b = if let Some(b) = args.body {
100 b
101 } else if let Some(path) = &args.body_file {
102 std::fs::read_to_string(path).map_err(AppError::Io)?
103 } else {
104 crate::stdin_helper::read_stdin_with_timeout(60)?
105 };
106 if b.len() > MAX_MEMORY_BODY_LEN {
107 return Err(AppError::LimitExceeded(
108 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
109 ));
110 }
111 raw_body = Some(b);
112 }
113
114 if let Some(ref desc) = args.description {
115 if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
116 return Err(AppError::Validation(
117 crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
118 ));
119 }
120 }
121
122 let row = memories::read_by_name(&conn, &namespace, &name)?
123 .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory row not found after check")))?;
124
125 let new_body = raw_body.unwrap_or(row.body.clone());
126 let new_description = args.description.unwrap_or(row.description.clone());
127 let new_hash = blake3::hash(new_body.as_bytes()).to_hex().to_string();
128 let memory_type = row.memory_type.clone();
129 let metadata = row.metadata.clone();
130
131 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
132
133 let affected = if let Some(ts) = args.expected_updated_at {
134 tx.execute(
135 "UPDATE memories SET description=?2, body=?3, body_hash=?4
136 WHERE id=?1 AND updated_at=?5 AND deleted_at IS NULL",
137 rusqlite::params![memory_id, new_description, new_body, new_hash, ts],
138 )?
139 } else {
140 tx.execute(
141 "UPDATE memories SET description=?2, body=?3, body_hash=?4
142 WHERE id=?1 AND deleted_at IS NULL",
143 rusqlite::params![memory_id, new_description, new_body, new_hash],
144 )?
145 };
146
147 if affected == 0 {
148 return Err(AppError::Conflict(
149 "optimistic lock conflict: memory was modified by another process".to_string(),
150 ));
151 }
152
153 let next_v = versions::next_version(&tx, memory_id)?;
154
155 versions::insert_version(
156 &tx,
157 memory_id,
158 next_v,
159 &name,
160 &memory_type,
161 &new_description,
162 &new_body,
163 &metadata,
164 None,
165 "edit",
166 )?;
167
168 tx.commit()?;
169
170 output::emit_json(&EditResponse {
171 memory_id,
172 name,
173 action: "updated".to_string(),
174 version: next_v,
175 elapsed_ms: inicio.elapsed().as_millis() as u64,
176 })?;
177
178 Ok(())
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn edit_response_serializes_all_fields() {
187 let resp = EditResponse {
188 memory_id: 42,
189 name: "my-memory".to_string(),
190 action: "updated".to_string(),
191 version: 3,
192 elapsed_ms: 7,
193 };
194 let json = serde_json::to_value(&resp).expect("serialization failed");
195 assert_eq!(json["memory_id"], 42i64);
196 assert_eq!(json["name"], "my-memory");
197 assert_eq!(json["action"], "updated");
198 assert_eq!(json["version"], 3i64);
199 assert!(json["elapsed_ms"].is_number());
200 }
201
202 #[test]
203 fn edit_response_action_contains_updated() {
204 let resp = EditResponse {
205 memory_id: 1,
206 name: "n".to_string(),
207 action: "updated".to_string(),
208 version: 1,
209 elapsed_ms: 0,
210 };
211 assert_eq!(
212 resp.action, "updated",
213 "action must be 'updated' for successful edits"
214 );
215 }
216
217 #[test]
218 fn edit_body_exceeds_limit_returns_error() {
219 let limit = crate::constants::MAX_MEMORY_BODY_LEN;
220 let large_body: String = "a".repeat(limit + 1);
221 assert!(
222 large_body.len() > limit,
223 "body above limit must have length > MAX_MEMORY_BODY_LEN"
224 );
225 }
226
227 #[test]
228 fn edit_description_exceeds_limit_returns_error() {
229 let limit = crate::constants::MAX_MEMORY_DESCRIPTION_LEN;
230 let large_desc: String = "d".repeat(limit + 1);
231 assert!(
232 large_desc.len() > limit,
233 "description above limit must have length > MAX_MEMORY_DESCRIPTION_LEN"
234 );
235 }
236}