Skip to main content

hayson_engine/database/
backup.rs

1use std::collections::BTreeSet;
2use std::fs;
3use std::io;
4use std::path::{Component, Path, PathBuf};
5
6use serde_json::{json, Value};
7
8use crate::atomic::write_atomic;
9use crate::catalog::{parse_catalog, read_catalog_text, Catalog, ReadCatalogError};
10use crate::crypto::{CipherOptions, Sealer};
11use crate::errors::{HaysonCipherError, HaysonSchemaError};
12use crate::lock::DirLock;
13use crate::storage::{partition_names_in, LOG_SUFFIX};
14
15use super::database::{Database, DatabaseError, HeldLock, LockMode};
16use super::layout::{Layout, LayoutOptions};
17use super::verify::{verify, VerifyOptions};
18
19/// The manifest a backup carries next to the files it copied.
20pub const BACKUP_MANIFEST: &str = "hayson-backup.json";
21const BACKUP_FORMAT: u64 = 1;
22const RESTORE_OLD: &str = ".restore-old";
23const RESTORE_NEW: &str = ".restore-new";
24
25#[derive(Debug, Clone)]
26pub struct BackupOptions {
27    /// How the writer lock is taken for the length of the copy. [`LockMode::Skip`] copies a database
28    /// a writer may be appending to, which can capture a half-written last line (the engine cuts
29    /// such a tail off on the next writable open) — but nothing worse.
30    pub lock: LockMode,
31    /// Also copy the `<table>.idx` snapshots. Off by default: they are caches the engine rebuilds
32    /// from the logs, so leaving them out makes a backup smaller and no less complete.
33    pub indexes: bool,
34    /// Tables whose data (log files, partitions, images, snapshot) is left out; their declarations
35    /// stay in the metadata document, so the copy opens with them empty. A name the database does
36    /// not declare is refused.
37    pub exclude_tables: Vec<String>,
38    /// The keys of an encrypted database: the files are copied as they are (still sealed), but the
39    /// metadata document has to be opened to know which files the database owns.
40    pub encryption: Option<CipherOptions>,
41}
42
43impl Default for BackupOptions {
44    fn default() -> Self {
45        BackupOptions {
46            lock: LockMode::default(),
47            indexes: false,
48            exclude_tables: Vec::new(),
49            encryption: None,
50        }
51    }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct BackupResult {
56    pub dest: PathBuf,
57    pub files: usize,
58    pub bytes: u64,
59}
60
61#[derive(Debug, Clone, Default)]
62pub struct RestoreOptions {
63    /// How the writer lock on the directory being restored into is taken. As in [`BackupOptions`].
64    pub lock: LockMode,
65    /// Refuses a backup holding an image file larger than this, before anything is replaced.
66    pub max_image_bytes: Option<u64>,
67    /// The keys of the encrypted database being restored into and restored from.
68    pub encryption: Option<CipherOptions>,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct RestoreResult {
73    pub dir: PathBuf,
74    pub files: usize,
75    pub bytes: u64,
76    /// Files of the database that was there before and were replaced.
77    pub replaced: usize,
78}
79
80/// The sealer for the keys of an encrypted database, if any were given.
81pub(super) fn sealer_of(encryption: Option<&CipherOptions>) -> Result<Option<std::sync::Arc<Sealer>>, DatabaseError> {
82    Ok(encryption.map(Sealer::new).transpose()?.map(std::sync::Arc::new))
83}
84
85pub(super) fn refuse(message: String) -> DatabaseError {
86    DatabaseError::Schema(HaysonSchemaError(message))
87}
88
89pub(super) fn read_catalog_of(layout: &Layout, sealer: Option<&Sealer>) -> Result<Catalog, DatabaseError> {
90    let path = layout.metadata_path();
91    let raw = match read_catalog_text(path, sealer) {
92        Ok(Some(raw)) => raw,
93        Ok(None) => {
94            return Err(refuse(format!(
95                "\"{}\" does not exist — there is no database to back up",
96                path.display()
97            )))
98        }
99        Err(ReadCatalogError::Io(error)) => return Err(DatabaseError::Io(error)),
100        Err(
101            ReadCatalogError::Cipher(error)
102            | ReadCatalogError::Encrypted(error)
103            | ReadCatalogError::NotEncrypted(error),
104        ) => return Err(DatabaseError::Cipher(Box::new(error))),
105    };
106    let value: Value = serde_json::from_str(&raw)
107        .map_err(|error| DatabaseError::Catalog(format!("\"{}\" is not valid JSON: {error}", path.display())))?;
108    Ok(parse_catalog(&value)?)
109}
110
111fn relative_safely(root: &Path, path: &Path) -> Result<PathBuf, DatabaseError> {
112    let relative = path
113        .strip_prefix(root)
114        .map_err(|_| refuse(format!("\"{}\" is outside the database directory", path.display())))?;
115    check_relative(relative)?;
116    Ok(relative.to_path_buf())
117}
118
119/// A path a backup or a restore may join onto a root: relative, no `..`, no root, no prefix.
120pub(super) fn check_relative(path: &Path) -> Result<(), DatabaseError> {
121    let sane = path.components().all(|part| matches!(part, Component::Normal(_)));
122    if sane && path.components().next().is_some() {
123        Ok(())
124    } else {
125        Err(refuse(format!(
126            "\"{}\" is not a path inside the database directory",
127            path.display()
128        )))
129    }
130}
131
132fn files_in(dir: &Path) -> Result<Vec<PathBuf>, DatabaseError> {
133    let mut found = Vec::new();
134    let Ok(entries) = fs::read_dir(dir) else {
135        return Ok(found);
136    };
137    for entry in entries {
138        let entry = entry?;
139        let kind = entry.file_type()?;
140        if kind.is_symlink() {
141            return Err(refuse(format!(
142                "\"{}\" is a symbolic link — refusing to follow it",
143                entry.path().display()
144            )));
145        }
146        if kind.is_file() {
147            found.push(entry.path());
148        }
149    }
150    found.sort();
151    Ok(found)
152}
153
154/// Every file the database at `root` accounts for, as paths relative to `root`: its metadata
155/// document, the logs of its tables (one file, or one per partition), the files under each table's
156/// image directory and, when asked, the index snapshots. Anything else in the directory — another
157/// database in a subfolder, say — is not the database's and is left out.
158pub(super) fn owned_files(
159    root: &Path,
160    layout: &Layout,
161    catalog: &Catalog,
162    indexes: bool,
163    exclude: &[String],
164) -> Result<Vec<PathBuf>, DatabaseError> {
165    if let Some(unknown) = exclude.iter().find(|name| !catalog.tables.contains_key(*name)) {
166        return Err(refuse(format!(
167            "cannot leave out table \"{unknown}\" — the database declares no such table"
168        )));
169    }
170    let mut owned: BTreeSet<PathBuf> = BTreeSet::new();
171    let mut add = |path: &Path| -> Result<(), DatabaseError> {
172        owned.insert(relative_safely(root, path)?);
173        Ok(())
174    };
175    add(layout.metadata_path())?;
176    for (name, entry) in &catalog.tables {
177        if exclude.contains(name) {
178            continue;
179        }
180        let flat = layout.log_path(name);
181        match fs::symlink_metadata(&flat) {
182            Ok(meta) if meta.file_type().is_symlink() => {
183                return Err(refuse(format!(
184                    "\"{}\" is a symbolic link — refusing to follow it",
185                    flat.display()
186                )))
187            }
188            Ok(meta) if meta.is_file() => add(&flat)?,
189            _ => {}
190        }
191        let partitions = layout.tables().join(name);
192        for part in partition_names_in(&partitions) {
193            add(&partitions.join(format!("{part}{LOG_SUFFIX}")))?;
194        }
195        if indexes && layout.index_path(name).is_file() {
196            add(&layout.index_path(name))?;
197        }
198        let image_dir = entry
199            .options
200            .as_ref()
201            .and_then(|options| options.image_dir.clone())
202            .or_else(|| catalog.defaults.as_ref().and_then(|d| d.image_dir.clone()))
203            .map(|dir| root.join(dir))
204            .unwrap_or_else(|| layout.tables().join(format!("{name}.images")));
205        for file in files_in(&image_dir)? {
206            add(&file)?;
207        }
208    }
209    Ok(owned.into_iter().collect())
210}
211
212/// The flat log files of the tables `exclude` leaves out, as paths relative to `root`. They are
213/// packed or copied empty: the catalog still declares those tables, and an unpacked database whose
214/// declared table has no log at all does not open read-only.
215pub(super) fn emptied_logs(root: &Path, layout: &Layout, catalog: &Catalog, exclude: &[String]) -> Vec<PathBuf> {
216    exclude
217        .iter()
218        .filter(|name| {
219            catalog
220                .tables
221                .get(*name)
222                .is_some_and(|entry| entry.partition_by.is_none())
223        })
224        .filter_map(|name| relative_safely(root, &layout.log_path(name)).ok())
225        .collect()
226}
227
228pub(super) fn hold(root: &Path, layout: &Layout, lock: &LockMode) -> Result<HeldLock, DatabaseError> {
229    let LockMode::Enabled(options) = lock else {
230        return Ok(HeldLock(None));
231    };
232    if root.is_dir() {
233        fs::create_dir_all(layout.runtime())?;
234    }
235    Ok(HeldLock(Some(DirLock::acquire_as(
236        layout.lock_path(),
237        options.clone(),
238        root.to_path_buf(),
239    )?)))
240}
241
242fn copy_synced(from: &Path, to: &Path) -> io::Result<u64> {
243    if let Some(parent) = to.parent() {
244        fs::create_dir_all(parent)?;
245    }
246    let bytes = fs::copy(from, to)?;
247    fs::File::open(to)?.sync_all()?;
248    Ok(bytes)
249}
250
251/// Copies a database directory into `dest`: the files the database accounts for (see
252/// [`owned_files`]) plus a `hayson-backup.json` manifest listing them with their sizes.
253///
254/// `dest` must not exist or must be an empty directory. The copy is built next to it and renamed
255/// into place, so a backup that fails halfway leaves no half-filled `dest`. The directory is held
256/// under the writer lock for the length of the copy unless `options.lock` is [`LockMode::Skip`];
257/// a database with an unfinished unit of work is refused, because its log and journal disagree
258/// until a writable open finishes it.
259///
260/// History kept in a database of its own is not part of this database's files, so it is not copied.
261pub fn backup_database(dir: &Path, dest: &Path, options: &BackupOptions) -> Result<BackupResult, DatabaseError> {
262    let sealer = sealer_of(options.encryption.as_ref())?;
263    let layout = Database::resolve_layout_sealed(dir, &LayoutOptions::default(), sealer.as_deref())?;
264    let catalog = read_catalog_of(&layout, sealer.as_deref())?;
265    if dest.exists()
266        && fs::read_dir(dest)
267            .map(|mut entries| entries.next().is_some())
268            .unwrap_or(true)
269    {
270        return Err(refuse(format!(
271            "\"{}\" already exists and is not an empty directory",
272            dest.display()
273        )));
274    }
275    let partial = sibling(dest, ".partial");
276    if partial.exists() {
277        fs::remove_dir_all(&partial)?;
278    }
279
280    let held = hold(dir, &layout, &options.lock)?;
281    let outcome = copy_database(dir, &layout, &catalog, &partial, options);
282    drop(held);
283    match outcome {
284        Ok(result) => {
285            if dest.exists() {
286                fs::remove_dir(dest)?;
287            }
288            fs::rename(&partial, dest)?;
289            Ok(BackupResult {
290                dest: dest.to_path_buf(),
291                ..result
292            })
293        }
294        Err(error) => {
295            let _ = fs::remove_dir_all(&partial);
296            Err(error)
297        }
298    }
299}
300
301pub(super) fn sibling(path: &Path, suffix: &str) -> PathBuf {
302    let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
303    name.push(suffix);
304    path.with_file_name(name)
305}
306
307fn copy_database(
308    root: &Path,
309    layout: &Layout,
310    catalog: &Catalog,
311    partial: &Path,
312    options: &BackupOptions,
313) -> Result<BackupResult, DatabaseError> {
314    if layout.journal_path().exists() {
315        return Err(refuse(format!(
316            "\"{}\" holds an unfinished unit of work — open the database for writing once so it is finished, then back it up",
317            layout.journal_path().display()
318        )));
319    }
320    let mut files = owned_files(root, layout, catalog, options.indexes, &options.exclude_tables)?;
321    let emptied = emptied_logs(root, layout, catalog, &options.exclude_tables);
322    files.extend(emptied.iter().cloned());
323    files.sort();
324    fs::create_dir_all(partial)?;
325    let mut listed = Vec::new();
326    let mut total = 0u64;
327    for relative in &files {
328        let bytes = if emptied.contains(relative) {
329            let target = partial.join(relative);
330            if let Some(parent) = target.parent() {
331                fs::create_dir_all(parent)?;
332            }
333            fs::File::create(&target)?.sync_all()?;
334            0
335        } else {
336            copy_synced(&root.join(relative), &partial.join(relative))?
337        };
338        total += bytes;
339        listed.push(json!({ "path": relative.to_string_lossy().replace('\\', "/"), "bytes": bytes }));
340    }
341    let manifest = json!({
342        "format": BACKUP_FORMAT,
343        "createdAt": chrono::Utc::now().timestamp_millis(),
344        "engine": env!("CARGO_PKG_VERSION"),
345        "metadataFile": layout.metadata_file(),
346        "files": listed,
347    });
348    let mut text = serde_json::to_string_pretty(&manifest).map_err(|e| DatabaseError::Catalog(e.to_string()))?;
349    text.push('\n');
350    write_atomic(&partial.join(BACKUP_MANIFEST), text.as_bytes(), None)?;
351    Ok(BackupResult {
352        dest: partial.to_path_buf(),
353        files: files.len(),
354        bytes: total,
355    })
356}
357
358#[derive(Clone)]
359pub(super) struct ManifestEntry {
360    pub(super) relative: PathBuf,
361    pub(super) bytes: u64,
362}
363
364fn read_manifest(backup: &Path) -> Result<(String, Vec<ManifestEntry>), DatabaseError> {
365    let path = backup.join(BACKUP_MANIFEST);
366    let raw = fs::read_to_string(&path).map_err(|error| {
367        refuse(format!(
368            "\"{}\" is not a readable backup manifest: {error}",
369            path.display()
370        ))
371    })?;
372    parse_manifest(&raw, &path.display().to_string())
373}
374
375pub(super) fn parse_manifest(raw: &str, label: &str) -> Result<(String, Vec<ManifestEntry>), DatabaseError> {
376    let manifest: Value =
377        serde_json::from_str(raw).map_err(|error| refuse(format!("\"{label}\" is not valid JSON: {error}")))?;
378    if manifest.get("format").and_then(Value::as_u64) != Some(BACKUP_FORMAT) {
379        return Err(refuse(format!("\"{label}\" is not a backup format this engine reads")));
380    }
381    let metadata_file = manifest
382        .get("metadataFile")
383        .and_then(Value::as_str)
384        .ok_or_else(|| refuse("backup manifest names no \"metadataFile\"".to_string()))?
385        .to_string();
386    let listed = manifest
387        .get("files")
388        .and_then(Value::as_array)
389        .ok_or_else(|| refuse("backup manifest lists no \"files\"".to_string()))?;
390    let mut entries = Vec::new();
391    for item in listed {
392        let relative = PathBuf::from(
393            item.get("path")
394                .and_then(Value::as_str)
395                .ok_or_else(|| refuse("a backup manifest entry has no \"path\"".to_string()))?,
396        );
397        check_relative(&relative)?;
398        let bytes = item
399            .get("bytes")
400            .and_then(Value::as_u64)
401            .ok_or_else(|| refuse(format!("manifest entry \"{}\" has no \"bytes\"", relative.display())))?;
402        entries.push(ManifestEntry { relative, bytes });
403    }
404    Ok((metadata_file, entries))
405}
406
407/// Restores a backup made by [`backup_database`] into `dir`, replacing the database that is there.
408///
409/// Recoverable: nothing is deleted until the replacement is in place. The backup is copied into
410/// `<dir>/.restore-new` and checked (sizes against the manifest, then [`verify`] with no error);
411/// the files of the database being replaced are moved into `<dir>/.restore-old`; the new files are
412/// moved in; and only then is `.restore-old` removed. If a move fails, the files already moved are
413/// put back, and when even that fails both errors are reported. A `.restore-old` left by an
414/// interrupted restore is refused, because it may hold the only good copy.
415///
416/// Only the files the database accounts for are replaced, so another database living in a
417/// subfolder of `dir` is untouched.
418pub fn restore_database(backup: &Path, dir: &Path, options: &RestoreOptions) -> Result<RestoreResult, DatabaseError> {
419    let (metadata_file, entries) = read_manifest(backup)?;
420    for entry in &entries {
421        let path = backup.join(&entry.relative);
422        let meta = fs::symlink_metadata(&path).map_err(|error| {
423            refuse(format!(
424                "backup file \"{}\" is missing: {error}",
425                entry.relative.display()
426            ))
427        })?;
428        if !meta.is_file() || meta.len() != entry.bytes {
429            return Err(refuse(format!(
430                "backup file \"{}\" does not match its manifest entry ({} bytes expected)",
431                entry.relative.display(),
432                entry.bytes
433            )));
434        }
435    }
436    let part = RestorePart {
437        sub: PathBuf::new(),
438        encryption: options.encryption.clone(),
439        metadata_file,
440        entries: entries.clone(),
441    };
442    restore_staged(dir, &[part], &options.lock, options.max_image_bytes, |staged| {
443        let mut total = 0u64;
444        for entry in &entries {
445            total += copy_synced(&backup.join(&entry.relative), &staged.join(&entry.relative))?;
446        }
447        Ok(total)
448    })
449}
450
451/// One database of a restore: where it lives under the directory being restored into (`sub`, empty
452/// for the directory itself), its metadata file name, and its files as paths relative to that
453/// directory (already prefixed with `sub`).
454pub(super) struct RestorePart {
455    pub(super) sub: PathBuf,
456    /// The keys of this database, when it is encrypted.
457    pub(super) encryption: Option<CipherOptions>,
458    pub(super) metadata_file: String,
459    pub(super) entries: Vec<ManifestEntry>,
460}
461
462/// The recoverable half of a restore, shared with unpacking: `stage` fills the given staging
463/// directory with the files of every part (returning their byte total) while the writer lock of each
464/// database is held. All parts are staged and verified before any of them is swapped in, and the
465/// swap moves every part's files through one `.restore-old`, so a failure puts all of them back.
466pub(super) fn restore_staged(
467    dir: &Path,
468    parts: &[RestorePart],
469    lock: &LockMode,
470    max_image_bytes: Option<u64>,
471    stage: impl FnOnce(&Path) -> Result<u64, DatabaseError>,
472) -> Result<RestoreResult, DatabaseError> {
473    let old = dir.join(RESTORE_OLD);
474    if old.exists() {
475        return Err(refuse(format!(
476            "\"{}\" exists — an earlier restore was interrupted and it may hold the only good copy of the database; move its files back (or delete it) before restoring again",
477            old.display()
478        )));
479    }
480    let mut created: Vec<PathBuf> = Vec::new();
481    let mut made_roots: Vec<bool> = Vec::new();
482    let mut layouts = Vec::new();
483    let mut held = Vec::new();
484    for part in parts {
485        let root = dir.join(&part.sub);
486        // NOTE: the topmost directory this call is about to make, so a refusal can take it away again.
487        let first_new = root.ancestors().take_while(|path| !path.exists()).last();
488        made_roots.push(first_new.is_some());
489        if let Some(first_new) = first_new {
490            created.push(first_new.to_path_buf());
491        }
492        fs::create_dir_all(&root)?;
493        let sealer = sealer_of(part.encryption.as_ref())?;
494        let layout = Database::resolve_layout_sealed(
495            &root,
496            &LayoutOptions {
497                metadata_file: Some(part.metadata_file.clone()),
498                ..LayoutOptions::default()
499            },
500            sealer.as_deref(),
501        )?;
502        held.push(hold(&root, &layout, lock)?);
503        layouts.push(layout);
504    }
505    let staged = dir.join(RESTORE_NEW);
506    let outcome = install(dir, &layouts, parts, &staged, &old, max_image_bytes, stage);
507    let _ = fs::remove_dir_all(&staged);
508    drop(held);
509    if outcome.is_err() {
510        // NOTE: directories this call made and nothing was installed into must not outlive the refusal.
511        for (layout, made) in layouts.iter().zip(&made_roots) {
512            if *made {
513                let _ = fs::remove_dir_all(layout.runtime());
514            }
515        }
516        for path in created.iter().rev() {
517            let _ = fs::remove_dir(path);
518            let mut parent = path.parent();
519            while let Some(up) = parent {
520                if up == dir || fs::remove_dir(up).is_err() {
521                    break;
522                }
523                parent = up.parent();
524            }
525        }
526        if dir.exists() && created.iter().any(|path| path == dir) {
527            let _ = fs::remove_dir(dir);
528        }
529    }
530    outcome
531}
532
533fn install(
534    root: &Path,
535    layouts: &[Layout],
536    parts: &[RestorePart],
537    staged: &Path,
538    old: &Path,
539    max_image_bytes: Option<u64>,
540    stage: impl FnOnce(&Path) -> Result<u64, DatabaseError>,
541) -> Result<RestoreResult, DatabaseError> {
542    if staged.exists() {
543        fs::remove_dir_all(staged)?;
544    }
545    let total = stage(staged)?;
546    for part in parts {
547        let report = verify(
548            &staged.join(&part.sub),
549            &VerifyOptions {
550                relations: false,
551                max_image_bytes,
552                encryption: part.encryption.clone(),
553                ..VerifyOptions::default()
554            },
555        );
556        let which = if part.sub.as_os_str().is_empty() {
557            String::new()
558        } else {
559            format!(" (database \"{}\")", part.sub.display())
560        };
561        if let Some(problem) = report.problems.iter().find(|p| {
562            matches!(
563                p.code,
564                "catalog-encrypted" | "catalog-key-rejected" | "catalog-not-encrypted"
565            )
566        }) {
567            return Err(DatabaseError::Cipher(Box::new(HaysonCipherError::new(
568                "",
569                crate::crypto::STORAGE_FIELD,
570                format!("{which}: {}", problem.message),
571            ))));
572        }
573        if let Some(problem) = report.problems.iter().find(|p| p.code == "image-oversize") {
574            return Err(refuse(format!(
575                "the backup holds an image over the size limit{which} ({}) — nothing was changed",
576                problem.message
577            )));
578        }
579        if let Some(problem) = report
580            .problems
581            .iter()
582            .find(|p| p.severity == super::verify::Severity::Error)
583        {
584            return Err(refuse(format!(
585                "the backup does not verify{which} ({}: {}) — nothing was changed",
586                problem.code, problem.message
587            )));
588        }
589    }
590
591    // The files of the databases now there: what each catalog accounts for (when it can be read),
592    // plus whatever the backup is about to overwrite.
593    let entries: Vec<&ManifestEntry> = parts.iter().flat_map(|part| part.entries.iter()).collect();
594    let mut replaced: BTreeSet<PathBuf> = entries.iter().map(|e| e.relative.clone()).collect();
595    for (part, layout) in parts.iter().zip(layouts) {
596        let part_root = root.join(&part.sub);
597        let sealer = sealer_of(part.encryption.as_ref()).ok().flatten();
598        if let Ok(catalog) = read_catalog_of(layout, sealer.as_deref()) {
599            if let Ok(current) = owned_files(&part_root, layout, &catalog, true, &[]) {
600                replaced.extend(current.into_iter().map(|relative| part.sub.join(relative)));
601            }
602        }
603    }
604    replaced.retain(|relative| root.join(relative).is_file());
605
606    fs::create_dir_all(old)?;
607    let mut moved_out: Vec<PathBuf> = Vec::new();
608    let mut moved_in: Vec<PathBuf> = Vec::new();
609    let swap = (|| -> io::Result<()> {
610        for relative in &replaced {
611            move_file(&root.join(relative), &old.join(relative))?;
612            moved_out.push(relative.clone());
613        }
614        for entry in &entries {
615            move_file(&staged.join(&entry.relative), &root.join(&entry.relative))?;
616            moved_in.push(entry.relative.clone());
617        }
618        Ok(())
619    })();
620    match swap {
621        Ok(()) => {
622            fs::remove_dir_all(old)?;
623            Ok(RestoreResult {
624                dir: root.to_path_buf(),
625                files: entries.len(),
626                bytes: total,
627                replaced: replaced.len(),
628            })
629        }
630        Err(error) => {
631            let rollback = (|| -> io::Result<()> {
632                for relative in &moved_in {
633                    fs::remove_file(root.join(relative))?;
634                }
635                for relative in &moved_out {
636                    move_file(&old.join(relative), &root.join(relative))?;
637                }
638                Ok(())
639            })();
640            match rollback {
641                Ok(()) => {
642                    let _ = fs::remove_dir_all(old);
643                    Err(DatabaseError::Io(error))
644                }
645                Err(rollback_error) => Err(refuse(format!(
646                    "restore failed ({error}) and putting the previous files back failed too ({rollback_error}) — the previous database is in \"{}\"",
647                    old.display()
648                ))),
649            }
650        }
651    }
652}
653
654fn move_file(from: &Path, to: &Path) -> io::Result<()> {
655    if let Some(parent) = to.parent() {
656        fs::create_dir_all(parent)?;
657    }
658    fs::rename(from, to)
659}