Use generic for try_get
This commit is contained in:
parent
59b747bf55
commit
69a52b6c7e
@ -14,38 +14,47 @@ pub(crate) enum QueryResultRow {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct TypeErr;
|
pub struct TypeErr;
|
||||||
|
|
||||||
// QueryResult //
|
pub trait TryGetable {
|
||||||
|
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr>
|
||||||
|
where
|
||||||
|
Self: std::marker::Sized;
|
||||||
|
}
|
||||||
|
|
||||||
impl QueryResult {
|
// TryGetable //
|
||||||
pub fn try_get_i32(&self, col: &str) -> Result<i32, TypeErr> {
|
|
||||||
match &self.row {
|
impl TryGetable for i32 {
|
||||||
|
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr> {
|
||||||
|
match &res.row {
|
||||||
QueryResultRow::SqlxMySql(row) => {
|
QueryResultRow::SqlxMySql(row) => {
|
||||||
use sqlx::Row;
|
use sqlx::Row;
|
||||||
|
Ok(row.try_get(col)?)
|
||||||
if let Ok(val) = row.try_get(col) {
|
|
||||||
Ok(val)
|
|
||||||
} else {
|
|
||||||
Err(TypeErr)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn try_get_string(&self, col: &str) -> Result<String, TypeErr> {
|
impl TryGetable for String {
|
||||||
match &self.row {
|
fn try_get(res: &QueryResult, col: &str) -> Result<Self, TypeErr> {
|
||||||
|
match &res.row {
|
||||||
QueryResultRow::SqlxMySql(row) => {
|
QueryResultRow::SqlxMySql(row) => {
|
||||||
use sqlx::Row;
|
use sqlx::Row;
|
||||||
|
Ok(row.try_get(col)?)
|
||||||
if let Ok(val) = row.try_get(col) {
|
|
||||||
Ok(val)
|
|
||||||
} else {
|
|
||||||
Err(TypeErr)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// QueryResult //
|
||||||
|
|
||||||
|
impl QueryResult {
|
||||||
|
pub fn try_get<T>(&self, col: &str) -> Result<T, TypeErr>
|
||||||
|
where
|
||||||
|
T: TryGetable,
|
||||||
|
{
|
||||||
|
T::try_get(self, col)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TypeErr //
|
// TypeErr //
|
||||||
|
|
||||||
impl Error for TypeErr {}
|
impl Error for TypeErr {}
|
||||||
@ -55,3 +64,9 @@ impl fmt::Display for TypeErr {
|
|||||||
write!(f, "{:?}", self)
|
write!(f, "{:?}", self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for TypeErr {
|
||||||
|
fn from(_: sqlx::Error) -> TypeErr {
|
||||||
|
TypeErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -53,8 +53,8 @@ impl Relation for CakeRelation {
|
|||||||
impl Model for CakeModel {
|
impl Model for CakeModel {
|
||||||
fn from_query_result(row: QueryResult) -> Result<Self, TypeErr> {
|
fn from_query_result(row: QueryResult) -> Result<Self, TypeErr> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id: row.try_get_i32("id")?,
|
id: row.try_get("id")?,
|
||||||
name: row.try_get_string("name")?,
|
name: row.try_get("name")?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user