Skip to main content

quack_rs/testing/
mock_vector.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//! In-memory mock types for `DuckDB` vectors.
7//!
8//! [`MockVectorWriter`] and [`MockVectorReader`] let you test callback logic —
9//! the code that reads input rows and writes output values — without a live
10//! `DuckDB` instance.
11//!
12//! # Why these exist
13//!
14//! `DuckDB` loadable extensions use `libduckdb-sys` with
15//! `features = ["loadable-extension"]`, which routes every C API call through a
16//! lazy dispatch table. That table is only initialized when `DuckDB` calls
17//! `duckdb_rs_extension_api_init` at extension load time. In `cargo test`, no
18//! `DuckDB` process loads the extension, so the dispatch table is never
19//! initialized and any call to `VectorReader::new` or `VectorWriter::new` panics
20//! with `DuckDB API not initialized`.
21//!
22//! These mock types provide the same write/read interface but store data in a
23//! plain `Vec`, with no `DuckDB` dependency at all.
24//!
25//! # What they are for
26//!
27//! Keep the per-row computation in plain Rust functions and test those
28//! directly. The mocks are for the row loop around it. They mirror
29//! [`VectorReader`][crate::vector::VectorReader] and
30//! [`VectorWriter`][crate::vector::VectorWriter] without matching them method
31//! for method — [`MockVectorWriter`] shares most `write_*` names, while
32//! [`MockVectorReader`] offers `try_get_*` getters that return `None` for NULL
33//! where the real reader has `is_valid` plus `read_*` — and they are
34//! **separate types**, so a function written against them cannot be handed the
35//! real reader and writer.
36//! To run a real callback against real vectors, use
37//! `InMemoryDb` (`bundled-test` / `bundled-test-prebuilt` features).
38//!
39//! [`MockVectorWriter`] reproduces a real output vector's NULL and capacity
40//! behaviour rather than being more forgiving than it; see its type docs.
41//! [`MockVectorReader`] likewise panics on a row past its end, where a real
42//! reader would read out of bounds.
43//!
44//! ```rust
45//! use quack_rs::testing::{MockVectorWriter, MockVectorReader, MockDuckValue};
46//!
47//! /// A row loop prototyped against the mocks.
48//! fn compute_double(reader: &MockVectorReader, writer: &mut MockVectorWriter) {
49//!     for i in 0..reader.row_count() {
50//!         if reader.is_valid(i) {
51//!             let v = reader.try_get_i64(i).unwrap_or(0);
52//!             writer.write_i64(i, v * 2);
53//!         } else {
54//!             writer.set_null(i);
55//!         }
56//!     }
57//! }
58//!
59//! let reader = MockVectorReader::from_i64s([Some(1), Some(5), None, Some(-3)]);
60//! let mut writer = MockVectorWriter::new(4);
61//! compute_double(&reader, &mut writer);
62//!
63//! assert_eq!(writer.try_get_i64(0), Some(2));
64//! assert_eq!(writer.try_get_i64(1), Some(10));
65//! assert!(writer.is_null(2));
66//! assert_eq!(writer.try_get_i64(3), Some(-6));
67//! ```
68
69mod reader;
70#[cfg(test)]
71mod tests;
72mod writer;
73
74use crate::interval::DuckInterval;
75
76/// A `DuckDB`-compatible value variant for testing.
77///
78/// Used by both [`MockVectorWriter`] and [`MockVectorReader`] to represent the
79/// typed values in a column without requiring a live `DuckDB` runtime.
80#[derive(Debug, Clone, PartialEq)]
81#[non_exhaustive]
82pub enum MockDuckValue {
83    /// `TINYINT` / `INT8`
84    I8(i8),
85    /// `SMALLINT` / `INT16`
86    I16(i16),
87    /// `INTEGER` / `INT32`
88    I32(i32),
89    /// `BIGINT` / `INT64`
90    I64(i64),
91    /// `UTINYINT` / `UINT8`
92    U8(u8),
93    /// `USMALLINT` / `UINT16`
94    U16(u16),
95    /// `UINTEGER` / `UINT32`
96    U32(u32),
97    /// `UBIGINT` / `UINT64`
98    U64(u64),
99    /// `FLOAT`
100    F32(f32),
101    /// `DOUBLE`
102    F64(f64),
103    /// `BOOLEAN`
104    Bool(bool),
105    /// `HUGEINT`
106    I128(i128),
107    /// `VARCHAR`
108    Varchar(String),
109    /// `BLOB`
110    Blob(Vec<u8>),
111    /// `INTERVAL`
112    Interval(DuckInterval),
113}
114
115/// An in-memory mock output vector for testing finalize and scan callbacks.
116///
117/// Write typed values and NULL flags using the same method names as
118/// [`VectorWriter`][crate::vector::VectorWriter]. Inspect the results with
119/// [`try_get_i64`][Self::try_get_i64], [`is_null`][Self::is_null], etc.
120///
121/// # Example
122///
123/// ```rust
124/// use quack_rs::testing::{MockVectorWriter, MockDuckValue};
125///
126/// let mut w = MockVectorWriter::new(3);
127/// w.write_i64(0, 42);
128/// w.write_i64(1, -7);
129/// w.set_null(2);
130///
131/// assert_eq!(w.try_get_i64(0), Some(42));
132/// assert_eq!(w.try_get_i64(1), Some(-7));
133/// assert!(w.is_null(2));
134/// ```
135///
136/// # It behaves like a real output vector, including where that hurts
137///
138/// A mock that is more forgiving than `DuckDB` makes a test pass for code that
139/// is wrong in production. So, as with a real vector (verified against
140/// `DuckDB` 1.5.5):
141///
142/// - **Validity is separate from data.** [`set_null`][Self::set_null] clears a
143///   validity bit and a later `write_*` does **not** set it again — a real
144///   vector keeps returning NULL for that row. Use
145///   [`set_valid`][Self::set_valid] to undo a NULL.
146/// - **A row that is never written is valid, not NULL.** `DuckDB` hands out
147///   output vectors whose rows are all valid and whose data is whatever the
148///   buffer last held, so a callback that forgets `set_null` returns garbage.
149///   Here such a row reports [`is_null`][Self::is_null] `== false` and
150///   [`is_written`][Self::is_written] `== false`, so a test can catch it.
151/// - **Capacity is fixed.** Writing at or past the capacity given to
152///   [`new`][Self::new] panics; on a real vector it is out-of-bounds memory
153///   access.
154/// - **Strings over [`MAX_STRING_LEN`][crate::vector::string::MAX_STRING_LEN]
155///   panic**, as [`VectorWriter::write_varchar`][crate::vector::VectorWriter::write_varchar]
156///   does.
157#[derive(Debug, Default)]
158pub struct MockVectorWriter {
159    /// Data per row; `None` means never written.
160    rows: Vec<Option<MockDuckValue>>,
161    /// Validity per row; `true` (valid) until `set_null`.
162    valid: Vec<bool>,
163}
164
165/// An in-memory mock input vector for testing update and scan callbacks.
166///
167/// Construct from typed slices using the convenience constructors, then call
168/// `row_count()`, `is_valid()`, and `try_get_*()` in your callback logic,
169/// matching the method names used in real `DuckDB` callbacks.
170///
171/// # Example
172///
173/// ```rust
174/// use quack_rs::testing::{MockVectorReader, MockDuckValue};
175///
176/// let reader = MockVectorReader::from_i64s([Some(10), None, Some(30)]);
177/// assert_eq!(reader.row_count(), 3);
178/// assert!(reader.is_valid(0));
179/// assert!(!reader.is_valid(1));
180/// assert_eq!(reader.try_get_i64(0), Some(10));
181/// assert_eq!(reader.try_get_i64(1), None); // NULL row
182/// assert_eq!(reader.try_get_i64(2), Some(30));
183/// ```
184#[derive(Debug, Clone)]
185pub struct MockVectorReader {
186    rows: Vec<Option<MockDuckValue>>,
187}