quack_rs/scalar/typed/fallible.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//! Closure-based scalar constructors whose closure can fail.
7//!
8//! Each `try_*` constructor mirrors its infallible namesake — same argument
9//! types, same NULL propagation, same registered signature — except that the
10//! closure returns `Result<R, E>`. An `Err` stops the chunk and is reported
11//! through `duckdb_scalar_function_set_error`, the same channel a panic and
12//! [`scalar_callback!`][crate::scalar_callback] use, so the query fails with
13//! `E`'s `Display` text.
14
15use std::fmt::Display;
16
17use crate::error::ExtensionError;
18use crate::scalar::builder::ScalarFunctionBuilder;
19use crate::scalar::typed::{ScalarOut, ScalarValue};
20use crate::scalar::typed_builder::TypedScalarFunctionBuilder;
21use crate::types::{NullHandling, TypeId};
22
23/// Turns a closure's error into the error the trampoline reports, verbatim.
24///
25/// An empty `Display` is replaced by a placeholder when it is reported; see
26/// [`ScalarFunctionInfo::set_error`][crate::scalar::ScalarFunctionInfo::set_error].
27pub(super) fn user_error<E: Display>(err: &E) -> ExtensionError {
28 ExtensionError::new(err.to_string())
29}
30
31impl ScalarFunctionBuilder {
32 /// A unary scalar function from a fallible closure, with SQL NULL
33 /// propagation.
34 ///
35 /// Like [`map1`][Self::map1], but the closure returns `Result<R, E>`.
36 /// `Ok(v)` writes `v`; return `Ok(None)` (with `R = Option<_>`) for SQL
37 /// NULL. A row whose argument is NULL yields NULL without calling the
38 /// closure, exactly as in `map1`.
39 ///
40 /// # What an `Err` does
41 ///
42 /// The first `Err` in a chunk stops processing that chunk: no later row is
43 /// passed to the closure. Its `Display` text is reported through the
44 /// scalar function's `set_error`, and `DuckDB` fails the whole query with
45 /// that message. Rows already written into the result vector are
46 /// discarded with the rest of the query — the statement returns an error,
47 /// never a partial result. (A client that is *streaming* a result may
48 /// already have fetched earlier chunks before the failing one is computed;
49 /// the fetch that reaches the failing chunk returns the error.)
50 ///
51 /// A panic in the closure is reported the same way.
52 ///
53 /// # Errors
54 ///
55 /// Returns an error if `name` is not a valid SQL identifier.
56 ///
57 /// # Example
58 ///
59 /// ```rust,no_run
60 /// use quack_rs::scalar::ScalarFunctionBuilder;
61 ///
62 /// # fn demo(con: libduckdb_sys::duckdb_connection)
63 /// # -> Result<(), quack_rs::error::ExtensionError> {
64 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
65 /// unsafe {
66 /// ScalarFunctionBuilder::try_map1("checked_square", |x: i64| {
67 /// x.checked_mul(x).ok_or_else(|| format!("{x} squared overflows BIGINT"))
68 /// })?
69 /// .register(con)
70 /// }
71 /// # }
72 /// ```
73 pub fn try_map1<A, R, E, F>(
74 name: &str,
75 f: F,
76 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
77 where
78 A: ScalarValue,
79 R: ScalarOut,
80 E: Display,
81 F: Fn(A) -> Result<R, E> + Send + Sync + 'static,
82 {
83 TypedScalarFunctionBuilder::from_exec(
84 name,
85 &[A::type_id()],
86 R::type_id(),
87 NullHandling::DefaultNullHandling,
88 Box::new(move |chunk, writer| {
89 // SAFETY: DuckDB declared one parameter, so column 0 exists and
90 // has the type `A::type_id()` named at registration.
91 let a = unsafe { chunk.reader(0) };
92 for row in 0..chunk.size() {
93 // SAFETY: `row` is within the chunk.
94 if unsafe { a.is_valid(row) } {
95 // SAFETY: the column's type was declared as `A`.
96 let value = f(unsafe { A::read(&a, row) }).map_err(|e| user_error(&e))?;
97 // SAFETY: the result vector's type was declared as `R`.
98 unsafe { R::write(writer, row, value) };
99 } else {
100 // SAFETY: `row` is within the output vector.
101 unsafe { writer.set_null(row) };
102 }
103 }
104 Ok(())
105 }),
106 )
107 }
108
109 /// A binary scalar function from a fallible closure, with SQL NULL
110 /// propagation.
111 ///
112 /// Like [`map2`][Self::map2], with `Err` handled as in
113 /// [`try_map1`][Self::try_map1]. A row with either argument NULL yields
114 /// NULL without calling the closure.
115 ///
116 /// # Errors
117 ///
118 /// Returns an error if `name` is not a valid SQL identifier.
119 ///
120 /// # Example
121 ///
122 /// ```rust,no_run
123 /// use quack_rs::scalar::ScalarFunctionBuilder;
124 ///
125 /// # fn demo(con: libduckdb_sys::duckdb_connection)
126 /// # -> Result<(), quack_rs::error::ExtensionError> {
127 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
128 /// unsafe {
129 /// ScalarFunctionBuilder::try_map2("strict_div", |a: i64, b: i64| {
130 /// a.checked_div(b).ok_or("strict_div: division by zero")
131 /// })?
132 /// .register(con)
133 /// }
134 /// # }
135 /// ```
136 // As for `map2`: the `&& -> ||` mutant of the per-row NULL test lives in a
137 // closure only DuckDB's executor runs. It is killed end to end by
138 // `try_closures_propagate_null_arguments` in
139 // `tests/ffi_roundtrip/typed_scalar_opt.rs`, which NULLs one argument at a
140 // time from a real column.
141 #[cfg_attr(test, mutants::skip)]
142 pub fn try_map2<A, B, R, E, F>(
143 name: &str,
144 f: F,
145 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
146 where
147 A: ScalarValue,
148 B: ScalarValue,
149 R: ScalarOut,
150 E: Display,
151 F: Fn(A, B) -> Result<R, E> + Send + Sync + 'static,
152 {
153 TypedScalarFunctionBuilder::from_exec(
154 name,
155 &[A::type_id(), B::type_id()],
156 R::type_id(),
157 NullHandling::DefaultNullHandling,
158 Box::new(move |chunk, writer| {
159 // SAFETY: two parameters were declared, so both columns exist
160 // with the types named at registration.
161 let (a, b) = unsafe { (chunk.reader(0), chunk.reader(1)) };
162 for row in 0..chunk.size() {
163 // SAFETY: `row` is within the chunk.
164 if unsafe { a.is_valid(row) && b.is_valid(row) } {
165 // SAFETY: the columns' types were declared as `A` and `B`.
166 let value = unsafe { f(A::read(&a, row), B::read(&b, row)) }
167 .map_err(|e| user_error(&e))?;
168 // SAFETY: the result vector's type was declared as `R`.
169 unsafe { R::write(writer, row, value) };
170 } else {
171 // SAFETY: `row` is within the output vector.
172 unsafe { writer.set_null(row) };
173 }
174 }
175 Ok(())
176 }),
177 )
178 }
179
180 /// A `VARCHAR`-argument scalar function from a fallible closure, with SQL
181 /// NULL propagation.
182 ///
183 /// Like [`map1_str`][Self::map1_str] — the closure borrows the string
184 /// straight out of the vector — with `Err` handled as in
185 /// [`try_map1`][Self::try_map1].
186 ///
187 /// # Errors
188 ///
189 /// Returns an error if `name` is not a valid SQL identifier.
190 ///
191 /// # Example
192 ///
193 /// ```rust,no_run
194 /// use quack_rs::scalar::ScalarFunctionBuilder;
195 ///
196 /// # fn demo(con: libduckdb_sys::duckdb_connection)
197 /// # -> Result<(), quack_rs::error::ExtensionError> {
198 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
199 /// unsafe {
200 /// // '' is NULL, 'x@y' is 'y', anything else fails the query.
201 /// ScalarFunctionBuilder::try_map1_str("email_domain", |s: &str| {
202 /// if s.is_empty() {
203 /// return Ok(None);
204 /// }
205 /// match s.split_once('@') {
206 /// Some((_, domain)) => Ok(Some(domain.to_owned())),
207 /// None => Err(format!("not an email address: {s:?}")),
208 /// }
209 /// })?
210 /// .register(con)
211 /// }
212 /// # }
213 /// ```
214 pub fn try_map1_str<R, E, F>(
215 name: &str,
216 f: F,
217 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
218 where
219 R: ScalarOut,
220 E: Display,
221 F: for<'a> Fn(&'a str) -> Result<R, E> + Send + Sync + 'static,
222 {
223 TypedScalarFunctionBuilder::from_exec(
224 name,
225 &[TypeId::Varchar],
226 R::type_id(),
227 NullHandling::DefaultNullHandling,
228 Box::new(move |chunk, writer| {
229 // SAFETY: one VARCHAR parameter was declared, so column 0 exists
230 // and holds VARCHAR.
231 let a = unsafe { chunk.reader(0) };
232 for row in 0..chunk.size() {
233 // SAFETY: `row` is within the chunk.
234 if unsafe { a.is_valid(row) } {
235 // SAFETY: the column was declared VARCHAR; the borrow
236 // ends before the chunk does.
237 let value = f(unsafe { a.read_str(row) }).map_err(|e| user_error(&e))?;
238 // SAFETY: the result vector's type was declared as `R`.
239 unsafe { R::write(writer, row, value) };
240 } else {
241 // SAFETY: `row` is within the output vector.
242 unsafe { writer.set_null(row) };
243 }
244 }
245 Ok(())
246 }),
247 )
248 }
249
250 /// A two-`VARCHAR` scalar function from a fallible closure, with SQL NULL
251 /// propagation.
252 ///
253 /// Like [`map2_str`][Self::map2_str], with `Err` handled as in
254 /// [`try_map1`][Self::try_map1].
255 ///
256 /// # Errors
257 ///
258 /// Returns an error if `name` is not a valid SQL identifier.
259 ///
260 /// # Example
261 ///
262 /// ```rust,no_run
263 /// use quack_rs::scalar::ScalarFunctionBuilder;
264 ///
265 /// # fn demo(con: libduckdb_sys::duckdb_connection)
266 /// # -> Result<(), quack_rs::error::ExtensionError> {
267 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
268 /// unsafe {
269 /// ScalarFunctionBuilder::try_map2_str("field", |line: &str, key: &str| {
270 /// line.split(',')
271 /// .find_map(|kv| kv.strip_prefix(key)?.strip_prefix('='))
272 /// .map(str::to_owned)
273 /// .ok_or_else(|| format!("no field {key:?}"))
274 /// })?
275 /// .register(con)
276 /// }
277 /// # }
278 /// ```
279 // As for `map2_str`: the `&& -> ||` mutant of the per-row NULL test lives
280 // in a closure only DuckDB's executor runs. It is killed end to end by
281 // `try_closures_propagate_null_arguments` in
282 // `tests/ffi_roundtrip/typed_scalar_opt.rs`.
283 #[cfg_attr(test, mutants::skip)]
284 pub fn try_map2_str<R, E, F>(
285 name: &str,
286 f: F,
287 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
288 where
289 R: ScalarOut,
290 E: Display,
291 F: for<'a, 'b> Fn(&'a str, &'b str) -> Result<R, E> + Send + Sync + 'static,
292 {
293 TypedScalarFunctionBuilder::from_exec(
294 name,
295 &[TypeId::Varchar, TypeId::Varchar],
296 R::type_id(),
297 NullHandling::DefaultNullHandling,
298 Box::new(move |chunk, writer| {
299 // SAFETY: two VARCHAR parameters were declared.
300 let (a, b) = unsafe { (chunk.reader(0), chunk.reader(1)) };
301 for row in 0..chunk.size() {
302 // SAFETY: `row` is within the chunk.
303 if unsafe { a.is_valid(row) && b.is_valid(row) } {
304 // SAFETY: both columns were declared VARCHAR.
305 let value = unsafe { f(a.read_str(row), b.read_str(row)) }
306 .map_err(|e| user_error(&e))?;
307 // SAFETY: the result vector's type was declared as `R`.
308 unsafe { R::write(writer, row, value) };
309 } else {
310 // SAFETY: `row` is within the output vector.
311 unsafe { writer.set_null(row) };
312 }
313 }
314 Ok(())
315 }),
316 )
317 }
318}