sqlx-transparent-json-decode

Crates.iosqlx-transparent-json-decode
lib.rssqlx-transparent-json-decode
version3.0.0
sourcesrc
created_at2023-05-27 08:08:51.794988
updated_at2024-07-23 18:50:10.012662
descriptionDecode JSON from Postgres sqlx queries, without the Json<> wrapper type
homepage
repositoryhttps://github.com/dimfeld/sqlx-transparent-json-decode
max_upload_size
id875818
size29,589
Daniel Imfeld (dimfeld)

documentation

https://docs.rs/sqlx-transparent-json-decode

README

sqlx-transparent-json-decode

docs.rs docs Download

This crate is meant for use with sqlx and allows you to query JSON or JSONB fields from PostgreSQL without needing to wrap the types in a sqlx::types::Json<> wrapper type.

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 crate 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?;

This crate also provides BoxedRawValue, a wrapper around Box<serde_json::value::RawValue> which can be decoded directly. This is otherwise difficult to do using sqlx's query macros.

let result = sqlx::query!(
    r##"SELECT id, data as "data: BoxedRawValue" FROM table##"
).fetch_one(&pool).await?;
Commit count: 17

cargo fmt