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`
可以使用什么类型,以便 return json 值无需将其转换为文本?
为了使用 Json 和 Jsonb 值,您需要在 postgres create with 中启用该功能
features = ["with-serde_json-1"]
然后您可以将 return 类型更改为 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))
}
目前我可以使用以下代码,但我不想在我的 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`
可以使用什么类型,以便 return json 值无需将其转换为文本?
为了使用 Json 和 Jsonb 值,您需要在 postgres create with 中启用该功能
features = ["with-serde_json-1"]
然后您可以将 return 类型更改为 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))
}