0

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(())
}
Neotenic Primate
  • 313
  • 3
  • 13
  • You probably want to approach this a different way, e.g. have `#[async_trait] trait Insertable { async fn insert_with(client: &tokio_postgres::GenericClient) -> Result<(), tokio_postgres::error::Error> }` and implement that on your type instead. `Row` is intended to get data out of the database; it's not really designed to put data back in. – cdhowie Jun 15 '22 at 20:59
  • `Insertable` is a Diesel trait, correct? Do you know of a way of doing the same using only [Tokio-Postgres](https://docs.rs/tokio-postgres/latest/tokio_postgres/) (i.e., [ToSql](https://docs.rs/tokio-postgres/latest/tokio_postgres/types/trait.ToSql.html)) – Neotenic Primate Jun 15 '22 at 21:33
  • It might also be a Diesel trait, but I just made up a trait there that you could implement on whatever you want. – cdhowie Jun 15 '22 at 21:33
  • Ah, I see. But then what would the body of your fn look like? My whole problem is finding a way of inserting the struct using only this crate. – Neotenic Primate Jun 15 '22 at 21:39
  • You'd invoke one of the query methods of `GenericClient` and construct an `INSERT` statement. This crate isn't an ORM like Diesel, so it doesn't have a way to generate statements. You have to do that yourself. – cdhowie Jun 15 '22 at 22:25

0 Answers0