mongo_collection_macro/lib.rs
1use inflector::Inflector;
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::{Data, DeriveInput, Lit, parse_macro_input};
5
6/// Automatically derives the Collection trait implementation
7///
8/// # Usage
9///
10/// ## Basic usage (using default collection name - auto pluralization)
11/// ```ignore
12/// #[derive(Collection, Serialize, Deserialize, Debug, Clone)]
13/// struct User {
14/// id: String,
15/// name: String,
16/// }
17/// // Collection name will be "users" (automatically pluralized)
18/// ```
19///
20/// ## Specifying a custom collection name
21/// ```ignore
22/// #[derive(Collection, Serialize, Deserialize, Debug, Clone)]
23/// #[collection(name = "users")]
24/// struct User {
25/// id: String,
26/// name: String,
27/// }
28/// // Collection name will be "users"
29/// ```
30#[proc_macro_derive(Collection, attributes(collection))]
31pub fn derive_collection(input: TokenStream) -> TokenStream {
32 let input = parse_macro_input!(input as DeriveInput);
33
34 // Get the struct name
35 let name = &input.ident;
36
37 // Look for #[collection(name = "...")] attribute
38 let collection_name =
39 get_collection_name(&input).unwrap_or_else(|| to_plural_snake_case(&name.to_string()));
40
41 // Ensure it's a struct
42 match input.data {
43 Data::Struct(_) => {}
44 _ => {
45 return syn::Error::new_spanned(name, "Collection can only be derived for structs")
46 .to_compile_error()
47 .into();
48 }
49 }
50
51 // Generate implementation
52 let expanded = quote! {
53 impl Collection for #name {
54 fn name() -> &'static str {
55 #collection_name
56 }
57 }
58 };
59
60 TokenStream::from(expanded)
61}
62
63/// Extracts the collection name from attributes
64fn get_collection_name(input: &DeriveInput) -> Option<String> {
65 for attr in &input.attrs {
66 if attr.path().is_ident("collection") {
67 if let Ok(meta_list) = attr.meta.require_list() {
68 // Store parsing result
69 let mut name = None;
70
71 // Parse name = "value" format
72 let _ = meta_list.parse_nested_meta(|meta| {
73 if meta.path.is_ident("name") {
74 let value = meta.value()?;
75 let lit: Lit = value.parse()?;
76 if let Lit::Str(lit_str) = lit {
77 name = Some(lit_str.value());
78 }
79 }
80 Ok(())
81 });
82
83 if name.is_some() {
84 return name;
85 }
86 }
87 }
88 }
89 None
90}
91
92/// Converts CamelCase to plural snake_case
93/// Examples: "User" -> "users", "UserProfile" -> "user_profiles"
94fn to_plural_snake_case(s: &str) -> String {
95 // Use inflector to convert CamelCase to snake_case and pluralize
96 s.to_table_case()
97}
98
99/// Automatically derives the CollectionRepository trait implementation
100///
101/// This macro automatically implements the `CollectionRepository` trait for a struct
102/// that already implements the `Collection` trait. The struct must also implement
103/// `Clone`, `Send`, `Sync`, `Unpin`, `Serialize`, and `Deserialize`.
104///
105/// # Usage
106///
107/// ```ignore
108/// use mongo_collection::{Collection, CollectionRepository};
109/// use serde::{Serialize, Deserialize};
110///
111/// #[derive(Collection, CollectionRepository, Serialize, Deserialize, Debug, Clone)]
112/// struct User {
113/// #[serde(rename = "_id")]
114/// id: String,
115/// name: String,
116/// email: String,
117/// }
118///
119/// // Now you can use all CRUD operations:
120/// // User::create(&db, &user).await?;
121/// // User::find_by_id(&db, "123").await?;
122/// // User::find_paginated(&db, doc!{}, &query).await?;
123/// ```
124///
125/// # Requirements
126///
127/// The struct must derive or implement:
128/// - `Collection` - Provides collection name and reference
129/// - `Clone` - Required for return values
130/// - `Serialize` - For MongoDB serialization
131/// - `Deserialize` - For MongoDB deserialization
132///
133/// # Example with all derives
134///
135/// ```ignore
136/// #[derive(Collection, CollectionRepository, Serialize, Deserialize, Debug, Clone)]
137/// #[collection(name = "users")]
138/// struct User {
139/// #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
140/// id: Option<String>,
141/// name: String,
142/// email: String,
143/// }
144/// ```
145#[proc_macro_derive(CollectionRepository)]
146pub fn derive_collection_repository(input: TokenStream) -> TokenStream {
147 let input = parse_macro_input!(input as DeriveInput);
148
149 // Get the struct name
150 let name = &input.ident;
151
152 // Ensure it's a struct
153 match input.data {
154 Data::Struct(_) => {}
155 _ => {
156 return syn::Error::new_spanned(name, "CollectionRepository can only be derived for structs")
157 .to_compile_error()
158 .into();
159 }
160 }
161
162 // Generate implementation
163 // Note: We don't need to implement any methods because CollectionRepository
164 // trait provides default implementations for all methods
165 let expanded = quote! {
166 impl CollectionRepository for #name {}
167 };
168
169 TokenStream::from(expanded)
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 #[test]
177 fn test_to_plural_snake_case() {
178 assert_eq!(to_plural_snake_case("User"), "users");
179 assert_eq!(to_plural_snake_case("UserProfile"), "user_profiles");
180 assert_eq!(to_plural_snake_case("Course"), "courses");
181 assert_eq!(to_plural_snake_case("Category"), "categories");
182 assert_eq!(to_plural_snake_case("Book"), "books");
183 }
184}