#[derive(Model)]
{
// Attributes available to this derive:
#[orm]
}
Expand description
Derives the Model trait for a struct.
This procedural macro inspects the struct fields and generates the necessary
code to map the struct to a database table. It automatically implements the
Model trait with methods for retrieving table metadata and converting
instances to/from database format.
§Supported Attributes
The macro recognizes the following #[orm(...)] attributes on struct fields:
primary_key- Marks the field as a primary keyunique- Adds a UNIQUE constraintindex- Creates a database indexcreate_time- Sets default value to CURRENT_TIMESTAMPupdate_time- Auto-updates timestamp (future feature)size = N- Sets column size (VARCHAR(N))foreign_key = "Table::Column"- Defines a Foreign Key relationship
§Type Mapping
The macro automatically maps Rust types to SQL types:
- Primitives:
i32→ INTEGER,i64→ BIGINT,bool→ BOOLEAN, etc. - UUID:
Uuid→ UUID (supports all versions 1-7) - Strings:
String→ TEXT or VARCHAR(N) with size attribute - Date/Time:
DateTime<Utc>→ TIMESTAMPTZ, etc. - Nullable:
Option<T>→ SQL type of T with NULL allowed
§Requirements
The struct must have named fields. Tuple structs and unit structs are not supported.
§Generated Implementation
The macro generates an implementation of the Model trait with four methods:
table_name()- Returns the struct name as a static stringcolumns()- Returns column metadata asVec<ColumnInfo>active_columns()- Returns column names asVec<&'static str>to_map()- Serializes the instance toHashMap<String, String>
§Example
ⓘ
use bottle_orm::Model;
use uuid::Uuid;
use chrono::{DateTime, Utc};
#[derive(Model)]
struct User {
#[orm(primary_key)]
id: Uuid,
#[orm(size = 50, unique)]
username: String,
#[orm(size = 100)]
email: String,
age: i32,
#[orm(create_time)]
created_at: DateTime<Utc>,
}§Panics
The macro will panic at compile time if:
- The input is not a struct
- The struct doesn’t have named fields
- An
#[orm(...)]attribute is malformed - A
foreign_keyattribute doesn’t follow the “Table::Column” format
§See Also
Model- The trait being implementedColumnInfo- Column metadata structure