簡體   English   中英

Rust 使用 Postgres JSON 屬性:不能在 Rust 類型 `alloc::string::String` 和 Postgres 類型 `jsonb 之間轉換

[英]Rust use Postgres JSON attribute: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb`

目前我可以使用以下代碼,但我不想在我的 postgres 查詢中將 JSON 轉換為文本,因為它會增加延遲。

async fn reverse_geocode(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))
}

如果我不將 JSON 轉換為文本,則會收到以下錯誤:

error retrieving column 0: error deserializing column 0: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb`

可以使用什么類型,以便我返回 json 值而不將其轉換為文本?

為了使用 Json 和 Jsonb 值,您需要在 postgres create with 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"

在你的 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))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM