Problem of using rust-postgres

How to build the object required by execute?

use postgres::{Client, NoTls};

/*
struct relations {
    name : String,
    hobby: Vec<String>,
}
*/

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = Client::connect("host=127.0.0.1 user=postgres", NoTls)?;

    client.simple_query("
        DROP TABLE 
        IF EXISTS following_relation;
        ")?;

    println!("{}", "where is the problem");
    client.simple_query("
        CREATE TABLE following_relation (
            id      SERIAL PRIMARY KEY,
            relation  JSON NOT NULL
        )
    ")?;

    let mut a : String= "czfzdxx".to_string();
    let mut b : Vec<String> = vec!["basketball".to_string(), "jogging".to_string()];
    client.execute(
        r#"INSERT INTO following_relation(relation) 
           VALUE ('{"name" : $1, "hobby" : $2}')"#,
        &[&a, &b],
    )?;

    Ok(())
}

the definition of execute is https://docs.rs/postgres/0.17.0/postgres/struct.Client.html#method.execute

I have been given some hints to build my object and wrap by https://docs.rs/postgres/0.17.0/postgres/types/struct.Json.html, I don't know what that really means.

I have not tried to run your code, but wrapping in Json means doing something like this:

    client.execute(
        r#"INSERT INTO following_relation(relation) 
           VALUE ('{"name" : $1, "hobby" : $2}')"#,
        &[&a, &Json(b)],
    )?;

To me value as a whole - {"name" : $1, "hobby" : $2} should be in Json format. How do I wrap my struct with pub struct Json<T>(pub T); ?

You can implement serde's Serialize for your struct.

#[derive(Serialize)]
struct relations {
    name: String,
    hobby: Vec<String>,
}

let rel = relations {
    name: "czfzdxx".to_string(),
    hobby: vec![
        "basketball".to_string(),
        "jogging".to_string()
    ],
};

client.execute(
    r#"INSERT INTO following_relation(relation)
         VALUE ($1)"#,
    &[&Json(&rel)]
)?;

If you want to read relations from the database, you'd also derive Deserialize.

1 Like

No words can describe my gratitude.

Though there is an error

error[E0277]: the trait bound Json<&relations>: postgres_types::ToSql is not satisfied

No words can describe my gratitude.

Though there is an error

error[E0277]: the trait bound Json<&relations>: postgres_types::ToSql is not satisfied

I missed that Json's ToSql implementation requires that the contained type also implement Debug. If you change the derive on relations to #[derive(Debug, Serialize)], that might fix the issue.

1 Like

I followed you suggestion yet the same error remains.

Sorry, I guess the error was

error[E0432]: unresolved import `postgres::types::Json`

Since I forget to add use postgres::types::Json; before

I hate me asking too much from you and being lazy thinking, I appreciate your help and I will try to solve, you already give me enough inspiration. :vulcan_salute:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.