https://github.com/dimfeld/sqlx-transparent-json-decode
Easier JSON decoding with sqlx
https://github.com/dimfeld/sqlx-transparent-json-decode
Last synced: 7 months ago
JSON representation
Easier JSON decoding with sqlx
- Host: GitHub
- URL: https://github.com/dimfeld/sqlx-transparent-json-decode
- Owner: dimfeld
- License: apache-2.0
- Created: 2023-05-27T08:07:05.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2024-04-24T08:20:31.000Z (over 2 years ago)
- Last Synced: 2024-04-24T13:41:22.344Z (over 2 years ago)
- Language: Rust
- Size: 22.5 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE-APACHE
Awesome Lists containing this project
README
# sqlx-transparent-json-decode
This crate is meant for use with [sqlx](https://github.com/launchbadge/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.
```rust
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,
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` as the type for `params` in the above example. This crate allows you to use `SomeJsonField` directly.
```rust
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` which can be decoded directly. This is
otherwise difficult to do using sqlx's query macros.
```rust
let result = sqlx::query!(
r##"SELECT id, data as "data: BoxedRawValue" FROM table##"
).fetch_one(&pool).await?;
```