Casting (Type Mapping)
10/30/24Less than 1 minute
Casting (Type Mapping)
Sea-ORM supports custom type mapping for special column types like enums and JSON.
Enum Mapping
use sea_orm::entity::prelude::*;
#[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(Some(20))")]
pub enum UserStatus {
#[sea_orm(string_value = "active")]
Active,
#[sea_orm(string_value = "inactive")]
Inactive,
#[sea_orm(string_value = "locked")]
Locked,
}
#[derive(Debug, Clone, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "sys_user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub status: UserStatus, // Auto-mapped to/from VARCHAR
}JSON Column Mapping
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, DeriveEntityModel)]
#[sea_orm(table_name = "sys_config")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(column_type = "Json")]
pub config_value: Json, // Automatically maps to JSON column
}
// Usage
let config = entity::sys_config::Entity::find_by_id(1).one(&db).await?.unwrap();
let value: serde_json::Value = config.config_value;
println!("Value: {}", value["key"].as_str().unwrap_or(""));Sea-ORM Type Mapping Reference
| Rust Type | MySQL Type | PostgreSQL Type |
|---|---|---|
| i32 | INT | INTEGER |
| i64 | BIGINT | BIGINT |
| String | VARCHAR | TEXT/VARCHAR |
| bool | TINYINT(1) | BOOLEAN |
| DateTimeUtc | DATETIME | TIMESTAMPTZ |
| NaiveDateTime | DATETIME | TIMESTAMP |
| Json | JSON | JSONB |
Vec<u8> | BLOB | BYTEA |