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
Model | Schema |
Bool | bool (smallest int on your platform) |
Tiny/TinyInt | i8 |
SmallInt/Short/i2 | i16 |
Integer/Long | i32 |
Long/LongLong/BigInt | i64 |
Float/Float4 | f32 |
Double/Float8 | f64 |
Numeric/Double | bigdecimal::BigDecimal |
Text/String/VARCHAR/LONGTEXT/MEDIUMTEXT/TINYTEXT | String, &str |
TinyBlob/MediumBlob/LongBlob/Blob/varbinary/bit | Vec<u8>,&[u8] |
Text/Date | chrono::NaiveDate, time::Date |
Interval/PgInterval | chrono::Duration |
Time | chrono::NativeTime, time::Time |
Text/Timestamp | std::time::SystemTime, chrono::NaiveDateTime, time::PrimitiveDateTime, time::OffsetDateTime |
String | serde_json::Value |
Uuid | Uuid |
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!