Skip to content

Instantly share code, notes, and snippets.

@danbruder
Created February 15, 2019 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbruder/e982756f30f6ca5ca9a8464da42865b8 to your computer and use it in GitHub Desktop.
Save danbruder/e982756f30f6ca5ca9a8464da42865b8 to your computer and use it in GitHub Desktop.
Store JSON blob in Postgres with Diesel
ALTER TABLE orders
ADD COLUMN meta_data jsonb;
#[derive(Serialize, Identifiable, Clone, Queryable, Debug)]
#[table_name = "orders"]
pub struct Order {
pub id: i32,
// ... other fields
pub meta_data: Option<serde_json::Value>,
}
#[derive(Insertable)]
#[table_name = "orders"]
pub struct NewOrder {
// ... other fields
pub meta_data: Option<serde_json::Value>
}
#[derive(Serialize)]
pub struct MetaData {
pub avatar: String,
pub coupon_code: String
}
let meta_data = MetaData {
avatar: "https://someplace.com/12345/avatar.png".to_string(),
coupon_code: "123COUPON".to_string()
}
let order = &NewOrder{
meta_data: Some(serde_json::to_value(meta_data)?)
}
// Insert order with serialized Json
diesel::insert_into(orders::table)
.values(order)
.get_result::<Order>(&conn)?;
// Diesel schema definition
table! {
orders (id) {
id -> Int4,
// ... other fields
// uses Jsonb type
meta_data -> Nullable<Jsonb>,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment