Skip to main content

quack_rs/query/
bind.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Binding a [`PreparedStatement`]'s parameters: the typed `bind_*` methods and `bind_value`.
7
8use libduckdb_sys::{
9    duckdb_bind_blob, duckdb_bind_boolean, duckdb_bind_double, duckdb_bind_int64, duckdb_bind_null,
10    duckdb_bind_varchar_length, idx_t, DuckDBSuccess,
11};
12
13use super::PreparedStatement;
14use crate::error::ExtensionError;
15use crate::types::TypeId;
16
17impl PreparedStatement {
18    /// Binds a `BIGINT` at 1-based `index`.
19    ///
20    /// # Errors
21    ///
22    /// Returns an error if `DuckDB` rejects the binding (bad index or type).
23    pub fn bind_i64(&self, index: usize, value: i64) -> Result<(), ExtensionError> {
24        // SAFETY: `self.statement` is valid for this value's lifetime.
25        self.check(
26            unsafe { duckdb_bind_int64(self.statement, index as idx_t, value) },
27            index,
28        )
29    }
30
31    /// Binds a `DOUBLE` at 1-based `index`.
32    ///
33    /// # Errors
34    ///
35    /// See [`bind_i64`][Self::bind_i64].
36    pub fn bind_f64(&self, index: usize, value: f64) -> Result<(), ExtensionError> {
37        // SAFETY: `self.statement` is valid for this value's lifetime.
38        self.check(
39            unsafe { duckdb_bind_double(self.statement, index as idx_t, value) },
40            index,
41        )
42    }
43
44    /// Binds a `BOOLEAN` at 1-based `index`.
45    ///
46    /// # Errors
47    ///
48    /// See [`bind_i64`][Self::bind_i64].
49    pub fn bind_bool(&self, index: usize, value: bool) -> Result<(), ExtensionError> {
50        // SAFETY: `self.statement` is valid for this value's lifetime.
51        self.check(
52            unsafe { duckdb_bind_boolean(self.statement, index as idx_t, value) },
53            index,
54        )
55    }
56
57    /// Binds a `VARCHAR` at 1-based `index`.
58    ///
59    /// The length is passed explicitly, so embedded NUL bytes are preserved and
60    /// no `CString` conversion can fail.
61    ///
62    /// # Errors
63    ///
64    /// See [`bind_i64`][Self::bind_i64].
65    pub fn bind_str(&self, index: usize, value: &str) -> Result<(), ExtensionError> {
66        crate::vector::string::check_string_len(value.len())
67            .map_err(|e| ExtensionError::new(format!("bind_str (parameter {index}): {e}")))?;
68        // SAFETY: `value` is valid for the duration of the call; the length is
69        // passed explicitly so the pointer need not be NUL-terminated.
70        let state = unsafe {
71            duckdb_bind_varchar_length(
72                self.statement,
73                index as idx_t,
74                value.as_ptr().cast::<std::os::raw::c_char>(),
75                idx_t::try_from(value.len()).unwrap_or(idx_t::MAX),
76            )
77        };
78        self.check(state, index)
79    }
80
81    /// Binds a `BLOB` at 1-based `index`.
82    ///
83    /// # Errors
84    ///
85    /// See [`bind_i64`][Self::bind_i64].
86    pub fn bind_blob(&self, index: usize, value: &[u8]) -> Result<(), ExtensionError> {
87        crate::vector::string::check_string_len(value.len())
88            .map_err(|e| ExtensionError::new(format!("bind_blob (parameter {index}): {e}")))?;
89        // SAFETY: `value` is valid for the duration of the call.
90        let state = unsafe {
91            duckdb_bind_blob(
92                self.statement,
93                index as idx_t,
94                value.as_ptr().cast::<std::os::raw::c_void>(),
95                idx_t::try_from(value.len()).unwrap_or(idx_t::MAX),
96            )
97        };
98        self.check(state, index)
99    }
100
101    /// Binds SQL `NULL` at 1-based `index`.
102    ///
103    /// # Errors
104    ///
105    /// See [`bind_i64`][Self::bind_i64].
106    pub fn bind_null(&self, index: usize) -> Result<(), ExtensionError> {
107        // SAFETY: `self.statement` is valid for this value's lifetime.
108        self.check(
109            unsafe { duckdb_bind_null(self.statement, index as idx_t) },
110            index,
111        )
112    }
113
114    /// Binds a `TINYINT` at 1-based `index`.
115    ///
116    /// # Errors
117    ///
118    /// See [`bind_i64`][Self::bind_i64].
119    pub fn bind_i8(&self, index: usize, value: i8) -> Result<(), ExtensionError> {
120        // SAFETY: `self.statement` is valid for this value's lifetime.
121        self.check(
122            unsafe { libduckdb_sys::duckdb_bind_int8(self.statement, index as idx_t, value) },
123            index,
124        )
125    }
126
127    /// Binds a `SMALLINT` at 1-based `index`.
128    ///
129    /// # Errors
130    ///
131    /// See [`bind_i64`][Self::bind_i64].
132    pub fn bind_i16(&self, index: usize, value: i16) -> Result<(), ExtensionError> {
133        // SAFETY: `self.statement` is valid for this value's lifetime.
134        self.check(
135            unsafe { libduckdb_sys::duckdb_bind_int16(self.statement, index as idx_t, value) },
136            index,
137        )
138    }
139
140    /// Binds an `INTEGER` at 1-based `index`.
141    ///
142    /// # Errors
143    ///
144    /// See [`bind_i64`][Self::bind_i64].
145    pub fn bind_i32(&self, index: usize, value: i32) -> Result<(), ExtensionError> {
146        // SAFETY: `self.statement` is valid for this value's lifetime.
147        self.check(
148            unsafe { libduckdb_sys::duckdb_bind_int32(self.statement, index as idx_t, value) },
149            index,
150        )
151    }
152
153    /// Binds a `UTINYINT` at 1-based `index`.
154    ///
155    /// # Errors
156    ///
157    /// See [`bind_i64`][Self::bind_i64].
158    pub fn bind_u8(&self, index: usize, value: u8) -> Result<(), ExtensionError> {
159        // SAFETY: `self.statement` is valid for this value's lifetime.
160        self.check(
161            unsafe { libduckdb_sys::duckdb_bind_uint8(self.statement, index as idx_t, value) },
162            index,
163        )
164    }
165
166    /// Binds a `USMALLINT` at 1-based `index`.
167    ///
168    /// # Errors
169    ///
170    /// See [`bind_i64`][Self::bind_i64].
171    pub fn bind_u16(&self, index: usize, value: u16) -> Result<(), ExtensionError> {
172        // SAFETY: `self.statement` is valid for this value's lifetime.
173        self.check(
174            unsafe { libduckdb_sys::duckdb_bind_uint16(self.statement, index as idx_t, value) },
175            index,
176        )
177    }
178
179    /// Binds a `UINTEGER` at 1-based `index`.
180    ///
181    /// # Errors
182    ///
183    /// See [`bind_i64`][Self::bind_i64].
184    pub fn bind_u32(&self, index: usize, value: u32) -> Result<(), ExtensionError> {
185        // SAFETY: `self.statement` is valid for this value's lifetime.
186        self.check(
187            unsafe { libduckdb_sys::duckdb_bind_uint32(self.statement, index as idx_t, value) },
188            index,
189        )
190    }
191
192    /// Binds a `UBIGINT` at 1-based `index`.
193    ///
194    /// # Errors
195    ///
196    /// See [`bind_i64`][Self::bind_i64].
197    pub fn bind_u64(&self, index: usize, value: u64) -> Result<(), ExtensionError> {
198        // SAFETY: `self.statement` is valid for this value's lifetime.
199        self.check(
200            unsafe { libduckdb_sys::duckdb_bind_uint64(self.statement, index as idx_t, value) },
201            index,
202        )
203    }
204
205    /// Binds a `FLOAT` at 1-based `index`.
206    ///
207    /// # Errors
208    ///
209    /// See [`bind_i64`][Self::bind_i64].
210    pub fn bind_f32(&self, index: usize, value: f32) -> Result<(), ExtensionError> {
211        // SAFETY: `self.statement` is valid for this value's lifetime.
212        self.check(
213            unsafe { libduckdb_sys::duckdb_bind_float(self.statement, index as idx_t, value) },
214            index,
215        )
216    }
217
218    /// Binds a `HUGEINT` at 1-based `index`.
219    ///
220    /// # Errors
221    ///
222    /// See [`bind_i64`][Self::bind_i64].
223    pub fn bind_i128(&self, index: usize, value: i128) -> Result<(), ExtensionError> {
224        let raw = crate::value::hugeint_from_i128(value);
225        // SAFETY: `self.statement` is valid for this value's lifetime.
226        self.check(
227            unsafe { libduckdb_sys::duckdb_bind_hugeint(self.statement, index as idx_t, raw) },
228            index,
229        )
230    }
231
232    /// Binds a `UHUGEINT` at 1-based `index`.
233    ///
234    /// # Errors
235    ///
236    /// See [`bind_i64`][Self::bind_i64].
237    pub fn bind_u128(&self, index: usize, value: u128) -> Result<(), ExtensionError> {
238        let raw = crate::value::uhugeint_from_u128(value);
239        // SAFETY: `self.statement` is valid for this value's lifetime.
240        self.check(
241            unsafe { libduckdb_sys::duckdb_bind_uhugeint(self.statement, index as idx_t, raw) },
242            index,
243        )
244    }
245
246    /// Binds a `DECIMAL(width, scale)` at 1-based `index`.
247    ///
248    /// `unscaled` is the value multiplied by `10^scale`.
249    ///
250    /// # Errors
251    ///
252    /// Returns an error, without calling `DuckDB`, when `width` is not in
253    /// `1..=38`, `scale > width`, or `unscaled` has more than `width` digits.
254    /// `duckdb_bind_decimal` validates none of these: a bad width or an
255    /// `unscaled` too wide for the physical type throws (aborting the
256    /// process), and for `width <= 18` it keeps only the low 64 bits of
257    /// `unscaled`, silently binding a different number. Otherwise see
258    /// [`bind_i64`][Self::bind_i64].
259    pub fn bind_decimal(
260        &self,
261        index: usize,
262        width: u8,
263        scale: u8,
264        unscaled: i128,
265    ) -> Result<(), ExtensionError> {
266        crate::value::validate_decimal(width, scale, unscaled)?;
267        let raw = libduckdb_sys::duckdb_decimal {
268            width,
269            scale,
270            value: crate::value::hugeint_from_i128(unscaled),
271        };
272        // SAFETY: `self.statement` is valid for this value's lifetime, and the
273        // decimal was validated above so `Value::DECIMAL` cannot throw.
274        self.check(
275            unsafe { libduckdb_sys::duckdb_bind_decimal(self.statement, index as idx_t, raw) },
276            index,
277        )
278    }
279
280    /// Binds a `DATE` at 1-based `index`, as days since 1970-01-01.
281    ///
282    /// Every `i32` is accepted, as by [`Value::date`][crate::value::Value::date]:
283    /// `DuckDB` renders any day count without failing. Days outside the range
284    /// its SQL produces (`i32::MIN` renders as `5877642-06-23 (BC)`) come back
285    /// as text `DuckDB` cannot parse again.
286    ///
287    /// # Errors
288    ///
289    /// See [`bind_i64`][Self::bind_i64].
290    pub fn bind_date(&self, index: usize, days: i32) -> Result<(), ExtensionError> {
291        // SAFETY: `self.statement` is valid for this value's lifetime.
292        self.check(
293            unsafe {
294                libduckdb_sys::duckdb_bind_date(
295                    self.statement,
296                    index as idx_t,
297                    libduckdb_sys::duckdb_date { days },
298                )
299            },
300            index,
301        )
302    }
303
304    /// Binds a `TIME` at 1-based `index`, as microseconds since midnight.
305    ///
306    /// # Errors
307    ///
308    /// See [`bind_i64`][Self::bind_i64]; also refuses, before calling `DuckDB`,
309    /// a value outside `0..=86_400_000_000` (`00:00:00`–`24:00:00`).
310    /// `duckdb_bind_time` checks nothing, and rendering such a value crashed
311    /// the process (`i64::MIN`) or invalidated the database (`i64::MAX`).
312    pub fn bind_time(&self, index: usize, micros: i64) -> Result<(), ExtensionError> {
313        check_temporal(
314            TypeId::Time,
315            micros,
316            "bind_time",
317            index,
318            "00:00:00 to 24:00:00",
319        )?;
320        // SAFETY: `self.statement` is valid for this value's lifetime.
321        self.check(
322            unsafe {
323                libduckdb_sys::duckdb_bind_time(
324                    self.statement,
325                    index as idx_t,
326                    libduckdb_sys::duckdb_time { micros },
327                )
328            },
329            index,
330        )
331    }
332
333    /// Binds a `TIMESTAMP` at 1-based `index`, as microseconds since the epoch.
334    ///
335    /// # Errors
336    ///
337    /// See [`bind_i64`][Self::bind_i64]; also refuses, before calling `DuckDB`,
338    /// a value below `290309-12-22 (BC)` other than `-infinity` — the range of
339    /// [`Value::timestamp`][crate::value::Value::timestamp]. `DuckDB` stores
340    /// such a value unchecked and then fails every read of it.
341    pub fn bind_timestamp(&self, index: usize, micros: i64) -> Result<(), ExtensionError> {
342        check_temporal(
343            TypeId::Timestamp,
344            micros,
345            "bind_timestamp",
346            index,
347            "290309-12-22 (BC) 00:00:00 up to the maximum, or ±infinity",
348        )?;
349        // SAFETY: `self.statement` is valid for this value's lifetime.
350        self.check(
351            unsafe {
352                libduckdb_sys::duckdb_bind_timestamp(
353                    self.statement,
354                    index as idx_t,
355                    libduckdb_sys::duckdb_timestamp { micros },
356                )
357            },
358            index,
359        )
360    }
361
362    /// Binds a `TIMESTAMP WITH TIME ZONE` at 1-based `index`, as microseconds
363    /// since the epoch.
364    ///
365    /// # Errors
366    ///
367    /// See [`bind_i64`][Self::bind_i64]; also refuses the out-of-range values
368    /// [`bind_timestamp`][Self::bind_timestamp] refuses.
369    pub fn bind_timestamp_tz(&self, index: usize, micros: i64) -> Result<(), ExtensionError> {
370        check_temporal(
371            TypeId::TimestampTz,
372            micros,
373            "bind_timestamp_tz",
374            index,
375            "290309-12-22 (BC) 00:00:00 up to the maximum, or ±infinity",
376        )?;
377        // SAFETY: `self.statement` is valid for this value's lifetime.
378        self.check(
379            unsafe {
380                libduckdb_sys::duckdb_bind_timestamp_tz(
381                    self.statement,
382                    index as idx_t,
383                    libduckdb_sys::duckdb_timestamp { micros },
384                )
385            },
386            index,
387        )
388    }
389
390    /// Binds an `INTERVAL` at 1-based `index`.
391    ///
392    /// # Errors
393    ///
394    /// See [`bind_i64`][Self::bind_i64].
395    pub fn bind_interval(
396        &self,
397        index: usize,
398        value: crate::interval::DuckInterval,
399    ) -> Result<(), ExtensionError> {
400        // SAFETY: `self.statement` is valid for this value's lifetime.
401        self.check(
402            unsafe {
403                libduckdb_sys::duckdb_bind_interval(
404                    self.statement,
405                    index as idx_t,
406                    libduckdb_sys::duckdb_interval {
407                        months: value.months,
408                        days: value.days,
409                        micros: value.micros,
410                    },
411                )
412            },
413            index,
414        )
415    }
416
417    /// Binds an arbitrary [`Value`][crate::value::Value] at 1-based `index`.
418    ///
419    /// This is the escape hatch for everything the typed `bind_*` methods do
420    /// not cover — `STRUCT`, `LIST`, `MAP`, `ARRAY`, `UNION`, `ENUM`, `UUID`,
421    /// `BIT`, and any type a future `DuckDB` adds. `DuckDB` copies the value, so
422    /// `value` may be dropped immediately afterwards.
423    ///
424    /// # Errors
425    ///
426    /// See [`bind_i64`][Self::bind_i64].
427    ///
428    /// # Example
429    ///
430    /// ```rust,no_run
431    /// use quack_rs::types::{LogicalType, TypeId};
432    /// use quack_rs::value::Value;
433    ///
434    /// # fn demo(stmt: &quack_rs::query::PreparedStatement)
435    /// # -> Result<(), quack_rs::error::ExtensionError> {
436    /// let ty = LogicalType::list(TypeId::BigInt);
437    /// let list = Value::list_value(&ty, &[Value::bigint(1), Value::bigint(2)])?;
438    /// stmt.bind_value(1, &list)?;
439    /// # Ok(())
440    /// # }
441    /// ```
442    pub fn bind_value(
443        &self,
444        index: usize,
445        value: &crate::value::Value,
446    ) -> Result<(), ExtensionError> {
447        if value.is_null() {
448            return Err(ExtensionError::new(format!(
449                "bind_value: the Value at parameter {index} has a null handle"
450            )));
451        }
452        // SAFETY: `self.statement` is valid for this value's lifetime, and
453        // `value` outlives the call (DuckDB copies it).
454        self.check(
455            unsafe {
456                libduckdb_sys::duckdb_bind_value(self.statement, index as idx_t, value.as_raw())
457            },
458            index,
459        )
460    }
461
462    fn check(
463        &self,
464        state: libduckdb_sys::duckdb_state,
465        index: usize,
466    ) -> Result<(), ExtensionError> {
467        if state == DuckDBSuccess {
468            Ok(())
469        } else {
470            Err(ExtensionError::new(format!(
471                "failed to bind parameter {index} (statement has {} parameter(s))",
472                self.parameter_count()
473            )))
474        }
475    }
476}
477
478/// Refuses a 64-bit temporal payload outside the range `DuckDB` can render,
479/// before it is bound; `what` and `range` name the method and the range.
480fn check_temporal(
481    type_id: TypeId,
482    v: i64,
483    what: &str,
484    index: usize,
485    range: &str,
486) -> Result<(), ExtensionError> {
487    if crate::value::temporal_checks::temporal_in_range(type_id, v) {
488        Ok(())
489    } else {
490        Err(ExtensionError::new(format!(
491            "{what} (parameter {index}): {v} is outside DuckDB's range for {} ({range}); \
492             DuckDB would bind it unchecked and then crash, abort or fail every read of it",
493            type_id.sql_name()
494        )))
495    }
496}