Model

Derive Macro Model 

Source
#[derive(Model)]
{
    // Attributes available to this derive:
    #[orm]
}
Expand description

Re-export of the procedural macro for deriving the Model trait.

This macro is defined in the bottle-orm-macro crate and allows automatic implementation of the Model trait for structs representing database tables. 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 key
  • unique - Adds a UNIQUE constraint
  • index - Creates a database index
  • create_time - Sets default value to CURRENT_TIMESTAMP
  • update_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:

  1. table_name() - Returns the struct name as a static string
  2. columns() - Returns column metadata as Vec<ColumnInfo>
  3. active_columns() - Returns column names as Vec<&'static str>
  4. to_map() - Serializes the instance to HashMap<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_key attribute doesn’t follow the “Table::Column” format

§See Also

  • Model - The trait being implemented
  • ColumnInfo - Column metadata structure