feat(src/db.rs): handle time formatting errors without panic

Signed-off-by: Lars Wirzenius <liw@liw.fi>
This commit is contained in:
Lars Wirzenius
2024-07-29 14:15:08 +03:00
parent 1bf620feca
commit 1e736c46ea
+12 -4
View File
@@ -251,7 +251,7 @@ impl Db {
let json = serde_json::to_string(&event).map_err(DbError::event_to_json)?;
let id = QueueId::default();
let ts = now();
let ts = now().map_err(DbError::time_format)?;
let mut insert =
self.prepare("INSERT INTO event_queue (id, timestamp, event) VALUES (:id, :ts, :e)")?;
@@ -391,7 +391,7 @@ impl Db {
pub fn push_run(&self, run: Run) -> Result<RunId, DbError> {
let id = run.adapter_run_id().ok_or(DbError::without_id())?.clone();
let json = serde_json::to_string(&run).expect("serialize BrokerEvent to JSON");
let json = serde_json::to_string(&run).map_err(DbError::event_to_json)?;
let mut insert = self.prepare("INSERT INTO ci_runs (run_id, json) VALUES (:id, :json)")?;
insert
@@ -429,10 +429,10 @@ impl Db {
}
}
fn now() -> String {
fn now() -> Result<String, time::error::Format> {
let fmt =
format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:6]Z");
OffsetDateTime::now_utc().format(fmt).expect("format time")
OffsetDateTime::now_utc().format(fmt)
}
// A wrapper around a statement that remembers its text form.
@@ -516,6 +516,10 @@ impl QueuedEvent {
/// All errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum DbError {
/// Error formatting a time as a string.
#[error(transparent)]
Timeformat(#[from] time::error::Format),
#[error("failed to set a busy timer one SQLite database {0}")]
BusyTimer(PathBuf, #[source] sqlite::Error),
@@ -591,6 +595,10 @@ pub enum DbError {
}
impl DbError {
fn time_format(e: time::error::Format) -> Self {
Self::Timeformat(e)
}
fn busy_timer(filename: &Path, e: sqlite::Error) -> Self {
Self::BusyTimer(filename.into(), e)
}