[][src]Macro df_st_db::optional_filter

macro_rules! optional_filter {
    { $query:ident, $id_filter:ident,
      $id_list:ident => $id_variable:ident,
      [$($key:expr => $variable:ident),*,],
      $order_by_block:block,
      } => { ... };
    { $query:ident, $id_filter:ident,
      [$($key:expr => $variable:ident),*,],
      $order_by_block:block,
      } => { ... };
    { $query:ident, $id_filter:ident,
      $id_list:ident => $id_variable:ident,
      [$($key_id:expr => $variable_id:ident),*,],
      $string_filter:ident,
      [$($key_s:expr => $variable_s:ident),*,],
      $order_by_block:block,
      } => { ... };
}

Add if statements for all the possible filters. The function must return in this statement for the filters to work. Parameters:

  • query: First part of the Diesel query. (stored in variable)
  • id_filter: HashMap<String,i32>, a list where the keys are the field to filter.
  • [key => value,...]: A list of allowed filters
    • key: &str, name of the field that matches the order_by.
    • value: Diesel column, the column that matches the key.
  • {...}: A block of code with anything in it. But it must return in all cases. The query variable can be used the further extend the result after the addition of the filter. Return: The value output from the last code block. Example use:
optional_filter!{
    query, id_filter,
    id_list => id,
    [
        "id" => id,
        "region_id" => region_id,
    ],
    {return Ok(order_by!{
        order_by, asc, query, conn,
        "id" => id,
        "region_id" => region_id,
        "x" => x,
        "y" => y,
    });},
};

Example generated code output:

let mut query = query.into_boxed::<diesel::sqlite::Sqlite>(); // Or Postgres
if let Some(id_list) = id_list {
    query = query.filter(id.eq_any(id_list));
}
if let Some(id_x) = id_filter.get("id"){
    query = query.filter(id.eq(id_x));
}
if let Some(id_x) = id_filter.get("region_id"){
    query = query.filter(region_id.eq(id_x));
}
return Ok(order_by!{
    order_by, asc, query, conn,
    "id" => id,
    "region_id" => region_id,
    "x" => x,
    "y" => y,
});