dylanhart / ulid-rs

This is a Rust implementation of the ulid project
https://crates.io/crates/ulid
MIT License
381 stars 36 forks source link

[FEATURE] SQLx support #69

Open TroyKomodo opened 11 months ago

TroyKomodo commented 11 months ago

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.

KnowZero commented 7 months ago

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))
    }
}
foltik commented 1 month ago

It works (almost) out of the box without a wrapper type if you enable the uuid feature on both sqlx and ulid:

#[derive(Debug, sqlx::FromRow)]
struct User {
    id: Ulid,
    name: String,
}

let user: User = sqlx::query_as!(User, "SELECT * FROM users WHERE ...")
    .fetch_one(&pool).await?;

or when manually binding:

let id: Ulid = sqlx::query!("SELECT id FROM users WHERE name LIKE foo")
    .fetch_one(&pool).await?
    .id.into();

sqlx::query!("DELETE FROM users WHERE id = $1", Uuid::from(id))
    .execute(&pool).await?;