Skip to content

Commit

Permalink
Use atomic-file-write for writing query data
Browse files Browse the repository at this point in the history
  • Loading branch information
mattfbacon committed Sep 28, 2023
1 parent a922f83 commit 4e79ee3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 29 deletions.
1 change: 1 addition & 0 deletions sqlx-macros-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ tokio = { workspace = true, optional = true }

dotenvy = { workspace = true }

atomic-write-file = { version = "0.1" }
hex = { version = "0.4.3" }
heck = { version = "0.4", features = ["unicode"] }
either = "1.6.1"
Expand Down
42 changes: 13 additions & 29 deletions sqlx-macros-core/src/query/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,39 +151,23 @@ where
}

pub(super) fn save_in(&self, dir: impl AsRef<Path>) -> crate::Result<()> {
fn inner<DB>(data: &QueryData<DB>, file: &mut std::fs::File) -> crate::Result<()>
where
DB: DatabaseExt,
Describe<DB>: serde::Serialize + serde::de::DeserializeOwned,
{
serde_json::to_writer_pretty(&mut *file, data)
.map_err(|err| format!("failed to serialize query data to file: {err:?}"))?;
let path = dir.as_ref().join(format!("query-{}.json", self.hash));
let mut file = atomic_write_file::AtomicWriteFile::open(&path)
.map_err(|err| format!("failed to open the temporary file: {err:?}"))?;

// Ensure there is a newline at the end of the JSON file to avoid accidental modification by IDE
// and make github diff tool happier.
file.write_all(b"\n")
.map_err(|err| format!("failed to append a newline to file: {err:?}"))?;
serde_json::to_writer_pretty(file.as_file_mut(), self)
.map_err(|err| format!("failed to serialize query data to file: {err:?}"))?;

Ok(())
}
// Ensure there is a newline at the end of the JSON file to avoid
// accidental modification by IDE and make github diff tool happier.
file.as_file_mut()
.write_all(b"\n")
.map_err(|err| format!("failed to append a newline to file: {err:?}"))?;

let path = dir.as_ref().join(format!("query-{}.json", self.hash));
let mut file = match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Ok(()),
Err(error) => return Err(format!("failed to create query file: {error:?}").into()),
};
let res = inner(self, &mut file);

if res.is_err() {
_ = std::fs::remove_file(&path);
}
file.commit()
.map_err(|err| format!("failed to commit the query data to {path:?}: {err:?}"))?;

res
Ok(())
}
}

Expand Down

0 comments on commit 4e79ee3

Please sign in to comment.