Skip to main content

uuid/
sqlx.rs

1//! Integration with [`sqlx`] for PostgreSQL UUID support.
2//!
3//! Enabled via the `sqlx` feature flag (requires the `postgres` database feature on `sqlx`).
4//!
5//! # Supported traits
6//!
7//! | Trait | Purpose |
8//! |---|---|
9//! | [`sqlx::Type`] | Declares the PostgreSQL type mapping as `uuid`. |
10//! | [`sqlx::postgres::PgHasArrayType`] | Declares the PostgreSQL array type mapping as `_uuid`. |
11//! | [`sqlx::Encode`] | Encodes a [`Uuid`] as 16 binary bytes for query arguments. |
12//! | [`sqlx::Decode`] | Decodes a [`Uuid`] from both binary and text wire formats. |
13
14use sqlx::{
15    Postgres,
16    decode::Decode,
17    encode::{Encode, IsNull},
18    error::BoxDynError,
19    postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef},
20    types::Type,
21};
22
23use crate::Uuid;
24
25impl Type<Postgres> for Uuid {
26    fn type_info() -> PgTypeInfo {
27        PgTypeInfo::with_name("uuid")
28    }
29}
30
31impl PgHasArrayType for Uuid {
32    fn array_type_info() -> PgTypeInfo {
33        PgTypeInfo::with_name("_uuid")
34    }
35}
36
37impl Encode<'_, Postgres> for Uuid {
38    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
39        buf.extend_from_slice(&self.0);
40        Ok(IsNull::No)
41    }
42}
43
44impl Decode<'_, Postgres> for Uuid {
45    fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
46        match value.format() {
47            PgValueFormat::Binary => Uuid::from_slice(value.as_bytes()?).map_err(Into::into),
48            PgValueFormat::Text => Uuid::parse(value.as_str()?).map_err(Into::into),
49        }
50    }
51}