Assuming I have the following structs:
#[derive(Debug, Serialize, FromRow)]
struct PublicUser {
id: Uuid,
username: String,
}
#[derive(Debug, Serialize, FromRow)]
struct PublicEvent {
id: Uuid,
name: String,
owner: PublicUser,
}
And I’d want to query a PublicEvent from my PostgreSQL DB including the owner as a PublicUser and I have a column “owner_id” on PublicEvent, which references the corresponding PublicUser and must be set, how can I query this in one query?
I currently have this:
pub async fn list_events(pool: &PgPool) -> Result<Vec<PublicEvent>, anyhow::Error> {
Ok(query_as(r#"
SELECT "Event".*, "User" as "owner: PublicUser"
FROM "Event"
JOIN "User" ON "Event".owner_id = "User".id"#)
.fetch_all(&pool).await?,
)
}
But this results in the error the trait `sqlx::Decode<'_, Postgres>` is not implemented for `PublicUser`, which is required by `for<'r> PublicEvent: FromRow<'r, PgRow>`
.
The only workaround I can come up with right now, would be to create a struct that holds all fields of both structs above, query into that and then impl From<HelperStruct> for PublicEvent
, but that seems bad to me.
Is there an elegant solution to query an Event with its Owner in SQLX?