ormlite_attr/metadata/
insert.rs

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use crate::Ident;
use crate::{TableAttr, TableMeta};
use syn::DeriveInput;

/// Metadata used for IntoArguments, TableMeta, and (subset of) Model
/// This structs are constructed from the *Attribute structs in crate::attr.
#[derive(Debug, Clone)]
pub struct InsertMeta {
    pub table: TableMeta,
    pub returns: Ident,
    /// Only gets set if the table attribute was set
    pub name: Option<String>,
}

impl InsertMeta {
    pub fn from_derive(ast: &DeriveInput) -> Self {
        let attrs = TableAttr::from_attrs(&ast.attrs);
        let table = TableMeta::new(ast, &attrs);
        let mut returns = None;
        let mut name = None;
        for attr in attrs {
            if let Some(v) = attr.returns {
                returns = Some(v.value());
            }
            if let Some(v) = attr.table {
                name = Some(v.value());
            }
        }
        let returns =
            returns.expect("You must specify #[ormlite(returns = \"...\")] for structs marked with #[derive(Insert)]");
        let returns = Ident::from(returns);
        Self { table, returns, name }
    }
}

impl std::ops::Deref for InsertMeta {
    type Target = TableMeta;

    fn deref(&self) -> &Self::Target {
        &self.table
    }
}

#[cfg(test)]
mod tests {
    use syn::{parse_str, ItemStruct};

    use super::*;

    #[test]
    fn test_name() {
        let s = r#"#[derive(Insert)]
        #[ormlite(returns = "User")]
        pub struct InsertUser2 {
            name: String,
            number: i32,
            ty: i32,
            org_id: i32,
            }"#;
        let s: ItemStruct = parse_str(s).unwrap();
        let s = DeriveInput::from(s);
        let meta = InsertMeta::from_derive(&s);
        assert_eq!(meta.returns, "User");
    }
}