#Diesel query structs not related by any table schema

5 messages · Page 1 of 1 (latest)

stark musk
#

I have the following schema

diesel::table! {
    expenses (expense_id) {
        expense_id -> Int8,
        number -> Int8,
        description -> Nullable<Text>,
        date -> Timestamp,
    }
}
diesel::table! {
    monthly_expenses (month, year, expense_id) {
        month -> Int4,
        year -> Int4,
        expense_id -> Int8,
    }
}

I want to do an aggregating query and i want to get its result

let expense_used_query = format!(
        r#"
        SELECT me.year as `year`, m.month as `month`, SUM(e.number) as `total`
        FROM monthly_expenses me
        JOIN expenses e
        ON me.expense_id = e.expense_id
        WHERE me.year = {} AND me.month = {}\
        GROUP BY me.year, me.month
        "#,
        partition.year, partition.month
    );

    let mut expense_used: i64 = 0;

    match sql_query(expense_used_query).load::<MonthlyTotalPartition>(conn.deref()) {
        Ok(monthly_totals) => {
            if let Some(monthly_total) = monthly_totals.first() {
                expense_used = monthly_total.total.unwrap_or(0)
            } else {
                Err(status::Custom(Status::InternalServerError, "Error occurred in server".to_string()))
            }
        }
        Err(_) => Err(status::Custom(Status::InternalServerError, "Error occurred in server".to_string()))
    }
#

I made a struct to take the results

#[derive(QueryableByName)]
pub struct MonthlyTotalPartition {
    #[sql_type="Integer"]
    pub month: i32,
    #[sql_type="Integer"]
    pub year: i32,
    #[sql_type="BigInt"]
    pub total: Option<i64>
}

But this gives the following error

error[E0277]: the trait bound `SqlQuery: LoadQuery<_, queryable::MonthlyTotalPartition>` is not satisfied
    --> src\api\financial\helper.rs:63:71
     |
63   |     match sql_query(expense_used_query).load::<MonthlyTotalPartition>(conn.deref()) {
     |                                         ----                          ^^^^^^^^^^^^ the trait `LoadQuery<_, queryable::MonthlyTotalPartition>` is not implemented for `SqlQuery`
     |                                         |
     |                                         required by a bound introduced by this call
     |
     = help: the trait `LoadQuery<Conn, T>` is implemented for `SqlQuery`
note: required by a bound in `load`
#

Diesel query structs not related by any table schema

stark musk
#

Turns out Option<i64> requires Nullable<BigInt> as sql_type 😅

#

error is so unrelated tho