quack_rs/value/scalars.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//! The scalar constructors other than the temporal ones (`value/temporal.rs`):
7//! numbers, text, `BLOB`, `UUID`, `DECIMAL` and SQL `NULL`.
8
9use std::os::raw::c_char;
10
11use super::{hugeint_from_i128, uhugeint_from_u128, validate_decimal, Value};
12use crate::error::ExtensionError;
13
14impl Value {
15 // ── Construction ─────────────────────────────────────────────────────
16 //
17 // Needed for `ConfigOptionBuilder::default_value` and anywhere else DuckDB
18 // wants a `duckdb_value` rather than a Rust scalar.
19
20 /// Creates a `BOOLEAN` value.
21 #[inline]
22 #[must_use]
23 pub fn boolean(value: bool) -> Self {
24 // SAFETY: duckdb_create_bool accepts any bool and returns an owned value.
25 Self {
26 // SAFETY: the argument is a plain value DuckDB accepts unconditionally, and
27 // the returned handle is owned by this `Value`.
28 raw: unsafe { libduckdb_sys::duckdb_create_bool(value) },
29 }
30 }
31
32 /// Creates a `BIGINT` value.
33 #[inline]
34 #[must_use]
35 pub fn bigint(value: i64) -> Self {
36 // SAFETY: duckdb_create_int64 accepts any i64 and returns an owned value.
37 Self {
38 // SAFETY: the argument is a plain value DuckDB accepts unconditionally, and
39 // the returned handle is owned by this `Value`.
40 raw: unsafe { libduckdb_sys::duckdb_create_int64(value) },
41 }
42 }
43
44 /// Creates a `DOUBLE` value.
45 #[inline]
46 #[must_use]
47 pub fn double(value: f64) -> Self {
48 // SAFETY: duckdb_create_double accepts any f64 and returns an owned value.
49 Self {
50 // SAFETY: the argument is a plain value DuckDB accepts unconditionally, and
51 // the returned handle is owned by this `Value`.
52 raw: unsafe { libduckdb_sys::duckdb_create_double(value) },
53 }
54 }
55
56 /// Creates a `VARCHAR` value.
57 ///
58 /// The length is passed explicitly, so no `CString` conversion can fail and
59 /// `DuckDB` stores every byte — but note that [`as_str`][Self::as_str] reads
60 /// back through a NUL-terminated C string and will truncate at an interior
61 /// NUL.
62 #[must_use]
63 pub fn varchar(value: &str) -> Self {
64 // SAFETY: `value` is valid for the duration of the call; DuckDB copies it.
65 let raw = unsafe {
66 libduckdb_sys::duckdb_create_varchar_length(
67 value.as_ptr().cast::<c_char>(),
68 libduckdb_sys::idx_t::try_from(value.len()).unwrap_or(libduckdb_sys::idx_t::MAX),
69 )
70 };
71 Self { raw }
72 }
73
74 /// Creates a `UUID` value from its **textual** 128 bits, matching
75 /// [`VectorWriter::write_uuid`][crate::vector::VectorWriter::write_uuid]
76 /// and [`as_uuid`][Self::as_uuid].
77 ///
78 /// `DuckDB` applies its internal top-bit flip itself here, so these are the
79 /// bits the value renders as — not the raw `HUGEINT` a `UUID` vector holds.
80 #[inline]
81 #[must_use]
82 pub fn uuid(bits: u128) -> Self {
83 let raw = uhugeint_from_u128(bits);
84 // SAFETY: duckdb_create_uuid accepts any 128-bit pattern.
85 Self {
86 // SAFETY: the argument is a plain value DuckDB accepts unconditionally, and
87 // the returned handle is owned by this `Value`.
88 raw: unsafe { libduckdb_sys::duckdb_create_uuid(raw) },
89 }
90 }
91
92 /// Creates a SQL `NULL` value.
93 #[inline]
94 #[must_use]
95 pub fn null_value() -> Self {
96 // SAFETY: duckdb_create_null_value takes no arguments and returns an
97 // owned SQLNULL value.
98 Self {
99 // SAFETY: the argument is a plain value DuckDB accepts unconditionally, and
100 // the returned handle is owned by this `Value`.
101 raw: unsafe { libduckdb_sys::duckdb_create_null_value() },
102 }
103 }
104
105 // ── The rest of DuckDB's scalar constructors ─────────────────────────
106 //
107 // Every one of these lives in the *stable* prefix of `duckdb_ext_api_v1`,
108 // so they need no feature gate and work against every DuckDB from v1.2.0.
109
110 /// Creates a `TINYINT` value.
111 #[inline]
112 #[must_use]
113 pub fn tinyint(value: i8) -> Self {
114 Self {
115 // SAFETY: a plain scalar DuckDB accepts unconditionally; the
116 // returned handle is owned by this `Value`.
117 raw: unsafe { libduckdb_sys::duckdb_create_int8(value) },
118 }
119 }
120
121 /// Creates a `SMALLINT` value.
122 #[inline]
123 #[must_use]
124 pub fn smallint(value: i16) -> Self {
125 Self {
126 // SAFETY: see [`tinyint`][Self::tinyint].
127 raw: unsafe { libduckdb_sys::duckdb_create_int16(value) },
128 }
129 }
130
131 /// Creates an `INTEGER` value.
132 #[inline]
133 #[must_use]
134 pub fn integer(value: i32) -> Self {
135 Self {
136 // SAFETY: see [`tinyint`][Self::tinyint].
137 raw: unsafe { libduckdb_sys::duckdb_create_int32(value) },
138 }
139 }
140
141 /// Creates a `UTINYINT` value.
142 #[inline]
143 #[must_use]
144 pub fn utinyint(value: u8) -> Self {
145 Self {
146 // SAFETY: see [`tinyint`][Self::tinyint].
147 raw: unsafe { libduckdb_sys::duckdb_create_uint8(value) },
148 }
149 }
150
151 /// Creates a `USMALLINT` value.
152 #[inline]
153 #[must_use]
154 pub fn usmallint(value: u16) -> Self {
155 Self {
156 // SAFETY: see [`tinyint`][Self::tinyint].
157 raw: unsafe { libduckdb_sys::duckdb_create_uint16(value) },
158 }
159 }
160
161 /// Creates a `UINTEGER` value.
162 #[inline]
163 #[must_use]
164 pub fn uinteger(value: u32) -> Self {
165 Self {
166 // SAFETY: see [`tinyint`][Self::tinyint].
167 raw: unsafe { libduckdb_sys::duckdb_create_uint32(value) },
168 }
169 }
170
171 /// Creates a `UBIGINT` value.
172 #[inline]
173 #[must_use]
174 pub fn ubigint(value: u64) -> Self {
175 Self {
176 // SAFETY: see [`tinyint`][Self::tinyint].
177 raw: unsafe { libduckdb_sys::duckdb_create_uint64(value) },
178 }
179 }
180
181 /// Creates a `HUGEINT` value.
182 #[inline]
183 #[must_use]
184 pub fn hugeint(value: i128) -> Self {
185 Self {
186 // SAFETY: see [`tinyint`][Self::tinyint].
187 raw: unsafe { libduckdb_sys::duckdb_create_hugeint(hugeint_from_i128(value)) },
188 }
189 }
190
191 /// Creates a `UHUGEINT` value.
192 #[inline]
193 #[must_use]
194 pub fn uhugeint(value: u128) -> Self {
195 Self {
196 // SAFETY: see [`tinyint`][Self::tinyint].
197 raw: unsafe { libduckdb_sys::duckdb_create_uhugeint(uhugeint_from_u128(value)) },
198 }
199 }
200
201 /// Creates a `FLOAT` value.
202 #[inline]
203 #[must_use]
204 pub fn float(value: f32) -> Self {
205 Self {
206 // SAFETY: see [`tinyint`][Self::tinyint].
207 raw: unsafe { libduckdb_sys::duckdb_create_float(value) },
208 }
209 }
210
211 /// Creates a `BLOB` value from arbitrary bytes.
212 ///
213 /// Unlike [`varchar`][Self::varchar] this is byte-exact in both directions:
214 /// [`as_blob`][Self::as_blob] returns what went in, NUL bytes and all.
215 #[must_use]
216 pub fn blob(bytes: &[u8]) -> Self {
217 // SAFETY: `bytes` is valid for the duration of the call; DuckDB copies it.
218 let raw = unsafe {
219 libduckdb_sys::duckdb_create_blob(
220 bytes.as_ptr(),
221 libduckdb_sys::idx_t::try_from(bytes.len()).unwrap_or(libduckdb_sys::idx_t::MAX),
222 )
223 };
224 Self { raw }
225 }
226
227 /// Creates a `DECIMAL(width, scale)` value from its unscaled integer.
228 ///
229 /// `unscaled` is the value multiplied by `10^scale` — `DECIMAL(18, 3)`
230 /// holding `1.234` has `unscaled == 1234`.
231 ///
232 /// # Errors
233 ///
234 /// - `width` is not in `1..=38`, or `scale > width`;
235 /// - `unscaled` has more than `width` digits (`|unscaled| >= 10^width`).
236 ///
237 /// All three are checked here, before `DuckDB` is called. For an
238 /// `unscaled` that does not fit the width's physical type,
239 /// `duckdb_create_decimal` throws (aborting the process); for one that
240 /// fits the physical type but not the width it stores a value the type
241 /// cannot hold; and one past `i64` with `width <= 18` kept only its low
242 /// 64 bits.
243 pub fn decimal(width: u8, scale: u8, unscaled: i128) -> Result<Self, ExtensionError> {
244 validate_decimal(width, scale, unscaled)?;
245 // SAFETY: a plain by-value struct, validated above so DuckDB's
246 // narrowing `NumericCast` cannot throw.
247 let raw = unsafe {
248 libduckdb_sys::duckdb_create_decimal(libduckdb_sys::duckdb_decimal {
249 width,
250 scale,
251 value: hugeint_from_i128(unscaled),
252 })
253 };
254 if raw.is_null() {
255 return Err(ExtensionError::new(format!(
256 "duckdb_create_decimal returned null for DECIMAL({width}, {scale}): \
257 width must be 1..=38 and scale must not exceed width"
258 )));
259 }
260 Ok(Self { raw })
261 }
262}