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
//! User-defined DuckDB functions: scalar functions and table functions.
//!
//! Requires the `udf` feature.
//!
//! Two kinds of function can be registered on a [`Connection`](crate::connection::Connection):
//!
//! - **Scalar functions** compute one value per row, for use in a `SELECT` list
//! or `WHERE` clause: `SELECT my_func(x) FROM t`.
//! - **Table functions** produce rows and columns, for use in a `FROM` clause:
//! `SELECT * FROM my_func(1, 2)`.
//!
//! The [`duckdb_scalar`](crate::duckdb_scalar) and
//! [`duckdb_table_function`](crate::duckdb_table_function) attribute macros turn
//! an ordinary Rust function into either kind without requiring any `unsafe` code
//! or manual vector handling. Parameter and return types are inferred from the
//! Rust signature via [`types::DuckLogicalType`](crate::types::DuckLogicalType) —
//! any type that already round-trips through [`AppendAble`](crate::AppendAble)
//! (all the integer widths, floats, `String`/`&str`, `bool`, …) works here too,
//! with no extra type table for the macros to maintain.
//!
//! # Scalar functions
//!
//! ```
//! use better_duck_core::{connection::Connection, duckdb_scalar};
//!
//! /// Repeats `s` `n` times.
//! #[duckdb_scalar]
//! fn repeat_str(s: &str, n: i32) -> String {
//! s.repeat(n.max(0) as usize)
//! }
//!
//! /// `Option` parameters/returns propagate `NULL` explicitly.
//! #[duckdb_scalar]
//! fn double_or_null(x: Option<i32>) -> Option<i32> {
//! x.map(|v| v * 2)
//! }
//!
//! /// A `Result<T, E>` return fails the query with `E`'s message on `Err`.
//! #[duckdb_scalar(name = "to_int")]
//! fn parse_int(s: &str) -> Result<i32, std::num::ParseIntError> {
//! s.parse()
//! }
//!
//! # fn main() -> better_duck_core::error::Result<()> {
//! let mut conn = Connection::open_in_memory()?;
//! repeat_str::register(&mut conn)?;
//! parse_int::register(&mut conn)?;
//!
//! let mut result = conn.execute("SELECT repeat_str('ab', 3) AS r")?;
//! assert_eq!(result.next().unwrap()?.get("r"), Some(&better_duck_core::types::value::DuckValue::text("ababab")));
//! # Ok(())
//! # }
//! ```
//!
//! # Table functions
//!
//! The function returns `impl Iterator<Item = T> + Send` — `T` for a single
//! column, or a tuple `(A, B, ...)` for several. DuckDB pulls rows in chunks, so
//! the iterator is driven lazily and may be scanned across several calls.
//!
//! ```
//! use better_duck_core::{connection::Connection, duckdb_table_function};
//!
//! /// The integers in `[start, stop)`.
//! #[duckdb_table_function(name = "series", columns("n"))]
//! fn series(start: i64, stop: i64) -> impl Iterator<Item = i64> + Send {
//! start..stop
//! }
//!
//! # fn main() -> better_duck_core::error::Result<()> {
//! let mut conn = Connection::open_in_memory()?;
//! series::register(&mut conn)?;
//! let mut result = conn.execute("SELECT sum(n) AS total FROM series(1, 101)")?;
//! assert_eq!(result.next().unwrap()?.get("total"), Some(&better_duck_core::types::value::DuckValue::HugeInt(5050)));
//! # Ok(())
//! # }
//! ```
//!
//! # Attribute options
//!
//! | option | scalar | table | meaning |
//! |---|---|---|---|
//! | `name = "sql_name"` | yes | yes | the SQL function name (defaults to the Rust fn's name) |
//! | `crate = ::path` | yes | yes | re-export escape hatch for generated code's `::better_duck_core` path |
//! | `volatile` | yes | — | disables DuckDB's zero-argument constant-folding |
//! | `columns("a", "b")` | — | yes | result column names (defaults: the fn name for one column, `column_0`, `column_1`, … for several) |
//!
//! `special_handling` (whether `NULL` inputs still invoke the function) is
//! inferred automatically: present whenever any parameter is `Option<T>`.
//!
//! # Panics and `panic = "abort"`
//!
//! Callback panics are caught and reported to DuckDB as a query error whenever
//! the crate is built with `panic = "unwind"` (the default for `dev` and `test`
//! profiles). Under a `panic = "abort"` build — this workspace's own `release`
//! profile, for instance — a panicking user-defined function aborts the process
//! instead: `catch_unwind` cannot catch anything once unwinding itself has been
//! compiled out. Prefer returning `Err` from a fallible user-defined function
//! over panicking; the ordinary error path never depends on unwinding.
pub
/// DuckDB scalar functions: row-wise functions used in a `SELECT` list or
/// `WHERE` clause.
/// DuckDB table functions: functions used in a `FROM` clause that produce rows
/// and columns.
/// An owned-or-borrowed DuckDB data chunk.
pub use DataChunkHandle;
/// An owned DuckDB logical type handle.
pub use LogicalType;
/// The trait behind DuckDB scalar functions, and its signature type.
pub use ;
/// The row type produced by a `#[duckdb_table_function]`-generated function,
/// and the shared init-data/execution-loop helpers it compiles down to.
pub use ;
/// The trait behind DuckDB table functions, and its callback-info types.
pub use ;
/// Read and write views over a single column of a [`DataChunkHandle`], plus the
/// [`ScalarArg`]/[`ScalarRet`] marshalling traits.
pub use ;
/// The error type returned by user-defined-function callbacks.
///
/// `+ Send + Sync` because callbacks may run on DuckDB worker threads.
pub type UdfResult<T> = Result;
/// Returns early from a fallible user-defined-function body with a formatted
/// error message.
///
/// Expands to `return Err(format!(...).into())` — the surrounding function's
/// error type must implement `From<String>`, which is true for `String` itself
/// and for `Box<dyn std::error::Error + Send + Sync>` (what `#[duckdb_scalar]`/
/// `#[duckdb_table_function]` route a `Result<T, E>` return through).
///
/// # Examples
///
/// ```
/// use better_duck_core::duck_bail;
///
/// fn check(stop: i64, start: i64) -> Result<i64, String> {
/// if stop < start {
/// duck_bail!("stop ({stop}) must be >= start ({start})");
/// }
/// Ok(stop - start)
/// }
/// assert!(check(1, 10).is_err());
/// ```
/// Items referenced by code generated by the `#[duckdb_scalar]`/
/// `#[duckdb_table_function]` attribute macros.
///
/// Not part of the public API: renamed or removed without notice. Referenced by
/// generated code as `::better_duck_core::udf::__private::…` so that a user
/// crate shadowing e.g. `Result` cannot break macro expansion.