Implement SQL Timeout as a newtype tuple struct

This commit is contained in:
Tobie Morgan Hitchcock 2022-05-04 22:45:00 +01:00
parent 42fa91c7bd
commit 1dd3095783
2 changed files with 17 additions and 21 deletions

View file

@ -84,12 +84,12 @@ pub enum Statement {
impl Statement {
pub fn timeout(&self) -> Option<Duration> {
match self {
Statement::Select(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Create(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Update(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Relate(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Delete(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Insert(v) => v.timeout.as_ref().map(|v| v.expr.value),
Statement::Select(v) => v.timeout.as_ref().map(|v| v.value),
Statement::Create(v) => v.timeout.as_ref().map(|v| v.value),
Statement::Update(v) => v.timeout.as_ref().map(|v| v.value),
Statement::Relate(v) => v.timeout.as_ref().map(|v| v.value),
Statement::Delete(v) => v.timeout.as_ref().map(|v| v.value),
Statement::Insert(v) => v.timeout.as_ref().map(|v| v.value),
_ => None,
}
}

View file

@ -4,15 +4,21 @@ use crate::sql::error::IResult;
use nom::bytes::complete::tag_no_case;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::Deref;
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Timeout {
pub expr: Duration,
pub struct Timeout(pub Duration);
impl Deref for Timeout {
type Target = Duration;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Timeout {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TIMEOUT {}", self.expr)
write!(f, "TIMEOUT {}", self.0)
}
}
@ -20,12 +26,7 @@ pub fn timeout(i: &str) -> IResult<&str, Timeout> {
let (i, _) = tag_no_case("TIMEOUT")(i)?;
let (i, _) = shouldbespace(i)?;
let (i, v) = duration(i)?;
Ok((
i,
Timeout {
expr: v,
},
))
Ok((i, Timeout(v)))
}
#[cfg(test)]
@ -39,12 +40,7 @@ mod tests {
let res = timeout(sql);
assert!(res.is_ok());
let out = res.unwrap().1;
assert_eq!(
out,
Timeout {
expr: Duration::from("5s")
}
);
assert_eq!(out, Timeout(Duration::from("5s")));
assert_eq!("TIMEOUT 5s", format!("{}", out));
}
}