odbc_api/
nullable.rs

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
use std::ffi::c_void;

use odbc_sys::NULL_DATA;

use crate::{
    buffers::{FetchRowMember, Indicator},
    fixed_sized::Pod,
    handles::{CData, CDataMut, HasDataType},
    parameter::CElement,
    OutputParameter,
};

/// Wraps a type T together with an additional indicator. This way the type gains a Null
/// representation, those memory layout is compatible with ODBC.
#[derive(Clone, Copy)]
pub struct Nullable<T> {
    indicator: isize,
    value: T,
}

impl<T> Nullable<T> {
    pub fn new(value: T) -> Self {
        Self {
            indicator: 0,
            value,
        }
    }

    pub fn null() -> Self
    where
        T: Default,
    {
        Self {
            indicator: NULL_DATA,
            value: Default::default(),
        }
    }

    pub fn as_opt(&self) -> Option<&T> {
        if self.indicator == NULL_DATA {
            None
        } else {
            Some(&self.value)
        }
    }

    pub fn into_opt(self) -> Option<T> {
        if self.indicator == NULL_DATA {
            None
        } else {
            Some(self.value)
        }
    }
}

impl<T> Default for Nullable<T>
where
    T: Default,
{
    fn default() -> Self {
        Self::null()
    }
}

unsafe impl<T> CData for Nullable<T>
where
    T: Pod,
{
    fn cdata_type(&self) -> odbc_sys::CDataType {
        self.value.cdata_type()
    }

    fn indicator_ptr(&self) -> *const isize {
        &self.indicator as *const isize
    }

    fn value_ptr(&self) -> *const c_void {
        self.value.value_ptr()
    }

    fn buffer_length(&self) -> isize {
        0
    }
}

impl<T> HasDataType for Nullable<T>
where
    T: Pod + HasDataType,
{
    fn data_type(&self) -> crate::DataType {
        self.value.data_type()
    }
}

unsafe impl<T> CElement for Nullable<T>
where
    T: Pod,
{
    /// Does nothing. `T` is fixed size and therfore always complete.
    fn assert_completness(&self) {}
}

unsafe impl<T> CDataMut for Nullable<T>
where
    T: Pod,
{
    fn mut_indicator_ptr(&mut self) -> *mut isize {
        &mut self.indicator as *mut isize
    }

    fn mut_value_ptr(&mut self) -> *mut c_void {
        &mut self.value as *mut T as *mut c_void
    }
}

unsafe impl<T> OutputParameter for Nullable<T> where T: Pod + HasDataType {}

unsafe impl<T> FetchRowMember for Nullable<T>
where
    T: Pod,
{
    fn indicator(&self) -> Option<crate::buffers::Indicator> {
        Some(Indicator::from_isize(self.indicator))
    }
}