diesel_derives/parsers/
belongs_to.rs

1use syn::parse::{Parse, ParseStream, Result};
2use syn::punctuated::Punctuated;
3use syn::token::Comma;
4use syn::{Ident, TypePath};
5
6use crate::util::{parse_eq, unknown_attribute, BELONGS_TO_NOTE};
7
8enum Attr {
9    ForeignKey(Ident),
10}
11
12impl Parse for Attr {
13    fn parse(input: ParseStream) -> Result<Self> {
14        let name: Ident = input.parse()?;
15        let name_str = name.to_string();
16
17        match &*name_str {
18            "foreign_key" => Ok(Attr::ForeignKey(parse_eq(input, BELONGS_TO_NOTE)?)),
19
20            _ => Err(unknown_attribute(&name, &["foreign_key"])),
21        }
22    }
23}
24
25pub struct BelongsTo {
26    pub parent: TypePath,
27    pub foreign_key: Option<Ident>,
28}
29
30impl Parse for BelongsTo {
31    fn parse(input: ParseStream) -> Result<Self> {
32        let parent = input.parse()?;
33
34        if !input.is_empty() {
35            input.parse::<Comma>()?;
36        }
37
38        let mut foreign_key = None;
39
40        for attr in Punctuated::<Attr, Comma>::parse_terminated(input)? {
41            match attr {
42                Attr::ForeignKey(value) => foreign_key = Some(value),
43            }
44        }
45
46        Ok(BelongsTo {
47            parent,
48            foreign_key,
49        })
50    }
51}