Use generic for try_get

This commit is contained in:
Chris Tsang 2021-05-07 21:37:29 +08:00
parent 59b747bf55
commit 69a52b6c7e
2 changed files with 35 additions and 20 deletions

View File

@ -14,38 +14,47 @@ pub(crate) enum QueryResultRow {
#[derive(Debug)]
pub struct TypeErr;
// QueryResult //
pub trait TryGetable {
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr>
where
Self: std::marker::Sized;
}
impl QueryResult {
pub fn try_get_i32(&self, col: &str) -> Result<i32, TypeErr> {
match &self.row {
// TryGetable //
impl TryGetable for i32 {
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr> {
match &res.row {
QueryResultRow::SqlxMySql(row) => {
use sqlx::Row;
if let Ok(val) = row.try_get(col) {
Ok(val)
} else {
Err(TypeErr)
}
Ok(row.try_get(col)?)
}
}
}
}
pub fn try_get_string(&self, col: &str) -> Result<String, TypeErr> {
match &self.row {
impl TryGetable for String {
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr> {
match &res.row {
QueryResultRow::SqlxMySql(row) => {
use sqlx::Row;
if let Ok(val) = row.try_get(col) {
Ok(val)
} else {
Err(TypeErr)
}
Ok(row.try_get(col)?)
}
}
}
}
// QueryResult //
impl QueryResult {
pub fn try_get<T>(&self, col: &str) -> Result<T, TypeErr>
where
T: TryGetable,
{
T::try_get(self, col)
}
}
// TypeErr //
impl Error for TypeErr {}
@ -55,3 +64,9 @@ impl fmt::Display for TypeErr {
write!(f, "{:?}", self)
}
}
impl From<sqlx::Error> for TypeErr {
fn from(_: sqlx::Error) -> TypeErr {
TypeErr
}
}

View File

@ -53,8 +53,8 @@ impl Relation for CakeRelation {
impl Model for CakeModel {
fn from_query_result(row: QueryResult) -> Result<Self, TypeErr> {
Ok(Self {
id: row.try_get_i32("id")?,
name: row.try_get_string("name")?,
id: row.try_get("id")?,
name: row.try_get("name")?,
})
}
}