Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deriving default on Joins so that we can derive Default on our models #64

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 21 additions & 17 deletions core/src/join.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::model::Model;
use async_trait::async_trait;
use serde::de::Error;
use serde::Deserialize;
use serde::{Serialize, Serializer};
use sqlmo::query::Join as JoinQueryFragment;
use sqlmo::query::SelectColumn;
use sqlx::{Database, Decode, Encode, Type};
use std::ops::{Deref, DerefMut};
use serde::de::Error;

pub trait JoinMeta {
type IdType: Clone + Send + Eq + PartialEq + std::hash::Hash;
Expand Down Expand Up @@ -37,15 +37,16 @@ pub trait Loadable<DB, T: JoinMeta> {
E: 'e + sqlx::Executor<'e, Database = DB>;
}

#[derive(Debug)]
#[derive(Debug, Default)]
pub struct Join<T: JoinMeta> {
pub id: T::IdType,
data: JoinData<T>,
}

/// Only represents a many-to-one relationship.
#[derive(Debug)]
#[derive(Debug, Default)]
pub enum JoinData<T: JoinMeta> {
#[default]
NotQueried,
QueryResult(T),
Modified(T),
Expand Down Expand Up @@ -228,20 +229,23 @@ impl<T: JoinMeta + Serialize> Serialize for Join<T> {
}

impl<'de, T> Deserialize<'de> for Join<T>
where
T: JoinMeta + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
T: JoinMeta + Deserialize<'de>,
D: serde::Deserializer<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let data = Option::<T>::deserialize(deserializer)?;

let (id_type, join_data) = match data {
Some(value) => (T::_id(&value), JoinData::QueryResult(value)),
None => return Err(D::Error::custom("Invalid value"))
};

Ok(Join { id: id_type, data: join_data })
}
let data = Option::<T>::deserialize(deserializer)?;

let (id_type, join_data) = match data {
Some(value) => (T::_id(&value), JoinData::QueryResult(value)),
None => return Err(D::Error::custom("Invalid value")),
};

Ok(Join {
id: id_type,
data: join_data,
})
}
}
Loading