2

我对如何使用PgNumeric十进制数的类型感到困惑。我在测试中注意到1.0-31.0使用以下实例插入到表中:

PgNumeric::Positive { weight: 0, scale: 1, digits: vec![1] } 

PgNumeric::Negative  {weight: 0, scale: 1, digits: vec![31] }

我似乎无法弄清楚如何将带有小数点右侧数字的值(如5.4321)插入表中。

4

1 回答 1

3

简短的回答:PgNumeric::Positive { weight: 0, scale: 4, digits: [5, 4321] }

更多示例:

// 9.87654321::numeric
PgNumeric::Positive { weight: 0, scale: 8, digits: [9, 8765, 4321] }

// 12345.6789::numeric
PgNumeric::Positive { weight: 1, scale: 4, digits: [1, 2345, 6789] }

// 100000000.000000002::numeric
PgNumeric::Positive { weight: 2, scale: 9, digits: [1, 0, 0, 0, 0, 2000] }

// 0.3::numeric
PgNumeric::Positive { weight: -1, scale: 1, digits: [3000] }

看起来算法是:

  1. 将您的号码分组为 4 位数字,从小数点开始向外计算。这些是数字

  2. 计算表示整数部分所需的块数并减去一个。这就是重量

  3. 计算表示小数部分所需的位数。这是规模

测试工具

这是我正在使用的代码,从测试中提取:

extern crate diesel;

use diesel::*;
use diesel::types::*;

use diesel::pg::data_types::PgNumeric;
use diesel::pg::PgConnection;

 type PgBackend = <PgConnection as Connection>::Backend;

fn main() {
    let query = "100000000.000000002::numeric";
    let expected_value = PgNumeric::Negative {
        digits: vec![31],
        weight: 0,
        scale: 1,
    };
    assert_eq!(expected_value, query_single_value::<Numeric, PgNumeric>(query));
}

fn query_single_value<T, U: Queryable<T, PgBackend>>(sql_str: &str) -> U
    where PgBackend: HasSqlType<T>,
{
    use diesel::expression::dsl::sql;
    let connection = connection();
    select(sql::<T>(sql_str)).first(&connection).unwrap()
}

fn connection() -> PgConnection {
    let result = connection_without_transaction();
    result.begin_test_transaction().unwrap();
    result
}

fn connection_without_transaction() -> PgConnection {
    let connection_url = "postgres://localhost/some_db";
    ::diesel::pg::PgConnection::establish(&connection_url).unwrap()
}

可能有用的背景信息

来自Postgres 文档

数字的小数位数是小数部分中小数位数的计数,位于小数点右侧。数字的精度是整数中有效位数的总数,即小数点两边的位数。所以数字 23.5141 的精度为 6,小数位数为 4。

但是,Postgres 代码说:

/*
 * In the NumericShort format, the remaining 14 bits of the header word
 * (n_short.n_header) are allocated as follows: 1 for sign (positive or
 * negative), 6 for dynamic scale, and 7 for weight.  In practice, most
 * commonly-encountered values can be represented this way.
 *
 * In the NumericLong format, the remaining 14 bits of the header word
 * (n_long.n_sign_dscale) represent the display scale; and the weight is
 * stored separately in n_weight.
 */
于 2016-07-04T01:01:47.340 回答