1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum ConfigOptionScope {
63 Local,
65 Session,
67 Global,
69}
70
71impl ConfigOptionScope {
72 #[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#[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 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 #[must_use]
117 pub fn name(&self) -> &str {
118 self.name.to_str().unwrap_or("")
119 }
120
121 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 pub const fn option_type(mut self, type_id: TypeId) -> Self {
136 self.option_type = Some(type_id);
137 self
138 }
139
140 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 pub const fn scope(mut self, scope: ConfigOptionScope) -> Self {
160 self.scope = scope;
161 self
162 }
163
164 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 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 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 unsafe { refuse_existing_setting(con, &name) }?;
261 let default = unsafe { typed_default(con, &name, type_id, default) }?;
263
264 let option: duckdb_config_option = unsafe { duckdb_create_config_option() };
266
267 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 unsafe {
277 duckdb_config_option_set_description(option, desc.as_ptr());
278 }
279 }
280
281 unsafe {
285 duckdb_config_option_set_default_value(option, default.as_raw());
286 }
287
288 let result = unsafe { duckdb_register_config_option(con, option) };
290
291 let mut option_mut = option;
293 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
313unsafe 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 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 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 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
365unsafe 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 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 let reader = unsafe { chunk.reader(0) };
410 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 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
428unsafe fn value_of_type(reader: &VectorReader, type_id: TypeId) -> Option<Value> {
435 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 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 #[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 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 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}