use jasonisnthappy::Database;let db = Database::open("my.db")?;// Create a backupdb.backup("./backups/my-backup.db")?;println!("Backup created successfully!");
Backups are created atomically - the backup file is written to a temporary location and renamed only when complete.
use std::fs;// Full backup (daily)db.backup("./backups/daily/full_backup.db")?;// Incremental backup (hourly) - copy WAL onlyfs::copy("app.db-wal", "./backups/hourly/wal_backup")?;// To restore: use full backup + apply WAL
Incremental backups require careful WAL management. For simplicity, prefer full backups.
use std::fs;// Test restore to temporary locationfs::copy("./backups/latest.db", "./test-restore.db")?;let test_db = Database::open("./test-restore.db")?;let info = test_db.info()?;println!("Restored database info:");println!(" Collections: {}", info.collections.len());println!(" Total documents: {}", info.total_documents);// Cleanuptest_db.close()?;fs::remove_file("./test-restore.db")?;
let db = Database::open("app.db")?;// ... use database ...db.close()?;
3
Replace database file
4
use std::fs;// Backup current database (optional but recommended)fs::copy("app.db", "app.db.old")?;// Restore from backupfs::copy("./backups/good-backup.db", "app.db")?;// Remove WAL file (important!)fs::remove_file("app.db-wal").ok();
5
Reopen database
6
let db = Database::open("app.db")?;println!("Database restored!");
Important: Always remove the WAL file when restoring from a backup, or open the database to checkpoint it before use.
use serde_json::json;// Open backup read-onlylet backup = Database::open_with_options( "./backups/backup.db", DatabaseOptions { read_only: true, ..Default::default() })?;// Open current database for writinglet db = Database::open("app.db")?;// Copy specific collectionlet backup_users = backup.collection("users");let current_users = db.collection("users");let all_users = backup_users.find_all()?;for user in all_users { current_users.insert(user)?;}println!("Users collection restored");
// Good: separate directorydb.backup("/mnt/backups/myapp/backup.db")?;// Good: different disk/serverdb.backup("/backup-drive/myapp/backup.db")?;// Bad: same directory as databasedb.backup("./backup.db")?;
// Good: includes timestamp and typelet name = format!("myapp_full_{}.db", Utc::now().format("%Y%m%d_%H%M%S"));db.backup(&format!("./backups/{}", name))?;// Good: includes version/environmentdb.backup("./backups/production_v2.1.0_20240115.db")?;// Bad: overwritten on each backupdb.backup("./backups/backup.db")?;
// 1. Start with base backupfs::copy("./backups/base.db", "restored.db")?;// 2. Apply WAL up to desired point// (Requires saved WAL files - advanced topic)// 3. Open restored databaselet db = Database::open("restored.db")?;
Point-in-time recovery requires saving WAL files separately. For most use cases, regular full backups are sufficient.