New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using raw sql to get structs not related to any table schema #1665

Closed
hweom opened this Issue Apr 28, 2018 · 2 comments

Comments

Projects
None yet
2 participants
@hweom

hweom commented Apr 28, 2018

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?

@hweom

This comment has been minimized.

hweom commented Apr 28, 2018

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

The error is quite misleading tho.

@hweom hweom closed this Apr 28, 2018

@sgrif

This comment has been minimized.

Member

sgrif commented Apr 28, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment