serde_db/de/db_value_into.rs
1use crate::de::conversion_error::ConversionError;
2
3/// Converts the given database value into a specific rust type.
4///
5/// We recommend to implement `try_into` as gracefully as possible, i.e.,
6/// supporting as many conversions as possible. For the numeric
7/// types this requires some lines of code, but the effort pays off for the users.
8///
9/// Example:
10///
11/// ```rust,ignore
12/// impl DbValueInto<u32> for MyDbValue {
13/// fn try_into(self) -> Result<u32, ConversionError> {
14/// match self {
15/// MyDbValue::TINYINT(u) => Ok(u as u32),
16///
17/// MyDbValue::SMALLINT(i) => if i >= 0 {
18/// Ok(i as u32)
19/// } else {
20/// Err(ConversionError::NumberRange(...))
21/// }
22///
23/// MyDbValue::INT(i) => if i >= 0 {
24/// Ok(i as u32)
25/// } else {
26/// Err(ConversionError::NumberRange(...))
27/// }
28///
29/// MyDbValue::BIGINT(i) => if (i >= 0) && (i <= u32::MAX as i64) {
30/// Ok(i as u32)
31/// } else {
32/// Err(ConversionError::NumberRange(...))
33/// }
34///
35/// _ => Err(ConversionError::ValueType(...)),
36/// }
37/// }
38/// }
39/// ```
40pub trait DbValueInto<T> {
41 /// Converts the database value into the target rust type.
42 ///
43 /// # Errors
44 ///
45 /// `ConversionError` if the value cannot be converted into the target type.
46 fn try_into(self) -> Result<T, ConversionError>;
47}