[][src]Macro df_st_db::group_by

macro_rules! group_by {
    { $group_by_opt:ident, $query:ident, $conn:ident,
      $default_key:expr => {$default_variable:ident: $default_type:ty},
      $($key:expr => {$variable:ident: $variable_type:ty}),* $(,)* } => { ... };
}

Creates a match condition on group_by used for counting the items with a particular value in the field that is grouped. Parameters:

This example is not tested
group_by!{
    group_by_opt, query, conn,

Example generated code output:

This example is not tested
let count_star = diesel::dsl::sql::<diesel::sql_types::BigInt>("count(*)");
if let Some(group_by) = group_by_opt {
    match group_by.as_ref() {
        "civ_id" => {
            let query = sites.select((count_star, civ_id));
            let query = query.group_by(civ_id);
            let result = query.load::<(i64, Option<i32>)>(conn)?;
            let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
                ItemCount{
                    count: count as u32,
                    value: serde_json::json!(value),
                }
            }).collect();
            return Ok(result);
        }
        _ => {
            let query = sites.select((count_star, type_));
            let query = query.group_by(type_);
            let result = query.load::<(i64, Option<String>)>(conn)?;
            let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{
                ItemCount{
                    count: count as u32,
                    value: serde_json::json!(value),
                }
            }).collect();
            return Ok(result);
        }
    }
}
let query = sites.select(count_star);
let result = query.load::<i64>(conn)?;
let result: Vec<ItemCount> = result.into_iter().map(|count|{
    ItemCount{
        count: count as u32,
        value: serde_json::json!("total"),
    }
}).collect();