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
//! Module containing bindings & wrappers to SQL types

use std::{slice, str};

use udf_sys::Item_result;

/// Enum representing possible SQL result types
///
/// This simply represents the possible types, but does not contain any values.
/// [`SqlResult`] is the corresponding enum that actually contains data.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[repr(i8)]
pub enum SqlType {
    /// Integer result
    Int = Item_result::INT_RESULT as i8,
    /// Real result
    Real = Item_result::REAL_RESULT as i8,
    /// String result
    String = Item_result::STRING_RESULT as i8,
    /// Decimal result
    Decimal = Item_result::DECIMAL_RESULT as i8,
}

impl SqlType {
    /// Convert this enum to a SQL [`Item_result`]. This is only useful if you
    /// work with [`udf_sys`] bindings directly.
    #[inline]
    pub fn to_item_result(&self) -> Item_result {
        match *self {
            Self::Int => Item_result::INT_RESULT,
            Self::Real => Item_result::REAL_RESULT,
            Self::String => Item_result::STRING_RESULT,
            Self::Decimal => Item_result::DECIMAL_RESULT,
        }
    }

    /// Small helper function to get a displayable type name.
    #[inline]
    pub fn display_name(&self) -> &'static str {
        match *self {
            Self::String => "string",
            Self::Real => "real",
            Self::Int => "int",
            Self::Decimal => "decimal",
        }
    }
}

impl TryFrom<i8> for SqlType {
    type Error = String;

    /// Create an [`SqlType`] from an integer
    #[inline]
    fn try_from(tag: i8) -> Result<Self, Self::Error> {
        let val = match tag {
            x if x == Self::String as i8 => Self::String,
            x if x == Self::Real as i8 => Self::Real,
            x if x == Self::Int as i8 => Self::Int,
            x if x == Self::Decimal as i8 => Self::Decimal,
            _ => return Err("invalid arg type {tag} received".to_owned()),
        };

        Ok(val)
    }
}

impl TryFrom<Item_result> for SqlType {
    type Error = String;

    /// Create an [`SqlType`] from an [`Item_result`], located in the `bindings`
    /// module.
    #[inline]
    fn try_from(tag: Item_result) -> Result<Self, Self::Error> {
        let val = match tag {
            Item_result::STRING_RESULT => Self::String,
            Item_result::REAL_RESULT => Self::Real,
            Item_result::INT_RESULT => Self::Int,
            Item_result::DECIMAL_RESULT => Self::Decimal,
            _ => return Err("invalid arg type {tag} received".to_owned()),
        };

        Ok(val)
    }
}

impl TryFrom<&SqlResult<'_>> for SqlType {
    type Error = String;

    /// Create an [`SqlType`] from an [`SqlResult`]
    #[inline]
    fn try_from(tag: &SqlResult) -> Result<Self, Self::Error> {
        let val = match *tag {
            SqlResult::String(_) => Self::String,
            SqlResult::Real(_) => Self::Real,
            SqlResult::Int(_) => Self::Int,
            SqlResult::Decimal(_) => Self::Decimal,
        };

        Ok(val)
    }
}

