sqlite_graphrag/commands/
restore.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;
10use crate::storage::versions;
11use rusqlite::params;
12use rusqlite::OptionalExtension;
13use serde::Serialize;
14
15#[derive(clap::Args)]
16#[command(after_long_help = "EXAMPLES:\n \
17 # Restore the latest non-`restore` version of a memory\n \
18 sqlite-graphrag restore --name onboarding\n\n \
19 # Restore a specific version\n \
20 sqlite-graphrag restore --name onboarding --version 3\n\n \
21 # Restore within a specific namespace\n \
22 sqlite-graphrag restore --name onboarding --namespace my-project")]
23pub struct RestoreArgs {
24 #[arg(
26 value_name = "NAME",
27 conflicts_with = "name",
28 help = "Memory name to restore; alternative to --name"
29 )]
30 pub name_positional: Option<String>,
31 #[arg(long)]
33 pub name: Option<String>,
34 #[arg(long)]
38 pub version: Option<i64>,
39 #[arg(
40 long,
41 help = "Namespace (env: SQLITE_GRAPHRAG_NAMESPACE, default: global)"
42 )]
43 pub namespace: Option<String>,
44 #[arg(
46 long,
47 value_name = "EPOCH_OR_RFC3339",
48 value_parser = crate::parsers::parse_expected_updated_at,
49 long_help = "Optimistic lock: reject if updated_at does not match. \
50Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
51 )]
52 pub expected_updated_at: Option<i64>,
53 #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
55 pub format: JsonOutputFormat,
56 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
57 pub json: bool,
58 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
59 pub db: Option<String>,
60}
61
62#[derive(Serialize)]
63struct RestoreResponse {
64 memory_id: i64,
65 name: String,
66 version: i64,
67 restored_from: i64,
68 elapsed_ms: u64,
70}
71
72pub fn run(args: RestoreArgs) -> Result<(), AppError> {
73 let start = std::time::Instant::now();
74 let _ = args.format;
75 let name = args
76 .name_positional
77 .as_deref()
78 .or(args.name.as_deref())
79 .ok_or_else(|| {
80 AppError::Validation(
81 "name required: pass as positional argument or via --name".to_string(),
82 )
83 })?
84 .to_string();
85 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
86 let paths = AppPaths::resolve(args.db.as_deref())?;
87 let mut conn = open_rw(&paths.db)?;
88
89 let result: Option<(i64, i64)> = conn
91 .query_row(
92 "SELECT id, updated_at FROM memories WHERE namespace = ?1 AND name = ?2",
93 params![namespace, name],
94 |r| Ok((r.get(0)?, r.get(1)?)),
95 )
96 .optional()?;
97 let (memory_id, current_updated_at) = result
98 .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
99
100 if let Some(expected) = args.expected_updated_at {
101 if expected != current_updated_at {
102 return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
103 expected,
104 current_updated_at,
105 )));
106 }
107 }
108
109 let target_version: i64 = match args.version {
113 Some(v) => v,
114 None => {
115 let last: Option<i64> = conn
116 .query_row(
117 "SELECT MAX(version) FROM memory_versions
118 WHERE memory_id = ?1 AND change_reason != 'restore'",
119 params![memory_id],
120 |r| r.get(0),
121 )
122 .optional()?
123 .flatten();
124 let v = last.ok_or_else(|| {
125 AppError::NotFound(errors_msg::memory_not_found(&name, &namespace))
126 })?;
127 tracing::info!(
128 "restore --version omitted; using latest non-restore version: {}",
129 v
130 );
131 v
132 }
133 };
134
135 let version_row: (String, String, String, String, String) = {
136 let mut stmt = conn.prepare(
137 "SELECT name, type, description, body, metadata
138 FROM memory_versions
139 WHERE memory_id = ?1 AND version = ?2",
140 )?;
141
142 stmt.query_row(params![memory_id, target_version], |r| {
143 Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
144 })
145 .map_err(|_| AppError::NotFound(errors_msg::version_not_found(target_version, &name)))?
146 };
147
148 let (old_name, old_type, old_description, old_body, old_metadata) = version_row;
149
150 output::emit_progress_i18n(
154 "Re-computing embedding for restored memory...",
155 crate::i18n::validation::runtime_pt::restore_recomputing_embedding(),
156 );
157 let embedding = crate::daemon::embed_passage_or_local(&paths.models, &old_body)?;
158 let snippet: String = old_body.chars().take(300).collect();
159
160 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
161
162 let affected = if let Some(ts) = args.expected_updated_at {
164 tx.execute(
165 "UPDATE memories SET name=?2, type=?3, description=?4, body=?5, body_hash=?6, deleted_at=NULL
166 WHERE id=?1 AND updated_at=?7",
167 rusqlite::params![
168 memory_id,
169 old_name,
170 old_type,
171 old_description,
172 old_body,
173 blake3::hash(old_body.as_bytes()).to_hex().to_string(),
174 ts
175 ],
176 )?
177 } else {
178 tx.execute(
179 "UPDATE memories SET name=?2, type=?3, description=?4, body=?5, body_hash=?6, deleted_at=NULL
180 WHERE id=?1",
181 rusqlite::params![
182 memory_id,
183 old_name,
184 old_type,
185 old_description,
186 old_body,
187 blake3::hash(old_body.as_bytes()).to_hex().to_string()
188 ],
189 )?
190 };
191
192 if affected == 0 {
193 return Err(AppError::Conflict(errors_msg::concurrent_process_conflict()));
194 }
195
196 let next_v = versions::next_version(&tx, memory_id)?;
197
198 versions::insert_version(
199 &tx,
200 memory_id,
201 next_v,
202 &old_name,
203 &old_type,
204 &old_description,
205 &old_body,
206 &old_metadata,
207 None,
208 "restore",
209 )?;
210
211 memories::upsert_vec(
213 &tx, memory_id, &namespace, &old_type, &embedding, &old_name, &snippet,
214 )?;
215
216 tx.commit()?;
217
218 output::emit_json(&RestoreResponse {
219 memory_id,
220 name: old_name,
221 version: next_v,
222 restored_from: target_version,
223 elapsed_ms: start.elapsed().as_millis() as u64,
224 })?;
225
226 Ok(())
227}
228
229#[cfg(test)]
230mod tests {
231 use crate::errors::AppError;
232
233 #[test]
234 fn optimistic_lock_conflict_returns_exit_3() {
235 let err = AppError::Conflict(
236 "optimistic lock conflict: expected updated_at=50, but current is 99".to_string(),
237 );
238 assert_eq!(err.exit_code(), 3);
239 assert!(err.to_string().contains("conflict"));
240 }
241}