Created
February 15, 2019 16:23
-
-
Save danbruder/e982756f30f6ca5ca9a8464da42865b8 to your computer and use it in GitHub Desktop.
Store JSON blob in Postgres with Diesel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ALTER TABLE orders | |
ADD COLUMN meta_data jsonb; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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)?; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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