Skip to main content

Crate bottle_orm_macro

Crate bottle_orm_macro 

Source
Expand description

§Bottle ORM Procedural Macros

This crate provides procedural macros for the Bottle ORM framework. It contains the #[derive(Model)] macro that automatically implements the Model trait for structs representing database tables.

§Overview

The procedural macros in this crate analyze struct definitions and their attributes to generate the necessary boilerplate code for ORM functionality. This includes:

  • Table name resolution
  • Column metadata generation
  • Type mapping from Rust to SQL
  • Serialization methods

§Architecture

The crate is organized into three modules:

  • lib.rs (this file): Entry point and macro definitions
  • derive_model.rs: Implementation of the Model derive macro
  • types.rs: Type mapping utilities (Rust → SQL)

§Usage

This crate is not meant to be used directly. Instead, it’s re-exported by the main bottle-orm crate:

use bottle_orm::Model;
use uuid::Uuid;

#[derive(Model)]
struct User {
    #[orm(primary_key)]
    id: Uuid,
    username: String,
}

§Supported Attributes

The #[orm(...)] attribute supports the following options:

§Primary Key

#[orm(primary_key)]
id: Uuid,

Marks the field as the table’s primary key. Generates PRIMARY KEY constraint.

§Unique Constraint

#[orm(unique)]
username: String,

Adds a UNIQUE constraint to prevent duplicate values.

§Database Index

#[orm(index)]
email: String,

Creates a database index on the column for faster queries.

§Column Size

#[orm(size = 100)]
username: String,

Sets VARCHAR(N) size for String fields. Default is TEXT.

§Auto-Timestamp (Creation)

#[orm(create_time)]
created_at: DateTime<Utc>,

Adds DEFAULT CURRENT_TIMESTAMP to auto-populate on INSERT.

§Auto-Timestamp (Update)

#[orm(update_time)]
updated_at: DateTime<Utc>,

Auto-updates timestamp on UPDATE (future feature).

§Foreign Key

#[orm(foreign_key = "User::id")]
user_id: Uuid,

Creates a foreign key relationship. Format: "TargetTable::target_column".

§Omit Field

#[orm(omit)]
password: String,

Excludes this field from query results by default. Returns a placeholder value instead of the actual data ("omited" for strings, 1970-01-01T00:00:00Z for dates, etc.).

§Combining Attributes

#[orm(size = 50, unique, index)]
username: String,

Multiple attributes can be combined on a single field.

§Generated Field Constants

The macro also generates a {model}_fields module with constants for each field, enabling IDE autocomplete:

// For struct User, the macro generates:
pub mod user_fields {
    pub const ID: &'static str = "id";
    pub const USERNAME: &'static str = "username";
    pub const PASSWORD: &'static str = "password";
}

// Use with filter, select, omit, etc:
db.model::<User>()
    .filter(user_fields::AGE, ">=", 18)
    .omit(user_fields::PASSWORD)
    .scan()
    .await?;

§Type Support

The macro supports automatic type mapping for:

§Primitive Types

  • i32INTEGER
  • i64BIGINT
  • f64DOUBLE PRECISION
  • boolBOOLEAN
  • StringTEXT or VARCHAR(N)

§UUID Types (All Versions 1-7)

  • UuidUUID

§Date/Time Types

  • DateTime<Utc>TIMESTAMPTZ
  • NaiveDateTimeTIMESTAMP
  • NaiveDateDATE
  • NaiveTimeTIME

§Nullable Types

  • Option<T> → SQL type of T with NULL allowed

§Complete Example

use bottle_orm::Model;
use uuid::Uuid;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Model, Debug, Clone, Serialize, Deserialize, FromRow)]
struct User {
    #[orm(primary_key)]
    id: Uuid,

    #[orm(size = 50, unique, index)]
    username: String,

    #[orm(size = 100, unique)]
    email: String,

    age: Option<i32>,

    active: bool,

    #[orm(create_time)]
    created_at: DateTime<Utc>,

    #[orm(update_time)]
    updated_at: Option<DateTime<Utc>>,
}

#[derive(Model, Debug, Clone, Serialize, Deserialize, FromRow)]
struct Post {
    #[orm(primary_key)]
    id: Uuid,

    #[orm(foreign_key = "User::id", index)]
    user_id: Uuid,

    #[orm(size = 200)]
    title: String,

    content: String,

    published: bool,

    #[orm(create_time)]
    created_at: DateTime<Utc>,
}

Derive Macros§

BottleEnum
Derives Display and FromStr for an enum to facilitate database mapping.
FromAnyRow
Derives the FromRow trait for AnyRow and the AnyImpl trait.
Model
Derives the Model trait for a struct.