quack_rs/copy_function/info.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//! Callback info wrappers for copy function callbacks.
7//!
8//! Each copy function phase (bind, global init, sink, finalize) receives an
9//! opaque info handle from `DuckDB`. These wrappers provide safe, ergonomic
10//! access to the underlying C API functions.
11
12use std::ffi::CStr;
13use std::os::raw::c_void;
14
15use crate::error::ExtensionError;
16
17use libduckdb_sys::{
18 duckdb_copy_function_bind_get_client_context, duckdb_copy_function_bind_get_column_count,
19 duckdb_copy_function_bind_get_column_type, duckdb_copy_function_bind_get_extra_info,
20 duckdb_copy_function_bind_info, duckdb_copy_function_bind_set_bind_data,
21 duckdb_copy_function_bind_set_error, duckdb_copy_function_finalize_get_bind_data,
22 duckdb_copy_function_finalize_get_client_context, duckdb_copy_function_finalize_get_extra_info,
23 duckdb_copy_function_finalize_get_global_state, duckdb_copy_function_finalize_info,
24 duckdb_copy_function_finalize_set_error, duckdb_copy_function_global_init_get_bind_data,
25 duckdb_copy_function_global_init_get_client_context,
26 duckdb_copy_function_global_init_get_extra_info,
27 duckdb_copy_function_global_init_get_file_path, duckdb_copy_function_global_init_info,
28 duckdb_copy_function_global_init_set_error, duckdb_copy_function_global_init_set_global_state,
29 duckdb_copy_function_sink_get_bind_data, duckdb_copy_function_sink_get_client_context,
30 duckdb_copy_function_sink_get_extra_info, duckdb_copy_function_sink_get_global_state,
31 duckdb_copy_function_sink_info, duckdb_copy_function_sink_set_error, duckdb_delete_callback_t,
32};
33
34/// What `set_error` reports when it is given an empty message: `DuckDB` would
35/// otherwise show the error type followed by nothing.
36pub const EMPTY_ERROR_PLACEHOLDER: &str = "copy function reported an error without a message";
37use crate::types::LogicalType;
38
39// ── CopyBindInfo ─────────────────────────────────────────────────────────────
40
41/// Wrapper around the `duckdb_copy_function_bind_info` handle provided to a
42/// copy function bind callback.
43pub struct CopyBindInfo {
44 info: duckdb_copy_function_bind_info,
45}
46
47impl CopyBindInfo {
48 /// Wraps a raw `duckdb_copy_function_bind_info` handle.
49 ///
50 /// # Safety
51 ///
52 /// `info` must be a valid handle passed by `DuckDB` to a copy function bind
53 /// callback.
54 #[inline]
55 #[must_use]
56 pub const unsafe fn new(info: duckdb_copy_function_bind_info) -> Self {
57 Self { info }
58 }
59
60 /// Returns the number of columns in the output.
61 #[cfg_attr(test, mutants::skip)]
62 #[must_use]
63 pub fn column_count(&self) -> u64 {
64 // SAFETY: self.info is valid per constructor contract.
65 unsafe { duckdb_copy_function_bind_get_column_count(self.info) }
66 }
67
68 /// Returns the logical type of the column at `index`, or `None` if
69 /// `index` is not less than [`column_count`][Self::column_count].
70 ///
71 /// `duckdb_copy_function_bind_get_column_type` returns a null handle for
72 /// an out-of-range index; wrapping that in a [`LogicalType`] would hand
73 /// `DuckDB` a null pointer on the first use. This mirrors
74 /// [`BindInfo::result_column_type`][crate::table::BindInfo::result_column_type].
75 ///
76 /// # Safety
77 ///
78 /// Must be called during the bind callback, while `self.info` is live.
79 #[must_use]
80 pub unsafe fn column_type(&self, index: u64) -> Option<LogicalType> {
81 if index >= self.column_count() {
82 return None;
83 }
84 // SAFETY: self.info is valid and `index` is in range.
85 let raw = unsafe { duckdb_copy_function_bind_get_column_type(self.info, index) };
86 if raw.is_null() {
87 return None;
88 }
89 // SAFETY: DuckDB returns a freshly allocated handle the caller owns.
90 Some(unsafe { LogicalType::from_raw(raw) })
91 }
92
93 /// Retrieves the extra-info pointer previously set on the copy function.
94 ///
95 /// # Safety
96 ///
97 /// The returned pointer is only valid as long as the copy function is
98 /// registered and `DuckDB` has not yet called the destructor.
99 #[must_use]
100 pub unsafe fn get_extra_info(&self) -> *mut c_void {
101 // SAFETY: self.info is valid per constructor contract.
102 unsafe { duckdb_copy_function_bind_get_extra_info(self.info) }
103 }
104
105 /// The options given to the `COPY … TO` statement, as a `STRUCT` value.
106 ///
107 /// `COPY t TO 'f' (FORMAT my_format, COMPRESSION 'zstd', LEVEL 3)` arrives
108 /// here as a `STRUCT` whose fields are the option names. Read them with
109 /// [`Value::struct_field_names`][crate::value::Value::struct_field_names]
110 /// and [`Value::struct_child`][crate::value::Value::struct_child].
111 ///
112 /// How `DuckDB` 1.5.5 builds it (`MakeValueFromCopyOptions`,
113 /// `src/main/capi/copy_function-c.cpp`):
114 ///
115 /// - **Field names are upper-cased**: `compression` arrives as
116 /// `COMPRESSION`, whatever case the user typed. `FORMAT` itself is not
117 /// among them.
118 /// - **No options at all** gives a SQL `NULL`, not an empty `STRUCT`:
119 /// the returned [`Value`][crate::value::Value] is non-null as a handle but
120 /// [`is_sql_null`][crate::value::Value::is_sql_null], and has no fields.
121 /// - **An option with no value** (`(FORMAT f, HEADER)`) is a `NULL`
122 /// field.
123 /// - **An option with several values** (`LST (1, 2)`) is a `LIST` when
124 /// they share a type and an unnamed `STRUCT` otherwise; one value is
125 /// that value.
126 /// - An explicit `NULL` value (`(FORMAT f, X NULL)`) never gets here:
127 /// the binder rejects it ("NULL is not supported as a valid option").
128 ///
129 /// Returns `None` only when `DuckDB` hands back a null handle.
130 ///
131 /// # Example
132 ///
133 /// ```rust,no_run
134 /// use quack_rs::copy_function::CopyBindInfo;
135 ///
136 /// # fn demo(bind: &CopyBindInfo) -> Option<String> {
137 /// let options = bind.options()?;
138 /// if options.is_sql_null() {
139 /// return None; // COPY ... (FORMAT my_format) with no other options
140 /// }
141 /// let names = options.struct_field_names();
142 /// // Option names arrive upper-cased.
143 /// let idx = names.iter().position(|n| n == "COMPRESSION")?;
144 /// options.struct_child(idx)?.as_str().ok()
145 /// # }
146 /// ```
147 #[must_use]
148 pub fn options(&self) -> Option<crate::value::Value> {
149 // SAFETY: `self.info` is valid per the constructor's contract. DuckDB
150 // returns a freshly allocated `duckdb_value` the caller owns.
151 let raw = unsafe { libduckdb_sys::duckdb_copy_function_bind_get_options(self.info) };
152 if raw.is_null() {
153 return None;
154 }
155 // SAFETY: `raw` is owned by us from here; `Value` destroys it on drop.
156 Some(unsafe { crate::value::Value::from_raw(raw) })
157 }
158
159 /// Sets the bind data pointer and its destructor.
160 ///
161 /// # Safety
162 ///
163 /// `data` must remain valid until `DuckDB` calls `destroy`, or for the
164 /// lifetime of the query if `destroy` is `None`.
165 pub unsafe fn set_bind_data(&self, data: *mut c_void, destroy: duckdb_delete_callback_t) {
166 // SAFETY: self.info is valid; data validity is the caller's responsibility.
167 unsafe {
168 duckdb_copy_function_bind_set_bind_data(self.info, data, destroy);
169 }
170 }
171
172 /// Stores `data` as this statement's bind data: the safe, typed form of
173 /// [`set_bind_data`][Self::set_bind_data]. Read it with `bind_data_ref`
174 /// in the global init, sink and finalize callbacks.
175 ///
176 /// quack-rs boxes `data` behind a type tag and generates its destructor,
177 /// which contains a panic in `T::drop`. `DuckDB` runs it once, when the
178 /// statement's bind result is released — also when a later callback
179 /// reports an error (`copy_function-c.cpp` hands the pointer to its bind
180 /// result before it checks for one). `T` is `Send + Sync` because every
181 /// sink thread reads it. Call this at most once per bind: a second call
182 /// replaces the first value, which is then never dropped.
183 pub fn set_bind_data_typed<T: Send + Sync + 'static>(&self, data: T) {
184 let (ptr, destroy) = crate::extra_info::into_tagged(data);
185 // SAFETY: a fresh allocation, used by no one else, and the destructor
186 // that frees it exactly once without unwinding.
187 unsafe { self.set_bind_data(ptr, Some(destroy)) };
188 }
189
190 /// Borrows the copy function's extra info, set with
191 /// [`CopyFunctionBuilder::extra_info_typed`][crate::copy_function::CopyFunctionBuilder::extra_info_typed],
192 /// as a `T`; `None` when none was set or it holds another type.
193 ///
194 /// # Safety
195 ///
196 /// The extra info, if any, was set through `extra_info_typed`, not the
197 /// raw `extra_info`, whose pointer carries no type tag.
198 #[must_use]
199 pub unsafe fn extra_info_ref<T: 'static>(&self) -> Option<&T> {
200 // SAFETY: null or tagged (this method's contract); DuckDB keeps it
201 // alive while the function is registered, which outlasts `&self`.
202 unsafe { crate::extra_info::tagged_ref(self.get_extra_info()) }
203 }
204
205 /// Reports a fatal error, causing `DuckDB` to abort the current query.
206 ///
207 /// An interior null byte in `message` is replaced by `?`, and an empty
208 /// message by [`EMPTY_ERROR_PLACEHOLDER`].
209 #[cfg_attr(test, mutants::skip)]
210 pub fn set_error(&self, message: &str) {
211 let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
212 // SAFETY: self.info is valid per constructor contract.
213 unsafe {
214 duckdb_copy_function_bind_set_error(self.info, c_msg.as_ptr());
215 }
216 }
217
218 /// Returns the client context for this callback.
219 ///
220 /// The returned [`ClientContext`][crate::client_context::ClientContext] provides
221 /// access to the connection's catalog, configuration, and connection ID.
222 ///
223 /// # Safety
224 ///
225 /// The inner handle must be valid (requires `DuckDB` runtime), and the
226 /// returned context must not be used after the connection running this
227 /// query is closed — see
228 /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
229 pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
230 // SAFETY: self.info is a valid copy-bind-info handle per this fn's contract.
231 let ctx = unsafe { duckdb_copy_function_bind_get_client_context(self.info) };
232 // SAFETY: `ctx` is a client-context handle returned by DuckDB.
233 unsafe { crate::client_context::ClientContext::from_raw(ctx) }
234 }
235
236 /// Returns the underlying raw handle.
237 #[cfg_attr(test, mutants::skip)]
238 #[inline]
239 #[must_use]
240 pub const fn as_raw(&self) -> duckdb_copy_function_bind_info {
241 self.info
242 }
243}
244
245// ── CopyGlobalInitInfo ───────────────────────────────────────────────────────
246
247/// Wrapper around the `duckdb_copy_function_global_init_info` handle provided
248/// to a copy function global init callback.
249pub struct CopyGlobalInitInfo {
250 info: duckdb_copy_function_global_init_info,
251}
252
253impl CopyGlobalInitInfo {
254 /// Wraps a raw `duckdb_copy_function_global_init_info` handle.
255 ///
256 /// # Safety
257 ///
258 /// `info` must be a valid handle passed by `DuckDB` to a copy function
259 /// global init callback.
260 #[inline]
261 #[must_use]
262 pub const unsafe fn new(info: duckdb_copy_function_global_init_info) -> Self {
263 Self { info }
264 }
265
266 /// Retrieves the bind data pointer set during the bind phase.
267 ///
268 /// # Safety
269 ///
270 /// The returned pointer must be cast back to the original type.
271 #[must_use]
272 pub unsafe fn get_bind_data(&self) -> *mut c_void {
273 // SAFETY: self.info is valid per constructor contract.
274 unsafe { duckdb_copy_function_global_init_get_bind_data(self.info) }
275 }
276
277 /// Retrieves the extra-info pointer previously set on the copy function.
278 ///
279 /// # Safety
280 ///
281 /// The returned pointer is only valid as long as the copy function is
282 /// registered and `DuckDB` has not yet called the destructor.
283 #[must_use]
284 pub unsafe fn get_extra_info(&self) -> *mut c_void {
285 // SAFETY: self.info is valid per constructor contract.
286 unsafe { duckdb_copy_function_global_init_get_extra_info(self.info) }
287 }
288
289 /// Returns the destination path for the copy operation.
290 ///
291 /// The returned `String` is a copy. `DuckDB` keeps ownership of its own
292 /// buffer — `duckdb_copy_function_global_init_get_file_path` returns
293 /// `info_ref.file_path.c_str()`, the interior pointer of a live C++
294 /// `std::string`, so it must **not** be freed. Doing so corrupts the heap.
295 ///
296 /// # Errors
297 ///
298 /// Returns an error if the path is not valid UTF-8, which a path on Linux
299 /// need not be (`COPY t TO '~/out.x'` with a non-UTF-8 home directory, for
300 /// one). A lossy conversion would name a different file, so use
301 /// [`get_file_path_bytes`][Self::get_file_path_bytes] to open such a path.
302 ///
303 /// # Safety
304 ///
305 /// `self.info` must be a valid handle from an active callback invocation.
306 pub unsafe fn get_file_path(&self) -> Result<String, ExtensionError> {
307 // SAFETY: forwarded from this function's own contract.
308 let bytes = unsafe { self.get_file_path_bytes() };
309 String::from_utf8(bytes).map_err(|e| {
310 ExtensionError::new(format!(
311 "the COPY destination path is not valid UTF-8 ({e}); read it with \
312 get_file_path_bytes"
313 ))
314 })
315 }
316
317 /// Returns the destination path for the copy operation as the exact bytes
318 /// `DuckDB` holds, whatever their encoding (empty if `DuckDB` has none).
319 ///
320 /// On Unix, `std::ffi::OsStr::from_bytes` turns them into a path that
321 /// opens the same file. See [`get_file_path`][Self::get_file_path] for the
322 /// ownership of `DuckDB`'s buffer.
323 ///
324 /// # Safety
325 ///
326 /// `self.info` must be a valid handle from an active callback invocation.
327 #[must_use]
328 pub unsafe fn get_file_path_bytes(&self) -> Vec<u8> {
329 // SAFETY: self.info is valid per constructor contract.
330 let c_str = unsafe { duckdb_copy_function_global_init_get_file_path(self.info) };
331 if c_str.is_null() {
332 return Vec::new();
333 }
334 // SAFETY: c_str is a valid NUL-terminated string that DuckDB owns and
335 // keeps alive for the duration of this callback. It is copied here and
336 // deliberately not freed: unlike the `char *` returns elsewhere in the
337 // C API (which `strdup` or `duckdb_malloc`), this one is `const char *`
338 // and borrowed.
339 unsafe { CStr::from_ptr(c_str) }.to_bytes().to_vec()
340 }
341
342 /// Sets the global state pointer and its destructor.
343 ///
344 /// # Safety
345 ///
346 /// `state` must remain valid until `DuckDB` calls `destroy`, or for the
347 /// lifetime of the query if `destroy` is `None`.
348 pub unsafe fn set_global_state(&self, state: *mut c_void, destroy: duckdb_delete_callback_t) {
349 // SAFETY: self.info is valid; state validity is the caller's responsibility.
350 unsafe {
351 duckdb_copy_function_global_init_set_global_state(self.info, state, destroy);
352 }
353 }
354
355 /// Stores `state` as this statement's global state: the safe, typed form
356 /// of [`set_global_state`][Self::set_global_state]. Read it with
357 /// `global_state_ref` in the sink and finalize callbacks.
358 ///
359 /// The destructor is generated and panic-safe, as for
360 /// [`CopyBindInfo::set_bind_data_typed`], and `DuckDB` runs it once when
361 /// the statement ends, also after a sink or finalize error. `T` is
362 /// `Send + Sync` because the sink can run on several threads at once:
363 /// state they change needs a `Mutex` or atomics inside `T`. A
364 /// [`FileHandle`][crate::file_system::FileHandle] kept here belongs in a
365 /// `Mutex` (see its docs on keeping a file open across callbacks). Call
366 /// this at most once per global init.
367 pub fn set_global_state_typed<T: Send + Sync + 'static>(&self, state: T) {
368 let (ptr, destroy) = crate::extra_info::into_tagged(state);
369 // SAFETY: a fresh allocation, used by no one else, and the destructor
370 // that frees it exactly once without unwinding.
371 unsafe { self.set_global_state(ptr, Some(destroy)) };
372 }
373
374 /// Borrows the bind data set with
375 /// [`CopyBindInfo::set_bind_data_typed`] as a `T`; `None` when none was
376 /// set or it holds another type.
377 ///
378 /// # Safety
379 ///
380 /// The bind data, if any, was set through `set_bind_data_typed`, not the
381 /// raw `set_bind_data`, whose pointer carries no type tag.
382 #[must_use]
383 pub unsafe fn bind_data_ref<T: 'static>(&self) -> Option<&T> {
384 // SAFETY: null or tagged (this method's contract); DuckDB keeps it
385 // alive for the whole statement, which outlasts `&self`.
386 unsafe { crate::extra_info::tagged_ref(self.get_bind_data()) }
387 }
388
389 /// Borrows the copy function's extra info as a `T`; see
390 /// [`CopyBindInfo::extra_info_ref`].
391 ///
392 /// # Safety
393 ///
394 /// As for [`CopyBindInfo::extra_info_ref`].
395 #[must_use]
396 pub unsafe fn extra_info_ref<T: 'static>(&self) -> Option<&T> {
397 // SAFETY: as in `CopyBindInfo::extra_info_ref`.
398 unsafe { crate::extra_info::tagged_ref(self.get_extra_info()) }
399 }
400
401 /// Reports a fatal error, causing `DuckDB` to abort the current query.
402 ///
403 /// An interior null byte in `message` is replaced by `?`, and an empty
404 /// message by [`EMPTY_ERROR_PLACEHOLDER`].
405 #[cfg_attr(test, mutants::skip)]
406 pub fn set_error(&self, message: &str) {
407 let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
408 // SAFETY: self.info is valid per constructor contract.
409 unsafe {
410 duckdb_copy_function_global_init_set_error(self.info, c_msg.as_ptr());
411 }
412 }
413
414 /// Returns the client context for this callback.
415 ///
416 /// # Safety
417 ///
418 /// The inner handle must be valid (requires `DuckDB` runtime), and the
419 /// returned context must not be used after the connection running this
420 /// query is closed — see
421 /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
422 pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
423 // SAFETY: self.info is a valid copy-global-init-info handle per this fn's contract.
424 let ctx = unsafe { duckdb_copy_function_global_init_get_client_context(self.info) };
425 // SAFETY: `ctx` is a client-context handle returned by DuckDB.
426 unsafe { crate::client_context::ClientContext::from_raw(ctx) }
427 }
428
429 /// Returns the underlying raw handle.
430 #[cfg_attr(test, mutants::skip)]
431 #[inline]
432 #[must_use]
433 pub const fn as_raw(&self) -> duckdb_copy_function_global_init_info {
434 self.info
435 }
436}
437
438// ── CopySinkInfo ─────────────────────────────────────────────────────────────
439
440/// Wrapper around the `duckdb_copy_function_sink_info` handle provided to a
441/// copy function sink callback.
442pub struct CopySinkInfo {
443 info: duckdb_copy_function_sink_info,
444}
445
446impl CopySinkInfo {
447 /// Wraps a raw `duckdb_copy_function_sink_info` handle.
448 ///
449 /// # Safety
450 ///
451 /// `info` must be a valid handle passed by `DuckDB` to a copy function
452 /// sink callback.
453 #[inline]
454 #[must_use]
455 pub const unsafe fn new(info: duckdb_copy_function_sink_info) -> Self {
456 Self { info }
457 }
458
459 /// Retrieves the bind data pointer set during the bind phase.
460 ///
461 /// # Safety
462 ///
463 /// The returned pointer must be cast back to the original type.
464 #[must_use]
465 pub unsafe fn get_bind_data(&self) -> *mut c_void {
466 // SAFETY: self.info is valid per constructor contract.
467 unsafe { duckdb_copy_function_sink_get_bind_data(self.info) }
468 }
469
470 /// Retrieves the extra-info pointer previously set on the copy function.
471 ///
472 /// # Safety
473 ///
474 /// The returned pointer is only valid as long as the copy function is
475 /// registered and `DuckDB` has not yet called the destructor.
476 #[must_use]
477 pub unsafe fn get_extra_info(&self) -> *mut c_void {
478 // SAFETY: self.info is valid per constructor contract.
479 unsafe { duckdb_copy_function_sink_get_extra_info(self.info) }
480 }
481
482 /// Retrieves the global state pointer set during the global init phase.
483 ///
484 /// # Safety
485 ///
486 /// The returned pointer must be cast back to the original type.
487 #[must_use]
488 pub unsafe fn get_global_state(&self) -> *mut c_void {
489 // SAFETY: self.info is valid per constructor contract.
490 unsafe { duckdb_copy_function_sink_get_global_state(self.info) }
491 }
492
493 /// Borrows the bind data as a `T`; see
494 /// [`CopyGlobalInitInfo::bind_data_ref`].
495 ///
496 /// # Safety
497 ///
498 /// As for [`CopyGlobalInitInfo::bind_data_ref`].
499 #[must_use]
500 pub unsafe fn bind_data_ref<T: 'static>(&self) -> Option<&T> {
501 // SAFETY: as in `CopyGlobalInitInfo::bind_data_ref`.
502 unsafe { crate::extra_info::tagged_ref(self.get_bind_data()) }
503 }
504
505 /// Borrows the global state set with
506 /// [`CopyGlobalInitInfo::set_global_state_typed`] as a `T`; `None` when
507 /// none was set or it holds another type.
508 ///
509 /// # Safety
510 ///
511 /// The global state, if any, was set through `set_global_state_typed`,
512 /// not the raw `set_global_state`, whose pointer carries no type tag.
513 #[must_use]
514 pub unsafe fn global_state_ref<T: 'static>(&self) -> Option<&T> {
515 // SAFETY: null or tagged (this method's contract); DuckDB keeps it
516 // alive until the statement ends, which outlasts `&self`.
517 unsafe { crate::extra_info::tagged_ref(self.get_global_state()) }
518 }
519
520 /// Borrows the copy function's extra info as a `T`; see
521 /// [`CopyBindInfo::extra_info_ref`].
522 ///
523 /// # Safety
524 ///
525 /// As for [`CopyBindInfo::extra_info_ref`].
526 #[must_use]
527 pub unsafe fn extra_info_ref<T: 'static>(&self) -> Option<&T> {
528 // SAFETY: as in `CopyBindInfo::extra_info_ref`.
529 unsafe { crate::extra_info::tagged_ref(self.get_extra_info()) }
530 }
531
532 /// Reports a fatal error, causing `DuckDB` to abort the current query.
533 ///
534 /// An interior null byte in `message` is replaced by `?`, and an empty
535 /// message by [`EMPTY_ERROR_PLACEHOLDER`].
536 #[cfg_attr(test, mutants::skip)]
537 pub fn set_error(&self, message: &str) {
538 let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
539 // SAFETY: self.info is valid per constructor contract.
540 unsafe {
541 duckdb_copy_function_sink_set_error(self.info, c_msg.as_ptr());
542 }
543 }
544
545 /// Returns the client context for this callback.
546 ///
547 /// # Safety
548 ///
549 /// The inner handle must be valid (requires `DuckDB` runtime), and the
550 /// returned context must not be used after the connection running this
551 /// query is closed — see
552 /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
553 pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
554 // SAFETY: self.info is a valid copy-sink-info handle per this fn's contract.
555 let ctx = unsafe { duckdb_copy_function_sink_get_client_context(self.info) };
556 // SAFETY: `ctx` is a client-context handle returned by DuckDB.
557 unsafe { crate::client_context::ClientContext::from_raw(ctx) }
558 }
559
560 /// Returns the underlying raw handle.
561 #[cfg_attr(test, mutants::skip)]
562 #[inline]
563 #[must_use]
564 pub const fn as_raw(&self) -> duckdb_copy_function_sink_info {
565 self.info
566 }
567}
568
569// ── CopyFinalizeInfo ─────────────────────────────────────────────────────────
570
571/// Wrapper around the `duckdb_copy_function_finalize_info` handle provided to
572/// a copy function finalize callback.
573pub struct CopyFinalizeInfo {
574 info: duckdb_copy_function_finalize_info,
575}
576
577impl CopyFinalizeInfo {
578 /// Wraps a raw `duckdb_copy_function_finalize_info` handle.
579 ///
580 /// # Safety
581 ///
582 /// `info` must be a valid handle passed by `DuckDB` to a copy function
583 /// finalize callback.
584 #[inline]
585 #[must_use]
586 pub const unsafe fn new(info: duckdb_copy_function_finalize_info) -> Self {
587 Self { info }
588 }
589
590 /// Retrieves the bind data pointer set during the bind phase.
591 ///
592 /// # Safety
593 ///
594 /// The returned pointer must be cast back to the original type.
595 #[must_use]
596 pub unsafe fn get_bind_data(&self) -> *mut c_void {
597 // SAFETY: self.info is valid per constructor contract.
598 unsafe { duckdb_copy_function_finalize_get_bind_data(self.info) }
599 }
600
601 /// Retrieves the extra-info pointer previously set on the copy function.
602 ///
603 /// # Safety
604 ///
605 /// The returned pointer is only valid as long as the copy function is
606 /// registered and `DuckDB` has not yet called the destructor.
607 #[must_use]
608 pub unsafe fn get_extra_info(&self) -> *mut c_void {
609 // SAFETY: self.info is valid per constructor contract.
610 unsafe { duckdb_copy_function_finalize_get_extra_info(self.info) }
611 }
612
613 /// Retrieves the global state pointer set during the global init phase.
614 ///
615 /// # Safety
616 ///
617 /// The returned pointer must be cast back to the original type.
618 #[must_use]
619 pub unsafe fn get_global_state(&self) -> *mut c_void {
620 // SAFETY: self.info is valid per constructor contract.
621 unsafe { duckdb_copy_function_finalize_get_global_state(self.info) }
622 }
623
624 /// Borrows the bind data as a `T`; see
625 /// [`CopyGlobalInitInfo::bind_data_ref`].
626 ///
627 /// # Safety
628 ///
629 /// As for [`CopyGlobalInitInfo::bind_data_ref`].
630 #[must_use]
631 pub unsafe fn bind_data_ref<T: 'static>(&self) -> Option<&T> {
632 // SAFETY: as in `CopyGlobalInitInfo::bind_data_ref`.
633 unsafe { crate::extra_info::tagged_ref(self.get_bind_data()) }
634 }
635
636 /// Borrows the global state as a `T`; see
637 /// [`CopySinkInfo::global_state_ref`].
638 ///
639 /// # Safety
640 ///
641 /// As for [`CopySinkInfo::global_state_ref`].
642 #[must_use]
643 pub unsafe fn global_state_ref<T: 'static>(&self) -> Option<&T> {
644 // SAFETY: as in `CopySinkInfo::global_state_ref`.
645 unsafe { crate::extra_info::tagged_ref(self.get_global_state()) }
646 }
647
648 /// Borrows the copy function's extra info as a `T`; see
649 /// [`CopyBindInfo::extra_info_ref`].
650 ///
651 /// # Safety
652 ///
653 /// As for [`CopyBindInfo::extra_info_ref`].
654 #[must_use]
655 pub unsafe fn extra_info_ref<T: 'static>(&self) -> Option<&T> {
656 // SAFETY: as in `CopyBindInfo::extra_info_ref`.
657 unsafe { crate::extra_info::tagged_ref(self.get_extra_info()) }
658 }
659
660 /// Reports a fatal error, causing `DuckDB` to abort the current query.
661 ///
662 /// An interior null byte in `message` is replaced by `?`, and an empty
663 /// message by [`EMPTY_ERROR_PLACEHOLDER`].
664 #[cfg_attr(test, mutants::skip)]
665 pub fn set_error(&self, message: &str) {
666 let c_msg = crate::table::cstr::error_cstring(message, EMPTY_ERROR_PLACEHOLDER);
667 // SAFETY: self.info is valid per constructor contract.
668 unsafe {
669 duckdb_copy_function_finalize_set_error(self.info, c_msg.as_ptr());
670 }
671 }
672
673 /// Returns the client context for this callback.
674 ///
675 /// # Safety
676 ///
677 /// The inner handle must be valid (requires `DuckDB` runtime), and the
678 /// returned context must not be used after the connection running this
679 /// query is closed — see
680 /// [`ClientContext`](crate::client_context::ClientContext#lifetime).
681 pub unsafe fn get_client_context(&self) -> crate::client_context::ClientContext {
682 // SAFETY: self.info is a valid copy-finalize-info handle per this fn's contract.
683 let ctx = unsafe { duckdb_copy_function_finalize_get_client_context(self.info) };
684 // SAFETY: `ctx` is a client-context handle returned by DuckDB.
685 unsafe { crate::client_context::ClientContext::from_raw(ctx) }
686 }
687
688 /// Returns the underlying raw handle.
689 #[cfg_attr(test, mutants::skip)]
690 #[inline]
691 #[must_use]
692 pub const fn as_raw(&self) -> duckdb_copy_function_finalize_info {
693 self.info
694 }
695}
696
697// ── Tests ────────────────────────────────────────────────────────────────────
698
699crate::debug_repr::impl_handle_debug!(
700 CopyBindInfo.info,
701 CopyGlobalInitInfo.info,
702 CopySinkInfo.info,
703 CopyFinalizeInfo.info
704);
705
706#[cfg(test)]
707mod tests {
708 use super::*;
709
710 /// Each wrapper hands back exactly the handle it was built from.
711 #[test]
712 fn info_wrappers_round_trip_their_handles() {
713 let raw = std::ptr::NonNull::<u8>::dangling().as_ptr();
714 // SAFETY: the handles are only stored and read back, never passed to DuckDB.
715 unsafe {
716 assert_eq!(CopyBindInfo::new(raw.cast()).as_raw().cast(), raw);
717 assert_eq!(CopyGlobalInitInfo::new(raw.cast()).as_raw().cast(), raw);
718 assert_eq!(CopySinkInfo::new(raw.cast()).as_raw().cast(), raw);
719 assert_eq!(CopyFinalizeInfo::new(raw.cast()).as_raw().cast(), raw);
720 }
721 }
722
723 /// A null bind info reports no columns, so `column_type` refuses every
724 /// index before reaching `duckdb_copy_function_bind_get_column_type`.
725 #[test]
726 #[cfg(feature = "_duckdb-testing")]
727 fn column_type_is_none_out_of_range() {
728 let _db = crate::testing::InMemoryDb::open().expect("dispatch table");
729 // SAFETY: DuckDB null-checks the bind info in both calls.
730 let info = unsafe { CopyBindInfo::new(std::ptr::null_mut()) };
731 assert_eq!(info.column_count(), 0);
732 // SAFETY: as above.
733 assert!(unsafe { info.column_type(0) }.is_none());
734 }
735}