如何根据请求将 PostgreSQL 数字类型解析为 Rust 原生类型?

rtv*_*iii 6 postgresql types traits rust

相关代码是这样的:

use chrono::{DateTime, Utc}; // 0.4.10
use postgres::{Client, NoTls, Config, types::{FromSql, Type}};
//...
for row in client.query("SELECT * FROM pricetable;", &[])? {
    let time:DateTime<Utc> = row.get(0);
    let price:i64      = row.get(1);

    println!("found datum:  {:?}", &row);
    println!("found datum: {} {} ", time, price);
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到的错误是这样的:

thread 'main' panicked at 'error retrieving column 1: error

deserializing column 1: cannot convert between the Rust type `i64` 

and the Postgres type `numeric`', /home/me/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-postgres-0.7.6/src/row.rs:151:25
Run Code Online (Sandbox Code Playgroud)

其中priceNUMERICSQL 类型的类型。我似乎无法将其解析为任何标准的 Rust 类型u64,例如i64等,因为它们似乎没有实现板条箱导出FromSql的特征postgres。(我意识到这里清楚地说明了它们确实如此,但这不是我的错误所说的。我需要启用某些功能吗?Cargo.tomlpostgres={version="0.19.3",features= ["with-chrono-0_4"]}

我见过有人建议声明你自己的包装类型,比如struct Float64(u64)和 实现ToSqlFromSql。这是将数据从 Postgres 获取到 Rust 的唯一方法吗?如果有的话有参考实现吗?

rtv*_*iii 2

使用类似的东西decimal来代替原生数据类型:它实际上FromSqlToSql没有实现常规 rust 的数字类型和 SQL 的NUMERIC. 这是由于NUMERIC任意精度。