postgresqlrustrust-diesel

Handle Jsonb postgresql columns in rust-diesel


I have a table with a Jsonb column

diesel::table! {
    user (id) {
        id -> Uuid,
        data -> Jsonb,
        ...
    }
}

I created an struct like:

use crate::schema::user;
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Serialize, Deserialize, Queryable, Insertable)]
#[table_name = "user"]
pub struct User {
    pub id: Uuid,
    pub data: serde_json::Value,
    ...

}

...

This code complains that the data field has some problems

pub data: serde_json::Value
    ^^^^ the trait `diesel::Expression` is not implemented for `Value`

I'm new to rust and diesel and I can't find how the implementation is done. I thought serde_json is all I need it but I guess something else is missing.

These are the versions I have in my Cargo.toml

actix-web = "4.4.0"
actix-rt = "2.9.0"
chrono = { version = "0.4.31", features = ["serde"] }
diesel = { version = "2.1.4", features = ["postgres","r2d2", "uuid", "chrono"] }
diesel_migrations = "2.1.0"
dotenv = "0.15.0"
env_logger = "0.10.1"
lazy_static = "1.4.0"
listenfd = "1.0.1"
log = "0.4.20"
r2d2 = "0.8.10"
rand = "0.8.5"
rust-argon2 = "2.0.0"
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"
uuid = { version = "1.6.1", features = ["serde", "v4"] }

Solution

  • You didn't enable serde_json extra feature in Cargo.toml:

    diesel = { version = "2.1.4", features = ["postgres","serde_json","r2d2","uuid","chrono"] }
    

    This feature flag adds the necessary trait implementations.

    pub struct User {
        pub id: Uuid,
        pub data: serde_json::Value,
        ...
    
    }