quack_rs/appender/chunk.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//! Chunk-at-a-time appends: handing the [`Appender`] a whole [`DataChunk`].
7
8use libduckdb_sys::duckdb_append_data_chunk;
9#[cfg(feature = "duckdb-1-5")]
10use libduckdb_sys::duckdb_append_default_to_chunk;
11
12use super::{append_error, AppendError, Appender};
13use crate::data_chunk::DataChunk;
14
15impl Appender {
16 // ── Chunk appends ───────────────────────────────────────────────────
17
18 /// Appends an entire [`DataChunk`].
19 ///
20 /// The chunk's column types must match the appender's active columns; see
21 /// [`column_type`][Self::column_type] to discover them.
22 ///
23 /// **Order:** `DuckDB` keeps row-at-a-time rows in a separate buffer until
24 /// 2,048 of them accumulate, and adds a chunk to the table-bound buffer
25 /// directly, so a chunk lands *ahead of* rows appended before it that are
26 /// still buffered. [`flush`][Self::flush] first if insertion order
27 /// matters.
28 ///
29 /// # Errors
30 ///
31 /// Returns an [`AppendError`] if the append fails, if the appender is
32 /// closed or poisoned, or — without calling `DuckDB` — in the middle of a
33 /// row appended by hand: when the chunk tips `DuckDB`'s buffer over its
34 /// automatic-flush threshold, that flush fails on the open row *after* the
35 /// chunk has been buffered, so an error would be reported for rows that
36 /// were in fact kept.
37 pub fn append_chunk(&self, chunk: &DataChunk) -> Result<(), AppendError> {
38 self.usable()?;
39 if self.column.get() != 0 {
40 return Err(append_error(&format!(
41 "append_chunk: a row is in progress ({} value(s) without end_row); finish it \
42 first",
43 self.column.get()
44 )));
45 }
46 // SAFETY: self.handle and chunk.as_raw() are valid.
47 let state = unsafe { duckdb_append_data_chunk(self.handle, chunk.as_raw()) };
48 self.check(state)?;
49 let rows = u64::try_from(chunk.size()).unwrap_or(u64::MAX);
50 self.buffered.set(self.buffered.get().saturating_add(rows));
51 Ok(())
52 }
53
54 /// Writes the table column `col`'s `DEFAULT` value into row `row` of
55 /// `chunk`.
56 ///
57 /// Useful when building a chunk to append: columns without an explicit
58 /// value can be filled with their schema default.
59 ///
60 /// # Errors
61 ///
62 /// Returns an [`AppendError`] if the default cannot be written.
63 #[cfg(feature = "duckdb-1-5")]
64 pub fn append_default_to_chunk(
65 &self,
66 chunk: &DataChunk,
67 col: u64,
68 row: u64,
69 ) -> Result<(), AppendError> {
70 // SAFETY: self.handle and chunk.as_raw() are valid.
71 let state =
72 unsafe { duckdb_append_default_to_chunk(self.handle, chunk.as_raw(), col, row) };
73 self.check(state)
74 }
75}