sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.52k stars 446 forks source link

How to implemt FromSql trait for type like `Role` #1124

Open HosMercury opened 8 months ago

HosMercury commented 8 months ago

How to implemt FromSql trait for type like Role

pub struct Role {
    pub uid: Uuid,
    pub name: String,
}
sfackler commented 8 months ago

What value do you want that to turn into in the database?

HosMercury commented 8 months ago

Thx for fast reply

    pub async fn with_roles(&self, state: &AppState) -> Result<()> {
        let pool = state.pool.clone();
        let sql = r#"
            SELECT users.* , Arr_AGG(roles.*) AS roles
            FROM users
            JOIN users_roles ON users_roles.user_uid = users.uid
            JOIN roles ON roles.uid = users_roles.role_uid
            WHERE users.uid = $1
            GROUP BY users.uid
            "#;

        let conn = pool.get().await.unwrap();
        // use the connection
        // it will be returned to the pool when it falls out of scope.

        let rows = conn.query(sql, &[&self.uid]).await.unwrap();

        // let value: &str = rows[0].get(0);

        Ok(())
    }

I'm getting array from postgres I get Vec it as array I want to convert it to Vec<Role> ?