sqlx_exasol_impl/types/
text.rs

1use std::fmt::Display;
2
3use sqlx_core::{
4    decode::Decode,
5    encode::{Encode, IsNull},
6    error::BoxDynError,
7    types::{Text, Type},
8};
9
10use crate::{arguments::ExaBuffer, types::ExaHasArrayType, ExaTypeInfo, ExaValueRef, Exasol};
11
12impl<T> Type<Exasol> for Text<T> {
13    fn type_info() -> ExaTypeInfo {
14        <String as Type<Exasol>>::type_info()
15    }
16}
17
18impl<T> ExaHasArrayType for Text<T> where T: ExaHasArrayType {}
19
20impl<T> Encode<'_, Exasol> for Text<T>
21where
22    T: Display,
23{
24    fn encode_by_ref(&self, buf: &mut ExaBuffer) -> Result<IsNull, BoxDynError> {
25        let prev_len = buf.buffer.len();
26        buf.append(format_args!("{}", self.0))?;
27
28        // Serializing an empty string would result in just the quotes being added to the buffer.
29        // Important because Exasol treats empty strings as NULL.
30        if buf.buffer.len() - prev_len == 2 {
31            Ok(IsNull::Yes)
32        } else {
33            // Otherwise, the resulted text was not an empty string.
34            Ok(IsNull::No)
35        }
36    }
37}
38
39impl<'r, T> Decode<'r, Exasol> for Text<T>
40where
41    for<'a> T: TryFrom<&'a str>,
42    for<'a> BoxDynError: From<<T as TryFrom<&'a str>>::Error>,
43{
44    fn decode(value: ExaValueRef<'r>) -> Result<Self, BoxDynError> {
45        let s: &str = Decode::<Exasol>::decode(value)?;
46        Ok(Self(s.try_into()?))
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use sqlx::{types::Text, Encode};
53
54    use crate::{ExaArguments, Exasol};
55
56    #[test]
57    fn test_text_null_string() {
58        let mut arg_buffer = ExaArguments::default();
59        let value = Text(String::new());
60        let is_null = Encode::<Exasol>::encode_by_ref(&value, &mut arg_buffer.buf).unwrap();
61
62        assert!(is_null.is_null());
63    }
64
65    #[test]
66    fn test_text_null_str() {
67        let mut arg_buffer = ExaArguments::default();
68        let value = Text("");
69        let is_null = Encode::<Exasol>::encode_by_ref(&value, &mut arg_buffer.buf).unwrap();
70
71        assert!(is_null.is_null());
72    }
73
74    #[test]
75    fn test_text_non_null_string() {
76        let mut arg_buffer = ExaArguments::default();
77        let value = Text(String::from("something"));
78        let is_null = Encode::<Exasol>::encode_by_ref(&value, &mut arg_buffer.buf).unwrap();
79
80        assert!(!is_null.is_null());
81    }
82
83    #[test]
84    fn test_text_non_null_str() {
85        let mut arg_buffer = ExaArguments::default();
86        let value = Text("something");
87        let is_null = Encode::<Exasol>::encode_by_ref(&value, &mut arg_buffer.buf).unwrap();
88
89        assert!(!is_null.is_null());
90    }
91}