Skip to main content

oracledb_derive/
lib.rs

1//! Procedural macros for the `oracledb` driver.
2//!
3//! This crate hosts the `#[derive(FromRow)]` macro. It is an implementation
4//! detail of the `oracledb` crate: end users never depend on it directly. The
5//! `oracledb` crate re-exports the derive (gated behind its default-on `derive`
6//! feature) alongside the `FromRow` trait the generated code implements, so the
7//! single import
8//!
9//! ```ignore
10//! use oracledb::FromRow;
11//! ```
12//!
13//! brings both the trait and the derive into scope.
14//!
15//! # What the derive generates
16//!
17//! For a struct
18//!
19//! ```ignore
20//! #[derive(FromRow)]
21//! struct Emp { id: i64, name: String, hired: Option<chrono::NaiveDate> }
22//! ```
23//!
24//! the macro emits an `impl oracledb::FromRow for Emp`, whose `from_row` pulls
25//! each field out of the row **by column name** through the existing typed
26//! accessor (`TypedRow::get_by_name`), which itself goes through the real
27//! `FromSql` conversion. There is no stringly-typed shortcut: an `i64` field is
28//! genuinely converted from the Oracle `NUMBER`, an `Option<T>` field accepts a
29//! SQL `NULL`, and a `chrono::NaiveDate` field is decoded from a `DATE`.
30//!
31//! # Supported shapes and attributes
32//!
33//! * Named-field structs — each field maps to a column named after the field.
34//! * Tuple structs — each field maps to a column **by position** (index 0, 1, …).
35//! * `#[oracledb(rename_all = "UPPERCASE" | "lowercase" | "snake_case" |
36//!   "SCREAMING_SNAKE_CASE" | "camelCase" | "PascalCase")]` on the struct
37//!   renames every field's column (column resolution is case-insensitive, so
38//!   `UPPERCASE`/`lowercase` are cosmetic, but the others change word casing).
39//! * `#[oracledb(column = "…")]` on a field overrides that one column name.
40//! * `#[oracledb(rename = "…")]` is an accepted alias for `column = "…"`.
41//!
42//! Enums, unions, and unit/zero-field structs produce a clear `compile_error!`.
43
44use proc_macro::TokenStream;
45use proc_macro2::TokenStream as TokenStream2;
46use quote::quote;
47use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Fields, LitStr, Meta, Token};
48
49/// Derive an `oracledb::FromRow` implementation that maps a query row into the
50/// annotated struct, with compile-time-checked field types.
51///
52/// See the [crate-level documentation](crate) for the supported shapes and the
53/// `#[oracledb(...)]` attributes.
54#[proc_macro_derive(FromRow, attributes(oracledb))]
55pub fn derive_from_row(input: TokenStream) -> TokenStream {
56    let input = parse_macro_input!(input as DeriveInput);
57    expand(input)
58        .unwrap_or_else(syn::Error::into_compile_error)
59        .into()
60}
61
62/// One of the case-conversion strategies accepted by `rename_all`.
63#[derive(Clone, Copy)]
64enum RenameAll {
65    Upper,
66    Lower,
67    Snake,
68    ScreamingSnake,
69    Camel,
70    Pascal,
71}
72
73impl RenameAll {
74    fn parse(value: &LitStr) -> syn::Result<Self> {
75        Ok(match value.value().as_str() {
76            "UPPERCASE" => RenameAll::Upper,
77            "lowercase" => RenameAll::Lower,
78            "snake_case" => RenameAll::Snake,
79            "SCREAMING_SNAKE_CASE" => RenameAll::ScreamingSnake,
80            "camelCase" => RenameAll::Camel,
81            "PascalCase" => RenameAll::Pascal,
82            other => {
83                return Err(syn::Error::new(
84                    value.span(),
85                    format!(
86                        "unknown rename_all rule {other:?}; expected one of \
87                         \"UPPERCASE\", \"lowercase\", \"snake_case\", \
88                         \"SCREAMING_SNAKE_CASE\", \"camelCase\", \"PascalCase\""
89                    ),
90                ));
91            }
92        })
93    }
94
95    fn apply(self, field: &str) -> String {
96        match self {
97            RenameAll::Upper => field.to_uppercase(),
98            RenameAll::Lower => field.to_lowercase(),
99            RenameAll::Snake => to_snake(field),
100            RenameAll::ScreamingSnake => to_snake(field).to_uppercase(),
101            RenameAll::Camel => to_camel(field, false),
102            RenameAll::Pascal => to_camel(field, true),
103        }
104    }
105}
106
107/// Convert an identifier (`fooBar`, `FooBar`, `foo_bar`) to `foo_bar`.
108fn to_snake(field: &str) -> String {
109    let mut out = String::with_capacity(field.len() + 4);
110    let mut prev_lower_or_digit = false;
111    for ch in field.chars() {
112        if ch.is_uppercase() {
113            if prev_lower_or_digit {
114                out.push('_');
115            }
116            for lower in ch.to_lowercase() {
117                out.push(lower);
118            }
119            prev_lower_or_digit = false;
120        } else {
121            out.push(ch);
122            prev_lower_or_digit = ch.is_lowercase() || ch.is_ascii_digit();
123        }
124    }
125    out
126}
127
128/// Convert an identifier to camelCase (`pascal = false`) or PascalCase
129/// (`pascal = true`), treating `_` as a word boundary.
130fn to_camel(field: &str, pascal: bool) -> String {
131    let mut out = String::with_capacity(field.len());
132    let mut upper_next = pascal;
133    for ch in field.chars() {
134        if ch == '_' {
135            upper_next = true;
136            continue;
137        }
138        if upper_next {
139            for upper in ch.to_uppercase() {
140                out.push(upper);
141            }
142            upper_next = false;
143        } else {
144            out.push(ch);
145        }
146    }
147    out
148}
149
150/// Container-level options parsed from `#[oracledb(...)]` on the struct.
151#[derive(Default)]
152struct ContainerOpts {
153    rename_all: Option<RenameAll>,
154}
155
156/// Field-level options parsed from `#[oracledb(...)]` on a field.
157#[derive(Default)]
158struct FieldOpts {
159    column: Option<String>,
160}
161
162/// Parse every `#[oracledb(...)]` attribute on a struct into container options.
163fn parse_container_opts(input: &DeriveInput) -> syn::Result<ContainerOpts> {
164    let mut opts = ContainerOpts::default();
165    for attr in &input.attrs {
166        if !attr.path().is_ident("oracledb") {
167            continue;
168        }
169        let metas =
170            attr.parse_args_with(syn::punctuated::Punctuated::<Meta, Token![,]>::parse_terminated)?;
171        for meta in metas {
172            match &meta {
173                Meta::NameValue(nv) if nv.path.is_ident("rename_all") => {
174                    let lit = expect_str_lit(&nv.value)?;
175                    opts.rename_all = Some(RenameAll::parse(&lit)?);
176                }
177                _ => {
178                    return Err(syn::Error::new(
179                        meta.span(),
180                        "unsupported #[oracledb(...)] container option; \
181                         expected `rename_all = \"...\"`",
182                    ));
183                }
184            }
185        }
186    }
187    Ok(opts)
188}
189
190/// Parse every `#[oracledb(...)]` attribute on a field into field options.
191fn parse_field_opts(attrs: &[syn::Attribute]) -> syn::Result<FieldOpts> {
192    let mut opts = FieldOpts::default();
193    for attr in attrs {
194        if !attr.path().is_ident("oracledb") {
195            continue;
196        }
197        let metas =
198            attr.parse_args_with(syn::punctuated::Punctuated::<Meta, Token![,]>::parse_terminated)?;
199        for meta in metas {
200            match &meta {
201                Meta::NameValue(nv) if nv.path.is_ident("column") || nv.path.is_ident("rename") => {
202                    let lit = expect_str_lit(&nv.value)?;
203                    opts.column = Some(lit.value());
204                }
205                _ => {
206                    return Err(syn::Error::new(
207                        meta.span(),
208                        "unsupported #[oracledb(...)] field option; \
209                         expected `column = \"...\"` or `rename = \"...\"`",
210                    ));
211                }
212            }
213        }
214    }
215    Ok(opts)
216}
217
218/// If `ty` is syntactically `Option<Inner>` (in any of the spellings
219/// `Option<T>`, `std::option::Option<T>`, `core::option::Option<T>`), return
220/// `Some(Inner)`. This drives the choice between the NULL-rejecting accessor and
221/// the NULL-tolerant one in the generated code: an `Option<T>` field accepts a
222/// SQL `NULL` (mapping to `None`), a bare `T` field does not.
223fn option_inner(ty: &syn::Type) -> Option<&syn::Type> {
224    let syn::Type::Path(type_path) = ty else {
225        return None;
226    };
227    if type_path.qself.is_some() {
228        return None;
229    }
230    let segments = &type_path.path.segments;
231    // Accept `Option`, `option::Option`, `std::option::Option`, etc. — the last
232    // segment must be `Option` and the leading segments (if any) must be the
233    // `std`/`core` option path.
234    let last = segments.last()?;
235    if last.ident != "Option" {
236        return None;
237    }
238    let ok_prefix = match segments.len() {
239        1 => true,
240        n => {
241            let lead: Vec<String> = segments
242                .iter()
243                .take(n - 1)
244                .map(|s| s.ident.to_string())
245                .collect();
246            let lead: Vec<&str> = lead.iter().map(String::as_str).collect();
247            matches!(
248                lead.as_slice(),
249                ["option"] | ["std", "option"] | ["core", "option"]
250            )
251        }
252    };
253    if !ok_prefix {
254        return None;
255    }
256    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
257        return None;
258    };
259    args.args.iter().find_map(|arg| match arg {
260        syn::GenericArgument::Type(inner) => Some(inner),
261        _ => None,
262    })
263}
264
265/// Require an expression to be a string literal, returning it.
266fn expect_str_lit(expr: &syn::Expr) -> syn::Result<LitStr> {
267    if let syn::Expr::Lit(syn::ExprLit {
268        lit: syn::Lit::Str(s),
269        ..
270    }) = expr
271    {
272        Ok(s.clone())
273    } else {
274        Err(syn::Error::new(expr.span(), "expected a string literal"))
275    }
276}
277
278fn expand(input: DeriveInput) -> syn::Result<TokenStream2> {
279    let data = match &input.data {
280        Data::Struct(data) => data,
281        Data::Enum(e) => {
282            return Err(syn::Error::new(
283                e.enum_token.span(),
284                "#[derive(FromRow)] cannot be applied to enums: a query row maps \
285                 to a fixed set of columns, which an enum's variants do not model",
286            ));
287        }
288        Data::Union(u) => {
289            return Err(syn::Error::new(
290                u.union_token.span(),
291                "#[derive(FromRow)] cannot be applied to unions",
292            ));
293        }
294    };
295
296    let container = parse_container_opts(&input)?;
297    let name = &input.ident;
298    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
299
300    let body = match &data.fields {
301        Fields::Named(named) => named_body(named, &container)?,
302        Fields::Unnamed(unnamed) => unnamed_body(unnamed)?,
303        Fields::Unit => {
304            return Err(syn::Error::new(
305                input.ident.span(),
306                "#[derive(FromRow)] needs at least one field to map; a unit struct \
307                 maps no columns",
308            ));
309        }
310    };
311
312    Ok(quote! {
313        #[automatically_derived]
314        impl #impl_generics ::oracledb::FromRow for #name #ty_generics #where_clause {
315            fn from_row(
316                row: &::oracledb::TypedRow<'_>,
317            ) -> ::core::result::Result<Self, ::oracledb::ConversionError> {
318                ::core::result::Result::Ok(#name #body)
319            }
320        }
321    })
322}
323
324/// Build the `{ field: ..., ... }` construction for a named-field struct.
325fn named_body(named: &syn::FieldsNamed, container: &ContainerOpts) -> syn::Result<TokenStream2> {
326    if named.named.is_empty() {
327        return Err(syn::Error::new(
328            named.span(),
329            "#[derive(FromRow)] needs at least one field to map",
330        ));
331    }
332    let mut inits = Vec::with_capacity(named.named.len());
333    for field in &named.named {
334        let ident = field
335            .ident
336            .as_ref()
337            .ok_or_else(|| syn::Error::new(field.span(), "named field without an identifier"))?;
338        let ty = &field.ty;
339        let opts = parse_field_opts(&field.attrs)?;
340        let column = match opts.column {
341            Some(explicit) => explicit,
342            None => {
343                let base = ident.to_string();
344                let base = base.strip_prefix("r#").unwrap_or(&base);
345                match container.rename_all {
346                    Some(rule) => rule.apply(base),
347                    None => base.to_string(),
348                }
349            }
350        };
351        let access = match option_inner(ty) {
352            // Option<Inner>: NULL -> None. Call the NULL-tolerant accessor with
353            // the *inner* type so it returns Option<Inner> == the field type.
354            Some(inner) => quote! { row.try_get_by_name_opt::<#inner>(#column)? },
355            // Bare T: NULL is an error.
356            None => quote! { row.try_get_by_name::<#ty>(#column)? },
357        };
358        inits.push(quote! { #ident: #access });
359    }
360    Ok(quote! { { #(#inits),* } })
361}
362
363/// Build the `( ..., ... )` construction for a tuple struct, mapping by position.
364fn unnamed_body(unnamed: &syn::FieldsUnnamed) -> syn::Result<TokenStream2> {
365    if unnamed.unnamed.is_empty() {
366        return Err(syn::Error::new(
367            unnamed.span(),
368            "#[derive(FromRow)] needs at least one field to map",
369        ));
370    }
371    let mut inits = Vec::with_capacity(unnamed.unnamed.len());
372    for (index, field) in unnamed.unnamed.iter().enumerate() {
373        // Reject field-level attributes that only make sense on named fields.
374        let opts = parse_field_opts(&field.attrs)?;
375        if opts.column.is_some() {
376            return Err(syn::Error::new(
377                field.span(),
378                "#[oracledb(column = ...)] is not supported on a tuple struct field; \
379                 tuple-struct fields map to columns by position",
380            ));
381        }
382        let ty = &field.ty;
383        let access = match option_inner(ty) {
384            Some(inner) => quote! { row.try_get_opt::<#inner>(#index)? },
385            None => quote! { row.try_get::<#ty>(#index)? },
386        };
387        inits.push(access);
388    }
389    // Trailing comma so a single-field tuple struct constructs as a tuple
390    // (`Foo(x,)`) rather than a parenthesized expression (`Foo(x)`).
391    Ok(quote! { ( #(#inits,)* ) })
392}