Skip to main content

rustclamp_macros/
lib.rs

1//! Derive macros for rustclamp. Use them through `rustclamp`, which
2//! re-exports each next to its trait: `rustclamp::db::Model`.
3
4use proc_macro::TokenStream;
5use quote::quote;
6use syn::{Data, DeriveInput, Fields, LitStr, parse_macro_input};
7
8/// Implements `rustclamp::db::Model` for a struct with named fields: each
9/// field is read from the column of the same name.
10///
11/// ```ignore
12/// #[derive(Model)]
13/// #[model(table = "posts")]
14/// pub struct Post {
15///     pub id: i64,
16///     pub title: String,
17///     pub published_at: Option<String>,
18/// }
19/// ```
20///
21/// The table is always named: a guessed plural would get `categories` wrong.
22#[proc_macro_derive(Model, attributes(model))]
23pub fn derive_model(input: TokenStream) -> TokenStream {
24    let input = parse_macro_input!(input as DeriveInput);
25    model(&input)
26        .unwrap_or_else(syn::Error::into_compile_error)
27        .into()
28}
29
30fn model(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
31    let mut table = None;
32    for attribute in input.attrs.iter().filter(|a| a.path().is_ident("model")) {
33        attribute.parse_nested_meta(|meta| {
34            if meta.path.is_ident("table") {
35                table = Some(meta.value()?.parse::<LitStr>()?);
36                Ok(())
37            } else {
38                Err(meta.error("expected `table = \"...\"`"))
39            }
40        })?;
41    }
42    let table = table.ok_or_else(|| {
43        syn::Error::new_spanned(&input.ident, "name the table: #[model(table = \"posts\")]")
44    })?;
45    let Data::Struct(data) = &input.data else {
46        return Err(syn::Error::new_spanned(
47            &input.ident,
48            "#[derive(Model)] needs a struct with named fields",
49        ));
50    };
51    let Fields::Named(fields) = &data.fields else {
52        return Err(syn::Error::new_spanned(
53            &input.ident,
54            "#[derive(Model)] needs a struct with named fields",
55        ));
56    };
57    let fields = fields.named.iter().map(|field| {
58        let name = field.ident.as_ref().expect("named field");
59        let column = name.to_string();
60        let column = column.strip_prefix("r#").unwrap_or(&column);
61        quote! { #name: row.get(#column)? }
62    });
63    let ident = &input.ident;
64    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
65    Ok(quote! {
66        impl #impl_generics ::rustclamp::db::Model for #ident #type_generics #where_clause {
67            const TABLE: &'static str = #table;
68
69            fn from_row(row: &::rustclamp::db::Row) -> ::rustclamp::db::Result<Self> {
70                ::core::result::Result::Ok(Self { #(#fields,)* })
71            }
72        }
73    })
74}