quack_rs/scalar/typed/ternary.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//! Three-argument closure-based scalar constructors.
7//!
8//! [`map3`][ScalarFunctionBuilder::map3] and
9//! [`try_map3`][ScalarFunctionBuilder::try_map3] extend
10//! [`map2`][ScalarFunctionBuilder::map2] / [`try_map2`][ScalarFunctionBuilder::try_map2]
11//! by one [`ScalarValue`] column — enough for `clamp(x, lo, hi)`,
12//! `lerp(a, b, t)` and similar functions without dropping to
13//! [`scalar_callback!`][crate::scalar_callback].
14
15use std::fmt::Display;
16
17use super::fallible::user_error;
18use crate::error::ExtensionError;
19use crate::scalar::builder::ScalarFunctionBuilder;
20use crate::scalar::typed::{ScalarOut, ScalarValue};
21use crate::scalar::typed_builder::TypedScalarFunctionBuilder;
22use crate::types::NullHandling;
23
24impl ScalarFunctionBuilder {
25 /// A ternary scalar function from a safe closure, with SQL NULL
26 /// propagation.
27 ///
28 /// A row with any argument NULL yields NULL without calling the closure.
29 /// Return `Option<R>` to produce NULL for other rows too.
30 ///
31 /// # Errors
32 ///
33 /// Returns an error if `name` is not a valid SQL identifier.
34 ///
35 /// # Example
36 ///
37 /// ```rust,no_run
38 /// use quack_rs::scalar::ScalarFunctionBuilder;
39 ///
40 /// # fn demo(con: libduckdb_sys::duckdb_connection)
41 /// # -> Result<(), quack_rs::error::ExtensionError> {
42 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
43 /// unsafe {
44 /// ScalarFunctionBuilder::map3("lerp", |a: f64, b: f64, t: f64| a + (b - a) * t)?
45 /// .register(con)
46 /// }
47 /// # }
48 /// ```
49 pub fn map3<A, B, C, R, F>(
50 name: &str,
51 f: F,
52 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
53 where
54 A: ScalarValue,
55 B: ScalarValue,
56 C: ScalarValue,
57 R: ScalarOut,
58 F: Fn(A, B, C) -> R + Send + Sync + 'static,
59 {
60 Self::try_map3(name, move |a: A, b: B, c: C| {
61 Ok::<R, std::convert::Infallible>(f(a, b, c))
62 })
63 }
64
65 /// A ternary scalar function from a fallible closure, with SQL NULL
66 /// propagation.
67 ///
68 /// Like [`map3`][Self::map3], with `Err` handled as in
69 /// [`try_map1`][Self::try_map1]: the first `Err` stops the chunk and fails
70 /// the query with its `Display` text.
71 ///
72 /// # Errors
73 ///
74 /// Returns an error if `name` is not a valid SQL identifier.
75 ///
76 /// # Example
77 ///
78 /// ```rust,no_run
79 /// use quack_rs::scalar::ScalarFunctionBuilder;
80 ///
81 /// # fn demo(con: libduckdb_sys::duckdb_connection)
82 /// # -> Result<(), quack_rs::error::ExtensionError> {
83 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
84 /// unsafe {
85 /// ScalarFunctionBuilder::try_map3("strict_clamp", |x: i64, lo: i64, hi: i64| {
86 /// if lo > hi {
87 /// Err(format!("strict_clamp: empty range [{lo}, {hi}]"))
88 /// } else {
89 /// Ok(x.clamp(lo, hi))
90 /// }
91 /// })?
92 /// .register(con)
93 /// }
94 /// # }
95 /// ```
96 // As for `map2`: the `&& -> ||` mutants of the per-row NULL test live in a
97 // closure only DuckDB's executor runs. They are killed end to end by
98 // `map3_propagates_a_null_in_any_argument` in
99 // `tests/ffi_roundtrip/typed_scalar_opt.rs`, which NULLs each argument in
100 // turn from a real column.
101 #[cfg_attr(test, mutants::skip)]
102 pub fn try_map3<A, B, C, R, E, F>(
103 name: &str,
104 f: F,
105 ) -> Result<TypedScalarFunctionBuilder, ExtensionError>
106 where
107 A: ScalarValue,
108 B: ScalarValue,
109 C: ScalarValue,
110 R: ScalarOut,
111 E: Display,
112 F: Fn(A, B, C) -> Result<R, E> + Send + Sync + 'static,
113 {
114 TypedScalarFunctionBuilder::from_exec(
115 name,
116 &[A::type_id(), B::type_id(), C::type_id()],
117 R::type_id(),
118 NullHandling::DefaultNullHandling,
119 Box::new(move |chunk, writer| {
120 // SAFETY: three parameters were declared, so all three columns
121 // exist with the types named at registration.
122 let (a, b, c) = unsafe { (chunk.reader(0), chunk.reader(1), chunk.reader(2)) };
123 for row in 0..chunk.size() {
124 // SAFETY: `row` is within the chunk.
125 if unsafe { a.is_valid(row) && b.is_valid(row) && c.is_valid(row) } {
126 // SAFETY: the columns' types were declared as `A`, `B`
127 // and `C`.
128 let value =
129 unsafe { f(A::read(&a, row), B::read(&b, row), C::read(&c, row)) }
130 .map_err(|e| user_error(&e))?;
131 // SAFETY: the result vector's type was declared as `R`.
132 unsafe { R::write(writer, row, value) };
133 } else {
134 // SAFETY: `row` is within the output vector.
135 unsafe { writer.set_null(row) };
136 }
137 }
138 Ok(())
139 }),
140 )
141 }
142}