Skip to main content

Connection

Struct Connection 

Source
pub struct Connection { /* private fields */ }
Expand description

Wraps the duckdb_connection and duckdb_database provided to your extension at load time.

Connection implements Registrar, offering a single, uniform API for registering all extension components. It also exposes register_replacement_scan and register_replacement_scan_with_data, which require the duckdb_database handle and therefore cannot be part of the Registrar trait.

§Obtaining a Connection

Use init_extension_v2 (or the entry_point_v2! macro). Both pass a &Connection to your registration callback.

§Version compatibility

Connection provides a uniform API across DuckDB 1.4.x and 1.5.x. When future DuckDB releases add new C API surface, additional methods will be gated on the corresponding feature flag.

§What the collision checks cost

Before the first scalar and the first table function it registers, a Connection lists the catalog once each (see the field docs below), so that a registration that would silently replace a built-in, or be dropped, is refused instead. Each listing is a scan of duckdb_functions(), which builds a row for every function and macro in every attached database before any WHERE applies: the table function has no filter or projection pushdown (src/function/table/system/duckdb_functions.cpp), so narrowing the query to the names being registered, or to the name column, does not make it cheaper. Measured with the DuckDB CLI on a shared 4-vCPU machine: one scan takes about 20 ms on 1.5.6 and 13 ms on 2.0.0 in an empty database, and about 110 ms on both with 20,000 user macros, so a LOAD into a database with that many macros spends about 0.2 s more on its two scans. Registering on the raw connection (register(con) on a builder) scans once per call instead of once per load.

Implementations§

Source§

impl Connection

Source

pub const unsafe fn from_raw( con: duckdb_connection, db: duckdb_database, ) -> Self

Create a Connection from raw DuckDB handles.

init_extension_v2 makes the one an extension registers through. This constructor lets other code — a test of an extension’s registration function against a real database, say — drive the same Registrar implementation.

§Safety

Both con and db must be valid, non-null handles for the duration of the Connection’s lifetime, and con must be a connection to db.

Source

pub const fn as_raw_connection(&self) -> duckdb_connection

Return the raw duckdb_connection handle.

Use this to call C API functions that quack-rs does not yet wrap.

Source

pub const fn as_raw_database(&self) -> duckdb_database

Return the raw duckdb_database handle.

Use this to call C API functions that require the database handle, such as replacement scan registration or (with duckdb-1-5) config option registration.

§The handle dies when LOAD returns

DuckDB hands the entry point a database handle that belongs to the load: it is freed when LOAD finishes. Use it inside the registration closure only, and never store it (in a static, in extra_info, in a function’s state). A connection opened from a stored handle later is a use after free: valgrind reports it, and it fails or segfaults at random depending on what reuses the memory. To run SQL after loading, open an OwnedConnection during registration with open_connection and keep that (it holds its own reference to the database instance), mindful of what keeping one costs (see there).

Source

pub unsafe fn query(&self, sql: &str) -> Result<QueryResult, ExtensionError>

Runs sql on this connection and returns the materialised result.

Only valid inside your registration closure: the entry point disconnects this connection once the closure returns. For SQL that must run later, open an OwnedConnection with open_connection and keep it.

§Errors

Returns ExtensionError carrying DuckDB’s own message if the statement fails.

§Safety

The underlying connection must be valid for the duration of this call.

Source

pub unsafe fn execute(&self, sql: &str) -> Result<u64, ExtensionError>

Runs sql for its side effects, returning the number of rows changed.

§Errors

See query.

§Safety

The underlying connection must be valid for the duration of this call.

Source

pub unsafe fn prepare( &self, sql: &str, ) -> Result<PreparedStatement, ExtensionError>

Prepares sql on this connection.

Use this rather than interpolating values into SQL text.

§Errors

See query.

§Safety

The underlying connection must be valid for the duration of this call.

Source

pub unsafe fn table_names( &self, sql: &str, qualified: bool, ) -> Result<Vec<String>, ExtensionError>

The tables sql reads or writes, without running it; see query::table_names (DuckDB 1.5.0+).

