1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use {
    super::{ActiveModel, NamedValue},
    crate::{model::Model, Connection, Error, Stream},
};

#[derive(Debug)]
pub enum ActiveReference<T: Model> {
    Set(T::Primary),
    Insert(T::ActiveModel),
    Unset,
}

impl<T: Model> ActiveReference<T> {
    pub async fn insert_named_value<S: Stream>(
        self,
        vec: &mut Vec<NamedValue>,
        name: &'static str,
        conn: &mut Connection<S>,
    ) -> Result<(), Error> {
        match self {
            Self::Set(id) => vec.push(NamedValue(name, id.into())),
            Self::Insert(model) => {
                let primary = model.primary();
                let last_insert_id = model.insert(conn).await?;
                vec.push(NamedValue(name, primary.unwrap_or(last_insert_id.into())));
            }
            Self::Unset => (),
        }
        Ok(())
    }
}

impl<T: Model> Default for ActiveReference<T> {
    fn default() -> Self {
        Self::Unset
    }
}