Skip to main content

diesel_derives/
model.rs

1use proc_macro2::Span;
2use std::slice::from_ref;
3use syn::Result;
4use syn::punctuated::Punctuated;
5use syn::token::Comma;
6use syn::{
7    Data, DataStruct, DeriveInput, Field as SynField, Fields, FieldsNamed, FieldsUnnamed, Ident,
8    LitBool, Path, Type,
9};
10
11use crate::field::Field;
12use crate::util::camel_to_snake;
13use diesel_attribute_parser::CheckForBackend;
14use diesel_attribute_parser::parsers::{BelongsTo, MysqlType, PostgresType, SqliteType};
15use diesel_attribute_parser::{StructAttr, parse_attributes};
16
17pub struct Model {
18    name: Path,
19    table_names: Vec<Path>,
20    pub primary_key_names: Vec<Ident>,
21    treat_none_as_default_value: Option<LitBool>,
22    treat_none_as_null: Option<LitBool>,
23    pub belongs_to: Vec<BelongsTo>,
24    pub sql_types: Vec<Type>,
25    pub aggregate: bool,
26    pub not_sized: bool,
27    pub foreign_derive: bool,
28    pub enum_type: bool,
29    pub mysql_type: Option<MysqlType>,
30    pub sqlite_type: Option<SqliteType>,
31    pub postgres_type: Option<PostgresType>,
32    pub check_for_backend: Option<CheckForBackend>,
33    pub base_query: Option<syn::Expr>,
34    pub base_query_type: Option<syn::Type>,
35    fields: Vec<Field>,
36}
37
38impl Model {
39    pub fn from_item(
40        item: &DeriveInput,
41        allow_unit_structs: bool,
42        allow_multiple_table: bool,
43    ) -> Result<Self> {
44        let DeriveInput {
45            data, ident, attrs, ..
46        } = item;
47
48        let fields = match *data {
49            Data::Struct(DataStruct {
50                fields: Fields::Named(FieldsNamed { ref named, .. }),
51                ..
52            }) => Some(named),
53            Data::Struct(DataStruct {
54                fields: Fields::Unnamed(FieldsUnnamed { ref unnamed, .. }),
55                ..
56            }) => Some(unnamed),
57            _ if !allow_unit_structs => {
58                return Err(syn::Error::new(
59                    proc_macro2::Span::mixed_site(),
60                    "this derive can only be used on non-unit structs",
61                ));
62            }
63            _ => None,
64        };
65
66        let mut table_names = ::alloc::vec::Vec::new()vec![];
67        let mut primary_key_names = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Ident::new("id", Span::mixed_site())]))vec![Ident::new("id", Span::mixed_site())];
68        let mut treat_none_as_default_value = None;
69        let mut treat_none_as_null = None;
70        let mut belongs_to = ::alloc::vec::Vec::new()vec![];
71        let mut sql_types = ::alloc::vec::Vec::new()vec![];
72        let mut aggregate = false;
73        let mut not_sized = false;
74        let mut enum_type = false;
75        let mut foreign_derive = false;
76        let mut mysql_type = None;
77        let mut sqlite_type = None;
78        let mut postgres_type = None;
79        let mut check_for_backend = None;
80        let mut base_query = None;
81        let mut base_query_type = None;
82
83        for attr in parse_attributes(attrs)? {
84            match attr.item {
85                StructAttr::SqlType(_, value) => sql_types.push(Type::Path(value)),
86                StructAttr::TableName(ident, value) => {
87                    if !allow_multiple_table && !table_names.is_empty() {
88                        return Err(syn::Error::new(
89                            ident.span(),
90                            "expected a single table name attribute\n\
91                             note: remove this attribute",
92                        ));
93                    }
94                    table_names.push(value)
95                }
96                StructAttr::PrimaryKey(_, keys) => {
97                    primary_key_names = keys.into_iter().collect();
98                }
99                StructAttr::TreatNoneAsDefaultValue(_, val) => {
100                    treat_none_as_default_value = Some(val)
101                }
102                StructAttr::TreatNoneAsNull(_, val) => treat_none_as_null = Some(val),
103                StructAttr::BelongsTo(_, val) => belongs_to.push(val),
104                StructAttr::Aggregate(_) => aggregate = true,
105                StructAttr::NotSized(_) => not_sized = true,
106                StructAttr::ForeignDerive(_) => foreign_derive = true,
107                StructAttr::EnumType(_) => enum_type = true,
108                StructAttr::MysqlType(_, val) => mysql_type = Some(val),
109                StructAttr::SqliteType(_, val) => sqlite_type = Some(val),
110                StructAttr::PostgresType(_, val) => postgres_type = Some(val),
111                StructAttr::CheckForBackend(_, b) => {
112                    check_for_backend = Some(b);
113                }
114                StructAttr::BaseQuery(_, e) => base_query = Some(e),
115                StructAttr::BaseQueryType(_, t) => base_query_type = Some(t),
116                StructAttr::RenameAll(_, _) => { /*ignore here as only relevant for enums*/ }
117            }
118        }
119
120        let name = Ident::new(&infer_table_name(&ident.to_string()), ident.span()).into();
121
122        Ok(Self {
123            name,
124            table_names,
125            primary_key_names,
126            treat_none_as_default_value,
127            treat_none_as_null,
128            belongs_to,
129            sql_types,
130            aggregate,
131            not_sized,
132            foreign_derive,
133            mysql_type,
134            sqlite_type,
135            postgres_type,
136            fields: fields_from_item_data(fields)?,
137            check_for_backend,
138            base_query,
139            base_query_type,
140            enum_type,
141        })
142    }
143
144    pub fn table_names(&self) -> &[Path] {
145        match self.table_names.len() {
146            0 => from_ref(&self.name),
147            _ => &self.table_names,
148        }
149    }
150
151    pub fn fields(&self) -> &[Field] {
152        &self.fields
153    }
154
155    pub fn find_column(&self, column_name: &Ident) -> Result<&Field> {
156        self.fields()
157            .iter()
158            .find(|f| {
159                f.column_name()
160                    .map(|c| c == *column_name)
161                    .unwrap_or_default()
162            })
163            .ok_or_else(|| {
164                syn::Error::new(
165                    column_name.span(),
166                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no field with column name `{0}`",
                column_name))
    })format!("no field with column name `{column_name}`"),