§Errors

See query::table_names.

§Safety

The underlying connection must be valid for the duration of this call.

Source

pub unsafe fn open_connection(&self) -> Result<OwnedConnection, ExtensionError>

Opens a second, independently owned connection to the same database.

Unlike the borrowed registration connection, the returned OwnedConnection stays valid after extension loading finishes — a duckdb_connection holds its own reference to the database instance. Keep one when a callback or a background thread needs to run SQL.

§What keeping a connection costs

The retained connection keeps the database instance alive, so closing the host’s own connection does not shut the database down: a file database is not checkpointed (its .wal stays) and its lock is held until the process exits, which makes a second process fail with “Could not set lock on file”. If the connection is owned by state the extension registers (a closure captured by a function, say), the instance also references that function, and the cycle means it is never freed. A process-wide static holding the connection is first-wins: with several database instances in one process (a Python program that calls duckdb.connect() repeatedly), every instance’s functions would run on the first instance’s connection. Prefer opening a connection per instance, held by that instance’s own registered state, and decide whether the extension really needs to run SQL from a callback at all.

§Errors

Returns ExtensionError if DuckDB refuses to open the connection.

§Safety

The underlying duckdb_database must be valid for the duration of this call.

Source

pub unsafe fn register_replacement_scan( &self, callback: ReplacementScanFn, extra_data: *mut c_void, delete_callback: duckdb_delete_callback_t, )

Register a replacement scan backed by a raw function pointer and extra data.

For the ergonomic owned-data variant, see register_replacement_scan_with_data.

§Safety
  • The underlying duckdb_database must be valid.
  • extra_data must remain valid until delete_callback is called (or until the database is closed if delete_callback is None).
Source

pub unsafe fn register_replacement_scan_with_data<T: Send + Sync + 'static>( &self, callback: ReplacementScanFn, data: T, )

Register a replacement scan with owned extra data.

Boxes data and registers a drop destructor automatically. This is the safe, ergonomic alternative to register_replacement_scan.

T must be Send + Sync; see ReplacementScanBuilder::register_with_data.

§Safety

The underlying duckdb_database must be valid.

Trait Implementations§

Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Registrar for Connection

Source§

unsafe fn register_scalar( &self, builder: ScalarFunctionBuilder, ) -> Result<(), ExtensionError>

Register a scalar function. Read more
Source§

unsafe fn register_typed_scalar( &self, builder: TypedScalarFunctionBuilder, ) -> Result<(), ExtensionError>

Register a scalar function built from a Rust closure (ScalarFunctionBuilder::map1 and friends). Read more
Source§

unsafe fn register_scalar_set( &self, builder: ScalarFunctionSetBuilder, ) -> Result<(), ExtensionError>

Register a scalar function set (multiple overloads under one name). Read more
Source§

unsafe fn register_aggregate( &self, builder: AggregateFunctionBuilder, ) -> Result<(), ExtensionError>

Register an aggregate function. Read more
Source§

unsafe fn register_aggregate_set( &self, builder: AggregateFunctionSetBuilder, ) -> Result<(), ExtensionError>

Register an aggregate function set (multiple overloads under one name). Read more
Source§

unsafe fn register_table( &self, builder: TableFunctionBuilder, ) -> Result<(), ExtensionError>

Register a table function. Read more
Source§

unsafe fn register_sql_macro( &self, sql_macro: SqlMacro, ) -> Result<(), ExtensionError>

Register a SQL macro (scalar or table-returning). Read more
Source§

unsafe fn register_cast( &self, builder: CastFunctionBuilder, ) -> Result<(), ExtensionError>

Register a custom type cast function. Read more
Source§

unsafe fn register_copy_function( &self, builder: CopyFunctionBuilder, ) -> Result<(), ExtensionError>

Register a custom COPY TO function (DuckDB 1.5.0+). Read more
Source§

unsafe fn register_config_option( &self, builder: ConfigOptionBuilder, ) -> Result<(), ExtensionError>

Registers an extension-defined configuration option. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.