Get null fields from postgreSql

I am querying a database using deadpool_postgres,
but I get an error when converting to json because a field comes with null

pub async fn get_employees(client: &Client) -> Result<Vec<Employee>, AppError> {
    let stmt = client
        .prepare("select * from employee")
        .await?;

    let rowset = client
        .query(&stmt, &[])
        .await?
        .iter()
        .map(|row| {
            Employee::new(
                row.get("id"),
                row.get("store_id"),
                row.get("name"),
                Some(row.get("description")), //<-- This field sometimes contains null
            )
        })
        .collect::<Vec<Employee>>();


    Ok(rowset)
}

thread 'actix-rt:worker:0' panicked at 'error retrieving column description: error deserializing column 5: a Postgres value was NULL'

How do I capture a null value, to convert it to None?

Just pass in row.get("description"). Option<T> is the equivalent of a nullable Postgres value.

Shows the following error

 Compiling infraestructure v0.1.0 (/my-api/infraestructure)
error: comparison operators cannot be chained
  --> infraestructure/src/db.rs:45:45
   |
45 |                 row.get("description").Optio<T>
   |                                             ^ ^
   |
   = help: use `::<...>` instead of `<...>` to specify type arguments
   = help: or use `(...)` if you meant to specify fn arguments

error: aborting due to previous error

That “.” was the end of @sfackler's sentence, not part of any rust syntax. The next sentence starts with “Option<T>”.

As far as I understand, you just need to remove the Some() around the expression, turning Some(row.get("description")) into row.get("description"), to make it work.

I understand, I didn't see the point.

The query to the DB works perfect

The problem is the moment of serializing to json, there it throws the error because it does not recognize NULL

thread 'actix-rt:worker:0' panicked at 'error retrieving column description: error deserializing column 5: a Postgres value was NULL'

So it might have helped people help you if you showed the JSON serialization code that failed rather than something else.

I have potentially NULL fields in my database. The way to deal with it is to have Option fields in the structure that you are fetching rows into. My code looks like this:

#[derive(Serialize)]
struct Person {
    id: i64,
    name: String,
    data: Option<Vec<u8>>,
}

#[derive(Serialize)]
struct Persons {
    persons: Vec<Person>,
}

#[get("/public/api/persons")]
fn api_persons(model: State<Model>) -> Json<Persons> {
    let _current_count = model.count.fetch_add(1, Ordering::Relaxed);

    let mut conn = model.connect();
    let rows = conn
        .query("SELECT id, name, data FROM person", &[])
        .unwrap();

    let mut results = Persons { persons: vec![] };

    for row in &rows {
        let person = Person {
            id: row.get("id"),
            name: row.get("name"),
            data: row.get("data"),
        };
        results.persons.push(person);
    }
    Json(results)
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.