在 rust-postgres 中使用固定精度数的正确方法是什么?

ibr*_*ker 5 postgresql rust

定义固定精度数字(Postgres 中的小数或数字)并将其传递到 rust-postgres 中的插入的正确方法是什么?

transaction.execute("INSERT INTO commons_account(
            display_name, blocked, balance, blocked_balance, password, salt)
            VALUES ($1, $2, $3, $4, $5, $6);", &[&"bob", &false, &0, &0, &"dfasdfsa", &"dfsdsa"]).unwrap();
Run Code Online (Sandbox Code Playgroud)

余额和冻结余额都是numeric,运行此代码会出现此错误

thread 'test' panicked at 'called `Result::unwrap()` on an `Err` value: WrongType(Numeric)'
Run Code Online (Sandbox Code Playgroud)

ant*_*oyo 4

Numeric不属于支持的类型。您需要自己实现 ToSql 特征,如下所示:

struct Float64(f64);

impl ToSql for Float64 { // Or a fixed-precision type.
    to_sql_checked!();

    fn to_sql<W: Write + ?Sized>(&self, _: &Type, mut w: &mut W, _: &SessionInfo) -> Result<IsNull> {
        let num = 0;
        w.write_f64::<BigEndian>(num)?;
        *self = Float64(num);
        Ok(IsNull::No)
    }

    accepts!(Type::Numeric);
}
Run Code Online (Sandbox Code Playgroud)