dylanhart / ulid-rs

This is a Rust implementation of the ulid project

Home Page:https://crates.io/crates/ulid

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[FEATURE] SQLx support

TroyKomodo opened this issue · comments

Currently, the ulid crate implements postgres-types support but for some unknown reason the sqlx crate does not extend from the generic postgres-types crate. So anyone using a derivative of sqlx (sea-orm) or using the sqlx driver directly would be unable to use this crate directly without a custom wrapper type.

It is because FromSql/ToSql has been changed to Decode/Encode. It would be nice to have it updated for latest sqlx

In the meantime I made a wrapper based on uuid in sqlx

https://github.com/launchbadge/sqlx/blob/main/sqlx-postgres/src/types/uuid.rs

use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Ulid(ulid::Ulid);

impl Ulid {
    pub fn new() -> Self {
        Self( ulid::Ulid::new() )
    }
}

impl sqlx::Type<sqlx::Postgres> for Ulid {
    fn type_info() -> sqlx::postgres::PgTypeInfo {
        <&uuid::Uuid as sqlx::Type<sqlx::Postgres>>::type_info()
    }

    fn compatible(ty: &<sqlx::Postgres as sqlx::Database>::TypeInfo) -> bool {
        <&uuid::Uuid as sqlx::Type<sqlx::Postgres>>::compatible(ty)
    }
}

impl sqlx::postgres::PgHasArrayType for Ulid {
    fn array_type_info() -> sqlx::postgres::PgTypeInfo {
        <&Vec<uuid::Uuid> as sqlx::Type<sqlx::Postgres>>::type_info()
    }
    fn array_compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
        <&uuid::Uuid as sqlx::Type<sqlx::Postgres>>::compatible(ty)
    }
}


impl sqlx::Encode<'_, sqlx::Postgres> for Ulid {
    fn encode_by_ref(&self, buf: &mut sqlx::postgres::PgArgumentBuffer) -> sqlx::encode::IsNull {
        buf.extend_from_slice(&self.0.to_bytes());

        sqlx::encode::IsNull::No
    }
}

impl sqlx::Decode<'_, sqlx::Postgres> for Ulid {
    fn decode(value: sqlx::postgres::PgValueRef<'_>) -> Result<Self, sqlx::error::BoxDynError> {
        let ulid = match value.format() {
            sqlx::postgres::PgValueFormat::Binary => ulid::Ulid::from_bytes(value.as_bytes()?.try_into()?),
            sqlx::postgres::PgValueFormat::Text => ulid::Ulid::from_string(value.as_str()?)?,
        };

        Ok(Ulid(ulid))
    }
}