Open TroyKomodo opened 1 year 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))
}
}
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?;
Currently, the
ulid
crate implementspostgres-types
support but for some unknown reason thesqlx
crate does not extend from the genericpostgres-types
crate. So anyone using a derivative ofsqlx
(sea-orm
) or using the sqlx driver directly would be unable to use this crate directly without a custom wrapper type.