Diesel: Using raw sql to get structs not related to any table schema

Created on 28 Apr 2018  路  2Comments  路  Source: diesel-rs/diesel

Imagine I have the following schema:

table! {
    records (id) {
        id -> Int8,
        record_type -> Int2,
        amount -> Numeric,
        price -> Numeric,
    }
}

And I want to execute some aggregating query like this:

#[derive(QueryableByName)]
struct Entry {
    #[sql_type = "Integer"]
    record_type: i32,
    #[sql_type = "Numeric"]
    value: f64,
}

fn main() {
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let connection = PgConnection::establish(&database_url).unwrap();

    let query = "SELECT record_type, sum(price * amount) as value from records";
    let results = sql_query(query).load::<Entry>(&connection);
}

But this gives me an error:

error[E0277]: the trait bound `diesel::query_builder::SqlQuery: diesel::query_dsl::LoadQuery<_, Entry>` is not satisfied
  --> src/main.rs:25:36
   |
25 |     let results = sql_query(query).load::<Entry>(&connection);
   |                                    ^^^^ the trait `diesel::query_dsl::LoadQuery<_, Entry>` is not implemented for `diesel::query_builder::SqlQuery`
   |
   = help: the following implementations were found:
             <diesel::query_builder::SqlQuery as diesel::query_dsl::LoadQuery<Conn, T>>

Is there something that I'm missing?

Most helpful comment

Ugh, found the reason. diesel::sql_types::Numeric cannot be converted into f64, only into BigDecimal.

The error is quite misleading tho.

All 2 comments

Ugh, found the reason. diesel::sql_types::Numeric cannot be converted into f64, only into BigDecimal.

The error is quite misleading tho.

We don't have any control over the error Rust generates here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kollapsderwellenfunktion picture kollapsderwellenfunktion  路  4Comments

orionz picture orionz  路  3Comments

ghost picture ghost  路  3Comments

Fuckoffee picture Fuckoffee  路  3Comments

jimmycuadra picture jimmycuadra  路  4Comments