pub struct Value { /* private fields */ }Expand description
An owned, RAII-managed DuckDB value.
When dropped, the underlying duckdb_value handle is destroyed via
[duckdb_destroy_value]. This eliminates the manual duckdb_destroy_value
calls that are easy to forget and lead to memory leaks.
§Creation
Obtain a Value from:
BindInfo::get_parameter_valueBindInfo::get_named_parameter_valueValue::from_raw(escape hatch for rawduckdb_valuehandles)
§Extraction
Use typed accessors to extract the underlying data:
as_str— any scalar rendered as text →Result<String>as_blob— BLOB →Result<Vec<u8>>as_i32— cast to INTEGER →Option<i32>as_i64— cast to BIGINT →Option<i64>as_f32— cast to FLOAT →Option<f32>as_f64— cast to DOUBLE →Option<f64>as_bool— cast to BOOLEAN →Option<bool>as_bit/as_bignum— BIT and BIGNUM, which the C getters would abort the process on for aNULLtry_cast— cast to anyLogicalType, nested ones included;array_itemsreads anARRAY, whichlist_itemscannot
No accessor calls into DuckDB for a null handle or a SQL NULL — the
scalar getters return None, as_str/as_blob an error — and none
modifies the value. The as_*_or(default) forms (e.g.
as_i64_or) fold every None into a default.
Implementations§
Source§impl Value
impl Value
Sourcepub fn bit(bits: &[bool]) -> Result<Self, ExtensionError>
pub fn bit(bits: &[bool]) -> Result<Self, ExtensionError>
Creates a BIT value from its bits, leftmost first: [false, true, false, true] is '0101'::BIT.
§Errors
bits is empty: SQL has no empty BIT (''::BIT is an error), and
DuckDB cannot render one.
§Example
use quack_rs::value::Value;
let flags = Value::bit(&[false, true, false, true])?;
assert_eq!(flags.as_str()?, "0101");
assert_eq!(flags.as_bit(), Some(vec![false, true, false, true]));Sourcepub fn as_bit(&self) -> Option<Vec<bool>>
pub fn as_bit(&self) -> Option<Vec<bool>>
Reads a BIT value as its bits, leftmost first.
A value of another type is cast to BIT the way SQL’s TRY_CAST
would (through try_cast): a VARCHAR '0101'
reads as four bits, an INTEGER as its 32 bits.
Returns None for a null handle, a SQL NULL, a value that does not
cast to BIT ('abc', a DOUBLE), and a BIT whose bytes are not
well formed. duckdb_get_bit itself aborts the process on the first
two and segfaults on a null handle; it is only ever called here on a
non-NULL BIT (see the module docs).
Works on every supported DuckDB (1.4.4 to 2.0.x).
Sourcepub fn bignum(
magnitude_be: &[u8],
negative: bool,
) -> Result<Self, ExtensionError>
pub fn bignum( magnitude_be: &[u8], negative: bool, ) -> Result<Self, ExtensionError>
Creates a BIGNUM (arbitrary-precision integer) value from its
magnitude, most significant byte first, and its sign.
Leading zero bytes are dropped, and zero (an empty or all-zero
magnitude) is stored as non-negative, which is the canonical form
DuckDB requires; duckdb_create_bignum would store either as given.
§Errors
The magnitude is longer than DuckDB’s maximum of 8,388,607 bytes.
§Example
use quack_rs::value::Value;
// -(2^64)
let big = Value::bignum(&[1, 0, 0, 0, 0, 0, 0, 0, 0], true)?;
assert_eq!(big.as_str()?, "-18446744073709551616");
assert_eq!(big.as_bignum(), Some((vec![1, 0, 0, 0, 0, 0, 0, 0, 0], true)));Sourcepub fn as_bignum(&self) -> Option<(Vec<u8>, bool)>
pub fn as_bignum(&self) -> Option<(Vec<u8>, bool)>
Reads a BIGNUM value as its magnitude (most significant byte first,
no leading zero byte; zero is [0]) and whether it is negative.
An integer or floating-point value is cast to BIGNUM the way SQL’s
TRY_CAST would: a BIGINT -5 reads as ([5], true).
Returns None for a null handle, a SQL NULL and a value that does
not cast to BIGNUM ('abc', a BLOB, an infinite DOUBLE), on
all of which duckdb_get_bignum itself aborts the process.
A BIGNUM DuckDB builds is always well formed. One built through
the raw duckdb_create_bignum with an empty magnitude is not, and
reading it here — or rendering it with as_str —
throws inside DuckDB and aborts; bignum never
builds one.
Works on every supported DuckDB (1.4.4 to 2.0.x).
Source§impl Value
impl Value
Sourcepub fn as_blob(&self) -> Result<Vec<u8>, ExtensionError>
pub fn as_blob(&self) -> Result<Vec<u8>, ExtensionError>
Extracts the value as an owned Vec<u8> (BLOB).
DuckDB allocates the blob’s backing buffer; this method copies it into
an owned Vec<u8> and frees the original with duckdb_free. The bytes
are copied without UTF-8 validation.
§Errors
Returns ExtensionError if the value handle is null, the value is SQL
NULL, its type is not BLOB, duckdb_get_blob returns a null data
pointer for a non-empty blob, or the blob size cannot be represented by
usize on the current platform.
Only a BLOB is accepted. duckdb_get_blob casts anything else to
BLOB with a throwing cast — an INTEGER, or a VARCHAR with an
invalid \x escape, aborted the process — and it throws on SQL NULL
too. Read a VARCHAR with as_str.
Source§impl Value
impl Value
Sourcepub fn try_cast(&self, target: &LogicalType) -> Option<Self>
pub fn try_cast(&self, target: &LogicalType) -> Option<Self>
Casts the value to target, as SQL’s TRY_CAST(value AS target)
does, and returns the result as a new owned value; None when the cast
fails.
This is the general form of the casting as_* getters, for any
LogicalType — nested ones included — and the way to read the
values the C API has no reader for:
- an
ARRAYcast to aLISTof its element type reads withlist_items(or usearray_items, which does exactly that); - a
UNIONcast toVARCHARis its active member as text (DuckDBcasts aUNIONonly toVARCHARor to anotherUNION);Value::union_tag(featureduckdb-1-5) says which member it is; - a
VARCHARcast toLIST(INTEGER),STRUCT(..)orDATEparses it the way SQL does.
A SQL NULL casts to a NULL of the target type (Some), as in SQL.
self is never modified.
Returns None when the handle is null, the cast fails ('abc' to
INTEGER, a LIST to INTEGER, an ARRAY to a LIST of the wrong
size), target is ANY / INVALID or a type quack-rs does not
know, or the value holds a payload DuckDB cannot convert safely: the
same timestamp, time and DECIMAL payloads
as_str refuses to render (see
UNRENDERABLE), anywhere inside the value.
Those payloads do not come from SQL’s own constructors, but from
functions such as make_timestamp(-9223372036854775808); converting
one throws, or overflows a signed multiply, inside DuckDB. A UNION
whose member types include a timestamp, time or DECIMAL is refused
whatever its member holds, because the member cannot be read to check
it first.
Works on every supported DuckDB (1.4.4 to 2.0.x): it uses only
stable C API calls.
§Example
Reading an INTEGER[3] parameter of a table function (needs a live
engine, so it is not run here):
use quack_rs::types::{LogicalType, TypeId};
use quack_rs::value::Value;
let as_list = param.try_cast(&LogicalType::list(TypeId::Integer))?;
as_list.list_items().iter().map(Value::as_i32).collect()Sourcepub fn array_items(&self) -> Option<Vec<Self>>
pub fn array_items(&self) -> Option<Vec<Self>>
The elements of an ARRAY (or a LIST) value, in order; None for
a null handle, a SQL NULL or a value of any other type.
list_items reads a LIST only, and an ARRAY
value read through it looks empty: the C API has no ARRAY reader.
This casts an ARRAY(T, n) to LIST(T) first — a cast that copies
the elements unchanged — so a fixed-size-list parameter of a table
function, a COPY option or a scalar bind argument can be read.
Each element is an owned Value of type T, read with the usual
getters.
Works on every supported DuckDB (1.4.4 to 2.0.x).
§Example
use quack_rs::value::Value;
// A `DOUBLE[2]` parameter.
let items = point.array_items()?;
Some((items.first()?.as_f64()?, items.get(1)?.as_f64()?))Source§impl Value
impl Value
Sourcepub fn union_tag(&self) -> Option<u8>
pub fn union_tag(&self) -> Option<u8>
The tag of a UNION value: the 0-based index of its active member,
in the order the UNION type declares them (DuckDB 1.5.0+).
Returns None for a null handle, a SQL NULL and any value that is
not a UNION.
The member’s name is entry tag + 1 of
struct_field_names (a UNION lists its
hidden tag field first). Its value reads as text
with try_cast to VARCHAR, the only scalar type
DuckDB casts a UNION to; a member whose value is NULL reads as
the text "NULL" there (UnionToVarcharCast), which cannot be told
apart from a VARCHAR member holding that text.
§How
The C API reads a UNION value’s tag nowhere: duckdb_get_struct_child
refuses a UNION, and no cast yields the tag. A UNION is stored as a
STRUCT whose field 0 is the UTINYINT tag, so this references the
value into a one-row vector of its own type
(duckdb_vector_reference_value) and reads field 0 there. Requires
duckdb-1-5: duckdb_create_vector and
duckdb_vector_reference_value sit in the unstable region of the C API
struct.
§Example
use quack_rs::types::{LogicalType, TypeId};
use quack_rs::value::Value;
// A `UNION(num INTEGER, str VARCHAR)` parameter.
let tag = arg.union_tag()?;
let member = arg.struct_field_names().get(usize::from(tag) + 1)?.clone();
let text = arg.try_cast(&LogicalType::new(TypeId::Varchar))?.as_str().ok()?;
Some(format!("{member} = {text}"))Source§impl Value
impl Value
Sourcepub fn struct_value(
struct_type: &LogicalType,
fields: &[Self],
) -> Result<Self, ExtensionError>
pub fn struct_value( struct_type: &LogicalType, fields: &[Self], ) -> Result<Self, ExtensionError>
Creates a STRUCT value.
fields must line up positionally with struct_type’s fields.
§Errors
- The number of
fieldsdoes not match the type’s field count. This check is quack-rs’s, and it is not cosmetic:duckdb_create_struct_valuetakes no count argument and readsvalues[0..StructType::GetChildCount(type)], so passing a short slice reads past its end. struct_typeis not aSTRUCT, or contains anANY/INVALIDchild type —duckdb_create_struct_valuereturns null for those.
§Example
use quack_rs::types::{LogicalType, TypeId};
use quack_rs::value::Value;
let ty = LogicalType::struct_type(&[("x", TypeId::BigInt), ("y", TypeId::Varchar)]);
let v = Value::struct_value(&ty, &[Value::bigint(1), Value::varchar("two")])?;Sourcepub fn list_value(
element_type: &LogicalType,
items: &[Self],
) -> Result<Self, ExtensionError>
pub fn list_value( element_type: &LogicalType, items: &[Self], ) -> Result<Self, ExtensionError>
Creates a LIST value from its element type.
§element_type, not the list type
duckdb.h is self-contradictory here: the prose says “Creates a list
value from a child (element) type”, while the @param line says “The
type of the list”. The implementation settles it —
duckdb_create_list_value forwards to
Value::LIST(const LogicalType &child_type, vector<Value>), so it is the
element type, and passing LogicalType::list(..) instead makes
DuckDB try to cast every element to a list and return null.
For LIST<BIGINT>, pass LogicalType::new(TypeId::BigInt). A list of
lists is built the same way: for BIGINT[][], pass
LogicalType::list(TypeId::BigInt) and LIST items.
§Errors
Returns an error when duckdb_create_list_value reports failure: an
ANY or INVALID element type, or an item that will not cast to
element_type. When the element type is itself a LIST, the error
also points out the likelier mistake — passing the list type with
scalar items — since it is the one the header invites.
Sourcepub fn array_value(
element_type: &LogicalType,
items: &[Self],
) -> Result<Self, ExtensionError>
pub fn array_value( element_type: &LogicalType, items: &[Self], ) -> Result<Self, ExtensionError>
Creates an ARRAY (fixed-size list) value from its element type.
As with list_value, this is the element type, not
the array type — duckdb_create_array_value forwards to
Value::ARRAY(const LogicalType &child_type, vector<Value>), which
derives the array type as ARRAY(child_type, values.size()). The
resulting array’s size is therefore items.len(); there is nothing to
keep in sync. An array of arrays takes an ARRAY element type and
ARRAY items.
§Errors
Returns an error for an empty items: an ARRAY of size 0 is not a
type SQL can write (array_value() fails with “requires at least one
argument”), though a release DuckDB builds one. Also returns an error
when duckdb_create_array_value reports failure: an ANY / INVALID
element type, an item that will not cast to element_type, or a length
at or above DuckDB’s maximum array size.
Sourcepub fn enum_value(
enum_type: &LogicalType,
index: u64,
) -> Result<Self, ExtensionError>
pub fn enum_value( enum_type: &LogicalType, index: u64, ) -> Result<Self, ExtensionError>
Creates an ENUM value from its dictionary index.
§Errors
Returns an error when enum_type is not an ENUM or index is outside
its dictionary.
Sourcepub fn map(
map_type: &LogicalType,
keys: &[Self],
values: &[Self],
) -> Result<Self, ExtensionError>
pub fn map( map_type: &LogicalType, keys: &[Self], values: &[Self], ) -> Result<Self, ExtensionError>
Creates a MAP value from parallel key and value slices.
Named map rather than map_value because
map_value is already the accessor that reads the
value of the index-th entry.
map_type is the MAP type itself. Requires duckdb-1-5:
duckdb_create_map_value sits in the unstable region of the C API
struct.
§Errors
Returns an error when the slices differ in length, or when
duckdb_create_map_value reports failure — map_type is not a MAP,
a child type is ANY / INVALID, or a key repeats.
Sourcepub fn union_value(
union_type: &LogicalType,
tag_index: u64,
value: &Self,
) -> Result<Self, ExtensionError>
pub fn union_value( union_type: &LogicalType, tag_index: u64, value: &Self, ) -> Result<Self, ExtensionError>
Creates a UNION value for the member at tag_index.
Requires duckdb-1-5: duckdb_create_union_value sits in the unstable
region of the C API struct.
§Errors
Returns an error when union_type is not a UNION, tag_index is out
of range, or value’s type does not equal that member’s declared type —
DuckDB compares them exactly and returns null on a mismatch.
Source§impl Value
impl Value
Sourcepub fn as_str_or(&self, default: &str) -> String
pub fn as_str_or(&self, default: &str) -> String
Extracts the value as a String, returning default on failure.
Convenience for val.as_str().unwrap_or_else(|_| default.to_owned()).
Sourcepub fn as_str_or_default(&self) -> String
pub fn as_str_or_default(&self) -> String
Extracts the value as a String, returning an empty string on failure.
Convenience for val.as_str().unwrap_or_default().
Sourcepub fn as_i32_or(&self, default: i32) -> i32
pub fn as_i32_or(&self, default: i32) -> i32
Extracts the value as an i32, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_i64_or(&self, default: i64) -> i64
pub fn as_i64_or(&self, default: i64) -> i64
Extracts the value as an i64, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_f32_or(&self, default: f32) -> f32
pub fn as_f32_or(&self, default: f32) -> f32
Extracts the value as an f32, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_f64_or(&self, default: f64) -> f64
pub fn as_f64_or(&self, default: f64) -> f64
Extracts the value as an f64, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_bool_or(&self, default: bool) -> bool
pub fn as_bool_or(&self, default: bool) -> bool
Extracts the value as a bool, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_i8_or(&self, default: i8) -> i8
pub fn as_i8_or(&self, default: i8) -> i8
Extracts the value as an i8, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_i16_or(&self, default: i16) -> i16
pub fn as_i16_or(&self, default: i16) -> i16
Extracts the value as an i16, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_u8_or(&self, default: u8) -> u8
pub fn as_u8_or(&self, default: u8) -> u8
Extracts the value as a u8, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_u16_or(&self, default: u16) -> u16
pub fn as_u16_or(&self, default: u16) -> u16
Extracts the value as a u16, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_u32_or(&self, default: u32) -> u32
pub fn as_u32_or(&self, default: u32) -> u32
Extracts the value as a u32, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_u64_or(&self, default: u64) -> u64
pub fn as_u64_or(&self, default: u64) -> u64
Extracts the value as a u64, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Sourcepub fn as_i128_or(&self, default: i128) -> i128
pub fn as_i128_or(&self, default: i128) -> i128
Extracts the value as an i128, returning default if it is absent or unreadable.
default is returned for a null handle, a SQL NULL, and a failed
or impossible cast — every case in which the plain getter returns None.
Source§impl Value
impl Value
Sourcepub fn as_i32(&self) -> Option<i32>
pub fn as_i32(&self) -> Option<i32>
Reads the value as an i32, casting it to INTEGER the way SQL’s
TRY_CAST would.
Returns None if the handle is null, the value is SQL NULL, its type
is not a scalar (LIST, STRUCT, BLOB, ENUM, …), or the cast fails
('abc', or a number out of range). Casts follow DuckDB: a DOUBLE
1.5 reads as 2, a VARCHAR '42' as 42.
The value itself is never modified. The same rules apply to every
casting as_* accessor; see as_i32_or and its
siblings for a defaulting form.
Sourcepub fn as_i64(&self) -> Option<i64>
pub fn as_i64(&self) -> Option<i64>
Reads the value as an i64 (BIGINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_f32(&self) -> Option<f32>
pub fn as_f32(&self) -> Option<f32>
Reads the value as an f32 (FLOAT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_f64(&self) -> Option<f64>
pub fn as_f64(&self) -> Option<f64>
Reads the value as an f64 (DOUBLE). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_bool(&self) -> Option<bool>
pub fn as_bool(&self) -> Option<bool>
Reads the value as a bool (BOOLEAN). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_i8(&self) -> Option<i8>
pub fn as_i8(&self) -> Option<i8>
Reads the value as an i8 (TINYINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_i16(&self) -> Option<i16>
pub fn as_i16(&self) -> Option<i16>
Reads the value as an i16 (SMALLINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_u8(&self) -> Option<u8>
pub fn as_u8(&self) -> Option<u8>
Reads the value as a u8 (UTINYINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_u16(&self) -> Option<u16>
pub fn as_u16(&self) -> Option<u16>
Reads the value as a u16 (USMALLINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_u32(&self) -> Option<u32>
pub fn as_u32(&self) -> Option<u32>
Reads the value as a u32 (UINTEGER). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_u64(&self) -> Option<u64>
pub fn as_u64(&self) -> Option<u64>
Reads the value as a u64 (UBIGINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_i128(&self) -> Option<i128>
pub fn as_i128(&self) -> Option<i128>
Reads the value as an i128 (HUGEINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_u128(&self) -> Option<u128>
pub fn as_u128(&self) -> Option<u128>
Reads the value as a u128 (UHUGEINT). None on a null handle, SQL
NULL, non-scalar type or failed cast; see as_i32.
Sourcepub fn as_date(&self) -> Option<i32>
pub fn as_date(&self) -> Option<i32>
Reads a DATE as days since 1970-01-01. Decode it with
datetime::date_from_days.
None on a null handle, SQL NULL, non-scalar type or failed cast;
see as_i32.
Sourcepub fn as_time(&self) -> Option<i64>
pub fn as_time(&self) -> Option<i64>
Reads a TIME as microseconds since midnight. None on a null handle,
SQL NULL, non-scalar type or failed cast — including the time of an
infinite TIMESTAMP, which DuckDB refuses (it used to abort the
process here).
Sourcepub fn as_time_tz(&self) -> Option<u64>
pub fn as_time_tz(&self) -> Option<u64>
Reads a TIMETZ as DuckDB’s packed 64-bit representation. Decode it
with datetime::time_tz_from_bits.
None on a null handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_time_ns(&self) -> Option<i64>
pub fn as_time_ns(&self) -> Option<i64>
Reads a TIME_NS as nanoseconds since midnight (DuckDB 1.5.0+).
None on a null handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_timestamp(&self) -> Option<i64>
pub fn as_timestamp(&self) -> Option<i64>
Reads a TIMESTAMP as microseconds since the epoch. None on a null
handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_timestamp_tz(&self) -> Option<i64>
pub fn as_timestamp_tz(&self) -> Option<i64>
Reads a TIMESTAMPTZ as microseconds since the epoch, in UTC. None
on a null handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_timestamp_s(&self) -> Option<i64>
pub fn as_timestamp_s(&self) -> Option<i64>
Reads a TIMESTAMP_S as seconds since the epoch. None on a null
handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_timestamp_ms(&self) -> Option<i64>
pub fn as_timestamp_ms(&self) -> Option<i64>
Reads a TIMESTAMP_MS as milliseconds since the epoch. None on a
null handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_timestamp_ns(&self) -> Option<i64>
pub fn as_timestamp_ns(&self) -> Option<i64>
Reads a TIMESTAMP_NS as nanoseconds since the epoch. None on a
null handle, SQL NULL, non-scalar type or failed cast — including a
timestamp outside TIMESTAMP_NS’s range (before 1677-09-22 or after
2262-04-11), which DuckDB refuses (it used to abort the process here).
Sourcepub fn as_timestamp_tz_ns(&self) -> Option<i64>
pub fn as_timestamp_tz_ns(&self) -> Option<i64>
Reads a TIMESTAMPTZ_NS as nanoseconds since the epoch (DuckDB
2.0.0+). None on a null handle, SQL NULL, non-scalar type or failed
cast — including a timestamp outside the type’s range (before
1677-09-22 or after 2262-04-11). Always None on an engine before
2.0.0, which has no such type to cast to.
Pairs with timestamp_tz_ns and the
TypeId::TimestampTzNs column type.
Sourcepub fn as_interval(&self) -> Option<DuckInterval>
pub fn as_interval(&self) -> Option<DuckInterval>
Reads an INTERVAL. None on a null handle, SQL NULL, non-scalar
type or failed cast.
Sourcepub fn as_uuid(&self) -> Option<u128>
pub fn as_uuid(&self) -> Option<u128>
Reads a UUID as its textual 128 bits, matching
VectorReader::read_uuid
and uuid.
DuckDB undoes its internal top-bit flip itself here, so this is the
value the UUID renders as — not the raw HUGEINT a UUID vector holds.
None on a null handle, SQL NULL, non-scalar type or failed cast.
Sourcepub fn as_decimal(&self) -> Option<Decimal>
pub fn as_decimal(&self) -> Option<Decimal>
Reads a DECIMAL as its width, scale and unscaled value; the
represented number is value / 10^scale.
Does not cast: returns None unless the value is a non-NULL DECIMAL
(and for a null handle).
Sourcepub fn as_enum_index(&self) -> Option<u64>
pub fn as_enum_index(&self) -> Option<u64>
Returns the dictionary index of an ENUM value.
Does not cast: returns None unless the value is a non-NULL ENUM
(and for a null handle). The C function returns 0 in those cases,
which is also a legitimate index.
Source§impl Value
impl Value
Sourcepub fn list_len(&self) -> usize
pub fn list_len(&self) -> usize
Number of elements in a LIST value.
Returns 0 for non-LIST values, an ARRAY included: the C API reads
a LIST only. Read an ARRAY with
array_items.
Sourcepub fn list_child(&self, index: usize) -> Option<Self>
pub fn list_child(&self, index: usize) -> Option<Self>
Element index of a LIST value, or None if out of range.
The returned Value owns its handle.
Sourcepub fn list_items(&self) -> Vec<Self>
pub fn list_items(&self) -> Vec<Self>
Sourcepub fn struct_field_names(&self) -> Vec<String>
pub fn struct_field_names(&self) -> Vec<String>
Field names of a STRUCT value, in order.
DuckDB’s C API exposes a struct value’s children by position only —
the names live on the value’s LogicalType. Reading them by hand means
calling duckdb_get_value_type, whose result duckdb.h says “must not
be destroyed” because the value owns it, which is exactly the kind of
borrowed handle it is easy to hand to
LogicalType::from_raw and then
double-free (pitfall P11). This does the walk without exposing it.
Returns an empty vector for a null handle or a value whose type has no
struct children. A UNION type is stored as a struct of its tag and
its members, so for a UNION value it returns "" for the tag
followed by the member names. struct_child
returns None for every index of a UNION value; read the active
member’s index with union_tag (feature duckdb-1-5; its name is
then struct_field_names()[tag + 1]) and its value, as text, with
try_cast to VARCHAR.
Pair it with struct_child, which is positional:
let names = options.struct_field_names();
let idx = names.iter().position(|n| n == "compression")?;
options.struct_child(idx)?.as_str().ok()Sourcepub fn struct_child(&self, index: usize) -> Option<Self>
pub fn struct_child(&self, index: usize) -> Option<Self>
Field index of a STRUCT value, or None if the handle is null or the
index is out of range.
Field names come from the value’s LogicalType, not from the value
itself; DuckDB’s C API exposes children by position.
Source§impl Value
impl Value
Sourcepub fn varchar(value: &str) -> Self
pub fn varchar(value: &str) -> Self
Creates a VARCHAR value.
The length is passed explicitly, so no CString conversion can fail and
DuckDB stores every byte — but note that as_str reads
back through a NUL-terminated C string and will truncate at an interior
NUL.
Sourcepub fn uuid(bits: u128) -> Self
pub fn uuid(bits: u128) -> Self
Creates a UUID value from its textual 128 bits, matching
VectorWriter::write_uuid
and as_uuid.
DuckDB applies its internal top-bit flip itself here, so these are the
bits the value renders as — not the raw HUGEINT a UUID vector holds.
Sourcepub fn null_value() -> Self
pub fn null_value() -> Self
Creates a SQL NULL value.
Sourcepub fn decimal(
width: u8,
scale: u8,
unscaled: i128,
) -> Result<Self, ExtensionError>
pub fn decimal( width: u8, scale: u8, unscaled: i128, ) -> Result<Self, ExtensionError>
Creates a DECIMAL(width, scale) value from its unscaled integer.
unscaled is the value multiplied by 10^scale — DECIMAL(18, 3)
holding 1.234 has unscaled == 1234.
§Errors
widthis not in1..=38, orscale > width;unscaledhas more thanwidthdigits (|unscaled| >= 10^width).
All three are checked here, before DuckDB is called. For an
unscaled that does not fit the width’s physical type,
duckdb_create_decimal throws (aborting the process); for one that
fits the physical type but not the width it stores a value the type
cannot hold; and one past i64 with width <= 18 kept only its low
64 bits.
Source§impl Value
impl Value
Sourcepub fn date(days: i32) -> Self
pub fn date(days: i32) -> Self
Creates a DATE value from days since 1970-01-01.
Infallible: DuckDB renders and converts every i32. i32::MAX and
-i32::MAX are infinity and -infinity
(datetime::DATE_INFINITY_DAYS).
Sourcepub fn time(micros_since_midnight: i64) -> Result<Self, ExtensionError>
pub fn time(micros_since_midnight: i64) -> Result<Self, ExtensionError>
Creates a TIME value from microseconds since midnight.
§Errors
micros_since_midnight is outside 0..=86_400_000_000
(00:00:00–24:00:00, DuckDB’s TIME range).
Sourcepub fn time_tz(bits: u64) -> Result<Self, ExtensionError>
pub fn time_tz(bits: u64) -> Result<Self, ExtensionError>
Creates a TIME WITH TIME ZONE value from its packed 64-bit encoding.
DuckDB packs TIME_TZ as 40 bits of microseconds and 24 bits of UTC
offset. Build the encoding with
time_tz_bits rather than assembling it
by hand; every encoding it returns is accepted here.
§Errors
The time field exceeds 24:00:00 or the offset field encodes an
offset beyond ±15:59:59.
Sourcepub fn time_ns(nanos: i64) -> Result<Self, ExtensionError>
pub fn time_ns(nanos: i64) -> Result<Self, ExtensionError>
Creates a TIME_NS value (time of day with nanosecond precision) from a
raw nanosecond count (DuckDB 1.5.0+).
Pairs with as_time_ns and the
TypeId::TimeNs column type.
§Errors
nanos is outside 0..=86_400_000_000_000 (00:00:00–24:00:00).
Sourcepub fn timestamp(micros: i64) -> Result<Self, ExtensionError>
pub fn timestamp(micros: i64) -> Result<Self, ExtensionError>
Creates a TIMESTAMP value from microseconds since the epoch.
§Errors
micros is below -9_223_372_022_400_000_000
(290309-12-22 (BC) 00:00:00) and is not -i64::MAX (-infinity).
Every larger value is valid; i64::MAX is infinity.
Sourcepub fn timestamp_tz(micros: i64) -> Result<Self, ExtensionError>
pub fn timestamp_tz(micros: i64) -> Result<Self, ExtensionError>
Sourcepub fn timestamp_s(seconds: i64) -> Result<Self, ExtensionError>
pub fn timestamp_s(seconds: i64) -> Result<Self, ExtensionError>
Creates a TIMESTAMP_S value from seconds since the epoch.
§Errors
seconds is outside -9_223_372_022_400..=9_223_372_036_854 and is
not ±i64::MAX (±infinity): DuckDB converts a TIMESTAMP_S to
microseconds to render or cast it, and throws when that overflows.
Sourcepub fn timestamp_ms(millis: i64) -> Result<Self, ExtensionError>
pub fn timestamp_ms(millis: i64) -> Result<Self, ExtensionError>
Creates a TIMESTAMP_MS value from milliseconds since the epoch.
§Errors
millis is outside
-9_223_372_022_400_000..=9_223_372_036_854_775 and is not
±i64::MAX (±infinity), for the reason given on
timestamp_s.
Sourcepub fn timestamp_ns(nanos: i64) -> Result<Self, ExtensionError>
pub fn timestamp_ns(nanos: i64) -> Result<Self, ExtensionError>
Creates a TIMESTAMP_NS value from nanoseconds since the epoch.
§Errors
nanos is below -9_223_286_400_000_000_000 (1677-09-22 00:00:00)
and is not -i64::MAX (-infinity). Every larger value is valid;
i64::MAX is infinity.
Sourcepub fn timestamp_tz_ns(nanos: i64) -> Result<Self, ExtensionError>
pub fn timestamp_tz_ns(nanos: i64) -> Result<Self, ExtensionError>
Creates a TIMESTAMPTZ_NS value (a timestamp with time zone at
nanosecond precision) from nanoseconds since the epoch (DuckDB
2.0.0+).
Pairs with as_timestamp_tz_ns and the
TypeId::TimestampTzNs column type.
DuckDB 2.0.0 added duckdb_create_timestamp_tz_ns for this, but the
function sits in the two slots 2.0.0 appended to the C API struct, past
the 546 an extension built against the 1.5.2 - 1.5.6 bindings (and
every engine before 2.0.0) has. So this does not call it. It renders the
TIMESTAMP_NS for nanos as text and casts the text to
TIMESTAMPTZ_NS, which works on any bindings; no cast reaches
TIMESTAMPTZ_NS from TIMESTAMP_NS directly in DuckDB’s default
cast set (DefaultCasts::TimestampNsCastSwitch), and the text form
carries all nine fractional digits.
§Errors
nanosis below-9_223_286_400_000_000_000(1677-09-22 00:00:00) and is not-i64::MAX(-infinity), as fortimestamp_ns. Every larger value is valid;i64::MAXisinfinity.- The engine is older than 2.0.0 and has no
TIMESTAMPTZ_NStype.
Sourcepub fn interval(value: DuckInterval) -> Self
pub fn interval(value: DuckInterval) -> Self
Creates an INTERVAL value.
DuckDB intervals are { months, days, micros } and deliberately do not
collapse into a single duration — see
DuckInterval (pitfall P8).
Infallible: every combination renders.
Note that the derived PartialEq on DuckInterval compares the three
fields, while DuckDB’s SQL = compares normalized intervals:
INTERVAL '1 month' = INTERVAL '30 days' and
INTERVAL '1 day' = INTERVAL '24 hours' are both true in SQL, but the
corresponding DuckIntervals are not equal.
Source§impl Value
impl Value
Sourcepub const unsafe fn from_raw(raw: duckdb_value) -> Self
pub const unsafe fn from_raw(raw: duckdb_value) -> Self
Wraps a raw duckdb_value handle.
The returned Value takes ownership and will call duckdb_destroy_value
on drop.
§Safety
raw must be a valid duckdb_value obtained from a DuckDB API call
(e.g., duckdb_bind_get_parameter). The caller must not destroy the
value after passing it to this function.
Sourcepub fn as_str(&self) -> Result<String, ExtensionError>
pub fn as_str(&self) -> Result<String, ExtensionError>
Extracts the value as a String (VARCHAR).
Internally calls duckdb_get_varchar and frees the returned C string
with duckdb_free. Returns an error if the string is not valid UTF-8
or if the value handle is null.
§Embedded NUL bytes
duckdb_get_varchar returns a NUL-terminated char *, so a value whose
text contains an interior NUL is truncated at the first one. DuckDB
itself stores the full bytes; only this read path is limited. If the text
may contain NULs, keep it in a BLOB and use
as_blob.
§A UNION renders as its member
The text is the value cast to VARCHAR, as SQL casts it, so a UNION
renders as its active member alone: union_value(a := 5) as "5",
with the tag gone, and a UNION whose member is NULL as the text
"NULL" — returned as text, not as an error, because the UNION
itself is not SQL NULL. The Debug form keeps the tag.
§Errors
Returns ExtensionError if the handle is null, the value is SQL NULL
(duckdb_get_varchar would throw on it, aborting the process), the
text is not valid UTF-8, or the value holds something DuckDB cannot
render — see UNRENDERABLE. DuckDB builds such values from
ordinary SQL (make_timestamp(-9223372036854775808), or, before 2.0,
sum over a DECIMAL(38, s) column), and rendering one throws through the C API,
which aborted the process.
Sourcepub fn display_string(&self) -> Option<String>
pub fn display_string(&self) -> Option<String>
Returns the SQL literal representation of this value, as DuckDB
would render it (DuckDB 1.5.0+).
Note “SQL literal”, not “text”. A VARCHAR comes back quoted and typed values carry an explicit cast:
| Value | display_string() |
|---|---|
Value::varchar("hello") | 'hello' |
Value::bigint(-42) | -42 |
Value::date(0) | '1970-01-01'::DATE |
Value::timestamp(0) | '1970-01-01 00:00:00'::TIMESTAMP |
The exact text is DuckDB’s Value::ToSQLString, which changes
between releases. From 2.0.0 a typed NULL and a nested value carry
their type as well: a UNION whose member is NULL renders as
union_value(a := NULL::INTEGER)::UNION(a INTEGER), where 1.x
rendered union_value(a := NULL).
Use as_str for a VARCHAR’s contents. This is for
diagnostics and error messages, where it works for any value type.
Returns None if the handle is null, the rendered text is not valid
UTF-8, or the value is one DuckDB cannot render (see
UNRENDERABLE).
Sourcepub fn is_sql_null(&self) -> bool
pub fn is_sql_null(&self) -> bool
Returns true when this value’s SQL type is SQLNULL.
This is not is_null, which reports whether the
handle is null — a value that failed to construct, or one moved out
with into_raw. A SQL NULL has a perfectly valid
handle.
§Example
use quack_rs::value::Value;
let v = Value::null_value();
assert!(!v.is_null(), "the handle is fine");
assert!(v.is_sql_null(), "the value is SQL NULL");Sourcepub fn type_id(&self) -> Option<TypeId>
pub fn type_id(&self) -> Option<TypeId>
Returns the TypeId this value actually holds.
The casting as_* accessors follow SQL’s TRY_CAST — a VARCHAR
'42' reads as 42 through as_i64. Check the type
first when a value whose type you did not choose — a named parameter,
a bound constant, a config option — must be of one particular type.
Returns None for a null handle, and for a type id introduced by a
newer DuckDB than this build of quack-rs knows.
§Example
use quack_rs::types::TypeId;
use quack_rs::value::Value;
match value.type_id()? {
TypeId::BigInt | TypeId::Integer => value.as_i64(),
_ => None,
}Sourcepub const fn is_null(&self) -> bool
pub const fn is_null(&self) -> bool
Returns true if the underlying handle is null — not whether the
value is SQL NULL.
A SQL NULL (for example a NULL passed to a table function’s
parameter) has a valid handle, so this returns false for it. To test
for SQL NULL, use is_sql_null.