macro_rules! sqlx_json_decode {
($type:ty) => { ... };
}
Expand description
Generate a Decode implementation for a type that can read it from a PostgreSQL JSON/JSONB field.
ⓘ
use serde::{Deserialize, Serialize};
use sqlx_transparent_json_decode::sqlx_json_decode;
#[derive(Serialize, Deserialize)]
pub struct SomeJsonField {
// Whatever fields match the JSON structure
pub name: String,
pub some_param: Option<String>,
pub count: i32,
}
sqlx_json_decode!(SomeJsonField);
#[derive(sqlx::FromRow)]
pub struct QueryResult {
pub id: i32,
pub name: String,
pub params: SomeJsonField,
}
Normally, you would need to use Json<SomeJsonField>
as the type for params
in the above example. This macro allows you to use SomeJsonField
directly.
ⓘ
let result = sqlx::query_as!(
QueryResult,
r##"SELECT id,
name,
params as "params: SomeJsonField"
FROM some_table"##,
).fetch_one(&pool).await?;