Skip to main content

quack_rs/testing/
mock_registrar.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//! [`MockRegistrar`] — a [`Registrar`] implementation for testing.
7//!
8//! `MockRegistrar` records which functions were registered without calling any
9//! `DuckDB` C API. Use it to unit-test your registration logic — verifying that
10//! the right functions are registered with the right names — without a live
11//! `DuckDB` instance.
12//!
13//! It refuses, with the same error, a builder the real registration refuses
14//! before its first `DuckDB` call: a missing return type or callback, a
15//! function set with no overloads, a copy function that implements neither
16//! direction, a config option without a type or default, a composite or
17//! literal [`TypeId`] in any slot, an `ANY` return type. Checks that need
18//! `DuckDB` are not run: a name or signature collision, a type the running
19//! `DuckDB` lacks (`TIME_NS` before 1.5.0), a default that does not convert
20//! to its config option's type.
21//!
22//! # Limitation: builders with `LogicalType` fields
23//!
24//! Builders that contain [`LogicalType`] values (e.g.,
25//! created with `.returns_logical(...)` or `.param_logical(...)`) cannot be used
26//! with `MockRegistrar` in `loadable-extension` test mode. `LogicalType`'s `Drop`
27//! implementation calls `duckdb_destroy_logical_type`, which panics when the
28//! `DuckDB` dispatch table is uninitialized.
29//!
30//! Stick to [`TypeId`]-based parameter and return types
31//! when building functions for use with `MockRegistrar`.
32//!
33//! # Example
34//!
35//! ```rust
36//! use quack_rs::connection::Registrar;
37//! use quack_rs::testing::MockRegistrar;
38//! use quack_rs::scalar::ScalarFunctionBuilder;
39//! use quack_rs::aggregate::AggregateFunctionBuilder;
40//! use quack_rs::types::TypeId;
41//! use quack_rs::error::ExtensionError;
42//! use libduckdb_sys::{duckdb_data_chunk, duckdb_function_info, duckdb_vector};
43//!
44//! unsafe extern "C" fn word_count(
45//!     _info: duckdb_function_info,
46//!     _input: duckdb_data_chunk,
47//!     _output: duckdb_vector,
48//! ) {
49//!     // ...
50//! }
51//!
52//! fn register_all(reg: &impl Registrar) -> Result<(), ExtensionError> {
53//!     let scalar = ScalarFunctionBuilder::new("word_count")
54//!         .param(TypeId::Varchar)
55//!         .returns(TypeId::BigInt)
56//!         .function(word_count);
57//!     unsafe { reg.register_scalar(scalar) }
58//! }
59//!
60//! let mock = MockRegistrar::new();
61//! register_all(&mock).unwrap();
62//! assert!(mock.has_scalar("word_count"));
63//! assert_eq!(mock.total_registrations(), 1);
64//! ```
65
66use std::cell::RefCell;
67
68use crate::aggregate::{AggregateFunctionBuilder, AggregateFunctionSetBuilder};
69use crate::cast::CastFunctionBuilder;
70use crate::connection::Registrar;
71use crate::error::ExtensionError;
72use crate::scalar::{ScalarFunctionBuilder, ScalarFunctionSetBuilder};
73use crate::sql_macro::SqlMacro;
74use crate::table::TableFunctionBuilder;
75use crate::types::{LogicalType, TypeId};
76
77/// A record of a single cast function registration.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct CastRecord {
80    /// The source type being cast from (if set via simple `TypeId`).
81    pub source: Option<TypeId>,
82    /// The target type being cast to (if set via simple `TypeId`).
83    pub target: Option<TypeId>,
84}
85
86/// An in-memory mock implementation of [`Registrar`] for unit testing.
87///
88/// All `register_*` methods succeed silently (returning `Ok(())`) and record
89/// the function name (or types for casts). No `DuckDB` C API is called.
90///
91/// # Thread safety
92///
93/// `MockRegistrar` uses `RefCell` for interior mutability and is **not** `Sync`.
94/// Call it from a single thread within your tests.
95#[derive(Debug, Default)]
96pub struct MockRegistrar {
97    scalar_names: RefCell<Vec<String>>,
98    scalar_set_names: RefCell<Vec<String>>,
99    aggregate_names: RefCell<Vec<String>>,
100    aggregate_set_names: RefCell<Vec<String>>,
101    table_names: RefCell<Vec<String>>,
102    sql_macro_names: RefCell<Vec<String>>,
103    casts: RefCell<Vec<CastRecord>>,
104    #[cfg(feature = "duckdb-1-5")]
105    copy_function_names: RefCell<Vec<String>>,
106    #[cfg(feature = "duckdb-1-5")]
107    config_option_names: RefCell<Vec<String>>,
108}
109
110impl MockRegistrar {
111    /// Creates a new, empty `MockRegistrar`.
112    #[must_use]
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    // ── Inspection ──────────────────────────────────────────────────────────
118
119    /// Returns the names of all scalar functions registered so far.
120    #[must_use]
121    pub fn scalar_names(&self) -> Vec<String> {
122        self.scalar_names.borrow().clone()
123    }
124
125    /// Returns the names of all scalar function sets registered so far.
126    #[must_use]
127    pub fn scalar_set_names(&self) -> Vec<String> {
128        self.scalar_set_names.borrow().clone()
129    }
130
131    /// Returns the names of all aggregate functions registered so far.
132    #[must_use]
133    pub fn aggregate_names(&self) -> Vec<String> {
134        self.aggregate_names.borrow().clone()
135    }
136
137    /// Returns the names of all aggregate function sets registered so far.
138    #[must_use]
139    pub fn aggregate_set_names(&self) -> Vec<String> {
140        self.aggregate_set_names.borrow().clone()
141    }
142
143    /// Returns the names of all table functions registered so far.
144    #[must_use]
145    pub fn table_names(&self) -> Vec<String> {
146        self.table_names.borrow().clone()
147    }
148
149    /// Returns the names of all SQL macros registered so far.
150    #[must_use]
151    pub fn sql_macro_names(&self) -> Vec<String> {
152        self.sql_macro_names.borrow().clone()
153    }
154
155    /// Returns all cast registrations recorded so far.
156    #[must_use]
157    pub fn casts(&self) -> Vec<CastRecord> {
158        self.casts.borrow().clone()
159    }
160
161    /// Returns the names of all copy functions registered so far.
162    #[cfg(feature = "duckdb-1-5")]
163    #[must_use]
164    pub fn copy_function_names(&self) -> Vec<String> {
165        self.copy_function_names.borrow().clone()
166    }
167
168    /// Returns `true` if a copy function with the given name was registered.
169    #[cfg(feature = "duckdb-1-5")]
170    #[must_use]
171    pub fn has_copy_function(&self, name: &str) -> bool {
172        self.copy_function_names.borrow().iter().any(|n| n == name)
173    }
174
175    /// Returns the names of all config options registered so far.
176    #[cfg(feature = "duckdb-1-5")]
177    #[must_use]
178    pub fn config_option_names(&self) -> Vec<String> {
179        self.config_option_names.borrow().clone()
180    }
181
182    /// Returns `true` if a config option with the given name was registered.
183    #[cfg(feature = "duckdb-1-5")]
184    #[must_use]
185    pub fn has_config_option(&self, name: &str) -> bool {
186        self.config_option_names.borrow().iter().any(|n| n == name)
187    }
188
189    /// Returns the total number of registrations across all types.
190    #[must_use]
191    pub fn total_registrations(&self) -> usize {
192        let base = self.scalar_names.borrow().len()
193            + self.scalar_set_names.borrow().len()
194            + self.aggregate_names.borrow().len()
195            + self.aggregate_set_names.borrow().len()
196            + self.table_names.borrow().len()
197            + self.sql_macro_names.borrow().len()
198            + self.casts.borrow().len();
199        #[cfg(feature = "duckdb-1-5")]
200        {
201            base + self.copy_function_names.borrow().len() + self.config_option_names.borrow().len()
202        }
203        #[cfg(not(feature = "duckdb-1-5"))]
204        {
205            base
206        }
207    }
208
209    // ── Convenience predicates ──────────────────────────────────────────────
210
211    /// Returns `true` if a scalar function with the given name was registered.
212    #[must_use]
213    pub fn has_scalar(&self, name: &str) -> bool {
214        self.scalar_names.borrow().iter().any(|n| n == name)
215    }
216
217    /// Returns `true` if a scalar function set with the given name was registered.
218    #[must_use]
219    pub fn has_scalar_set(&self, name: &str) -> bool {
220        self.scalar_set_names.borrow().iter().any(|n| n == name)
221    }
222
223    /// Returns `true` if an aggregate function with the given name was registered.
224    #[must_use]
225    pub fn has_aggregate(&self, name: &str) -> bool {
226        self.aggregate_names.borrow().iter().any(|n| n == name)
227    }
228
229    /// Returns `true` if an aggregate function set with the given name was registered.
230    #[must_use]
231    pub fn has_aggregate_set(&self, name: &str) -> bool {
232        self.aggregate_set_names.borrow().iter().any(|n| n == name)
233    }
234
235    /// Returns `true` if a table function with the given name was registered.
236    #[must_use]
237    pub fn has_table(&self, name: &str) -> bool {
238        self.table_names.borrow().iter().any(|n| n == name)
239    }
240
241    /// Returns `true` if a SQL macro with the given name was registered.
242    #[must_use]
243    pub fn has_sql_macro(&self, name: &str) -> bool {
244        self.sql_macro_names.borrow().iter().any(|n| n == name)
245    }
246}
247
248impl Registrar for MockRegistrar {
249    /// Records a scalar function registration. Never calls `DuckDB` C API.
250    ///
251    /// # Safety
252    ///
253    /// This implementation is safe to call in any context — no `DuckDB`
254    /// connection is required.
255    unsafe fn register_scalar(&self, builder: ScalarFunctionBuilder) -> Result<(), ExtensionError> {
256        builder.check_parts()?;
257        builder.check_types(LogicalType::check_slot_offline)?;
258        self.scalar_names
259            .borrow_mut()
260            .push(builder.name().to_owned());
261        Ok(())
262    }
263
264    /// Records a scalar function set registration. Never calls `DuckDB` C API.
265    ///
266    /// # Safety
267    ///
268    /// This implementation is safe to call in any context.
269    unsafe fn register_scalar_set(
270        &self,
271        builder: ScalarFunctionSetBuilder,
272    ) -> Result<(), ExtensionError> {
273        builder.check_parts()?;
274        builder.check_types(LogicalType::check_slot_offline)?;
275        self.scalar_set_names
276            .borrow_mut()
277            .push(builder.name().to_owned());
278        Ok(())
279    }
280
281    /// Records an aggregate function registration. Never calls `DuckDB` C API.
282    ///
283    /// # Safety
284    ///
285    /// This implementation is safe to call in any context.
286    unsafe fn register_aggregate(
287        &self,
288        builder: AggregateFunctionBuilder,
289    ) -> Result<(), ExtensionError> {
290        builder.check_parts()?;
291        builder.check_types(LogicalType::check_slot_offline)?;
292        self.aggregate_names
293            .borrow_mut()
294            .push(builder.name().to_owned());
295        Ok(())
296    }
297
298    /// Records an aggregate function set registration. Never calls `DuckDB` C API.
299    ///
300    /// # Safety
301    ///
302    /// This implementation is safe to call in any context.
303    unsafe fn register_aggregate_set(
304        &self,
305        builder: AggregateFunctionSetBuilder,
306    ) -> Result<(), ExtensionError> {
307        builder.check_parts()?;
308        builder.check_types(LogicalType::check_slot_offline)?;
309        self.aggregate_set_names
310            .borrow_mut()
311            .push(builder.name().to_owned());
312        Ok(())
313    }
314
315    /// Records a table function registration. Never calls `DuckDB` C API.
316    ///
317    /// # Safety
318    ///
319    /// This implementation is safe to call in any context.
320    unsafe fn register_table(&self, builder: TableFunctionBuilder) -> Result<(), ExtensionError> {
321        builder.check_parts()?;
322        builder.check_types(LogicalType::check_slot_offline)?;
323        self.table_names
324            .borrow_mut()
325            .push(builder.name().to_owned());
326        Ok(())
327    }
328
329    /// Records a SQL macro registration. Never calls `DuckDB` C API.
330    ///
331    /// # Safety
332    ///
333    /// This implementation is safe to call in any context.
334    unsafe fn register_sql_macro(&self, sql_macro: SqlMacro) -> Result<(), ExtensionError> {
335        self.sql_macro_names
336            .borrow_mut()
337            .push(sql_macro.name().to_owned());
338        Ok(())
339    }
340
341    /// Records a cast function registration. Never calls `DuckDB` C API.
342    ///
343    /// The source and target types are captured from the builder.
344    ///
345    /// # Safety
346    ///
347    /// This implementation is safe to call in any context.
348    unsafe fn register_cast(&self, builder: CastFunctionBuilder) -> Result<(), ExtensionError> {
349        builder.check_parts()?;
350        builder.check_types(LogicalType::check_slot_offline)?;
351        self.casts.borrow_mut().push(CastRecord {
352            source: builder.source(),
353            target: builder.target(),
354        });
355        Ok(())
356    }
357
358    #[cfg(feature = "duckdb-1-5")]
359    unsafe fn register_copy_function(
360        &self,
361        builder: crate::copy_function::CopyFunctionBuilder,
362    ) -> Result<(), ExtensionError> {
363        builder.check_parts()?;
364        self.copy_function_names
365            .borrow_mut()
366            .push(builder.name().to_owned());
367        Ok(())
368    }
369
370    #[cfg(feature = "duckdb-1-5")]
371    unsafe fn register_config_option(
372        &self,
373        builder: crate::config_option::ConfigOptionBuilder,
374    ) -> Result<(), ExtensionError> {
375        builder.check_parts()?;
376        builder.check_types(LogicalType::check_slot_offline)?;
377        self.config_option_names
378            .borrow_mut()
379            .push(builder.name().to_owned());
380        Ok(())
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387    use crate::types::TypeId;
388    use libduckdb_sys::{
389        duckdb_aggregate_state, duckdb_bind_info, duckdb_data_chunk, duckdb_function_info,
390        duckdb_init_info, duckdb_vector, idx_t,
391    };
392
393    // Callbacks for complete builders. Never invoked: the mock only records.
394    unsafe extern "C" fn scalar_fn(
395        _: duckdb_function_info,
396        _: duckdb_data_chunk,
397        _: duckdb_vector,
398    ) {
399    }
400    unsafe extern "C" fn state_size(_: duckdb_function_info) -> idx_t {
401        0
402    }
403    unsafe extern "C" fn state_init(_: duckdb_function_info, _: duckdb_aggregate_state) {}
404    unsafe extern "C" fn update(
405        _: duckdb_function_info,
406        _: duckdb_data_chunk,
407        _: *mut duckdb_aggregate_state,
408    ) {
409    }
410    unsafe extern "C" fn combine(
411        _: duckdb_function_info,
412        _: *mut duckdb_aggregate_state,
413        _: *mut duckdb_aggregate_state,
414        _: idx_t,
415    ) {
416    }
417    unsafe extern "C" fn finalize(
418        _: duckdb_function_info,
419        _: *mut duckdb_aggregate_state,
420        _: duckdb_vector,
421        _: idx_t,
422        _: idx_t,
423    ) {
424    }
425    unsafe extern "C" fn table_bind(_: duckdb_bind_info) {}
426    unsafe extern "C" fn table_init(_: duckdb_init_info) {}
427    unsafe extern "C" fn table_scan(_: duckdb_function_info, _: duckdb_data_chunk) {}
428    unsafe extern "C" fn cast_fn(
429        _: duckdb_function_info,
430        _: idx_t,
431        _: duckdb_vector,
432        _: duckdb_vector,
433    ) -> bool {
434        true
435    }
436
437    fn scalar(name: &str) -> ScalarFunctionBuilder {
438        ScalarFunctionBuilder::new(name)
439            .param(TypeId::BigInt)
440            .returns(TypeId::BigInt)
441            .function(scalar_fn)
442    }
443
444    fn aggregate(name: &str) -> AggregateFunctionBuilder {
445        AggregateFunctionBuilder::new(name)
446            .param(TypeId::BigInt)
447            .returns(TypeId::BigInt)
448            .state_size(state_size)
449            .init(state_init)
450            .update(update)
451            .combine(combine)
452            .finalize(finalize)
453    }
454
455    fn table(name: &str) -> TableFunctionBuilder {
456        TableFunctionBuilder::new(name)
457            .bind(table_bind)
458            .init(table_init)
459            .scan(table_scan)
460    }
461
462    fn cast() -> CastFunctionBuilder {
463        CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer).function(cast_fn)
464    }
465
466    #[test]
467    fn mock_registrar_records_scalar() {
468        let mock = MockRegistrar::new();
469        unsafe { mock.register_scalar(scalar("my_fn")).unwrap() };
470        assert!(mock.has_scalar("my_fn"));
471        assert_eq!(mock.scalar_names(), vec!["my_fn"]);
472        assert_eq!(mock.total_registrations(), 1);
473    }
474
475    #[test]
476    fn mock_registrar_records_aggregate() {
477        let mock = MockRegistrar::new();
478        unsafe { mock.register_aggregate(aggregate("my_agg")).unwrap() };
479        assert!(mock.has_aggregate("my_agg"));
480        assert_eq!(mock.aggregate_names(), vec!["my_agg"]);
481        assert_eq!(mock.total_registrations(), 1);
482    }
483
484    #[test]
485    fn mock_registrar_records_scalar_set() {
486        let mock = MockRegistrar::new();
487        let builder = crate::scalar::ScalarFunctionSetBuilder::new("my_set").overload(
488            crate::scalar::ScalarOverloadBuilder::new()
489                .param(TypeId::BigInt)
490                .returns(TypeId::BigInt)
491                .function(scalar_fn),
492        );
493        unsafe { mock.register_scalar_set(builder).unwrap() };
494        assert!(mock.has_scalar_set("my_set"));
495        assert!(!mock.has_scalar_set("other"));
496        assert_eq!(mock.scalar_set_names(), vec!["my_set"]);
497        assert_eq!(mock.total_registrations(), 1);
498    }
499
500    #[test]
501    fn mock_registrar_records_aggregate_set() {
502        let mock = MockRegistrar::new();
503        let builder = AggregateFunctionSetBuilder::new("my_agg_set").overload(
504            crate::aggregate::AggregateOverloadBuilder::new()
505                .param(TypeId::BigInt)
506                .returns(TypeId::BigInt)
507                .state_size(state_size)
508                .init(state_init)
509                .update(update)
510                .combine(combine)
511                .finalize(finalize),
512        );
513        unsafe { mock.register_aggregate_set(builder).unwrap() };
514        assert!(mock.has_aggregate_set("my_agg_set"));
515        assert_eq!(mock.aggregate_set_names(), vec!["my_agg_set"]);
516        assert_eq!(mock.total_registrations(), 1);
517    }
518
519    #[test]
520    fn mock_registrar_records_table() {
521        let mock = MockRegistrar::new();
522        unsafe { mock.register_table(table("my_table")).unwrap() };
523        assert!(mock.has_table("my_table"));
524        assert_eq!(mock.table_names(), vec!["my_table"]);
525        assert_eq!(mock.total_registrations(), 1);
526    }
527
528    #[test]
529    fn mock_registrar_records_sql_macro() {
530        let mock = MockRegistrar::new();
531        let macro_ = SqlMacro::scalar("my_macro", &["x"], "x + 1").unwrap();
532        unsafe { mock.register_sql_macro(macro_).unwrap() };
533        assert!(mock.has_sql_macro("my_macro"));
534        assert_eq!(mock.sql_macro_names(), vec!["my_macro"]);
535        assert_eq!(mock.total_registrations(), 1);
536    }
537
538    #[test]
539    fn mock_registrar_records_cast() {
540        let mock = MockRegistrar::new();
541        unsafe { mock.register_cast(cast()).unwrap() };
542        let casts = mock.casts();
543        assert_eq!(casts.len(), 1);
544        assert_eq!(casts[0].source, Some(TypeId::Varchar));
545        assert_eq!(casts[0].target, Some(TypeId::Integer));
546        assert_eq!(mock.total_registrations(), 1);
547    }
548
549    #[test]
550    fn mock_registrar_multiple_registrations() {
551        let mock = MockRegistrar::new();
552
553        let s1 = scalar("fn_one");
554        let s2 = scalar("fn_two");
555
556        unsafe {
557            mock.register_scalar(s1).unwrap();
558            mock.register_scalar(s2).unwrap();
559        }
560
561        assert_eq!(mock.total_registrations(), 2);
562        assert!(mock.has_scalar("fn_one"));
563        assert!(mock.has_scalar("fn_two"));
564        assert!(!mock.has_scalar("fn_three"));
565    }
566
567    #[test]
568    #[cfg(feature = "duckdb-1-5")]
569    fn mock_registrar_records_copy_function() {
570        let mock = MockRegistrar::new();
571        assert!(!mock.has_copy_function("my_format"));
572        assert_eq!(mock.copy_function_names(), [] as [String; 0]);
573
574        let builder = crate::copy_function::CopyFunctionBuilder::try_new("my_format")
575            .unwrap()
576            .bind(copy_bind)
577            .sink(copy_sink)
578            .finalize(copy_finalize);
579        unsafe { mock.register_copy_function(builder).unwrap() };
580
581        assert!(mock.has_copy_function("my_format"));
582        assert!(!mock.has_copy_function("other_format"));
583        assert_eq!(mock.copy_function_names(), vec!["my_format"]);
584
585        // Config options go through the same trait, so an extension's whole
586        // registration closure is mockable rather than only part of it.
587        assert!(!mock.has_config_option("my_option"));
588        assert_eq!(mock.config_option_names(), [] as [String; 0]);
589
590        let option = crate::config_option::ConfigOptionBuilder::try_new("my_option")
591            .expect("name")
592            .option_type(TypeId::Varchar)
593            .default_value("x")
594            .expect("default");
595        // SAFETY: the mock ignores the connection entirely.
596        unsafe { mock.register_config_option(option) }.expect("register");
597        assert!(mock.has_config_option("my_option"));
598        // A name that was never registered must not match: without this, a
599        // `has_config_option` that always returns `true` passes every other
600        // assertion here. (Surviving mutant reported by the incremental
601        // mutation gate; mirrors the `has_copy_function` coverage above.)
602        assert!(!mock.has_config_option("other_option"));
603        assert_eq!(mock.config_option_names(), vec!["my_option"]);
604        assert_eq!(mock.copy_function_names().len(), 1);
605        assert_eq!(mock.total_registrations(), 2);
606    }
607
608    /// Registers one scalar **and** one copy function so that
609    /// `total_registrations` must add (not subtract) the copy-function count.
610    /// With the `+ with -` mutation, `base(1) - copy_len(1) = 0 ≠ 2`.
611    #[test]
612    #[cfg(feature = "duckdb-1-5")]
613    fn mock_registrar_total_registrations_scalar_plus_copy_function() {
614        let mock = MockRegistrar::new();
615
616        let scalar = scalar("my_scalar");
617        let copy_fn = crate::copy_function::CopyFunctionBuilder::try_new("my_format")
618            .unwrap()
619            .bind(copy_bind)
620            .sink(copy_sink)
621            .finalize(copy_finalize);
622
623        unsafe {
624            mock.register_scalar(scalar).unwrap();
625            mock.register_copy_function(copy_fn).unwrap();
626        }
627
628        assert_eq!(mock.total_registrations(), 2);
629        assert!(mock.has_scalar("my_scalar"));
630        assert!(mock.has_copy_function("my_format"));
631    }
632
633    #[test]
634    fn mock_registrar_has_aggregate_false_when_empty() {
635        let mock = MockRegistrar::new();
636        assert!(!mock.has_aggregate("x"));
637    }
638
639    #[test]
640    fn mock_registrar_has_aggregate_set_false_when_empty() {
641        let mock = MockRegistrar::new();
642        assert!(!mock.has_aggregate_set("x"));
643    }
644
645    #[test]
646    fn mock_registrar_has_table_false_when_empty() {
647        let mock = MockRegistrar::new();
648        assert!(!mock.has_table("x"));
649    }
650
651    #[test]
652    fn mock_registrar_has_sql_macro_false_when_empty() {
653        let mock = MockRegistrar::new();
654        assert!(!mock.has_sql_macro("x"));
655    }
656
657    #[test]
658    fn mock_registrar_has_scalar_false_when_empty() {
659        let mock = MockRegistrar::new();
660        assert!(!mock.has_scalar("x"));
661    }
662
663    #[test]
664    fn mock_registrar_empty_total_registrations() {
665        let mock = MockRegistrar::new();
666        assert_eq!(mock.total_registrations(), 0);
667    }
668
669    #[test]
670    fn mock_registrar_total_registrations_counts_all_types() {
671        let mock = MockRegistrar::new();
672
673        let scalar = scalar("sc");
674        let agg = aggregate("ag");
675        let table = table("tb");
676        let macro_ = SqlMacro::scalar("mc", &["x"], "x + 1").unwrap();
677        let cast = cast();
678
679        unsafe {
680            mock.register_scalar(scalar).unwrap();
681            mock.register_aggregate(agg).unwrap();
682            mock.register_table(table).unwrap();
683            mock.register_sql_macro(macro_).unwrap();
684            mock.register_cast(cast).unwrap();
685        }
686
687        assert_eq!(mock.total_registrations(), 5);
688    }
689
690    #[test]
691    fn mock_registrar_used_with_generic_registrar() {
692        // Demonstrates using MockRegistrar where &impl Registrar is expected.
693        fn register_all(reg: &impl Registrar) -> Result<(), ExtensionError> {
694            unsafe { reg.register_scalar(scalar("compute")) }
695        }
696
697        let mock = MockRegistrar::new();
698        register_all(&mock).unwrap();
699        assert!(mock.has_scalar("compute"));
700    }
701
702    #[cfg(feature = "duckdb-1-5")]
703    unsafe extern "C" fn copy_bind(_: libduckdb_sys::duckdb_copy_function_bind_info) {}
704    #[cfg(feature = "duckdb-1-5")]
705    unsafe extern "C" fn copy_sink(
706        _: libduckdb_sys::duckdb_copy_function_sink_info,
707        _: duckdb_data_chunk,
708    ) {
709    }
710    #[cfg(feature = "duckdb-1-5")]
711    unsafe extern "C" fn copy_finalize(_: libduckdb_sys::duckdb_copy_function_finalize_info) {}
712
713    /// The mock used to record any builder, so a test could pass with a
714    /// registration the real connection refuses at `LOAD` — the module's own
715    /// doc example registered a scalar with no function callback. It now
716    /// runs the same checks the real registration runs before its first
717    /// `DuckDB` call, with the same messages, and records nothing on failure.
718    #[test]
719    fn the_mock_refuses_what_registration_refuses() {
720        let mock = MockRegistrar::new();
721        let refuse = |result: Result<(), ExtensionError>, want: &str| {
722            let err = result.expect_err(want);
723            assert!(err.as_str().contains(want), "{want}: {err}");
724        };
725        // SAFETY (every call): the mock ignores the connection entirely.
726        unsafe {
727            refuse(
728                mock.register_scalar(ScalarFunctionBuilder::new("f").returns(TypeId::BigInt)),
729                "function callback not set",
730            );
731            refuse(
732                mock.register_scalar(ScalarFunctionBuilder::new("f").function(scalar_fn)),
733                "return type not set",
734            );
735            refuse(
736                mock.register_scalar_set(crate::scalar::ScalarFunctionSetBuilder::new("s")),
737                "no overloads",
738            );
739            refuse(
740                mock.register_scalar_set(
741                    crate::scalar::ScalarFunctionSetBuilder::new("s").overload(
742                        crate::scalar::ScalarOverloadBuilder::new().returns(TypeId::BigInt),
743                    ),
744                ),
745                "overload 0 has no function callback",
746            );
747            refuse(
748                mock.register_aggregate(
749                    AggregateFunctionBuilder::new("a")
750                        .returns(TypeId::BigInt)
751                        .state_size(state_size)
752                        .init(state_init)
753                        .update(update)
754                        .combine(combine),
755                ),
756                "finalize callback not set",
757            );
758            refuse(
759                mock.register_aggregate_set(AggregateFunctionSetBuilder::new("as")),
760                "no overloads",
761            );
762            refuse(
763                mock.register_table(
764                    TableFunctionBuilder::new("t")
765                        .bind(table_bind)
766                        .init(table_init),
767                ),
768                "scan callback not set",
769            );
770            refuse(
771                mock.register_cast(CastFunctionBuilder::new(TypeId::Varchar, TypeId::Integer)),
772                "cast function callback not set",
773            );
774        }
775        assert_eq!(mock.total_registrations(), 0, "nothing refused is recorded");
776    }
777
778    /// The mock ran only the missing-part checks, so it recorded builders
779    /// whose types the real registration refuses before its first `DuckDB`
780    /// call: a composite or literal `TypeId` in any slot, an `ANY` return.
781    #[test]
782    fn the_mock_refuses_the_types_registration_refuses() {
783        let mock = MockRegistrar::new();
784        let refuse = |result: Result<(), ExtensionError>, want: &str| {
785            let err = result.expect_err(want);
786            assert!(err.as_str().contains(want), "{want}: {err}");
787        };
788        // SAFETY (every call): the mock ignores the connection entirely.
789        unsafe {
790            refuse(
791                mock.register_scalar(scalar("f").param(TypeId::Struct)),
792                "scalar function parameter 1: ",
793            );
794            refuse(
795                mock.register_scalar(scalar("f").varargs(TypeId::IntegerLiteral)),
796                "scalar function varargs: ",
797            );
798            refuse(
799                mock.register_scalar(scalar("f").returns(TypeId::Any)),
800                "scalar function return type must not be or contain ANY",
801            );
802            refuse(
803                mock.register_scalar_set(
804                    crate::scalar::ScalarFunctionSetBuilder::new("s").overload(
805                        crate::scalar::ScalarOverloadBuilder::new()
806                            .param(TypeId::List)
807                            .returns(TypeId::BigInt)
808                            .function(scalar_fn),
809                    ),
810                ),
811                "overload 0 parameter 0: ",
812            );
813            refuse(
814                mock.register_aggregate(aggregate("a").returns(TypeId::StringLiteral)),
815                "aggregate function return type: ",
816            );
817            refuse(
818                mock.register_aggregate_set(
819                    AggregateFunctionSetBuilder::new("as")
820                        .returns(TypeId::Any)
821                        .overload(
822                            crate::aggregate::AggregateOverloadBuilder::new()
823                                .param(TypeId::BigInt)
824                                .state_size(state_size)
825                                .init(state_init)
826                                .update(update)
827                                .combine(combine)
828                                .finalize(finalize),
829                        ),
830                ),
831                "overload 0 return type must not be or contain ANY",
832            );
833            refuse(
834                mock.register_table(table("t").param(TypeId::Map)),
835                "table function parameter 0: ",
836            );
837            refuse(
838                mock.register_table(table("t").named_param("n", TypeId::Union)),
839                "table function named parameter n: ",
840            );
841            refuse(
842                mock.register_cast(
843                    CastFunctionBuilder::new(TypeId::Struct, TypeId::Integer).function(cast_fn),
844                ),
845                "cast function source type: ",
846            );
847        }
848        assert_eq!(mock.total_registrations(), 0, "nothing refused is recorded");
849    }
850
851    #[cfg(feature = "duckdb-1-5")]
852    #[test]
853    fn the_mock_refuses_incomplete_copy_functions_and_config_options() {
854        let mock = MockRegistrar::new();
855        let copy = crate::copy_function::CopyFunctionBuilder::try_new("fmt").unwrap();
856        // SAFETY: the mock ignores the connection entirely.
857        let err = unsafe { mock.register_copy_function(copy) }.expect_err("nothing set");
858        assert!(err.as_str().contains("implements nothing"), "{err}");
859        let option = crate::config_option::ConfigOptionBuilder::try_new("opt")
860            .expect("name")
861            .option_type(TypeId::Varchar);
862        // SAFETY: as above.
863        let err = unsafe { mock.register_config_option(option) }.expect_err("no default");
864        assert!(err.as_str().contains("has no default value"), "{err}");
865        let option = crate::config_option::ConfigOptionBuilder::try_new("opt")
866            .expect("name")
867            .option_type(TypeId::Struct)
868            .default_value("x")
869            .expect("default");
870        // SAFETY: as above.
871        let err = unsafe { mock.register_config_option(option) }.expect_err("composite type");
872        assert!(err.as_str().starts_with("config option type: "), "{err}");
873        assert_eq!(mock.total_registrations(), 0);
874    }
875}