-
Notifications
You must be signed in to change notification settings - Fork 13
/
db_utils.rs
60 lines (50 loc) · 1.7 KB
/
db_utils.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::fs;
use std::io;
use std::io::{Read, Write};
pub fn db_file_exists(db_url: &str) -> io::Result<()> {
// check if db file exists
if !db_url.starts_with("postgres://") && !std::path::Path::new(db_url).exists() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("DB file does not exist: {}", db_url),
));
}
Ok(())
}
pub fn backup_db_file(db_url: &str) -> io::Result<tempfile::NamedTempFile> {
db_file_exists(db_url)?;
let mut tmp_file = tempfile::NamedTempFile::new()?;
let content = fs::read(db_url)?;
tmp_file.write_all(&content)?;
Ok(tmp_file)
}
pub fn restore_db_file(backup_file: tempfile::NamedTempFile, db_url: &str) -> io::Result<()> {
let mut backup_file = backup_file.reopen()?;
let mut buff = Vec::new();
backup_file.read_to_end(&mut buff)?;
fs::write(db_url, &buff)
}
#[cfg(test)]
mod test {
use crate::db_utils::{backup_db_file, restore_db_file};
use std::{fs, io};
#[test]
fn backup_file() -> io::Result<()> {
let file_path = "./tmp_db.db";
let content = b"foo bar";
let content_vec = content.to_vec();
// create a file with some content
fs::write(file_path, content)?;
// backup the file
let tmp_file = backup_db_file(file_path)?;
// write nonsense in old file
fs::write(file_path, b"bar foo")?;
// restore file and read content, hopefully is the old one
restore_db_file(tmp_file, file_path)?;
let backup_content = fs::read(file_path)?;
fs::remove_file(file_path)?;
// check written and actual content
assert_eq!(&content_vec, &backup_content);
Ok(())
}
}