ormlite_attr/metadata/
insert.rs

1use crate::Ident;
2use crate::{TableAttr, TableMeta};
3use syn::DeriveInput;
4
5/// Metadata used for IntoArguments, TableMeta, and (subset of) Model
6/// This structs are constructed from the *Attribute structs in crate::attr.
7#[derive(Debug, Clone)]
8pub struct InsertMeta {
9    pub table: TableMeta,
10    pub returns: Ident,
11    /// Only gets set if the table attribute was set
12    pub name: Option<String>,
13}
14
15impl InsertMeta {
16    pub fn from_derive(ast: &DeriveInput) -> Self {
17        let attrs = TableAttr::from_attrs(&ast.attrs);
18        let table = TableMeta::new(ast, &attrs);
19        let mut returns = None;
20        let mut name = None;
21        for attr in attrs {
22            if let Some(v) = attr.returns {
23                returns = Some(v.value());
24            }
25            if let Some(v) = attr.table {
26                name = Some(v.value());
27            }
28        }
29        let returns =
30            returns.expect("You must specify #[ormlite(returns = \"...\")] for structs marked with #[derive(Insert)]");
31        let returns = Ident::from(returns);
32        Self { table, returns, name }
33    }
34}
35
36impl std::ops::Deref for InsertMeta {
37    type Target = TableMeta;
38
39    fn deref(&self) -> &Self::Target {
40        &self.table
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use syn::{parse_str, ItemStruct};
47
48    use super::*;
49
50    #[test]
51    fn test_name() {
52        let s = r#"#[derive(Insert)]
53        #[ormlite(returns = "User")]
54        pub struct InsertUser2 {
55            name: String,
56            number: i32,
57            ty: i32,
58            org_id: i32,
59            }"#;
60        let s: ItemStruct = parse_str(s).unwrap();
61        let s = DeriveInput::from(s);
62        let meta = InsertMeta::from_derive(&s);
63        assert_eq!(meta.returns, "User");
64    }
65}