/// A possible SQL result consisting of a type and nullable value
///
/// This enum is similar to [`SqlType`], but actually contains the object.
///
/// It is of note that both [`SqlResult::String`] and [`SqlResult::Decimal`]
/// contain slices of `u8` rather than a representation like `&str`. This is
/// because there is no guarantee that the data is `utf8`. Use
/// [`SqlResult::as_string()`] if you need an easy way to get a `&str`.
///
/// This enum is labeled `non_exhaustive` to leave room for future types and
/// coercion options.
#[derive(Debug, PartialEq, Clone)]
#[non_exhaustive]
pub enum SqlResult<'a> {
    // INVALID_RESULT and ROW_RESULT are other options, but not valid for UDFs
    /// A string result
    String(Option<&'a [u8]>),
    /// A floating point result
    Real(Option<f64>),
    /// A nullable integer
    Int(Option<i64>),
    /// This is a string that is to be represented as a decimal
    Decimal(Option<&'a [u8]>),
}

impl<'a> SqlResult<'a> {
    /// Construct a `SqlResult` from a pointer and a tag
    ///
    /// SAFETY: pointer must not be null. If a string or decimal result, must be
    /// exactly `len` long.
    pub(crate) unsafe fn from_ptr(
        ptr: *const u8,
        tag: Item_result,
        len: usize,
    ) -> Result<SqlResult<'a>, String> {
        // Handle nullptr right away here

        let marker =
            SqlType::try_from(tag).map_err(|_| format!("invalid arg type {tag:?} received"))?;

        let arg = if ptr.is_null() {
            match marker {
                SqlType::Int => SqlResult::Int(None),
                SqlType::Real => SqlResult::Real(None),
                SqlType::String => SqlResult::String(None),
                SqlType::Decimal => SqlResult::Decimal(None),
            }
        } else {
            // SAFETY: `tag` guarantees type. If decimal or String, caller
            // guarantees length
            unsafe {
                #[allow(clippy::cast_ptr_alignment)]
                match marker {
                    SqlType::Int => SqlResult::Int(Some(*(ptr.cast::<i64>()))),
                    SqlType::Real => SqlResult::Real(Some(*(ptr.cast::<f64>()))),
                    SqlType::String => SqlResult::String(Some(slice::from_raw_parts(ptr, len))),
                    SqlType::Decimal => SqlResult::Decimal(Some(slice::from_raw_parts(ptr, len))),
                }
            }
        };

        Ok(arg)
    }

    /// Small helper function to get a displayable type name.
    #[inline]
    pub fn display_name(&self) -> &'static str {
        SqlType::try_from(self).map_or("unknown", |v| v.display_name())
    }

    /// Check if this argument is an integer type, even if it may be null
    #[inline]
    pub fn is_int(&self) -> bool {
        matches!(*self, Self::Int(_))
    }
    /// Check if this argument is an real type, even if it may be null
    #[inline]
    pub fn is_real(&self) -> bool {
        matches!(*self, Self::Real(_))
    }
    /// Check if this argument is an string type, even if it may be null
    #[inline]
    pub fn is_string(&self) -> bool {
        matches!(*self, Self::String(_))
    }
    /// Check if this argument is an decimal type, even if it may be null
    #[inline]
    pub fn is_decimal(&self) -> bool {
        matches!(*self, Self::Decimal(_))
    }

    /// Return this type as an integer if possible
    ///
    /// This will exist if the variant is [`SqlResult::Int`], and it contains a
    /// value.
    ///
    /// These `as_*` methods are helpful to quickly obtain a value when you
    /// expect it to be of a specific type and present.
    #[inline]
    pub fn as_int(&self) -> Option<i64> {
        match *self {
            Self::Int(v) => v,
            _ => None,
        }
    }

    /// Return this type as a float if possible
    ///
    /// This will exist if the variant is [`SqlResult::Real`], and it contains a
    /// value. See [`SqlResult::as_int()`] for further details on `as_*` methods
    #[inline]
    pub fn as_real(&'a self) -> Option<f64> {
        match *self {
            Self::Real(v) => v,
            _ => None,
        }
    }

    /// Return this type as a string if possible
    ///
    /// This will exist if the variant is [`SqlResult::String`], or
    /// [`SqlResult::Decimal`], and it contains a value, _and_ the string can
    /// successfully be converted to `utf8` (using [`str::from_utf8`]). It does
    /// not distinguish among errors (wrong type, `None` value, or invalid utf8)
    /// - use pattern matching if you need that.
    ///
    /// See [`SqlResult::as_int()`] for further details on `as_*` methods
    #[inline]
    pub fn as_string(&'a self) -> Option<&'a str> {
        match *self {
            Self::String(Some(v)) | Self::Decimal(Some(v)) => Some(str::from_utf8(v).ok()?),
            _ => None,
        }
    }

    /// Return this type as a byte slice if possible
    ///
    /// This will exist if the variant is [`SqlResult::String`], or
    /// [`SqlResult::Decimal`]. See [`SqlResult::as_int()`] for further details
    /// on `as_*` methods
    #[inline]
    pub fn as_bytes(&'a self) -> Option<&'a [u8]> {
        match *self {
            Self::String(Some(v)) | Self::Decimal(Some(v)) => Some(v),
            _ => None,
        }
    }
}