Skip to main content

quack_rs/
config_option.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//! Extension-defined configuration options (`DuckDB` 1.5.0+).
7//!
8//! Extensions can register custom settings that users can read and write via
9//! `SET` / `RESET` / `current_setting()`. This module wraps the
10//! `duckdb_config_option` C API surface behind a safe builder.
11//!
12//! # Example
13//!
14//! ```rust,no_run
15//! use quack_rs::config_option::{ConfigOptionBuilder, ConfigOptionScope};
16//! use quack_rs::types::TypeId;
17//!
18//! let option = ConfigOptionBuilder::try_new("my_ext_threshold")?
19//!     .description("Maximum threshold for my_ext operations")?
20//!     .option_type(TypeId::BigInt)
21//!     .default_value("100")?
22//!     .scope(ConfigOptionScope::Global);
23//! # Ok::<(), quack_rs::error::ExtensionError>(())
24//! ```
25
26use std::ffi::CString;
27
28use libduckdb_sys::{
29    duckdb_config_option, duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_GLOBAL,
30    duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_LOCAL,
31    duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_SESSION,
32    duckdb_config_option_set_default_scope, duckdb_config_option_set_default_value,
33    duckdb_config_option_set_description, duckdb_config_option_set_name,
34    duckdb_config_option_set_type, duckdb_connection, duckdb_create_config_option,
35    duckdb_destroy_config_option, duckdb_register_config_option, DuckDBSuccess,
36};
37
38use crate::error::ExtensionError;
39use crate::types::logical_type::SlotCheck;
40use crate::types::{LogicalType, TypeId};
41use crate::value::Value;
42use crate::vector::VectorReader;
43
44/// Scope in which a configuration option takes effect.
45///
46/// `#[non_exhaustive]`: `DuckDB` may add a scope, so a `match` outside
47/// quack-rs needs a wildcard arm.
48///
49/// ```rust,compile_fail,E0004
50/// use quack_rs::config_option::ConfigOptionScope;
51///
52/// fn per_connection(scope: ConfigOptionScope) -> bool {
53///     match scope {
54///         ConfigOptionScope::Local | ConfigOptionScope::Session => true,
55///         ConfigOptionScope::Global => false,
56///         // error[E0004]: a wildcard arm is required
57///     }
58/// }
59/// ```
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum ConfigOptionScope {
63    /// Option is local to the current statement.
64    Local,
65    /// Option is scoped to the current session.
66    Session,
67    /// Option applies globally to the database.
68    Global,
69}
70
71impl ConfigOptionScope {
72    /// Converts to the `DuckDB` C API scope constant.
73    #[must_use]
74    pub(crate) const fn to_raw(self) -> u32 {
75        match self {
76            Self::Local => duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_LOCAL,
77            Self::Session => duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_SESSION,
78            Self::Global => duckdb_config_option_scope_DUCKDB_CONFIG_OPTION_SCOPE_GLOBAL,
79        }
80    }
81}
82
83/// Builder for registering extension-defined configuration options.
84///
85/// After building, call [`register`][Self::register] from your entry point to
86/// register the setting with `DuckDB`.
87#[must_use]
88#[derive(Debug)]
89pub struct ConfigOptionBuilder {
90    name: CString,
91    description: Option<CString>,
92    option_type: Option<TypeId>,
93    default_value: Option<CString>,
94    scope: ConfigOptionScope,
95}
96
97impl ConfigOptionBuilder {
98    /// Creates a new config option builder with the given name.
99    ///
100    /// # Errors
101    ///
102    /// Returns `ExtensionError` if the name contains a null byte.
103    pub fn try_new(name: &str) -> Result<Self, ExtensionError> {
104        let c_name = CString::new(name)
105            .map_err(|_| ExtensionError::new("config option name contains null byte"))?;
106        Ok(Self {
107            name: c_name,
108            description: None,
109            option_type: None,
110            default_value: None,
111            scope: ConfigOptionScope::Global,
112        })
113    }
114
115    /// Returns the name of this config option.
116    #[must_use]
117    pub fn name(&self) -> &str {
118        self.name.to_str().unwrap_or("")
119    }
120
121    /// Sets the human-readable description for this option.
122    ///
123    /// # Errors
124    ///
125    /// Returns `ExtensionError` if `desc` contains a null byte.
126    pub fn description(mut self, desc: &str) -> Result<Self, ExtensionError> {
127        self.description =
128            Some(CString::new(desc).map_err(|_| {
129                ExtensionError::new("config option description contains null byte")
130            })?);
131        Ok(self)
132    }
133
134    /// Sets the value type for this option (e.g. `TypeId::BigInt`, `TypeId::Varchar`).
135    pub const fn option_type(mut self, type_id: TypeId) -> Self {
136        self.option_type = Some(type_id);
137        self
138    }
139
140    /// Sets the default value as a string representation.
141    ///
142    /// The string is converted to the option's type at
143    /// [`register`][Self::register] time, with the same SQL cast `SET` uses;
144    /// a string that does not convert is an error there. Every option needs a
145    /// default — see [`register`][Self::register].
146    ///
147    /// # Errors
148    ///
149    /// Returns `ExtensionError` if `value` contains a null byte.
150    pub fn default_value(mut self, value: &str) -> Result<Self, ExtensionError> {
151        self.default_value =
152            Some(CString::new(value).map_err(|_| {
153                ExtensionError::new("config option default value contains null byte")
154            })?);
155        Ok(self)
156    }
157
158    /// Sets the scope for this option.
159    pub const fn scope(mut self, scope: ConfigOptionScope) -> Self {
160        self.scope = scope;
161        self
162    }
163
164    /// The checks that need no `DuckDB` call: a concrete option type and a
165    /// default value. [`MockRegistrar`][crate::testing::MockRegistrar] runs
166    /// them too.
167    pub(crate) fn check_parts(&self) -> Result<(), ExtensionError> {
168        let name = self.name.to_string_lossy();
169        let type_id = self
170            .option_type
171            .ok_or_else(|| ExtensionError::new("config option type not set"))?;
172        if matches!(
173            type_id,
174            TypeId::Any | TypeId::SqlNull | TypeId::IntegerLiteral | TypeId::StringLiteral
175        ) {
176            return Err(ExtensionError::new(format!(
177                "config option '{name}': {} cannot be the type of a config option; it is a \
178                 pseudo-type that no value is stored as. Use a concrete type such as VARCHAR.",
179                type_id.sql_name()
180            )));
181        }
182        if self.default_value.is_none() {
183            return Err(ExtensionError::new(format!(
184                "config option '{name}' has no default value. DuckDB treats an extension option \
185                 without one as unset: current_setting('{name}') fails with \"unrecognized \
186                 configuration parameter\" until it is SET. Call default_value(...)."
187            )));
188        }
189        Ok(())
190    }
191
192    /// Refuses a type [`register`][Self::register] refuses before its first
193    /// `DuckDB` call; `slot` checks each `TypeId` (see [`SlotCheck`]).
194    pub(crate) fn check_types(&self, slot: SlotCheck) -> Result<(), ExtensionError> {
195        self.option_type
196            .map_or(Ok(()), |id| slot(id, "config option type"))
197    }
198
199    /// Registers this config option with `DuckDB`.
200    ///
201    /// # The default is converted by SQL, never inside the C API
202    ///
203    /// `duckdb_config_option_set_default_value` converts a default whose type
204    /// differs from the option's with `Value::DefaultCastAs` — a *throwing*
205    /// cast with no `try`/`catch` around it — so a string default that does
206    /// not convert would abort the process ("Rust cannot catch foreign
207    /// exceptions"). Worse, `DefaultCastAs` uses only the built-in casts while
208    /// SQL uses the connection's, so a string one accepts can still make the
209    /// other throw: with ICU loaded, `'2020-01-01 10:00:00 America/New_York'`
210    /// is a valid `TIMESTAMPTZ` in SQL and an abort in `DefaultCastAs`.
211    ///
212    /// `register` therefore converts the default itself, by running
213    /// `SELECT TRY_CAST($1::VARCHAR AS <type>)` on `con` with the default bound
214    /// as a parameter, and hands `DuckDB` a value that **already has the
215    /// option's type**. `duckdb_config_option_set_default_value` stores such a
216    /// value as-is (it only casts when `coption->type != cvalue->type()`,
217    /// `src/main/capi/config_options-c.cpp`), so no cast can run inside the C
218    /// API. The stored default is exactly what `TRY_CAST('<default>' AS <type>)`
219    /// produces in SQL on `con`.
220    ///
221    /// Option types whose values the C API cannot construct from a query
222    /// result (`BIGNUM`, `GEOMETRY`, `VARIANT`, ...) are refused rather than
223    /// sent down the throwing path.
224    ///
225    /// # Errors
226    ///
227    /// Returns `ExtensionError`, before anything is registered, if:
228    ///
229    /// - the option type was not set, or is a pseudo-type (`ANY`, `SQLNULL`,
230    ///   the literal types) that no setting can have;
231    /// - no default value was set. `DuckDB` treats an extension option
232    ///   without a default as unset: `current_setting` reports it as an
233    ///   "unrecognized configuration parameter" until someone `SET`s it, and
234    ///   [`ClientContext::config_option`][crate::client_context::ClientContext::config_option]
235    ///   on it takes the path a debug build of `DuckDB` asserts on;
236    /// - the name is already a setting — built-in (`threads`), an alias of
237    ///   one (`worker_threads`), or another extension's. Names are compared
238    ///   case-insensitively, as `DuckDB` resolves them. `DuckDB` itself only
239    ///   refuses a name another *extension option* has, and silently lets an
240    ///   extension option shadow a built-in one for `current_setting`;
241    /// - the default does not convert to the option type (or the conversion
242    ///   query cannot run on `con`), or the type cannot carry a default;
243    /// - `duckdb_register_config_option` fails.
244    ///
245    /// # Safety
246    ///
247    /// `con` must be a valid, open `duckdb_connection`.
248    pub unsafe fn register(self, con: duckdb_connection) -> Result<(), ExtensionError> {
249        self.check_parts()?;
250        self.check_types(LogicalType::check_slot)?;
251        let name = self.name.to_string_lossy();
252        let type_id = self
253            .option_type
254            .ok_or_else(|| ExtensionError::new("config option type not set"))?;
255        let Some(ref default) = self.default_value else {
256            return Err(ExtensionError::new("config option has no default value"));
257        };
258        let lt = LogicalType::for_slot(type_id, "config option type")?;
259        // SAFETY: `con` is valid per this function's contract.
260        unsafe { refuse_existing_setting(con, &name) }?;
261        // SAFETY: `con` is valid per this function's contract.
262        let default = unsafe { typed_default(con, &name, type_id, default) }?;
263
264        // SAFETY: duckdb_create_config_option allocates a new handle.
265        let option: duckdb_config_option = unsafe { duckdb_create_config_option() };
266
267        // SAFETY: option is a valid newly created handle.
268        unsafe {
269            duckdb_config_option_set_name(option, self.name.as_ptr());
270            duckdb_config_option_set_type(option, lt.as_raw());
271            duckdb_config_option_set_default_scope(option, self.scope.to_raw());
272        }
273
274        if let Some(ref desc) = self.description {
275            // SAFETY: option and desc are valid.
276            unsafe {
277                duckdb_config_option_set_description(option, desc.as_ptr());
278            }
279        }
280
281        // SAFETY: option and the value are valid. The value already has the
282        // option's type, so DuckDB copies it without casting (no throw
283        // possible); `default` still owns it and destroys it on drop.
284        unsafe {
285            duckdb_config_option_set_default_value(option, default.as_raw());
286        }
287
288        // SAFETY: con is valid per caller's contract, option is fully configured.
289        let result = unsafe { duckdb_register_config_option(con, option) };
290
291        // SAFETY: option was created above and must be destroyed after registration.
292        let mut option_mut = option;
293        // SAFETY: `option_mut` holds the `new CConfigOption` from
294        // `duckdb_create_config_option` above, destroyed nowhere else.
295        // `duckdb_register_config_option` copied its name, description, type and
296        // default into the database config (`AddExtensionOption`,
297        // config_options-c.cpp) and kept no pointer to it, so this single
298        // `delete` is safe whether registration succeeded or not.
299        unsafe {
300            duckdb_destroy_config_option(&raw mut option_mut);
301        }
302
303        if result == DuckDBSuccess {
304            Ok(())
305        } else {
306            Err(ExtensionError::new(format!(
307                "duckdb_register_config_option failed for '{name}'"
308            )))
309        }
310    }
311}
312
313/// Refuses `name` if `duckdb_settings()` already lists it, as a setting or as
314/// an alias of one, compared case-insensitively.
315///
316/// # Safety
317///
318/// `con` must be a valid, open `duckdb_connection`.
319unsafe fn refuse_existing_setting(
320    con: duckdb_connection,
321    name: &str,
322) -> Result<(), ExtensionError> {
323    let context = |detail: String| {
324        ExtensionError::new(format!(
325            "config option '{name}': cannot check whether the name is taken: {detail}"
326        ))
327    };
328    // `aliases` is a VARCHAR[] column; unnesting it avoids lambda syntax,
329    // whose spelling DuckDB has been changing.
330    // Every function is qualified with `system.main`, so a user macro of the
331    // same name cannot change what the check computes.
332    let sql = "SELECT (SELECT count(*) FROM system.main.duckdb_settings() \
333                  WHERE system.main.lower(name) = system.main.lower($1)) \
334               + (SELECT count(*) FROM (SELECT system.main.unnest(aliases) AS alias \
335                  FROM system.main.duckdb_settings()) \
336                  WHERE system.main.lower(alias) = system.main.lower($1))";
337    // SAFETY: `con` is valid per this function's contract.
338    let statement =
339        unsafe { crate::query::prepare(con, sql) }.map_err(|e| context(e.to_string()))?;
340    statement
341        .bind_str(1, name)
342        .map_err(|e| context(e.to_string()))?;
343    let mut result = statement.execute().map_err(|e| context(e.to_string()))?;
344    let chunk = result
345        .next_chunk()
346        .map_err(|e| context(e.to_string()))?
347        .ok_or_else(|| context("the check returned no rows".into()))?;
348    if chunk.size() != 1 || chunk.column_count() != 1 {
349        return Err(context("the check returned an unexpected shape".into()));
350    }
351    // SAFETY: one row, one BIGINT column; a sum of two counts is never NULL.
352    let taken = unsafe { chunk.reader(0).read_i64(0) };
353    if taken == 0 {
354        Ok(())
355    } else {
356        Err(ExtensionError::new(format!(
357            "config option '{name}' already exists: DuckDB already has a setting (or setting \
358             alias) with this name — see `SELECT * FROM duckdb_settings()`. Registering it would \
359             fail, or silently shadow the built-in setting in current_setting(). Choose a name \
360             prefixed with your extension's name."
361        )))
362    }
363}
364
365/// Converts `default` to a value of type `type_id` with SQL
366/// `TRY_CAST($1::VARCHAR AS <type>)` and rebuilds the result as a
367/// `duckdb_value` of exactly that type.
368///
369/// This is what keeps `duckdb_config_option_set_default_value` from running
370/// its throwing `DefaultCastAs`: that call only casts when the value's type
371/// differs from the option's.
372///
373/// # Safety
374///
375/// `con` must be a valid, open `duckdb_connection`.
376unsafe fn typed_default(
377    con: duckdb_connection,
378    name: &str,
379    type_id: TypeId,
380    default: &CString,
381) -> Result<Value, ExtensionError> {
382    let default = default
383        .to_str()
384        .map_err(|_| ExtensionError::new("config option default value is not valid UTF-8"))?;
385    let context = |detail: String| {
386        ExtensionError::new(format!(
387            "config option '{name}': cannot convert default value {default:?} to {}: {detail}",
388            type_id.sql_name()
389        ))
390    };
391    let sql = format!("SELECT TRY_CAST($1::VARCHAR AS {})", type_id.sql_name());
392    // SAFETY: `con` is valid per this function's contract.
393    let statement =
394        unsafe { crate::query::prepare(con, &sql) }.map_err(|e| context(e.to_string()))?;
395    statement
396        .bind_str(1, default)
397        .map_err(|e| context(e.to_string()))?;
398    let mut result = statement.execute().map_err(|e| context(e.to_string()))?;
399    let chunk = result
400        .next_chunk()
401        .map_err(|e| context(e.to_string()))?
402        .ok_or_else(|| context("the conversion returned no rows".into()))?;
403    if chunk.size() != 1 || chunk.column_count() != 1 {
404        return Err(context(
405            "the conversion returned an unexpected shape".into(),
406        ));
407    }
408    // SAFETY: the chunk has one column and one row.
409    let reader = unsafe { chunk.reader(0) };
410    // SAFETY: row 0 exists.
411    if !unsafe { reader.is_valid(0) } {
412        return Err(ExtensionError::new(format!(
413            "config option '{name}': default value {default:?} cannot be cast to {}",
414            type_id.sql_name()
415        )));
416    }
417    // SAFETY: row 0 exists, is valid, and the column has type `type_id`.
418    unsafe { value_of_type(&reader, type_id) }.ok_or_else(|| {
419        ExtensionError::new(format!(
420            "config option '{name}': a default value of type {} is not supported; the C API \
421             cannot build one without a cast that may abort the process. Use a VARCHAR option \
422             and parse it yourself.",
423            type_id.sql_name()
424        ))
425    })
426}
427
428/// Reads row 0 of `reader` as a [`Value`] of type `type_id`, or `None` for a
429/// type the C API has no direct constructor for.
430///
431/// # Safety
432///
433/// Row 0 must exist, be valid, and hold a value of type `type_id`.
434unsafe fn value_of_type(reader: &VectorReader, type_id: TypeId) -> Option<Value> {
435    // SAFETY: (every arm) row 0 exists, is valid and holds a `type_id` value,
436    // per this function's `# Safety` contract, so each `read_*(0)` is in
437    // bounds and reads the physical layout it expects (`BIT` shares BLOB's
438    // `duckdb_string_t` layout). `reader` borrows the chunk, so the string
439    // bytes `read_str` / `read_blob` borrow stay live while the constructors
440    // copy them; `duckdb_create_bit` copies too (`Value::BIT`), and
441    // `Value::from_raw` takes the fresh handle it returns. The temporal
442    // constructors validate their payload; a value DuckDB's own `TRY_CAST`
443    // produced is always in range, so their `Err` arm is unreachable here and
444    // `.ok()?` only satisfies the type.
445    let value = unsafe {
446        match type_id {
447            TypeId::Boolean => Value::boolean(reader.read_bool(0)),
448            TypeId::TinyInt => Value::tinyint(reader.read_i8(0)),
449            TypeId::SmallInt => Value::smallint(reader.read_i16(0)),
450            TypeId::Integer => Value::integer(reader.read_i32(0)),
451            TypeId::BigInt => Value::bigint(reader.read_i64(0)),
452            TypeId::UTinyInt => Value::utinyint(reader.read_u8(0)),
453            TypeId::USmallInt => Value::usmallint(reader.read_u16(0)),
454            TypeId::UInteger => Value::uinteger(reader.read_u32(0)),
455            TypeId::UBigInt => Value::ubigint(reader.read_u64(0)),
456            TypeId::HugeInt => Value::hugeint(reader.read_i128(0)),
457            TypeId::UHugeInt => Value::uhugeint(reader.read_u128(0)),
458            TypeId::Float => Value::float(reader.read_f32(0)),
459            TypeId::Double => Value::double(reader.read_f64(0)),
460            TypeId::Date => Value::date(reader.read_date(0)),
461            TypeId::Time => Value::time(reader.read_time(0)).ok()?,
462            TypeId::TimeNs => Value::time_ns(reader.read_i64(0)).ok()?,
463            TypeId::TimeTz => Value::time_tz(reader.read_time_tz(0)).ok()?,
464            TypeId::Timestamp => Value::timestamp(reader.read_timestamp(0)).ok()?,
465            TypeId::TimestampS => Value::timestamp_s(reader.read_timestamp_s(0)).ok()?,
466            TypeId::TimestampMs => Value::timestamp_ms(reader.read_timestamp_ms(0)).ok()?,
467            TypeId::TimestampNs => Value::timestamp_ns(reader.read_timestamp_ns(0)).ok()?,
468            TypeId::TimestampTzNs => Value::timestamp_tz_ns(reader.read_timestamp_tz_ns(0)).ok()?,
469            TypeId::TimestampTz => Value::timestamp_tz(reader.read_timestamp_tz(0)).ok()?,
470            TypeId::Interval => Value::interval(reader.read_interval(0)),
471            TypeId::Varchar => Value::varchar(reader.read_str(0)),
472            TypeId::Blob => Value::blob(reader.read_blob(0)),
473            TypeId::Uuid => Value::uuid(reader.read_uuid(0)),
474            TypeId::Bit => {
475                // A BIT vector stores the same bytes `Value::BIT` takes: the
476                // padding byte followed by the bits.
477                let bytes = reader.read_blob(0);
478                let raw = libduckdb_sys::duckdb_create_bit(libduckdb_sys::duckdb_bit {
479                    data: bytes.as_ptr().cast_mut(),
480                    size: libduckdb_sys::idx_t::try_from(bytes.len()).ok()?,
481                });
482                Value::from_raw(raw)
483            }
484            _ => return None,
485        }
486    };
487    Some(value)
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use crate::types::TypeId;
494
495    #[test]
496    fn try_new_valid_name() {
497        let builder = ConfigOptionBuilder::try_new("my_option").unwrap();
498        assert_eq!(builder.name(), "my_option");
499    }
500
501    #[test]
502    fn try_new_null_byte_rejected() {
503        let result = ConfigOptionBuilder::try_new("bad\0name");
504        assert!(result.is_err());
505        let err = result.err().unwrap();
506        assert!(
507            err.to_string().contains("null byte"),
508            "error should mention null byte"
509        );
510    }
511
512    #[test]
513    fn description_null_byte_rejected() {
514        let result = ConfigOptionBuilder::try_new("opt")
515            .unwrap()
516            .description("bad\0desc");
517        assert!(result.is_err());
518    }
519
520    #[test]
521    fn default_value_null_byte_rejected() {
522        let result = ConfigOptionBuilder::try_new("opt")
523            .unwrap()
524            .default_value("bad\0val");
525        assert!(result.is_err());
526    }
527
528    #[test]
529    fn builder_stores_option_type() {
530        let builder = ConfigOptionBuilder::try_new("threshold")
531            .unwrap()
532            .option_type(TypeId::BigInt);
533        assert_eq!(builder.option_type, Some(TypeId::BigInt));
534    }
535
536    #[test]
537    fn builder_stores_description() {
538        let builder = ConfigOptionBuilder::try_new("threshold")
539            .unwrap()
540            .description("max threshold")
541            .unwrap();
542        assert_eq!(
543            builder.description.as_deref(),
544            Some(c"max threshold"),
545            "the description must be stored"
546        );
547    }
548
549    #[test]
550    fn builder_stores_default_value() {
551        let builder = ConfigOptionBuilder::try_new("limit")
552            .unwrap()
553            .default_value("100")
554            .unwrap();
555        assert_eq!(builder.default_value.as_deref(), Some(c"100"));
556    }
557
558    #[test]
559    fn scope_default_is_global() {
560        let builder = ConfigOptionBuilder::try_new("opt").unwrap();
561        assert_eq!(builder.scope, ConfigOptionScope::Global);
562        let builder = builder.scope(ConfigOptionScope::Session);
563        assert_eq!(builder.scope, ConfigOptionScope::Session);
564    }
565
566    /// The pseudo-type and missing-default checks run before `con` is used,
567    /// so a null connection is never dereferenced.
568    #[test]
569    fn pseudo_types_and_missing_defaults_are_refused_before_duckdb_is_called() {
570        for ty in [
571            TypeId::Any,
572            TypeId::SqlNull,
573            TypeId::IntegerLiteral,
574            TypeId::StringLiteral,
575        ] {
576            // SAFETY: `register` returns before using `con`.
577            let err = unsafe {
578                ConfigOptionBuilder::try_new("opt")
579                    .unwrap()
580                    .option_type(ty)
581                    .default_value("1")
582                    .unwrap()
583                    .register(std::ptr::null_mut())
584            }
585            .expect_err("a pseudo-type must be refused");
586            assert!(
587                err.as_str()
588                    .contains("cannot be the type of a config option"),
589                "{ty:?}: {err}"
590            );
591        }
592        // SAFETY: `register` returns before using `con`.
593        let err = unsafe {
594            ConfigOptionBuilder::try_new("opt")
595                .unwrap()
596                .option_type(TypeId::BigInt)
597                .register(std::ptr::null_mut())
598        }
599        .expect_err("an option without a default must be refused");
600        assert!(err.as_str().contains("no default value"), "{err}");
601    }
602
603    #[test]
604    fn scope_enum_to_raw_distinct_values() {
605        let local = ConfigOptionScope::Local.to_raw();
606        let session = ConfigOptionScope::Session.to_raw();
607        let global = ConfigOptionScope::Global.to_raw();
608        assert_ne!(local, session);
609        assert_ne!(session, global);
610        assert_ne!(local, global);
611    }
612
613    #[test]
614    fn scope_enum_debug_impl() {
615        assert_eq!(format!("{:?}", ConfigOptionScope::Local), "Local");
616        assert_eq!(format!("{:?}", ConfigOptionScope::Session), "Session");
617        assert_eq!(format!("{:?}", ConfigOptionScope::Global), "Global");
618    }
619
620    #[test]
621    fn scope_enum_clone_eq() {
622        let a = ConfigOptionScope::Session;
623        #[allow(clippy::clone_on_copy)]
624        let b = a.clone();
625        assert_eq!(a, b);
626    }
627
628    #[test]
629    fn full_builder_chain_stores_every_field() {
630        let builder = ConfigOptionBuilder::try_new("my_ext_threshold")
631            .unwrap()
632            .description("Maximum threshold")
633            .unwrap()
634            .option_type(TypeId::BigInt)
635            .default_value("100")
636            .unwrap()
637            .scope(ConfigOptionScope::Local);
638        assert_eq!(builder.name(), "my_ext_threshold");
639        assert_eq!(builder.description.as_deref(), Some(c"Maximum threshold"));
640        assert_eq!(builder.option_type, Some(TypeId::BigInt));
641        assert_eq!(builder.default_value.as_deref(), Some(c"100"));
642        assert_eq!(builder.scope, ConfigOptionScope::Local);
643    }
644}