diesel/mysql_like/types/
numeric.rs1#[cfg(feature = "numeric")]
2mod bigdecimal {
3 use bigdecimal::{BigDecimal, FromPrimitive};
4 use std::io::prelude::*;
5
6 use crate::deserialize::{self, FromSql};
7 use crate::mysql_like::MysqlLikeBackend;
8 use crate::mysql_like::{MysqlValue, NumericRepresentation};
9 use crate::serialize::{self, IsNull, Output, ToSql};
10 use crate::sql_types::Numeric;
11
12 impl<DB: MysqlLikeBackend> ToSql<Numeric, DB> for BigDecimal {
13 fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
14 out.write_fmt(format_args!("{0}", *self))write!(out, "{}", *self)
15 .map(|_| IsNull::No)
16 .map_err(Into::into)
17 }
18 }
19
20 impl<DB: MysqlLikeBackend> FromSql<Numeric, DB> for BigDecimal {
21 fn from_sql(value: MysqlValue<'_>) -> deserialize::Result<Self> {
22 match value.numeric_value()? {
23 NumericRepresentation::Tiny(x) => Ok(x.into()),
24 NumericRepresentation::Small(x) => Ok(x.into()),
25 NumericRepresentation::Medium(x) => Ok(x.into()),
26 NumericRepresentation::Big(x) => Ok(x.into()),
27 NumericRepresentation::Float(x) => BigDecimal::from_f32(x)
28 .ok_or_else(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not valid decimal number ",
x))
})format!("{x} is not valid decimal number ").into()),
29 NumericRepresentation::Double(x) => BigDecimal::from_f64(x)
30 .ok_or_else(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not valid decimal number ",
x))
})format!("{x} is not valid decimal number ").into()),
31 NumericRepresentation::Decimal(bytes) => BigDecimal::parse_bytes(bytes, 10)
32 .ok_or_else(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?} is not valid decimal number ",
bytes))
})format!("{bytes:?} is not valid decimal number ").into()),
33 }
34 }
35 }
36}