#enums #diesel #sql-database

macro diesel-enum

Interop between your enums and your database with diesel

10 releases

0.2.1 Jan 2, 2024
0.2.0 Jan 2, 2024
0.1.0 Jul 19, 2022
0.0.6 Jul 18, 2022
0.0.4 Jul 31, 2021

#1457 in Database interfaces

Download history 60/week @ 2024-07-30 128/week @ 2024-08-06 32/week @ 2024-08-13 142/week @ 2024-08-20 139/week @ 2024-08-27 69/week @ 2024-09-03 215/week @ 2024-09-10 215/week @ 2024-09-17 323/week @ 2024-09-24 346/week @ 2024-10-01 315/week @ 2024-10-08 269/week @ 2024-10-15 199/week @ 2024-10-22 252/week @ 2024-10-29 266/week @ 2024-11-05 129/week @ 2024-11-12

907 downloads per month

MIT license

19KB
340 lines

This crate allows the user to represent state in the database using Rust enums. This is achieved through a proc macro. First the macro looks at your chosen sql_type, and then it devises a corresponding Rust type. The mapping is as follows:

SQL Rust
SmallInt i16
Integer i32
Int i32
BigInt i64
VarChar String
Text String

The macro then generates three impls: a FromSql impl, an ToSql impl and a TryFrom impl, which allow conversion between the Sql type an the enum (FromSql and ToSql), and from the Rust type into the enum (TryInto).

Usage

use diesel_enum::DbEnum;
use diesel::{deserialize::FromSqlRow, sql_types::{SmallInt, VarChar}};

#[derive(Debug, thiserror::Error)]
#[error("CustomError: {msg}, {status}")]
pub struct CustomError {
    msg: String,
    status: u16,
}

impl CustomError {
    fn not_found(msg: String) -> Self {
        Self {
            msg,
            status: 404,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, AsExpression, FromSqlRow, DbEnum)]
#[diesel(sql_type = SmallInt)]
#[diesel_enum(error_fn = CustomError::not_found)]
#[diesel_enum(error_type = CustomError)]
pub enum Status {
    /// Will be represented as 0.
    Ready,
    /// Will be represented as 1.
    Pending,
}

Alternatively you can use strings, with will be cast to lowercase. (e.g. Status::Ready will be stored as "ready" in the database):

#[derive(Debug, Clone, Copy, PartialEq, Eq, AsExpression, FromSqlRow, DbEnum)]
#[diesel(sql_type = VarChar)]
#[diesel_enum(error_fn = CustomError::not_found)]
#[diesel_enum(error_type = CustomError)]
pub enum Status {
    /// Will be represented as `"ready"`.
    Ready,
    /// Will be represented as `"pending"`.
    Pending,
}

Another option is to manually override the values set for each or some of the variants. This is done using the val attribute:

#[derive(Debug, Clone, Copy, PartialEq, Eq, AsExpression, FromSqlRow, DbEnum)]
#[diesel(sql_type = VarChar)]
#[diesel_enum(error_fn = CustomError::not_found)]
#[diesel_enum(error_type = CustomError)]
pub enum Status {
    /// Will be represented as `"reddy"`.
    #[val = "reddy"]
    Ready,
    /// Will be represented as `"pending"`.
    Pending,
}

Dependencies

~1.5MB
~37K SLoC