167                )
168            })
169    }
170
171    pub fn treat_none_as_default_value(&self) -> bool {
172        self.treat_none_as_default_value
173            .as_ref()
174            .map(|v| v.value())
175            .unwrap_or(true)
176    }
177
178    pub fn treat_none_as_null(&self) -> bool {
179        self.treat_none_as_null
180            .as_ref()
181            .map(|v| v.value())
182            .unwrap_or(false)
183    }
184}
185
186fn fields_from_item_data(fields: Option<&Punctuated<SynField, Comma>>) -> Result<Vec<Field>> {
187    fields
188        .map(|fields| {
189            fields
190                .iter()
191                .enumerate()
192                .map(|(i, f)| Field::from_struct_field(f, i))
193                .collect::<Result<Vec<_>>>()
194        })
195        .unwrap_or_else(|| Ok(Vec::new()))
196}
197
198pub fn infer_table_name(name: &str) -> String {
199    let mut result = camel_to_snake(name);
200    result.push('s');
201    result
202}
203
204#[test]
205fn infer_table_name_pluralizes_and_downcases() {
206    assert_eq!("foos", &infer_table_name("Foo"));
207    assert_eq!("bars", &infer_table_name("Bar"));
208}
209
210#[test]
211fn infer_table_name_properly_handles_underscores() {
212    assert_eq!("foo_bars", &infer_table_name("FooBar"));
213    assert_eq!("foo_bar_bazs", &infer_table_name("FooBarBaz"));
214}