Skip to main content

diesel_enum_case/
lib.rs

1//! This crate allows the user to represent state in the database using Rust enums. This is achieved
2//! through a proc macro. First the macro looks at your chosen `sql_type`, and then it devises a
3//! corresponding Rust type. The mapping is as follows:
4//!
5//! | SQL        | Rust     |
6//! | ---------- | -------- |
7//! | `SmallInt` | `i16`    |
8//! | `Integer`  | `i32`    |
9//! | `Int`      | `i32`    |
10//! | `BigInt`   | `i64`    |
11//! | `VarChar`  | `String` |
12//! | `Text`     | `String` |
13//!
14//!  The macro then generates three impls: a `FromSql` impl, an `ToSql` impl and a
15//! `TryFrom` impl, which allow conversion between the Sql type an the enum (`FromSql` and `ToSql`),
16//! and from the Rust type into the enum (`TryInto`).
17//!
18//! ### Usage
19//! ```rust
20//! #[macro_use] extern crate diesel;
21//! use diesel_enum_case::DbEnum;
22//! use diesel::{deserialize::FromSqlRow, sql_types::SmallInt};
23//!
24//! #[derive(Debug, thiserror::Error)]
25//! #[error("CustomError: {msg}, {status}")]
26//! pub struct CustomError {
27//!     msg: String,
28//!     status: u16,
29//! }
30//!
31//! impl CustomError {
32//!     fn not_found(msg: String) -> Self {
33//!         Self {
34//!             msg,
35//!             status: 404,
36//!         }
37//!     }
38//! }
39//!
40//! #[derive(Debug, Clone, Copy, PartialEq, Eq, FromSqlRow, DbEnum)]
41//! #[diesel(sql_type = SmallInt)]
42//! #[diesel_enum(error_fn = CustomError::not_found)]
43//! #[diesel_enum(error_type = CustomError)]
44//! pub enum Status {
45//!     /// Will be represented as 0.
46//!     Ready,
47//!     /// Will be represented as 1.
48//!     Pending,
49//! }
50//! ```
51//! Alternatively you can use strings, which will be cast to lowercase by default. (e.g. `Status::Ready` will be
52//! stored as `"ready"` in the database):
53//! ```rust
54//! #[derive(Debug, Clone, Copy, PartialEq, Eq, FromSqlRow, DbEnum)]
55//! #[diesel(sql_type = VarChar)]
56//! #[diesel_enum(error_fn = CustomError::not_found)]
57//! #[diesel_enum(error_type = CustomError)]
58//! pub enum Status {
59//!     /// Will be represented as `"ready"`.
60//!     Ready,
61//!     /// Will be represented as `"pending"`.
62//!     Pending,
63//! }
64//! ```
65//!
66//! You can also specify a case convention using the `case` attribute. Supported options are:
67//! `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`, `snake_case`, `SCREAMING_SNAKE_CASE`, `kebab-case`.
68//! For example, using `snake_case`:
69//! ```rust
70//! #[derive(Debug, Clone, Copy, PartialEq, Eq, FromSqlRow, DbEnum)]
71//! #[diesel(sql_type = VarChar)]
72//! #[diesel_enum(error_fn = CustomError::not_found)]
73//! #[diesel_enum(error_type = CustomError)]
74//! #[diesel_enum(case = "snake_case")]
75//! pub enum Status {
76//!     /// Will be represented as `"ready_to_go"`.
77//!     ReadyToGo,
78//!     /// Will be represented as `"pending_review"`.
79//!     PendingReview,
80//! }
81//! ```
82
83use quote::quote;
84use syn::spanned::Spanned;
85
86#[derive(Clone, Copy, Default)]
87enum CaseConvention {
88    #[default]
89    Lowercase,
90    Uppercase,
91    CamelCase,
92    PascalCase,
93    SnakeCase,
94    ScreamingSnakeCase,
95    KebabCase,
96}
97
98impl CaseConvention {
99    fn from_str(s: &str) -> Result<Self, String> {
100        match s {
101            "lowercase" => Ok(CaseConvention::Lowercase),
102            "UPPERCASE" => Ok(CaseConvention::Uppercase),
103            "camelCase" => Ok(CaseConvention::CamelCase),
104            "PascalCase" => Ok(CaseConvention::PascalCase),
105            "snake_case" => Ok(CaseConvention::SnakeCase),
106            "SCREAMING_SNAKE_CASE" => Ok(CaseConvention::ScreamingSnakeCase),
107            "kebab-case" => Ok(CaseConvention::KebabCase),
108            _ => Err(format!(
109                "Invalid case convention: {}. Valid options are: lowercase, UPPERCASE, camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, kebab-case",
110                s
111            )),
112        }
113    }
114
115    fn convert(&self, variant_name: &str) -> String {
116        match self {
117            CaseConvention::Lowercase => variant_name.to_lowercase(),
118            CaseConvention::Uppercase => variant_name.to_uppercase(),
119            CaseConvention::PascalCase => variant_name.to_string(),
120            _ => {
121                // Rust enum variants are PascalCase, so we convert from PascalCase to target format
122                let words = Self::split_pascal_case(variant_name);
123                match self {
124                    CaseConvention::CamelCase => {
125                        let mut result = String::new();
126                        for (i, word) in words.iter().enumerate() {
127                            if i == 0 {
128                                result.push_str(&word.to_lowercase());
129                            } else {
130                                result.push_str(&Self::capitalize_first(word));
131                            }
132                        }
133                        result
134                    }
135                    CaseConvention::SnakeCase => words.join("_").to_lowercase(),
136                    CaseConvention::ScreamingSnakeCase => words.join("_").to_uppercase(),
137                    CaseConvention::KebabCase => words.join("-").to_lowercase(),
138                    _ => unreachable!(),
139                }
140            }
141        }
142    }
143
144    fn split_pascal_case(s: &str) -> Vec<String> {
145        let mut words = Vec::new();
146        let mut current = String::new();
147        
148        for ch in s.chars() {
149            if ch.is_uppercase() && !current.is_empty() {
150                words.push(current);
151                current = String::new();
152            }
153            current.push(ch);
154        }
155        if !current.is_empty() {
156            words.push(current);
157        }
158        words
159    }
160
161    fn capitalize_first(s: &str) -> String {
162        let mut chars = s.chars();
163        match chars.next() {
164            None => String::new(),
165            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
166        }
167    }
168}
169
170macro_rules! try_or_return {
171    ($inp:expr) => {
172        match $inp {
173            Ok(ok) => ok,
174            Err(msg) => return msg.into(),
175        }
176    };
177}
178
179struct MacroState<'a> {
180    name: syn::Ident,
181    variants: Vec<&'a syn::Variant>,
182    sql_type: syn::Ident,
183    rust_type: syn::Ident,
184    error_type: syn::Path,
185    error_fn: syn::Path,
186    case: CaseConvention,
187}
188
189impl<'a> MacroState<'a> {
190    fn val(variant: &syn::Variant) -> Option<syn::Lit> {
191        let val = variant
192            .attrs
193            .iter()
194            .find(|a| a.path.get_ident().map(|i| i == "val").unwrap_or(false))
195            .map(|a| a.tokens.to_string())?;
196        let trimmed = val[1..].trim();
197        syn::parse_str(trimmed).ok()
198    }
199
200    fn variant_string_literal(&self, variant: &syn::Variant, span: proc_macro2::Span) -> syn::Lit {
201        use syn::{Lit::Str, LitStr};
202        Self::val(variant).unwrap_or_else(|| {
203            let converted = self.case.convert(&variant.ident.to_string());
204            Str(LitStr::new(&converted, span))
205        })
206    }
207
208    fn rust_type(sql_type: &syn::Ident) -> Result<syn::Ident, proc_macro2::TokenStream> {
209        let name = match sql_type.to_string().as_str() {
210            "SmallInt" => "i16",
211            "Integer" | "Int" => "i32",
212            "BigInt" => "i64",
213            "VarChar" | "Text" => "String",
214            _ => {
215                let sql_types = "`SmallInt`, `Integer`, `Int`, `BigInt`, `VarChar`, `Text`";
216                let message = format!(
217                    "`sql_type` must be one of {}, but was {}",
218                    sql_types, sql_type,
219                );
220                return Err(error(sql_type.span(), &message));
221            }
222        };
223        let span = proc_macro2::Span::call_site();
224        Ok(syn::Ident::new(name, span))
225    }
226
227    fn try_from(&self) -> proc_macro2::TokenStream {
228        let span = proc_macro2::Span::call_site();
229        let variants = self.variants.iter().map(|f| &f.ident);
230        let error_fn = &self.error_fn;
231        let name = self.name.to_string();
232        let conversion = match self.rust_type.to_string().as_str() {
233            "i16" | "i32" | "i64" => {
234                let nums = self
235                    .variants
236                    .iter()
237                    .enumerate()
238                    .map(|(idx, &var)| (syn::LitInt::new(&idx.to_string(), span), var))
239                    .map(|(idx, var)| (syn::Lit::Int(idx), var))
240                    .map(|(idx, var)| Self::val(var).unwrap_or(idx));
241                quote! {
242                    match inp {
243                        #(#nums => Ok(Self::#variants),)*
244                        otherwise => {
245                            Err(#error_fn(format!("Unexpected `{}`: {}", #name, otherwise)))
246                        },
247                    }
248                }
249            }
250            "String" => {
251                let field_names = self.variants.iter().map(|v| self.variant_string_literal(v, span));
252
253                quote! {
254                    match inp.as_str() {
255                        #(#field_names => Ok(Self::#variants),)*
256                        otherwise => {
257                            Err(#error_fn(format!("Unexpected `{}`: {}", #name, otherwise)))
258                        },
259                    }
260                }
261            }
262            _ => panic!(),
263        };
264
265        let error_type = &self.error_type;
266        let rust_type = &self.rust_type;
267        let name = &self.name;
268        quote! {
269            impl TryFrom<#rust_type> for #name {
270                type Error = #error_type;
271
272                fn try_from(inp: #rust_type) -> std::result::Result<Self, Self::Error> {
273                    #conversion
274                }
275            }
276        }
277    }
278
279    fn as_impl(&self) -> proc_macro2::TokenStream {
280        let span = proc_macro2::Span::call_site();
281        let rust_type = &self.rust_type;
282        let name = &self.name;
283        let variants = self.variants.iter().map(|f| &f.ident);
284        let conversion = match self.rust_type.to_string().as_str() {
285            "i16" | "i32" | "i64" => {
286                let nums = self
287                    .variants
288                    .iter()
289                    .enumerate()
290                    .map(|(idx, &var)| (syn::LitInt::new(&idx.to_string(), span), var))
291                    .map(|(idx, var)| (syn::Lit::Int(idx), var))
292                    .map(|(idx, var)| Self::val(var).unwrap_or(idx));
293                quote! {
294                    match self {
295                        #(Self::#variants => #nums as #rust_type,)*
296                    }
297                }
298            }
299            "String" => {
300                let field_names = self.variants.iter().map(|v| self.variant_string_literal(v, span));
301
302                quote! {
303                    match self {
304                        #(Self::#variants => #field_names,)*
305                    }
306                }
307            }
308            _ => panic!(),
309        };
310
311        quote! {
312            impl Into<#rust_type> for #name {
313                fn into(self) -> #rust_type {
314                    #conversion.into()
315                }
316            }
317        }
318    }
319
320    fn impl_for_from_sql(&self) -> proc_macro2::TokenStream {
321        let sql_type = &self.sql_type;
322        let rust_type = &self.rust_type;
323        let name = &self.name;
324
325        quote! {
326            impl<Db> FromSql<#sql_type, Db> for #name
327            where
328                Db: diesel::backend::Backend,
329                #rust_type: FromSql<#sql_type, Db>
330            {
331                fn from_sql(bytes: <Db as diesel::backend::Backend>::RawValue<'_>) -> deserialize::Result<Self> {
332                    let s = <#rust_type as FromSql<#sql_type, Db>>::from_sql(bytes)?;
333                    let v = s.try_into()?;
334                    Ok(v)
335                }
336            }
337        }
338    }
339
340    fn to_sql(&self) -> proc_macro2::TokenStream {
341        let span = proc_macro2::Span::call_site();
342        let sql_type = &self.sql_type;
343        let rust_type = &self.rust_type;
344        let rust_type_borrowed = if rust_type == "String" {
345            quote! { str }
346        } else {
347            quote! { #rust_type }
348        };
349        let name = &self.name;
350        let conversion = match self.rust_type.to_string().as_str() {
351            "i16" | "i32" | "i64" => {
352                let variants = self.variants.iter().map(|f| &f.ident);
353                let values = self.variants.iter().map(|&v| {
354                    let ident = &v.ident;
355                    quote! {
356                        (Self::#ident as #rust_type).to_sql(out)
357                    }
358                });
359
360                quote! {
361                    match self {
362                        #(Self::#variants => #values,)*
363                    }
364                }
365            }
366            "String" => {
367                let variants = self.variants.iter().map(|f| &f.ident);
368                let field_names = self.variants.iter().map(|&v| {
369                    let val = self.variant_string_literal(v, span);
370                    quote! {
371                        #val.to_sql(out)
372                    }
373                });
374
375                quote! {
376                    match self {
377                        #(Self::#variants => #field_names,)*
378                    }
379                }
380            }
381            _ => panic!(),
382        };
383
384        quote! {
385            impl<Db> ToSql<#sql_type, Db> for #name
386            where
387                Db: diesel::backend::Backend,
388                #rust_type_borrowed: ToSql<#sql_type, Db>
389            {
390                fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Db>) -> serialize::Result {
391                    #conversion
392                }
393            }
394        }
395    }
396}
397
398fn get_attr_ident(
399    attrs: &[syn::Attribute],
400    outer: &str,
401    inner: &str,
402) -> Result<syn::Ident, proc_macro2::TokenStream> {
403    let stream = attrs
404        .iter()
405        .filter(|a| a.path.get_ident().map(|i| i == outer).unwrap_or(false))
406        .map(|a| &a.tokens)
407        .find(|s| s.to_string().contains(inner))
408        .ok_or_else(|| {
409            let span = proc_macro2::Span::call_site();
410            let msg = format!(
411                "Usage of the `DbEnum` macro requires the `{}` attribute to be present",
412                outer
413            );
414            error(span, &msg)
415        })?;
416    let s = stream.to_string();
417    let s = s
418        .split('=')
419        .nth(1)
420        .ok_or_else(|| error(stream.span(), "malformed attribute"))?
421        .trim_matches(|c| " )".contains(c));
422    Ok(syn::Ident::new(s, stream.span()))
423}
424
425fn get_attr_path(
426    attrs: &[syn::Attribute],
427    outer: &str,
428    inner: &str,
429) -> Result<syn::Path, proc_macro2::TokenStream> {
430    let stream = attrs
431        .iter()
432        .filter(|a| a.path.get_ident().map(|i| i == outer).unwrap_or(false))
433        .map(|a| &a.tokens)
434        .find(|s| s.to_string().contains(inner))
435        .ok_or_else(|| {
436            let span = proc_macro2::Span::call_site();
437            let msg = format!(
438                "Usage of the `DbEnum` macro requires the `{}` attribute to be present",
439                outer
440            );
441            error(span, &msg)
442        })?;
443    let s = stream.to_string();
444    let s = s
445        .split('=')
446        .nth(1)
447        .ok_or_else(|| error(stream.span(), "malformed attribute"))?
448        .trim_matches(|c| " )".contains(c));
449    syn::parse_str(s).map_err(|_| error(stream.span(), "Invalid path"))
450}
451
452fn get_optional_attr_string(
453    attrs: &[syn::Attribute],
454    outer: &str,
455    inner: &str,
456) -> Option<(String, proc_macro2::Span)> {
457    attrs
458        .iter()
459        .filter(|a| a.path.get_ident().map(|i| i == outer).unwrap_or(false))
460        .map(|a| &a.tokens)
461        .find(|s| s.to_string().contains(inner))
462        .and_then(|stream| {
463            let s = stream.to_string();
464            s.split('=')
465                .nth(1)
466                .map(|s| (s.trim_matches(|c| " )\"".contains(c)).to_string(), stream.span()))
467        })
468}
469
470fn get_attr_case(
471    attrs: &[syn::Attribute],
472    outer: &str,
473    inner: &str,
474) -> Result<CaseConvention, proc_macro2::TokenStream> {
475    match get_optional_attr_string(attrs, outer, inner) {
476        Some((case_str, span)) => {
477            CaseConvention::from_str(&case_str)
478                .map_err(|msg| error(span, &msg))
479        }
480        None => Ok(CaseConvention::default()),
481    }
482}
483
484fn error(span: proc_macro2::Span, message: &str) -> proc_macro2::TokenStream {
485    syn::Error::new(span, message).into_compile_error()
486}
487
488#[proc_macro_derive(DbEnum, attributes(diesel, diesel_enum))]
489pub fn db_enum(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
490    let input = syn::parse_macro_input!(input as syn::DeriveInput);
491    let name = input.ident;
492    let sql_type = try_or_return!(get_attr_ident(&input.attrs, "diesel", "sql_type"));
493    let error_fn = try_or_return!(get_attr_path(&input.attrs, "diesel_enum", "error_fn"));
494    let error_type = try_or_return!(get_attr_path(&input.attrs, "diesel_enum", "error_type"));
495    let case = try_or_return!(get_attr_case(&input.attrs, "diesel_enum", "case"));
496    let rust_type = try_or_return!(MacroState::rust_type(&sql_type));
497    let span = proc_macro2::Span::call_site();
498    let data = match input.data {
499        syn::Data::Enum(data) => data,
500        _ => return error(span, "DbEnum should be called on an Enum").into(),
501    };
502    let variants = data.variants.iter().collect();
503    let state = MacroState {
504        name,
505        variants,
506        sql_type,
507        rust_type,
508        error_fn,
509        error_type,
510        case,
511    };
512    let impl_for_from_sql = state.impl_for_from_sql();
513    let to_sql = state.to_sql();
514    let try_from = state.try_from();
515    let into = state.as_impl();
516    let name = state.name;
517    let mod_name = syn::Ident::new(
518        &format!("__impl_db_enum_{}", name),
519        proc_macro2::Span::call_site(),
520    );
521    let sql_type = state.sql_type;
522    let error_type = state.error_type;
523    let error_mod = state.error_fn.segments.first().expect("need `error_fn`");
524    let error_type_str = error_type
525        .segments
526        .iter()
527        .fold(String::new(), |a, b| a + &b.ident.to_string() + "::");
528    let error_type_str = &error_type_str[..error_type_str.len() - 2];
529    let error_import = if error_mod.ident == error_type_str {
530        quote! {}
531    } else {
532        quote! { use super::#error_mod; }
533    };
534
535    (quote! {
536        #[allow(non_snake_case, unused_extern_crates, unused_imports)]
537        mod #mod_name {
538            use super::{#name, #error_type};
539            #error_import
540
541            use diesel::{
542                self,
543                deserialize::{self, FromSql},
544                serialize::{self, Output, ToSql},
545                sql_types::#sql_type,
546            };
547            use std::{
548                convert::{TryFrom, TryInto},
549                io::Write,
550            };
551
552            #[automatically_derived]
553            #impl_for_from_sql
554
555            #[automatically_derived]
556            #to_sql
557
558            #[automatically_derived]
559            #try_from
560
561            #[automatically_derived]
562            #into
563        }
564    })
565    .into()
566}