From 4b2e88f7f9d4729f5f7788b6d2c48e4d347433c7 Mon Sep 17 00:00:00 2001 From: angrynode Date: Mon, 18 May 2026 12:54:32 +0200 Subject: [PATCH] docs: Mention example of binary-like newtype --- SeaORM/docs/04-generate-entity/05-newtype.md | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/SeaORM/docs/04-generate-entity/05-newtype.md b/SeaORM/docs/04-generate-entity/05-newtype.md index d2bd4603af..7602c5e196 100644 --- a/SeaORM/docs/04-generate-entity/05-newtype.md +++ b/SeaORM/docs/04-generate-entity/05-newtype.md @@ -384,3 +384,60 @@ impl std::str::FromStr for Tag3 { } } ``` + +## Binary-like newtypes + +It's also possible to use binary newtypes in your models. Even though there is no `DeriveValueType` for those, you can implement the traits directly. Here's an example implementation for a `Bin` newtype that implements `TryFrom>` and `Into>`: + +```rust +impl From for sea_orm::sea_query::Value { + fn from(t: Bin) -> Self { + Value::Bytes(Some(t.into())) + } +} + +impl sea_orm::TryGetable for Bin { + fn try_get_by( + res: &sea_orm::QueryResult, + index: I, + ) -> Result { + let val = as sea_orm::TryGetable>::try_get_by(res, index)?; + Bin::try_from(val).map_err(|e| { + sea_orm::error::TryGetError::DbErr(sea_orm::DbErr::TryIntoErr { + from: "Bytes", + into: "TorrentFile", + source: std::sync::Arc::new(e), + }) + }) + } +} + +impl sea_orm::sea_query::ValueType for Bin { + fn try_from(v: sea_orm::Value) -> Result { + match v { + sea_orm::Value::Bytes(Some(s)) => { + Bin::try_from(s).map_err(|_e| sea_orm::sea_query::ValueTypeErr) + } + _ => Err(sea_orm::sea_query::ValueTypeErr), + } + } + + fn type_name() -> String { + "Bin".to_string() + } + + fn array_type() -> sea_orm::sea_query::ArrayType { + sea_orm::sea_query::ArrayType::Bytes + } + + fn column_type() -> sea_orm::sea_query::ColumnType { + sea_orm::sea_query::ColumnType::VarBinary(StringLen::None) + } +} + +impl sea_orm::sea_query::Nullable for Bin { + fn null() -> sea_orm::sea_query::Value { + sea_orm::sea_query::Value::Bytes(None) + } +} +``` \ No newline at end of file