How to impl From<AStruct> for a tokio_postgres::Row

539 Views Asked by At

I've successfully impl From<tokio_postgres::Row> for AStruct, but is it possible to (1) impl From<AStruct> to tokio_postgres::Row and (2) subsequently insert the created tokio_postgres::Row into a table? I've looked at tokio_postgres::Row (see bellow), and also tried to impl tokio_postgres::types::ToSql as well as tokio_postgres::types::FromSql. I'd really like to exclusively use Tokio-Postgres for this project, if it's possible. I have written up a minimal code example bellow to show what I am trying to do.

Let me know if I can clarify my question in any way.

#[derive(ToSql, FromSql, Debug)]
enum E {
    A,
    B,
}

#[derive(ToSql, FromSql, Debug)]
struct AStruct {
    i: i32,
    e: E,
    d: DateTime<Utc>
}

impl From<Row> for AStruct {
    fn from(row: Row) -> Self {
        Self {
            i: row.get(0),
            e: row.get(1),
            d: row.get(2),
        }
    }
}

// TODO
impl From<AStruct> for Row {
    fn from(s: S) -> Self {
        Self {
            statement: ...?,
            body: ...?,
            ranges: ...?,
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (client, _) = tokio_postgres::connect(database_url, NoTls).await?;

    let s = AStruct {
        i: 1,
        e: E::A,
        d: Utc::now(),
    };

    // This works!
    let s: AStruct = client
        .query("SELECT * FROM structs WHERE id = $1", &[&id])
        .await?
        .into_iter()
        .next()
        .unwrap()
        .into();

    // This does not work :(
    let row: Row = s.into();

    Ok(())
}
0

There are 0 best solutions below