Skip to main content

pgorm_derive/
lib.rs

1//! Derive macros for pgorm
2//!
3//! Provides `#[derive(FromRow)]` and `#[derive(Model)]` macros.
4
5use proc_macro::TokenStream;
6use syn::{parse_macro_input, DeriveInput};
7
8mod from_row;
9mod model;
10
11/// Derive `FromRow` trait for a struct.
12///
13/// # Example
14///
15/// ```ignore
16/// use pgorm::FromRow;
17///
18/// #[derive(FromRow)]
19/// struct User {
20///     id: i64,
21///     username: String,
22///     #[orm(column = "email_address")]
23///     email: Option<String>,
24/// }
25/// ```
26///
27/// # Attributes
28///
29/// - `#[orm(column = "name")]` - Map field to a different column name
30#[proc_macro_derive(FromRow, attributes(orm))]
31pub fn derive_from_row(input: TokenStream) -> TokenStream {
32    let input = parse_macro_input!(input as DeriveInput);
33    from_row::expand(input)
34        .unwrap_or_else(|e| e.to_compile_error())
35        .into()
36}
37
38/// Derive `Model` metadata for a struct.
39///
40/// # Example
41///
42/// ```ignore
43/// use pgorm::Model;
44///
45/// #[derive(Model)]
46/// #[orm(table = "users")]
47/// struct User {
48///     #[orm(id)]
49///     user_id: i64,
50///     username: String,
51///     email: Option<String>,
52/// }
53/// ```
54///
55/// # Generated
56///
57/// - `TABLE: &'static str` - Table name
58/// - `COL_*: &'static str` - Column name constants
59/// - `SELECT_LIST: &'static str` - Comma-separated column list
60/// - `fn select_list_as(alias: &str) -> String` - Aliased column list for JOINs
61///
62/// # Attributes
63///
64/// - `#[orm(table = "name")]` - Specify table name (required)
65/// - `#[orm(id)]` - Mark field as primary key
66/// - `#[orm(column = "name")]` - Map field to different column name
67#[proc_macro_derive(Model, attributes(orm))]
68pub fn derive_model(input: TokenStream) -> TokenStream {
69    let input = parse_macro_input!(input as DeriveInput);
70    model::expand(input)
71        .unwrap_or_else(|e| e.to_compile_error())
72        .into()
73}