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
use std::{ffi::CStr, ops::Deref, sync::Arc};

use time::{Date, Duration, PrimitiveDateTime, Time};

use crate::{
    arrow::ArrowResultHandle,
    connection::ConnectionHandle,
    ffi,
    types::TypeId,
    value::{
        date_to_duckdb_date, datetime_to_duckdb_timestamp, i128_to_duckdb_hugeint,
        time_to_duckdb_time, DuckDbDecimal,
    },
};

#[derive(Debug)]
pub struct PreparedStatementHandle {
    handle: ffi::duckdb_prepared_statement,
    _parent: Arc<ConnectionHandle>,
}

impl Deref for PreparedStatementHandle {
    type Target = ffi::duckdb_prepared_statement;

    fn deref(&self) -> &Self::Target {
        &self.handle
    }
}

impl Drop for PreparedStatementHandle {
    fn drop(&mut self) {
        unsafe { self.destroy() }
    }
}

/// # Safety
/// * All parameter indices must be in range
impl PreparedStatementHandle {
    /// # Safety
    /// Takes ownership
    pub unsafe fn from_raw(
        raw: ffi::duckdb_prepared_statement,
        parent: Arc<ConnectionHandle>,
    ) -> Arc<Self> {
        Arc::new(Self {
            handle: raw,
            _parent: parent,
        })
    }
    /// # Safety
    /// Does not consider utilization. Normally, let Rust handle this automatically.
    pub unsafe fn destroy(&mut self) {
        ffi::duckdb_destroy_prepare(&mut self.handle);
    }
    pub fn nparams(&self) -> u64 {
        unsafe { ffi::duckdb_nparams(self.handle) }
    }
    /// # Safety
    /// * `param_idx` must be in range
    pub unsafe fn param_type(&self, param_idx: u64) -> TypeId {
        let ty = ffi::duckdb_param_type(self.handle, param_idx);
        TypeId::from_raw(ty).expect("invalid duckdb type")
    }
    pub fn clear_bindings(&self) -> Result<(), ()> {
        unsafe {
            let res = ffi::duckdb_clear_bindings(self.handle);
            if res != ffi::DuckDBSuccess {
                return Err(());
            }
            Ok(())
        }
    }

    pub unsafe fn bind_bool(&self, param_idx: u64, val: bool) -> Result<(), ()> {
        if ffi::duckdb_bind_boolean(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_i8(&self, param_idx: u64, val: i8) -> Result<(), ()> {
        if ffi::duckdb_bind_int8(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_i16(&self, param_idx: u64, val: i16) -> Result<(), ()> {
        if ffi::duckdb_bind_int16(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_i32(&self, param_idx: u64, val: i32) -> Result<(), ()> {
        if ffi::duckdb_bind_int32(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_i64(&self, param_idx: u64, val: i64) -> Result<(), ()> {
        if ffi::duckdb_bind_int64(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_i128(&self, param_idx: u64, val: i128) -> Result<(), ()> {
        let hugeint = i128_to_duckdb_hugeint(val);
        if ffi::duckdb_bind_hugeint(self.handle, param_idx, hugeint) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_decimal(&self, param_idx: u64, val: DuckDbDecimal) -> Result<(), ()> {
        let decimal = val.into();
        if ffi::duckdb_bind_decimal(self.handle, param_idx, decimal) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_u8(&self, param_idx: u64, val: u8) -> Result<(), ()> {
        if ffi::duckdb_bind_uint8(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_u16(&self, param_idx: u64, val: u16) -> Result<(), ()> {
        if ffi::duckdb_bind_uint16(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_u32(&self, param_idx: u64, val: u32) -> Result<(), ()> {
        if ffi::duckdb_bind_uint32(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_u64(&self, param_idx: u64, val: u64) -> Result<(), ()> {
        if ffi::duckdb_bind_uint64(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_f32(&self, param_idx: u64, val: f32) -> Result<(), ()> {
        if ffi::duckdb_bind_float(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_f64(&self, param_idx: u64, val: f64) -> Result<(), ()> {
        if ffi::duckdb_bind_double(self.handle, param_idx, val) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_date(&self, param_idx: u64, val: Date) -> Result<(), ()> {
        let date = date_to_duckdb_date(&val);
        if ffi::duckdb_bind_date(self.handle, param_idx, ffi::duckdb_to_date(date))
            != ffi::DuckDBSuccess
        {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_time(&self, param_idx: u64, val: Time) -> Result<(), ()> {
        let time = time_to_duckdb_time(&val);
        if ffi::duckdb_bind_time(self.handle, param_idx, ffi::duckdb_to_time(time))
            != ffi::DuckDBSuccess
        {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_timestamp(&self, param_idx: u64, val: PrimitiveDateTime) -> Result<(), ()> {
        let ts = datetime_to_duckdb_timestamp(&val);
        if ffi::duckdb_bind_timestamp(self.handle, param_idx, ffi::duckdb_to_timestamp(ts))
            != ffi::DuckDBSuccess
        {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_interval(&self, param_idx: u64, val: Duration) -> Result<(), ()> {
        todo!()
    }
    pub unsafe fn bind_varchar(&self, param_idx: u64, val: &CStr) -> Result<(), ()> {
        if ffi::duckdb_bind_varchar(self.handle, param_idx, val.as_ptr()) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_varchar_str(&self, param_idx: u64, val: &str) -> Result<(), ()> {
        let b = val.as_bytes();
        if ffi::duckdb_bind_varchar_length(self.handle, param_idx, b.as_ptr() as _, b.len() as u64)
            != ffi::DuckDBSuccess
        {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_blob(&self, param_idx: u64, data: &[u8]) -> Result<(), ()> {
        if ffi::duckdb_bind_blob(
            self.handle,
            param_idx,
            data.as_ptr() as _,
            data.len() as u64,
        ) != ffi::DuckDBSuccess
        {
            return Err(());
        }
        Ok(())
    }
    pub unsafe fn bind_null(&self, param_idx: u64) -> Result<(), ()> {
        if ffi::duckdb_bind_null(self.handle, param_idx) != ffi::DuckDBSuccess {
            return Err(());
        }
        Ok(())
    }
    pub fn execute(self: &Arc<Self>) -> Result<ArrowResultHandle, String> {
        unsafe {
            let mut result: ffi::duckdb_arrow = std::mem::zeroed();
            let r = ffi::duckdb_execute_prepared_arrow(self.handle, &mut result);
            let h = ArrowResultHandle::from_raw_statement(result, self.clone());
            if r != ffi::DuckDBSuccess {
                return Err(h.error());
            }
            Ok(h)
        }
    }
}