Rust 使用 Postgres JSON 属性:无法在 Rust 类型 `alloc::string::String` 和 Postgres 类型 `jsonb` 之间进行转换

Wer*_*ner 4 postgresql json rust rust-tokio

目前我可以使用以下代码,但我不想在 postgres 查询中将 JSON 转换为文本,因为它会增加延迟。

async fn filter_data(min : f32, max : f32, pool: &Pool) -> Result<String, PoolError> {
    let client: Client = pool.get().await?;
    let sql = format!("select \"json\"::TEXT from get_data({}, {})", min, max);
    let stmt = client.prepare(&sql).await?;
    let rows = client.query(&stmt, &[]).await?;
    Ok(rows[0].get(0))
}
Run Code Online (Sandbox Code Playgroud)

如果我不将 JSON 转换为文本,则会收到以下错误:

error retrieving column 0: error deserializing column 0: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb`
Run Code Online (Sandbox Code Playgroud)

可以使用什么类型以便我返回该 json 值而不将其转换为文本?

小智 6

为了使用 Json 和 Jsonb 值,您需要在 postgres create 中启用该功能 features = ["with-serde_json-1"]

然后你可以将你的返回类型更改为Result<serde_json::Value,PoolError>

所以你会在你的cargo.toml中

[dependencies]
postgres = {version = "0.17.3" , features = ["with-serde_json-1"] }
serde_json = "1.0.56"
Run Code Online (Sandbox Code Playgroud)

并在你的 main.rs 中

async fn reverse_geocode(min : f32, max : f32, pool: &Pool) -> Result<serde_json::Value, PoolError> {
    let client: Client = pool.get().await?;
    let sql = format!("select \"json\" from get_data({}, {})", min, max);
    let stmt = client.prepare(&sql).await?;
    let rows = client.query(&stmt, &[]).await?;
    Ok(rows[0].get(0))
}
Run Code Online (Sandbox Code Playgroud)