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
use serde::Deserialize;
use serde_json::Value;
use sqlx_core::{
    decode::Decode,
    encode::{Encode, IsNull},
    error::BoxDynError,
    types::Type,
};

use crate::{
    arguments::ExaBuffer,
    database::Exasol,
    type_info::{ExaDataType, ExaTypeInfo},
    value::ExaValueRef,
};

impl Type<Exasol> for f32 {
    fn type_info() -> ExaTypeInfo {
        ExaDataType::Double.into()
    }

    fn compatible(ty: &ExaTypeInfo) -> bool {
        <Self as Type<Exasol>>::type_info().compatible(ty)
    }
}

impl Encode<'_, Exasol> for f32 {
    fn encode_by_ref(&self, buf: &mut ExaBuffer) -> Result<IsNull, BoxDynError> {
        // NaN is treated as NULL by Exasol.
        // Infinity is not supported by Exasol but serde_json
        // serializes it as NULL as well.
        if self.is_finite() {
            buf.append(self)?;
            Ok(IsNull::No)
        } else {
            buf.append(())?;
            Ok(IsNull::Yes)
        }
    }

    fn produces(&self) -> Option<ExaTypeInfo> {
        Some(ExaDataType::Double.into())
    }
}

impl Decode<'_, Exasol> for f32 {
    fn decode(value: ExaValueRef<'_>) -> Result<Self, BoxDynError> {
        match value.value {
            Value::Number(n) => <Self as Deserialize>::deserialize(n).map_err(From::from),
            Value::String(s) => serde_json::from_str(s).map_err(From::from),
            v => Err(format!("invalid f32 value: {v}").into()),
        }
    }
}

impl Type<Exasol> for f64 {
    fn type_info() -> ExaTypeInfo {
        ExaDataType::Double.into()
    }

    fn compatible(ty: &ExaTypeInfo) -> bool {
        <Self as Type<Exasol>>::type_info().compatible(ty)
    }
}

impl Encode<'_, Exasol> for f64 {
    fn encode_by_ref(&self, buf: &mut ExaBuffer) -> Result<IsNull, BoxDynError> {
        // NaN is treated as NULL by Exasol.
        // Infinity is not supported by Exasol but serde_json
        // serializes it as NULL as well.
        if self.is_finite() {
            buf.append(self)?;
            Ok(IsNull::No)
        } else {
            buf.append(())?;
            Ok(IsNull::Yes)
        }
    }

    fn produces(&self) -> Option<ExaTypeInfo> {
        Some(ExaDataType::Double.into())
    }
}

impl Decode<'_, Exasol> for f64 {
    fn decode(value: ExaValueRef<'_>) -> Result<Self, BoxDynError> {
        match value.value {
            Value::Number(n) => <Self as Deserialize>::deserialize(n).map_err(From::from),
            Value::String(s) => serde_json::from_str(s).map_err(From::from),
            v => Err(format!("invalid f64 value: {v}").into()),
        }
    }
}