use indexmap::IndexMap;
use vantage_types::{Entity, Record};
use crate::{
column::flags::ColumnFlag,
table::Table,
traits::{column_like::ColumnLike, table_source::TableSource},
};
impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
pub fn row_fields(&self) -> Vec<String> {
self.columns()
.iter()
.filter(|(_, column)| !column.flags().contains(&ColumnFlag::RequestParam))
.map(|(name, _)| name.clone())
.collect()
}
}
pub fn retain_matching<V, W: ?Sized>(
rows: &mut IndexMap<String, Record<V>>,
filters: &[(&str, &W)],
row_fields: &[String],
eq: impl Fn(&V, &W) -> bool,
) {
rows.retain(|_, row| {
filters.iter().all(|(field, wanted)| match row.get(*field) {
Some(value) => eq(value, wanted),
None => !row_fields.iter().any(|f| f == field),
})
});
}
#[cfg(test)]
mod tests {
use indexmap::IndexMap;
use vantage_types::{EmptyEntity, Record};
use super::retain_matching;
use crate::column::flags::ColumnFlag;
use crate::mocks::{mock_column::MockColumn, mock_table_source::MockTableSource};
use crate::table::Table;
#[test]
fn a_missing_field_fails_only_when_rows_carry_it() {
let row = |pairs: &[(&str, i64)]| -> Record<i64> {
pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()
};
let mut rows: IndexMap<String, Record<i64>> = [
("a".to_string(), row(&[("size", 1)])),
("b".to_string(), row(&[("size", 2)])),
("c".to_string(), row(&[])),
]
.into_iter()
.collect();
let row_fields = vec!["size".to_string()];
retain_matching(&mut rows, &[("prefix", &9)], &row_fields, |a, b| a == b);
assert_eq!(rows.len(), 3);
retain_matching(&mut rows, &[("size", &1)], &row_fields, |a, b| a == b);
assert_eq!(rows.keys().collect::<Vec<_>>(), ["a"]);
}
#[test]
fn row_fields_leave_out_request_params_but_keep_hidden_columns() {
let table = Table::<MockTableSource, EmptyEntity>::new("buckets", MockTableSource::new())
.with_column(MockColumn::<String>::new("region").with_flag(ColumnFlag::RequestParam))
.with_column(MockColumn::<String>::new("name"))
.with_column(MockColumn::<String>::new("owner").with_flag(ColumnFlag::Hidden));
assert_eq!(table.row_fields(), ["name", "owner"]);
}
}