Skip to main content

vantage_table/table/
row_fields.rs

1//! The fields a table's returned rows carry, and the in-memory filter that
2//! relies on them.
3
4use indexmap::IndexMap;
5use vantage_types::{Entity, Record};
6
7use crate::{
8    column::flags::ColumnFlag,
9    table::Table,
10    traits::{column_like::ColumnLike, table_source::TableSource},
11};
12
13impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
14    /// The declared columns a returned row carries, in declaration order:
15    /// every column except those flagged
16    /// [`RequestParam`](ColumnFlag::RequestParam), whose values go to the
17    /// backend rather than come back from it. A `Hidden` column is still a
18    /// row field.
19    pub fn row_fields(&self) -> Vec<String> {
20        self.columns()
21            .iter()
22            .filter(|(_, column)| !column.flags().contains(&ColumnFlag::RequestParam))
23            .map(|(name, _)| name.clone())
24            .collect()
25    }
26}
27
28/// Keep the rows that match every `(field, wanted)` equality filter, for a
29/// backend that filters fetched rows in memory.
30///
31/// A row holding `field` passes when `eq(value, wanted)`. A row without it
32/// fails when `field` is one of `row_fields` (see [`Table::row_fields`]):
33/// rows were promised to carry it. Any other field (a `RequestParam` column,
34/// a URL placeholder, a parameter the table doesn't declare) went to the
35/// backend, which applied it without returning it, so its absence passes.
36pub fn retain_matching<V, W: ?Sized>(
37    rows: &mut IndexMap<String, Record<V>>,
38    filters: &[(&str, &W)],
39    row_fields: &[String],
40    eq: impl Fn(&V, &W) -> bool,
41) {
42    rows.retain(|_, row| {
43        filters.iter().all(|(field, wanted)| match row.get(*field) {
44            Some(value) => eq(value, wanted),
45            None => !row_fields.iter().any(|f| f == field),
46        })
47    });
48}