Backup & Export
PocketDB provides hot backup and JSON export/import utilities.
Installation
Add PocketDB to your Cargo.toml:
toml
[dependencies]
pocketdb = "0.1"Or via the command line:
bash
cargo add pocketdbHot Backup
Create a consistent backup of the database while it's running:
rust
use pocketdb::Database;
let db = Database::open("mydata.pdb")?;
// Create a hot backup
db.backup_to("mydata_backup.pdb")?;The backup is a byte-for-byte copy of the database file, consistent at the time of the copy.
JSON Export
Export a collection's documents to a JSON file:
rust
db.export_collection_json("users", "users_export.json")?;The output is a JSON array of documents:
json
[
{
"_id": "507f1f77bcf86cd799439011",
"name": "Alice",
"age": 30,
"email": "alice@example.com"
},
{
"_id": "507f1f77bcf86cd799439012",
"name": "Bob",
"age": 25,
"email": "bob@example.com"
}
]JSON Import
Import documents from a JSON array into a collection:
rust
let count = db.import_collection_json("users", "users_import.json")?;
println!("Imported {} documents", count);The import reads a JSON array and creates documents from each element. The _id field is preserved if present; otherwise a new ObjectId is generated.
Complete Backup Example
rust
use pocketdb::{Database, doc};
fn main() -> pocketdb::Result<()> {
let db = Database::open("production.pdb")?;
// Hot backup (binary copy)
db.backup_to("production_backup.pdb")?;
// Export all collections as JSON
for name in db.list_collections() {
let filename = format!("{}_export.json", name);
db.export_collection_json(&name, &filename)?;
println!("Exported {} to {}", name, filename);
}
Ok(())
}Restore from Backup
From Binary Backup
rust
// Simply open the backup file
let db = Database::open("production_backup.pdb")?;From JSON Import
rust
let db = Database::open("restored.pdb")?;
// Import each collection
let count = db.import_collection_json("users", "users_export.json")?;
println!("Restored {} users", count);Repair and Cleanup
Validate Integrity
rust
let db = Database::open("mydata.pdb")?;
if !db.validate()? {
eprintln!("Corruption detected");
}Repair Corrupted Database
rust
// Static method — works even if the database can't be opened
let corrupted = Database::repair("mydata.pdb")?;Clean Up Orphaned Files
If you delete a .pdb file but the .pocketdb/ directory still has WAL files:
rust
// Returns true if cleanup was performed
Database::cleanup_orphaned("mydata.pdb")?;Compact
rust
let db = Database::open("mydata.pdb")?;
db.compact()?; // Flushes data and cleans WALBest Practices
- Regular backups — schedule hot backups during low-traffic periods
- Test restores — periodically verify backups can be restored
- Keep multiple backups — maintain rolling backups for point-in-time recovery
- Export before migrating — use JSON export as a safety net before schema changes
- Monitor file size — check
db.stats().file_sizeto plan storage - Validate after crashes — use
db.validate()to check integrity