Trait sqlx_core::decode::Decode

source ·
pub trait Decode<'r, DB: Database>: Sized {
    // Required method
    fn decode(
        value: <DB as HasValueRef<'r>>::ValueRef,
    ) -> Result<Self, BoxDynError>;
}
Expand description

A type that can be decoded from the database.

§How can I implement Decode?

A manual implementation of Decode can be useful when adding support for types externally to SQLx.

The following showcases how to implement Decode to be generic over Database. The implementation can be marginally simpler if you remove the DB type parameter and explicitly use the concrete ValueRef and TypeInfo types.

struct MyType;

// DB is the database driver
// `'r` is the lifetime of the `Row` being decoded
impl<'r, DB: Database> Decode<'r, DB> for MyType
where
    // we want to delegate some of the work to string decoding so let's make sure strings
    // are supported by the database
    &'r str: Decode<'r, DB>
{
    fn decode(
        value: <DB as HasValueRef<'r>>::ValueRef,
    ) -> Result<MyType, Box<dyn Error + 'static + Send + Sync>> {
        // the interface of ValueRef is largely unstable at the moment
        // so this is not directly implementable

        // however, you can delegate to a type that matches the format of the type you want
        // to decode (such as a UTF-8 string)

        let value = <&str as Decode<DB>>::decode(value)?;

        // now you can parse this into your type (assuming there is a `FromStr`)

        Ok(value.parse()?)
    }
}

Required Methods§

source

fn decode(value: <DB as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError>

Decode a new value of this type using a raw value from the database.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<'r, DB, T> Decode<'r, DB> for Option<T>
where DB: Database, T: Decode<'r, DB>,

source§

fn decode(value: <DB as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError>

Implementors§