-
-
Notifications
You must be signed in to change notification settings - Fork 523
/
active_enum.rs
275 lines (251 loc) Β· 8.88 KB
/
active_enum.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use crate::{ColumnDef, DbErr, TryGetable};
use sea_query::{Nullable, Value, ValueType};
/// A Rust representation of enum defined in database.
///
/// # Implementations
///
/// You can implement [ActiveEnum] manually by hand or use the derive macro [DeriveActiveEnum](sea_orm_macros::DeriveActiveEnum).
///
/// # Examples
///
/// Implementing it manually versus using the derive macro [DeriveActiveEnum](sea_orm_macros::DeriveActiveEnum).
///
/// > See [DeriveActiveEnum](sea_orm_macros::DeriveActiveEnum) for the full specification of macro attributes.
///
/// ```rust
/// use sea_orm::entity::prelude::*;
///
/// // Using the derive macro
/// #[derive(Debug, PartialEq, DeriveActiveEnum)]
/// #[sea_orm(rs_type = "String", db_type = "String(Some(1))")]
/// pub enum DeriveCategory {
/// #[sea_orm(string_value = "B")]
/// Big,
/// #[sea_orm(string_value = "S")]
/// Small,
/// }
///
/// // Implementing it manually
/// #[derive(Debug, PartialEq)]
/// pub enum Category {
/// Big,
/// Small,
/// }
///
/// impl ActiveEnum for Category {
/// // The macro attribute `rs_type` is being pasted here
/// type Value = String;
///
/// // Will be atomically generated by `DeriveActiveEnum`
/// fn to_value(&self) -> Self::Value {
/// match self {
/// Self::Big => "B",
/// Self::Small => "S",
/// }
/// .to_owned()
/// }
///
/// // Will be atomically generated by `DeriveActiveEnum`
/// fn try_from_value(v: &Self::Value) -> Result<Self, DbErr> {
/// match v.as_ref() {
/// "B" => Ok(Self::Big),
/// "S" => Ok(Self::Small),
/// _ => Err(DbErr::Type(format!(
/// "unexpected value for Category enum: {}",
/// v
/// ))),
/// }
/// }
///
/// fn db_type() -> ColumnDef {
/// // The macro attribute `db_type` is being pasted here
/// ColumnType::String(Some(1)).def()
/// }
/// }
/// ```
///
/// Using [ActiveEnum] on Model.
///
/// ```
/// use sea_orm::entity::prelude::*;
///
/// // Define the `Category` active enum
/// #[derive(Debug, Clone, PartialEq, DeriveActiveEnum)]
/// #[sea_orm(rs_type = "String", db_type = "String(Some(1))")]
/// pub enum Category {
/// #[sea_orm(string_value = "B")]
/// Big,
/// #[sea_orm(string_value = "S")]
/// Small,
/// }
///
/// #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
/// #[sea_orm(table_name = "active_enum")]
/// pub struct Model {
/// #[sea_orm(primary_key)]
/// pub id: i32,
/// // Represents a db column using `Category` active enum
/// pub category: Category,
/// pub category_opt: Option<Category>,
/// }
///
/// #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
/// pub enum Relation {}
///
/// impl ActiveModelBehavior for ActiveModel {}
/// ```
pub trait ActiveEnum: Sized {
/// Define the Rust type that each enum variant represents.
type Value: Into<Value> + ValueType + Nullable + TryGetable;
/// Convert enum variant into the corresponding value.
fn to_value(&self) -> Self::Value;
/// Try to convert the corresponding value into enum variant.
fn try_from_value(v: &Self::Value) -> Result<Self, DbErr>;
/// Get the database column definition of this active enum.
fn db_type() -> ColumnDef;
}
#[cfg(test)]
mod tests {
use crate as sea_orm;
use crate::{entity::prelude::*, *};
use pretty_assertions::assert_eq;
#[test]
fn active_enum_string() {
#[derive(Debug, PartialEq)]
pub enum Category {
Big,
Small,
}
impl ActiveEnum for Category {
type Value = String;
fn to_value(&self) -> Self::Value {
match self {
Self::Big => "B",
Self::Small => "S",
}
.to_owned()
}
fn try_from_value(v: &Self::Value) -> Result<Self, DbErr> {
match v.as_ref() {
"B" => Ok(Self::Big),
"S" => Ok(Self::Small),
_ => Err(DbErr::Type(format!(
"unexpected value for Category enum: {}",
v
))),
}
}
fn db_type() -> ColumnDef {
ColumnType::String(Some(1)).def()
}
}
#[derive(Debug, PartialEq, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "String(Some(1))")]
pub enum DeriveCategory {
#[sea_orm(string_value = "B")]
Big,
#[sea_orm(string_value = "S")]
Small,
}
assert_eq!(Category::Big.to_value(), "B".to_owned());
assert_eq!(Category::Small.to_value(), "S".to_owned());
assert_eq!(DeriveCategory::Big.to_value(), "B".to_owned());
assert_eq!(DeriveCategory::Small.to_value(), "S".to_owned());
assert_eq!(
Category::try_from_value(&"A".to_owned()).err(),
Some(DbErr::Type(
"unexpected value for Category enum: A".to_owned()
))
);
assert_eq!(
Category::try_from_value(&"B".to_owned()).ok(),
Some(Category::Big)
);
assert_eq!(
Category::try_from_value(&"S".to_owned()).ok(),
Some(Category::Small)
);
assert_eq!(
DeriveCategory::try_from_value(&"A".to_owned()).err(),
Some(DbErr::Type(
"unexpected value for DeriveCategory enum: A".to_owned()
))
);
assert_eq!(
DeriveCategory::try_from_value(&"B".to_owned()).ok(),
Some(DeriveCategory::Big)
);
assert_eq!(
DeriveCategory::try_from_value(&"S".to_owned()).ok(),
Some(DeriveCategory::Small)
);
assert_eq!(Category::db_type(), ColumnType::String(Some(1)).def());
assert_eq!(DeriveCategory::db_type(), ColumnType::String(Some(1)).def());
}
#[test]
fn active_enum_derive_signed_integers() {
macro_rules! test_int {
($ident: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, DeriveActiveEnum)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
pub enum $ident {
#[sea_orm(num_value = 1)]
Big,
#[sea_orm(num_value = 0)]
Small,
#[sea_orm(num_value = -10)]
Negative,
}
assert_eq!($ident::Big.to_value(), 1);
assert_eq!($ident::Small.to_value(), 0);
assert_eq!($ident::Negative.to_value(), -10);
assert_eq!($ident::try_from_value(&1).ok(), Some($ident::Big));
assert_eq!($ident::try_from_value(&0).ok(), Some($ident::Small));
assert_eq!($ident::try_from_value(&-10).ok(), Some($ident::Negative));
assert_eq!(
$ident::try_from_value(&2).err(),
Some(DbErr::Type(format!(
"unexpected value for {} enum: 2",
stringify!($ident)
)))
);
assert_eq!($ident::db_type(), ColumnType::$col_def.def());
};
}
test_int!(I8, "i8", "TinyInteger", TinyInteger);
test_int!(I16, "i16", "SmallInteger", SmallInteger);
test_int!(I32, "i32", "Integer", Integer);
test_int!(I64, "i64", "BigInteger", BigInteger);
}
#[test]
fn active_enum_derive_unsigned_integers() {
macro_rules! test_uint {
($ident: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, DeriveActiveEnum)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
pub enum $ident {
#[sea_orm(num_value = 1)]
Big,
#[sea_orm(num_value = 0)]
Small,
}
assert_eq!($ident::Big.to_value(), 1);
assert_eq!($ident::Small.to_value(), 0);
assert_eq!($ident::try_from_value(&1).ok(), Some($ident::Big));
assert_eq!($ident::try_from_value(&0).ok(), Some($ident::Small));
assert_eq!(
$ident::try_from_value(&2).err(),
Some(DbErr::Type(format!(
"unexpected value for {} enum: 2",
stringify!($ident)
)))
);
assert_eq!($ident::db_type(), ColumnType::$col_def.def());
};
}
test_uint!(U8, "u8", "TinyInteger", TinyInteger);
test_uint!(U16, "u16", "SmallInteger", SmallInteger);
test_uint!(U32, "u32", "Integer", Integer);
test_uint!(U64, "u64", "BigInteger", BigInteger);
}
}