Diesel-rs to SQL Type Conversions

crop woman taking refueling pistol gun

While working on a project, I needed to find the correct types to use in my Table structs so that they would be valid types for those in my models. Many of the posts I found on the information either had bits and pieces (some, it turns out, very wrong), or were pointing to Diesel’s documentation which contained none of the information needed.

Below I list the type conversions from Models to Schemas, which have been pulled out of Diesel’s code base on Github. The blob is https://github.com/diesel-rs/diesel/blob/afed26473f3a044e75095d66fa0dc04b12bb56a9/diesel/src/sql_types/mod.rs

ModelSchema
Boolbool (smallest int on your platform)
Tiny/TinyInti8
SmallInt/Short/i2i16
Integer/Longi32
Long/LongLong/BigInti64
Float/Float4f32
Double/Float8f64
Numeric/Doublebigdecimal::BigDecimal
Text/String/VARCHAR/LONGTEXT/MEDIUMTEXT/TINYTEXTString, &str
TinyBlob/MediumBlob/LongBlob/Blob/varbinary/bitVec<u8>,&[u8]
Text/Datechrono::NaiveDate, time::Date
Interval/PgIntervalchrono::Duration
Timechrono::NativeTime, time::Time
Text/Timestampstd::time::SystemTime, chrono::NaiveDateTime, time::PrimitiveDateTime, time::OffsetDateTime
Stringserde_json::Value
UuidUuid
Nullable<T>Option<T>

So, for example, if we have the following schema

diesel::table! {
    organizations(id) {
        id -> Uuid,
        name -> Text,
        address -> Nullable<Text>,
        revenue -> Nullable<Numeric>,
        utilization -> Nullable<Integer>,
        date_incorporated -> Date,
    }
}

We could have the following model defined for the schema

use bigdecimal::BigDecimal

pub struct Organization {
    pub id: Uuid,
    pub name: String,
    pub address: Option<String>,
    pub revenue: Option<BigDecimal>,
    pub utilization -> Option<i32>,
    pub date_incorportated: Option<NaiveDate>,
}
    

To ensure that you can use these features, in your Cargo.toml you would need to include

// so that bigdecimal can be deserialized, include the serde feature
bigdecimal = { version=N.N, features=[ "serde"] }

// in addition to any other features, include uuid, chorono and //numeric for uuids, date/time, and things like BigDecimal, //respectively.
diesel = { version=N.N, features=[ **some features**, "uuid", "chrono", "numeric" ] }

// chrono and uuid need the serde features as well, as will any other
// data type crate you will use in this way.

I hope this helps with your journey through using Diesel!