черта `diesel :: Expression` не реализована для` bigdecimal :: BigDecimal` - PullRequest
0 голосов
/ 21 апреля 2019

Я пытаюсь создать структуру, которую я могу использовать в дизеле для вставки. В частности, я делаю структуру Insertable. При компиляции я получаю эту ошибку.

У меня есть структура, которую я пытаюсь создать Insertable через атрибут производного. У меня есть поле с именем Bounty, которое должно представлять деньги, поэтому я использую BigDecimal в качестве типа. После компиляции я получаю ошибку в заголовке. Я также пытался использовать f64, но это выдает ту же ошибку.

#[macro_use]
extern crate diesel;
extern crate bigdecimal;

mod schema {
    use bigdecimal::BigDecimal;
    table! {
        Threads (Id) {
            Id -> Int8,
            Views -> Int4,
            Points -> Int4,
            FlagPoints -> Int4,
            IsDisabled -> Bool,
            IsAnswered -> Bool,
            Bounty -> Numeric,
            Title -> Varchar,
            Body -> Text,
            UserId -> Int8,
            CreatedBy -> Varchar,
            CreatedOn -> Timestamptz,
            LastModifiedBy -> Varchar,
            LastModifiedOn -> Timestamptz,
        }
    }

    #[allow(non_snake_case)]
    #[derive(Debug, Insertable)]
    #[table_name = "Threads"]
    pub struct InsertableThread { 
        pub Bounty: BigDecimal,
        pub Title: String,
        pub Body: String,
        pub UserId: i64
    }
}

fn main() {}

У меня есть структура внутри собственного файла, и это весь код. Структура Thread компилируется без проблем. Ошибка происходит на InsertableThread, поскольку она использует BigDecimal. Это ошибка, которая в результате.

error[E0277]: the trait bound `bigdecimal::BigDecimal: diesel::Expression` is not satisfied
  --> src/main.rs:29:21
   |
29 |     #[derive(Debug, Insertable)]
   |                     ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `bigdecimal::BigDecimal`
   |
   = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Numeric>` for `bigdecimal::BigDecimal`

error[E0277]: the trait bound `bigdecimal::BigDecimal: diesel::Expression` is not satisfied
  --> src/main.rs:29:21
   |
29 |     #[derive(Debug, Insertable)]
   |                     ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `bigdecimal::BigDecimal`
   |
   = note: required because of the requirements on the impl of `diesel::Expression` for `&bigdecimal::BigDecimal`
   = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Numeric>` for `&bigdecimal::BigDecimal`

error[E0277]: the trait bound `bigdecimal::BigDecimal: diesel::Expression` is not satisfied
  --> src/main.rs:29:21
   |
29 |     #[derive(Debug, Insertable)]
   |                     ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `bigdecimal::BigDecimal`
   |
   = note: required because of the requirements on the impl of `diesel::Expression` for `&'insert bigdecimal::BigDecimal`
   = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Numeric>` for `&'insert bigdecimal::BigDecimal`

Я использую Rust 1.34, дизель 1.4.2 и Postgres 11.

Я готов изменить типы в базе данных, Postgres или в коде Rust. База данных использует numeric, а в коде Rust я пробовал f64 и BigDecimal. Я также готов реализовать эту черту непосредственно, но мне нужно несколько советов о том, как это сделать, поскольку я не смог найти образцы.

1 Ответ

0 голосов
/ 21 апреля 2019

Diesel использует Функции Cargo , чтобы включить расширенную функциональность.

Я не нашел четкой страницы документации для них, но они перечислены в Cargo.toml :

[features]
default = ["with-deprecated", "32-column-tables"]
extras = ["chrono", "serde_json", "uuid", "deprecated-time", "network-address", "numeric", "r2d2"]
unstable = ["diesel_derives/nightly"]
large-tables = ["32-column-tables"]
huge-tables = ["64-column-tables"]
x32-column-tables = ["32-column-tables"]
32-column-tables = []
x64-column-tables = ["64-column-tables"]
64-column-tables = ["32-column-tables"]
x128-column-tables = ["128-column-tables"]
128-column-tables = ["64-column-tables"]
postgres = ["pq-sys", "bitflags", "diesel_derives/postgres"]
sqlite = ["libsqlite3-sys", "diesel_derives/sqlite"]
mysql = ["mysqlclient-sys", "url", "diesel_derives/mysql"]
with-deprecated = []
deprecated-time = ["time"]
network-address = ["ipnetwork", "libc"]
numeric = ["num-bigint", "bigdecimal", "num-traits", "num-integer"]

Вам необходимо включить функцию числовой и убедиться, что вы используете версию bigdecimal, совместимую с Diesel:

[dependencies]
diesel = { version = "1.4.2", features = ["numeric"] }
bigdecimal = "0.0.14"

И код компилируется:

#[macro_use]
extern crate diesel;

use crate::schema::threads;
use bigdecimal::BigDecimal;

mod schema {
    table! {
        threads (id) {
            id -> Int4,
            bounty -> Numeric,
        }
    }
}

#[derive(Debug, Insertable)]
#[table_name = "threads"]
pub struct InsertableThread {
    pub bounty: BigDecimal,
}

См. Также:

...