Skip to content

dump_db: Use tempfile for temporary file/folder creation #8745

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 28, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
workers/jobs/dump_db: Use tempfile::tempdir() in DumpDirectory st…
…ruct
  • Loading branch information
Turbo87 committed May 28, 2024
commit 7560b9ecf4e4bebb7d35a3de4eb42bfd0dda9626
17 changes: 10 additions & 7 deletions src/worker/jobs/dump_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,23 @@ impl BackgroundJob for DumpDb {
/// make sure it gets deleted again even in the case of an error.
#[derive(Debug)]
pub struct DumpDirectory {
/// The temporary directory that contains the export directory. This is
/// allowing `dead_code` since we're only relying on the `Drop`
/// implementation to clean up the directory.
#[allow(dead_code)]
tempdir: tempfile::TempDir,

pub timestamp: chrono::DateTime<chrono::Utc>,
pub export_dir: PathBuf,
}

impl DumpDirectory {
pub fn create() -> anyhow::Result<Self> {
let tempdir = tempfile::tempdir()?;

let timestamp = chrono::Utc::now();
let timestamp_str = timestamp.format("%Y-%m-%d-%H%M%S").to_string();
let export_dir = std::env::temp_dir().join("dump-db").join(timestamp_str);
let export_dir = tempdir.path().join(timestamp_str);

debug!(?export_dir, "Creating database dump folder…");
fs::create_dir_all(&export_dir).with_context(|| {
Expand All @@ -90,6 +98,7 @@ impl DumpDirectory {
})?;

Ok(Self {
tempdir,
timestamp,
export_dir,
})
Expand Down Expand Up @@ -179,12 +188,6 @@ impl DumpDirectory {
}
}

impl Drop for DumpDirectory {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.export_dir).unwrap();
}
}

pub fn run_psql(script: &Path, database_url: &str) -> anyhow::Result<()> {
debug!(?script, "Running psql script…");
let psql_script =
Expand Down