Skip to main content

ormkit_derive/
lib.rs

1//! # ormkit-derive
2//!
3//! Procedural macros for ormkit ORM framework.
4//!
5//! This crate provides derive macros for automatically implementing ORM traits:
6//! - `#[derive(Entity)]` - Implements the Entity trait
7//! - `#[ormkit(table = "name")]` - Specifies table name
8//! - `#[ormkit(id)]` - Marks the primary key field
9//! - `#[ormkit(belongs_to = "Entity")]` - Defines relationships
10//!
11//! ## Example
12//!
13//! ```rust
14//! use ormkit::Entity;
15//!
16//! #[derive(ormkit::Entity)]
17//! #[ormkit(table = "users")]
18//! struct User {
19//!     #[ormkit(id)]
20//!     id: Uuid,
21//!     email: String,
22//!     name: String,
23//! }
24//! ```
25
26extern crate proc_macro;
27
28mod attributes;
29mod entity;
30mod active_model;
31mod relationships;
32
33use proc_macro::TokenStream;
34use syn::DeriveInput;
35
36/// Derive macro for implementing Entity trait
37///
38/// This macro automatically implements the `Entity` trait and generates
39/// an accompanying `ActiveModel` struct for tracking changes.
40///
41/// # Attributes
42///
43/// ## Struct-level attributes
44/// - `#[ormkit(table = "table_name")]` - Specify the database table name
45///
46/// ## Field-level attributes
47/// - `#[ormkit(id)]` - Mark the primary key field (required)
48/// - `#[ormkit(belongs_to = "EntityName")]` - Define foreign key relationship
49/// - `#[ormkit(column = "column_name")]` - Override default column name
50///
51/// # Example
52///
53/// ```rust
54/// use ormkit::Entity;
55/// use uuid::Uuid;
56///
57/// #[derive(ormkit::Entity)]
58/// #[ormkit(table = "users")]
59/// struct User {
60///     #[ormkit(id)]
61///     id: Uuid,
62///     email: String,
63///     name: String,
64///     #[ormkit(belongs_to = "Organization")]
65///     organization_id: Uuid,
66/// }
67/// ```
68///
69/// # Generated Code
70///
71/// The macro generates:
72/// 1. Implementation of `Entity` trait
73/// 2. An `ActiveModel` struct with `ActiveValue<T>` fields
74/// 3. Implementation of `ActiveModelTrait` for the generated ActiveModel
75/// 4. Helper methods for CRUD operations
76///
77/// # Constraints
78///
79/// - Exactly one field must be marked with `#[ormkit(id)]`
80/// - The struct must be named (not a tuple struct or unit struct)
81/// - Generic structs are not supported
82/// - The ID field type must be one of: Uuid, i32, i64, String
83#[proc_macro_derive(Entity, attributes(ormkit))]
84pub fn derive_entity(input: TokenStream) -> TokenStream {
85    let input = syn::parse_macro_input!(input as DeriveInput);
86    entity::derive_entity_impl(input)
87        .unwrap_or_else(|err| err.to_compile_error())
88        .into()
89}