1个不稳定版本
0.0.1 | 2023年8月3日 |
---|
#27 in #primary-key
在sea-orm-newtype中使用
15KB
275 行
sea-orm-newtype
该crate提供辅助derive宏以实现sea-orm的新类型模式。从sea-orm @ 0.12.x开始,您可以使用DeriveValueType宏。也请查看它。
示例
通过From和Into特性转换
use std::marker::PhantomData;
use uuid::Uuid;
use sea_orm_newtype::DeriveNewType;
/// New type for id that has specific type.
#[derive(Debug, Clone, PartialEq, DeriveNewType)]
#[sea_orm_newtype(from_into = "Uuid", primary_key)]
pub struct Id<T>(Uuid, PhantomData<T>);
impl<T> From<Uuid> for Id<T> {
fn from(id: Uuid) -> Id<T> {
Id(id, PhantomData)
}
}
impl<T> From<Id<T>> for Uuid {
fn from(value: Id<T>) -> Self {
value.0
}
}
use sea_orm::entity::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct ModelId;
#[derive(Clone, Debug, DeriveEntityModel)]
#[sea_orm(table_name = "foo")]
pub struct Model {
#[sea_orm(primary_key)]
id: Id<ModelId>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
通过TryFrom和Into特性转换
use std::fmt::Debug;
use std::str::FromStr;
use sea_orm_newtype::DeriveNewType;
#[derive(Clone, Debug, PartialEq, DeriveNewType)]
#[sea_orm_newtype(try_from_into = "String")]
pub struct EmailAddress(email_address::EmailAddress);
#[derive(Debug, thiserror::Error)]
#[error("ParseError")]
pub struct ParseError;
impl TryFrom<String> for EmailAddress {
type Error = ParseError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Ok(EmailAddress(
email_address::EmailAddress::from_str(&value).map_err(|_| ParseError)?,
))
}
}
impl From<EmailAddress> for String {
fn from(value: EmailAddress) -> Self {
value.0.to_string()
}
}
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, DeriveEntityModel)]
#[sea_orm(table_name = "foo")]
pub struct Model {
#[sea_orm(primary_key)]
id: uuid::Uuid,
email_address: EmailAddress,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
将其视为self.0类型
use sea_orm_newtype::DeriveNewType;
#[derive(Clone, Debug, PartialEq, Eq, DeriveNewType)]
#[sea_orm_newtype(transparent)]
pub struct Integer(i32);
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, DeriveEntityModel)]
#[sea_orm(table_name = "foo")]
pub struct Model {
#[sea_orm(primary_key)]
id: uuid::Uuid,
integer: Integer,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
依赖项
~0.6–1.1MB
~25K SLoC