dax: take the pivot, integrity and functions-reference files into the core slice (#2228)

This commit is contained in:
alosslessdev
2026-11-05 04:59:09 -05:00
parent 9e7497210b
commit 6dbb9e3c8e
7 changed files with 1779 additions and 0 deletions
+167
View File
@@ -0,0 +1,167 @@
//! Related pivot fields that must be **rejected**, never guessed and never panicked:
//! unrelated tables, two relationships between the same tables, a second chain (a cycle in the
//! relationship graph), inactive relationships and one-to-many paths.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::pivot_table::{PivotTable, PivotTableError};
use gridcraft_dax::value::Scalar;
fn columns(names: &[(&str, &str)]) -> Vec<ModelColumn> {
names.iter().map(|(name, kind)| ModelColumn { name: (*name).into(), data_type: Some((*kind).into()) }).collect()
}
fn relationship(from_table: &str, from_column: &str, to_table: &str, to_column: &str) -> Relationship {
Relationship {
from_table: from_table.into(),
from_column: from_column.into(),
to_table: to_table.into(),
to_column: to_column.into(),
bidirectional: false,
inactive: false,
}
}
fn text(value: &str) -> Scalar {
Scalar::String(value.into())
}
fn sales() -> ModelTable {
ModelTable {
name: "Sales".into(),
columns: columns(&[("ProductKey", "Int64"), ("AltKey", "Int64"), ("RegionKey", "Int64"), ("Amount", "Double")]),
rows: vec![vec![Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(10)]],
}
}
fn product() -> ModelTable {
ModelTable {
name: "Product".into(),
columns: columns(&[("ProductKey", "Int64"), ("AltKey", "Int64"), ("Name", "String"), ("RegionKey", "Int64")]),
rows: vec![vec![Scalar::Integer(1), Scalar::Integer(1), text("Widget"), Scalar::Integer(1)]],
}
}
fn region() -> ModelTable {
ModelTable {
name: "Region".into(),
columns: columns(&[("RegionKey", "Int64"), ("Name", "String")]),
rows: vec![vec![Scalar::Integer(1), text("North")]],
}
}
fn other() -> ModelTable {
ModelTable { name: "Other".into(), columns: columns(&[("Code", "String")]), rows: vec![vec![text("x")]] }
}
fn measure() -> Measure {
Measure { name: "Total Sales".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }
}
fn model(tables: Vec<ModelTable>, relationships: Vec<Relationship>) -> DataModel {
let mut model = DataModel { tables, relationships, measures: vec![measure()] };
model.parse_formulas().expect("model parses");
model
}
#[test]
fn a_field_on_an_unrelated_table_is_rejected() {
let model = model(vec![sales(), product(), other()], vec![relationship("Sales", "ProductKey", "Product", "ProductKey")]);
let error = PivotTable::new("p", "Total Sales").with_row_fields(vec!["Other[Code]".into()]).render(&model).expect_err("unrelated");
assert!(matches!(&error, PivotTableError::ForeignField { field, table } if field == "Code" && table == "Sales"), "{error:?}");
assert!(error.to_string().contains("no active relationship"), "{error}");
// A filter is bound the same way, so it is rejected too.
let filter = PivotTable::new("p", "Total Sales")
.with_filter(gridcraft_dax::pivot_table::PivotFilter::new("Other[Code]", [text("x")]))
.render(&model)
.expect_err("unrelated filter");
assert!(matches!(filter, PivotTableError::ForeignField { .. }), "{filter:?}");
}
#[test]
fn two_relationships_between_the_same_tables_are_ambiguous() {
// `Sales[ProductKey]` and `Sales[AltKey]` both point at `Product[ProductKey]`. A pivot field
// names a table and a column, not a relationship, so the lookup cannot pick one.
let model = model(
vec![sales(), product()],
vec![relationship("Sales", "ProductKey", "Product", "ProductKey"), relationship("Sales", "AltKey", "Product", "ProductKey")],
);
let error = PivotTable::new("p", "Total Sales").with_row_fields(vec!["Product[Name]".into()]).render(&model).expect_err("ambiguous");
assert!(
matches!(&error, PivotTableError::AmbiguousFieldPath { field, table, source_table, paths } if field == "Name" && table == "Product" && source_table == "Sales" && *paths == 2),
"{error:?}"
);
assert!(error.to_string().contains("2 relationship chains"), "{error}");
}
#[test]
fn a_cycle_in_the_relationship_graph_is_rejected_as_ambiguous() {
// Sales -> Product -> Region plus Sales -> Region: two chains reach Region, so the pivot cannot
// tell which lookup the field means. The search is bounded and never loops.
let mut product = product();
product.columns = columns(&[("ProductKey", "Int64"), ("Name", "String"), ("RegionKey", "Int64")]);
product.rows = vec![vec![Scalar::Integer(1), text("Widget"), Scalar::Integer(1)]];
let sales = ModelTable {
name: "Sales".into(),
columns: columns(&[("ProductKey", "Int64"), ("RegionKey", "Int64"), ("Amount", "Double")]),
rows: vec![vec![Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(10)]],
};
let model = model(
vec![sales, product, region()],
vec![
relationship("Sales", "ProductKey", "Product", "ProductKey"),
relationship("Product", "RegionKey", "Region", "RegionKey"),
relationship("Sales", "RegionKey", "Region", "RegionKey"),
],
);
let error = PivotTable::new("p", "Total Sales").with_row_fields(vec!["Region[Name]".into()]).render(&model).expect_err("cycle");
assert!(matches!(&error, PivotTableError::AmbiguousFieldPath { paths, .. } if *paths == 2), "{error:?}");
}
#[test]
fn an_inactive_relationship_is_rejected_and_named() {
let mut inactive = relationship("Sales", "ProductKey", "Product", "ProductKey");
inactive.inactive = true;
let model = model(vec![sales(), product()], vec![inactive]);
let error = PivotTable::new("p", "Total Sales").with_row_fields(vec!["Product[Name]".into()]).render(&model).expect_err("inactive");
assert!(
matches!(&error, PivotTableError::InactiveRelationship { field, table, source_table } if field == "Name" && table == "Product" && source_table == "Sales"),
"{error:?}"
);
let message = error.to_string();
assert!(message.contains("inactive relationship") && message.contains("USERELATIONSHIP"), "{message}");
}
#[test]
fn a_field_reachable_only_from_the_one_side_is_rejected() {
// The pivot groups `Product` (source_table) and asks for a field on the many side, `Sales`.
// One Product row reaches many Sales rows, so it has no single value to group by.
let model = model(vec![sales(), product()], vec![relationship("Sales", "ProductKey", "Product", "ProductKey")]);
let error = PivotTable::new("p", "Total Sales")
.with_source_table("Product")
.with_row_fields(vec!["Sales[Amount]".into()])
.render(&model)
.expect_err("one-to-many");
assert!(
matches!(&error, PivotTableError::FanOutField { field, table, source_table } if field == "Amount" && table == "Sales" && source_table == "Product"),
"{error:?}"
);
assert!(error.to_string().contains("many-to-one"), "{error}");
}
#[test]
fn a_bidirectional_relationship_still_groups_by_lookup() {
// Bidirectional only widens filter propagation; the lookup direction is unchanged, so the
// star still groups and filters from the fact side.
let mut both = relationship("Sales", "ProductKey", "Product", "ProductKey");
both.bidirectional = true;
let model = model(vec![sales(), product()], vec![both]);
let table = PivotTable::new("p", "Total Sales").with_row_fields(vec!["Product[Name]".into()]).render(&model).expect("render");
assert_eq!(table.rows, vec![vec![text("Widget"), Scalar::Decimal(10.0)]]);
}
+167
View File
@@ -0,0 +1,167 @@
//! Pivot groups over a snowflake: `Sales -> Product -> Category`, two hops from the fact table.
//!
//! ```text
//! Sales (fact) Product (dimension) Category (dimension)
//! ProductKey Amount ProductKey Name CategoryKey CategoryKey Category
//! 1 100 1 Widget 10 10 Hardware
//! 1 50 2 Gadget 20 20 Software
//! 2 25 4 Doohickey 10
//! 3 40 <- ProductKey 3 has no Product row (orphan key)
//! ```
//!
//! `Sales[ProductKey] -> Product[ProductKey]` and `Product[CategoryKey] -> Category[CategoryKey]`
//! are active, so `Category` is reachable from `Sales` only through `Product`.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::pivot_table::{PivotFilter, PivotLayout, PivotTable};
use gridcraft_dax::value::{Scalar, TableValue};
fn columns(names: &[(&str, &str)]) -> Vec<ModelColumn> {
names.iter().map(|(name, kind)| ModelColumn { name: (*name).into(), data_type: Some((*kind).into()) }).collect()
}
fn relationship(from_table: &str, from_column: &str, to_table: &str, to_column: &str) -> Relationship {
Relationship {
from_table: from_table.into(),
from_column: from_column.into(),
to_table: to_table.into(),
to_column: to_column.into(),
bidirectional: false,
inactive: false,
}
}
fn text(value: &str) -> Scalar {
Scalar::String(value.into())
}
fn int(value: i64) -> Scalar {
Scalar::Integer(value)
}
fn dec(value: f64) -> Scalar {
Scalar::Decimal(value)
}
fn header(table: &TableValue) -> Vec<String> {
table.columns.iter().map(|column| column.name.clone()).collect()
}
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: columns(&[("ProductKey", "Int64"), ("Amount", "Double")]),
rows: vec![vec![int(1), int(100)], vec![int(1), int(50)], vec![int(2), int(25)], vec![int(3), int(40)]],
},
ModelTable {
name: "Product".into(),
columns: columns(&[("ProductKey", "Int64"), ("Name", "String"), ("CategoryKey", "Int64")]),
rows: vec![vec![int(1), text("Widget"), int(10)], vec![int(2), text("Gadget"), int(20)], vec![int(4), text("Doohickey"), int(10)]],
},
ModelTable {
name: "Category".into(),
columns: columns(&[("CategoryKey", "Int64"), ("Category", "String")]),
rows: vec![vec![int(10), text("Hardware")], vec![int(20), text("Software")]],
},
],
relationships: vec![
relationship("Sales", "ProductKey", "Product", "ProductKey"),
relationship("Product", "CategoryKey", "Category", "CategoryKey"),
],
measures: vec![Measure {
name: "Total Sales".into(),
formula: "SUM(Sales[Amount])".into(),
table: Some("Sales".into()),
format: None,
expr: None,
}],
};
model.parse_formulas().expect("model parses");
model
}
fn pivot() -> PivotTable {
PivotTable::new("snowflake", "Total Sales")
}
#[test]
fn a_two_hop_related_field_groups_and_filters_through_both_hops() {
let table = pivot().with_row_fields(vec!["Category[Category]".into()]).with_layout(PivotLayout::Tabular).render(&model()).expect("render");
// Widget (key 1) is Hardware: 100 + 50. Gadget (key 2) is Software: 25. The orphan key 3
// reaches no Product row, so it is the BLANK member of both hops and its cell counts it (40).
assert_eq!(header(&table), vec!["Category[Category]".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows, vec![vec![Scalar::Blank, dec(40.0)], vec![text("Hardware"), dec(150.0)], vec![text("Software"), dec(25.0)]]);
}
#[test]
fn one_hop_and_two_hop_row_fields_mix() {
let table = pivot()
.with_row_fields(vec!["Product[Name]".into(), "Category[Category]".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Product[Name]".to_string(), "Category[Category]".to_string(), "Total Sales".to_string()]);
assert_eq!(
table.rows,
vec![
vec![Scalar::Blank, Scalar::Blank, dec(40.0)],
vec![text("Gadget"), text("Software"), dec(25.0)],
vec![text("Widget"), text("Hardware"), dec(150.0)],
]
);
}
#[test]
fn a_dimension_row_without_fact_rows_is_not_a_group() {
let table = pivot().with_row_fields(vec!["Product[Name]".into()]).with_layout(PivotLayout::Tabular).render(&model()).expect("render");
// Doohickey (ProductKey 4) has no fact row; the cells come from the fact table, so it never
// appears. The orphan key still does, as the BLANK member — and its cell counts it.
assert_eq!(table.rows, vec![vec![Scalar::Blank, dec(40.0)], vec![text("Gadget"), dec(25.0)], vec![text("Widget"), dec(150.0)]]);
}
#[test]
fn a_filter_two_hops_away_restricts_the_fact_table() {
let filtered = pivot()
.with_row_fields(vec!["Product[Name]".into()])
.with_filter(PivotFilter::new("Category[Category]", [text("Software")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
// Only Gadget is Software, and only the two Widget rows are Hardware.
assert_eq!(header(&filtered), vec!["Product[Name]".to_string(), "Total Sales".to_string()]);
assert_eq!(filtered.rows, vec![vec![text("Gadget"), dec(25.0)]]);
let hardware = pivot()
.with_row_fields(vec!["Category[Category]".into()])
.with_filter(PivotFilter::new("Category[Category]", [text("Hardware")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(hardware.rows, vec![vec![text("Hardware"), dec(150.0)]]);
}
#[test]
fn the_grand_total_spans_the_fact_table_across_the_snowflake() {
let table = pivot()
.with_row_fields(vec!["Category[Category]".into()])
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(
table.rows,
vec![
vec![Scalar::Blank, dec(40.0)],
vec![text("Hardware"), dec(150.0)],
vec![text("Software"), dec(25.0)],
vec![text("Grand Total"), dec(215.0)],
]
);
}
+293
View File
@@ -0,0 +1,293 @@
//! Pivot groups over a star schema: one fact table and two dimensions of different cardinality.
//!
//! ```text
//! Sales (fact) Product (dimension, 3 rows) Store (dimension, 2 rows)
//! ProductKey StoreKey Amount Quantity ProductKey Name Color StoreKey City
//! 1 10 100 1 1 Widget Red 10 North
//! 1 20 50 2 2 Gadget Blue 20 South
//! 2 10 25 3 4 Doohickey Red
//! 3 10 40 4 <- ProductKey 3 has no Product row (orphan key)
//! 2 20 10 1
//! 1 10 30 1
//! ```
//!
//! `Sales[ProductKey] -> Product[ProductKey]` and `Sales[StoreKey] -> Store[StoreKey]` are the two
//! active relationships.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::pivot_table::{PivotFilter, PivotLayout, PivotTable};
use gridcraft_dax::value::{Scalar, TableValue};
fn columns(names: &[(&str, &str)]) -> Vec<ModelColumn> {
names.iter().map(|(name, kind)| ModelColumn { name: (*name).into(), data_type: Some((*kind).into()) }).collect()
}
fn relationship(from_table: &str, from_column: &str, to_table: &str, to_column: &str) -> Relationship {
Relationship {
from_table: from_table.into(),
from_column: from_column.into(),
to_table: to_table.into(),
to_column: to_column.into(),
bidirectional: false,
inactive: false,
}
}
fn measure(name: &str, formula: &str, table: &str) -> Measure {
Measure { name: name.into(), formula: formula.into(), table: Some(table.into()), format: None, expr: None }
}
fn text(value: &str) -> Scalar {
Scalar::String(value.into())
}
fn int(value: i64) -> Scalar {
Scalar::Integer(value)
}
fn dec(value: f64) -> Scalar {
Scalar::Decimal(value)
}
fn header(table: &TableValue) -> Vec<String> {
table.columns.iter().map(|column| column.name.clone()).collect()
}
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: columns(&[("ProductKey", "Int64"), ("StoreKey", "Int64"), ("Amount", "Double"), ("Quantity", "Int64")]),
rows: vec![
vec![int(1), int(10), int(100), int(1)],
vec![int(1), int(20), int(50), int(2)],
vec![int(2), int(10), int(25), int(3)],
vec![int(3), int(10), int(40), int(4)],
vec![int(2), int(20), int(10), int(1)],
vec![int(1), int(10), int(30), int(1)],
],
},
ModelTable {
name: "Product".into(),
columns: columns(&[("ProductKey", "Int64"), ("Name", "String"), ("Color", "String")]),
rows: vec![
vec![int(1), text("Widget"), text("Red")],
vec![int(2), text("Gadget"), text("Blue")],
vec![int(4), text("Doohickey"), text("Red")],
],
},
ModelTable {
name: "Store".into(),
columns: columns(&[("StoreKey", "Int64"), ("City", "String")]),
rows: vec![vec![int(10), text("North")], vec![int(20), text("South")]],
},
],
relationships: vec![relationship("Sales", "ProductKey", "Product", "ProductKey"), relationship("Sales", "StoreKey", "Store", "StoreKey")],
measures: vec![measure("Total Sales", "SUM(Sales[Amount])", "Sales"), measure("Total Quantity", "SUM(Sales[Quantity])", "Sales")],
};
model.parse_formulas().expect("model parses");
model
}
fn pivot() -> PivotTable {
PivotTable::new("star", "Total Sales")
}
#[test]
fn related_row_field_groups_by_the_dimension_value() {
let table = pivot().with_row_fields(vec!["Product[Name]".into()]).with_layout(PivotLayout::Tabular).render(&model()).expect("render");
// A related field is labeled with its table, so two dimensions with the same column name stay
// apart. ProductKey 3 has no Product row: its fact row groups as BLANK, and the cell is BLANK
// because the BLANK member selects no related row, so the relationship filter keeps nothing.
assert_eq!(header(&table), vec!["Product[Name]".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows, vec![vec![Scalar::Blank, dec(40.0)], vec![text("Gadget"), dec(35.0)], vec![text("Widget"), dec(180.0)],]);
assert_eq!(table.lineage, Some(0), "the rendered table keeps the source table's lineage");
}
#[test]
fn two_dimensions_cross_tabulate_with_two_measures() {
let table = pivot()
.with_row_fields(vec!["Product[Name]".into()])
.with_column_fields(vec!["Store[City]".into()])
.with_values(vec!["Total Sales".into(), "Total Quantity".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
// Label columns come first, then one column per column group and measure.
assert_eq!(
header(&table),
vec![
"Product[Name]".to_string(),
"North | Total Sales".to_string(),
"North | Total Quantity".to_string(),
"South | Total Sales".to_string(),
"South | Total Quantity".to_string(),
]
);
assert_eq!(
table.rows,
vec![
vec![Scalar::Blank, dec(40.0), dec(4.0), Scalar::Blank, Scalar::Blank],
vec![text("Gadget"), dec(25.0), dec(3.0), dec(10.0), dec(1.0)],
// Widget x North: 100 + 30, quantities 1 + 1.
vec![text("Widget"), dec(130.0), dec(2.0), dec(50.0), dec(2.0)],
]
);
}
#[test]
fn two_related_row_fields_order_blank_first_and_total_every_fact_row() {
let table = pivot()
.with_row_fields(vec!["Product[Name]".into(), "Store[City]".into()])
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Product[Name]".to_string(), "Store[City]".to_string(), "Total Sales".to_string()]);
assert_eq!(
table.rows,
vec![
vec![Scalar::Blank, text("North"), dec(40.0)],
vec![text("Gadget"), text("North"), dec(25.0)],
vec![text("Gadget"), text("South"), dec(10.0)],
vec![text("Widget"), text("North"), dec(130.0)],
vec![text("Widget"), text("South"), dec(50.0)],
// The grand total constrains no dimension, so it is the whole fact table.
vec![text("Grand Total"), Scalar::Blank, dec(255.0)],
]
);
}
#[test]
fn a_filter_on_a_dimension_field_restricts_the_fact_table() {
let filtered = pivot()
.with_row_fields(vec!["Store[City]".into()])
.with_filter(PivotFilter::new("Product[Name]", [text("Widget")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
// Only Widget's fact rows (100 + 50 + 30) survive, so North is 130 and South is 50.
assert_eq!(header(&filtered), vec!["Store[City]".to_string(), "Total Sales".to_string()]);
assert_eq!(filtered.rows, vec![vec![text("North"), dec(130.0)], vec![text("South"), dec(50.0)]]);
let by_store = pivot()
.with_row_fields(vec!["Product[Name]".into()])
.with_filter(PivotFilter::new("Store[City]", [text("North")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(by_store.rows, vec![vec![Scalar::Blank, dec(40.0)], vec![text("Gadget"), dec(25.0)], vec![text("Widget"), dec(130.0)]]);
// A filter that matches no dimension row keeps no fact row, but the header survives.
let nothing = pivot()
.with_row_fields(vec!["Product[Name]".into()])
.with_filter(PivotFilter::new("Product[Name]", [text("Nope")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert!(nothing.rows.is_empty());
assert_eq!(header(&nothing), vec!["Product[Name]".to_string(), "Total Sales".to_string()]);
}
#[test]
fn same_table_fields_are_unchanged_by_the_relationships() {
// Before related fields existed this grid was the only supported shape; it must not move.
let table = pivot()
.with_row_fields(vec!["Sales[ProductKey]".into()])
.with_column_fields(vec!["Sales[StoreKey]".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["ProductKey".to_string(), "10".to_string(), "20".to_string()]);
assert_eq!(table.rows, vec![vec![int(1), dec(130.0), dec(50.0)], vec![int(2), dec(25.0), dec(10.0)], vec![int(3), dec(40.0), Scalar::Blank],]);
}
/// A model whose dimension repeats a key. The one side of a relationship must be unique; when it is
/// not, the pivot resolves each fact row to the **lowest** matching dimension row, so no fact row is
/// fanned out and no value is counted twice.
fn duplicate_key_model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: columns(&[("ProductKey", "Int64"), ("Amount", "Double")]),
rows: vec![vec![int(1), int(10)], vec![int(1), int(20)], vec![int(2), int(5)]],
},
ModelTable {
name: "Product".into(),
columns: columns(&[("ProductKey", "Int64"), ("Name", "String")]),
rows: vec![vec![int(1), text("Alpha")], vec![int(1), text("Beta")], vec![int(2), text("Gamma")]],
},
],
relationships: vec![relationship("Sales", "ProductKey", "Product", "ProductKey")],
measures: vec![measure("Total Sales", "SUM(Sales[Amount])", "Sales")],
};
model.parse_formulas().expect("model parses");
model
}
#[test]
fn a_duplicate_dimension_key_resolves_to_the_lowest_row_and_never_doubles_a_fact_row() {
let table = PivotTable::new("duplicates", "Total Sales")
.with_row_fields(vec!["Product[Name]".into()])
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&duplicate_key_model())
.expect("render");
// Both key-1 fact rows reach Product row 0 ("Alpha"), so Beta is no group at all and the two
// rows are summed once: 10 + 20. The grand total proves nothing was duplicated.
assert_eq!(header(&table), vec!["Product[Name]".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows, vec![vec![text("Alpha"), dec(30.0)], vec![text("Gamma"), dec(5.0)], vec![text("Grand Total"), dec(35.0)]]);
}
#[test]
fn an_empty_dimension_table_groups_every_fact_row_as_blank() {
let mut model = model();
model.tables[1].rows.clear();
let table = pivot()
.with_row_fields(vec!["Product[Name]".into()])
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model)
.expect("render");
// Every key is an orphan, so every fact row groups as BLANK. The relationship has no BLANK
// member to attach them to, so the leaf cell is the empty-set measure (BLANK) while the grand
// total, which constrains no dimension, still sums the fact table.
assert_eq!(header(&table), vec!["Product[Name]".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows, vec![vec![Scalar::Blank, dec(255.0)], vec![text("Grand Total"), dec(255.0)]]);
}
#[test]
fn related_grouping_survives_an_unfaithful_model() {
let mut model = model();
// A boolean/integer mix promotes the column to a dictionary, so the columnar copy is lossless
// only in the storage's own terms: the pivot must group from the model rows and follow the
// relationship by key, with the same grid and with related filters still propagating.
model.tables[1].columns.push(ModelColumn { name: "Rank".into(), data_type: Some("Boolean".into()) });
model.tables[1].rows[0].push(Scalar::Boolean(true));
model.tables[1].rows[1].push(int(2));
model.tables[1].rows[2].push(Scalar::Boolean(false));
let (table, stats) =
pivot().with_row_fields(vec!["Product[Name]".into()]).with_layout(PivotLayout::Tabular).render_with_stats(&model).expect("render");
assert_eq!(table.rows, vec![vec![Scalar::Blank, dec(40.0)], vec![text("Gadget"), dec(35.0)], vec![text("Widget"), dec(180.0)]]);
assert_eq!(stats.pivot_group_rows, 0, "grouping fell back to the model rows: {stats:?}");
assert!(stats.row_scan_fallbacks > 0, "the unfaithful model must be reported: {stats:?}");
let filtered = pivot()
.with_row_fields(vec!["Store[City]".into()])
.with_filter(PivotFilter::new("Product[Name]", [text("Widget")]))
.with_layout(PivotLayout::Tabular)
.render(&model)
.expect("render");
assert_eq!(filtered.rows, vec![vec![text("North"), dec(130.0)], vec![text("South"), dec(50.0)]]);
}
+429
View File
@@ -0,0 +1,429 @@
//! Integration tests for the model-backed `PivotTable` object.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::pivot::{PivotError, pivot_cross, pivot_fields};
use gridcraft_dax::pivot_table::{DEFAULT_MAX_CELLS, PivotFilter, PivotLayout, PivotTable, PivotTableError};
use gridcraft_dax::value::{Scalar, TableValue};
// Region | Category | Amount | Quantity
// East | Widget | 10 | 2
// West | Widget | 20 | 3
// East | Gadget | 30 | 4
// East | Widget | 5 | 1
// (Blank) | Gadget | 7 | 1
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::String("Widget".into()), Scalar::Integer(10), Scalar::Integer(2)],
vec![Scalar::String("West".into()), Scalar::String("Widget".into()), Scalar::Integer(20), Scalar::Integer(3)],
vec![Scalar::String("East".into()), Scalar::String("Gadget".into()), Scalar::Integer(30), Scalar::Integer(4)],
vec![Scalar::String("East".into()), Scalar::String("Widget".into()), Scalar::Integer(5), Scalar::Integer(1)],
vec![Scalar::Blank, Scalar::String("Gadget".into()), Scalar::Integer(7), Scalar::Integer(1)],
],
}],
relationships: Vec::new(),
measures: vec![
Measure { name: "Total Sales".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None },
Measure { name: "Total Quantity".into(), formula: "SUM(Sales[Quantity])".into(), table: Some("Sales".into()), format: None, expr: None },
Measure { name: "Homeless".into(), formula: "1".into(), table: None, format: None, expr: None },
],
};
model.parse_formulas().expect("model parses");
model
}
fn header(table: &TableValue) -> Vec<String> {
table.columns.iter().map(|column| column.name.clone()).collect()
}
fn row(table: &TableValue, index: usize) -> Vec<Scalar> {
table.rows.get(index).cloned().unwrap_or_default()
}
fn text(value: &str) -> Scalar {
Scalar::String(value.into())
}
fn sales_pivot() -> PivotTable {
PivotTable::new("Sales by region", "Total Sales")
}
#[test]
fn simple_rows_render_one_row_per_distinct_value() {
let table = sales_pivot().with_row_fields(vec!["Sales[Region]".into()]).with_layout(PivotLayout::Tabular).render(&model()).expect("render");
assert_eq!(header(&table), vec!["Region".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows.len(), 3);
// BLANK sorts first, then East (10 + 30 + 5), then West.
assert_eq!(row(&table, 0), vec![Scalar::Blank, Scalar::Decimal(7.0)]);
assert_eq!(row(&table, 1), vec![text("East"), Scalar::Decimal(45.0)]);
assert_eq!(row(&table, 2), vec![text("West"), Scalar::Decimal(20.0)]);
assert_eq!(table.lineage, Some(0));
}
#[test]
fn compact_layout_collapses_row_fields_and_labels_blanks() {
let table = sales_pivot().with_row_fields(vec!["Sales[Region]".into()]).render(&model()).expect("render");
assert_eq!(header(&table), vec!["Row Labels".to_string(), "Total Sales".to_string()]);
assert_eq!(row(&table, 0), vec![text("(Blank)"), Scalar::Decimal(7.0)]);
assert_eq!(row(&table, 1), vec![text("East"), Scalar::Decimal(45.0)]);
}
#[test]
fn row_and_column_cross_tab_puts_column_groups_in_columns() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_column_fields(vec!["Sales[Category]".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Region".to_string(), "Gadget".to_string(), "Widget".to_string()]);
assert_eq!(table.rows.len(), 3);
// BLANK has no Widget rows, so that cell stays blank rather than zero.
assert_eq!(row(&table, 0), vec![Scalar::Blank, Scalar::Decimal(7.0), Scalar::Blank]);
assert_eq!(row(&table, 1), vec![text("East"), Scalar::Decimal(30.0), Scalar::Decimal(15.0)]);
assert_eq!(row(&table, 2), vec![text("West"), Scalar::Blank, Scalar::Decimal(20.0)]);
}
#[test]
fn same_field_in_rows_and_columns_blanks_off_diagonal_cells() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_column_fields(vec!["Sales[Region]".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Region".to_string(), "(Blank)".to_string(), "East".to_string(), "West".to_string()]);
assert_eq!(table.rows.len(), 3);
// The row and column filter on Region intersect: only diagonal cells have rows at all.
assert_eq!(row(&table, 0), vec![Scalar::Blank, Scalar::Decimal(7.0), Scalar::Blank, Scalar::Blank]);
assert_eq!(row(&table, 1), vec![text("East"), Scalar::Blank, Scalar::Decimal(45.0), Scalar::Blank]);
assert_eq!(row(&table, 2), vec![text("West"), Scalar::Blank, Scalar::Blank, Scalar::Decimal(20.0)]);
}
#[test]
fn several_values_produce_one_column_per_measure() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_values(vec!["Total Sales".into(), "Total Quantity".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Region".to_string(), "Total Sales".to_string(), "Total Quantity".to_string()]);
assert_eq!(row(&table, 1), vec![text("East"), Scalar::Decimal(45.0), Scalar::Decimal(7.0)]);
}
#[test]
fn filters_keep_only_allowed_values() {
let filtered = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_filter(PivotFilter::new("Sales[Region]", [text("East")]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(filtered.rows.len(), 1);
assert_eq!(row(&filtered, 0), vec![text("East"), Scalar::Decimal(45.0)]);
// Two allowed values, and BLANK can be allowed explicitly.
let both = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_filter(PivotFilter::new("Sales[Region]", [text("East"), Scalar::Blank]))
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(both.rows.len(), 2);
assert_eq!(row(&both, 1), vec![text("East"), Scalar::Decimal(45.0)]);
// Filters also apply to column groups and to the totals.
let cross = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_column_fields(vec!["Sales[Category]".into()])
.with_filter(PivotFilter::new("Sales[Category]", [text("Widget")]))
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&cross), vec!["Region".to_string(), "Widget".to_string(), "Grand Total".to_string()]);
assert_eq!(cross.rows.len(), 3);
assert_eq!(row(&cross, 0), vec![text("East"), Scalar::Decimal(15.0), Scalar::Decimal(15.0)]);
assert_eq!(row(&cross, 1), vec![text("West"), Scalar::Decimal(20.0), Scalar::Decimal(20.0)]);
assert_eq!(row(&cross, 2), vec![text("Grand Total"), Scalar::Decimal(35.0), Scalar::Decimal(35.0)]);
// A filter that allows nothing yields no rows but keeps the header.
let empty = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into()])
.with_filter(PivotFilter::new("Sales[Region]", []))
.render(&model())
.expect("render");
assert!(empty.rows.is_empty());
assert_eq!(header(&empty), vec!["Row Labels".to_string(), "Total Sales".to_string()]);
}
#[test]
fn blank_column_groups_are_labeled() {
let table = sales_pivot().with_column_fields(vec!["Sales[Region]".into()]).with_layout(PivotLayout::Tabular).render(&model()).expect("render");
assert_eq!(header(&table), vec!["(Blank)".to_string(), "East".to_string(), "West".to_string()]);
assert_eq!(table.rows.len(), 1);
assert_eq!(row(&table, 0), vec![Scalar::Decimal(7.0), Scalar::Decimal(45.0), Scalar::Decimal(20.0)]);
}
#[test]
fn blank_groups_are_their_own_group() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into(), "Sales[Category]".into()])
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(row(&table, 0), vec![Scalar::Blank, text("Gadget"), Scalar::Decimal(7.0)]);
}
#[test]
fn row_subtotals_and_grand_total() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into(), "Sales[Category]".into()])
.with_row_subtotals(true)
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Region".to_string(), "Category".to_string(), "Total Sales".to_string()]);
let rows = table.rows.clone();
assert_eq!(rows.len(), 8);
assert_eq!(rows[0], vec![Scalar::Blank, text("Gadget"), Scalar::Decimal(7.0)]);
// Subtotal for the single BLANK region.
assert_eq!(rows[1], vec![Scalar::Blank, Scalar::Blank, Scalar::Decimal(7.0)]);
assert_eq!(rows[2], vec![text("East"), text("Gadget"), Scalar::Decimal(30.0)]);
assert_eq!(rows[3], vec![text("East"), text("Widget"), Scalar::Decimal(15.0)]);
// Subtotal for East (30 + 15).
assert_eq!(rows[4], vec![text("East"), Scalar::Blank, Scalar::Decimal(45.0)]);
assert_eq!(rows[5], vec![text("West"), text("Widget"), Scalar::Decimal(20.0)]);
assert_eq!(rows[6], vec![text("West"), Scalar::Blank, Scalar::Decimal(20.0)]);
// Grand total row: 7 + 30 + 15 + 20.
assert_eq!(rows[7], vec![text("Grand Total"), Scalar::Blank, Scalar::Decimal(72.0)]);
}
#[test]
fn column_subtotals_and_grand_total_columns() {
let table = sales_pivot()
.with_column_fields(vec!["Sales[Category]".into(), "Sales[Region]".into()])
.with_column_subtotals(true)
.with_grand_totals(true)
.with_layout(PivotLayout::Tabular)
.render(&model())
.expect("render");
assert_eq!(
header(&table),
vec![
"Gadget | (Blank)".to_string(),
"Gadget | East".to_string(),
"Gadget Total".to_string(),
"Widget | East".to_string(),
"Widget | West".to_string(),
"Widget Total".to_string(),
"Grand Total".to_string(),
]
);
assert_eq!(table.rows.len(), 1);
let row = row(&table, 0);
assert_eq!(row[0], Scalar::Decimal(7.0));
assert_eq!(row[1], Scalar::Decimal(30.0));
assert_eq!(row[2], Scalar::Decimal(37.0));
assert_eq!(row[3], Scalar::Decimal(15.0));
assert_eq!(row[4], Scalar::Decimal(20.0));
assert_eq!(row[5], Scalar::Decimal(35.0));
assert_eq!(row[6], Scalar::Decimal(72.0));
}
#[test]
fn outline_layout_blanks_repeated_ancestors_and_names_subtotals() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into(), "Sales[Category]".into()])
.with_row_subtotals(true)
.with_layout(PivotLayout::Outline)
.render(&model())
.expect("render");
let rows = table.rows.clone();
assert_eq!(rows[0], vec![Scalar::Blank, text("Gadget"), Scalar::Decimal(7.0)]);
// The subtotal of the BLANK region is named in its own column.
assert_eq!(rows[1], vec![text("(Blank) Total"), Scalar::Blank, Scalar::Decimal(7.0)]);
assert_eq!(rows[2], vec![text("East"), text("Gadget"), Scalar::Decimal(30.0)]);
// "East" does not repeat on the second East leaf row.
assert_eq!(rows[3], vec![Scalar::Blank, text("Widget"), Scalar::Decimal(15.0)]);
assert_eq!(rows[4], vec![text("East Total"), Scalar::Blank, Scalar::Decimal(45.0)]);
}
#[test]
fn compact_layout_indents_nested_rows() {
let table = sales_pivot()
.with_row_fields(vec!["Sales[Region]".into(), "Sales[Category]".into()])
.with_row_subtotals(true)
.render(&model())
.expect("render");
assert_eq!(header(&table), vec!["Row Labels".to_string(), "Total Sales".to_string()]);
assert_eq!(row(&table, 0), vec![text(" Gadget"), Scalar::Decimal(7.0)]);
assert_eq!(row(&table, 1), vec![text("Region (Blank) Total"), Scalar::Decimal(7.0)]);
assert_eq!(row(&table, 2), vec![text(" Gadget"), Scalar::Decimal(30.0)]);
assert_eq!(row(&table, 3), vec![text(" Widget"), Scalar::Decimal(15.0)]);
assert_eq!(row(&table, 4), vec![text("Region East Total"), Scalar::Decimal(45.0)]);
}
#[test]
fn grand_total_row_is_skipped_without_row_fields() {
let table = sales_pivot().with_grand_totals(true).render(&model()).expect("render");
assert_eq!(header(&table), vec!["Row Labels".to_string(), "Total Sales".to_string()]);
assert_eq!(table.rows.len(), 1);
assert_eq!(row(&table, 0), vec![text("Grand Total"), Scalar::Decimal(72.0)]);
}
#[test]
fn empty_model_reports_unknown_measure() {
let error = sales_pivot().render(&DataModel::default()).expect_err("empty model");
assert!(matches!(&error, PivotTableError::UnknownMeasure { measure, .. } if measure == "Total Sales"), "{error:?}");
let no_source = PivotTable::default().render(&model()).expect_err("no source");
assert!(matches!(no_source, PivotTableError::MissingSource { .. }), "{no_source:?}");
let homeless = PivotTable::new("homeless", "Homeless").render(&model()).expect_err("no home table");
assert!(matches!(homeless, PivotTableError::NoSourceTable { .. }), "{homeless:?}");
}
#[test]
fn invalid_fields_are_reported_not_panicked() {
let unknown_table = PivotTable::new("p", "Total Sales").with_source_table("Missing").render(&model()).expect_err("unknown table");
assert!(matches!(unknown_table, PivotTableError::UnknownTable(_)), "{unknown_table:?}");
let unknown_column = sales_pivot().with_row_fields(vec!["Sales[Nope]".into()]).render(&model()).expect_err("unknown column");
assert!(matches!(unknown_column, PivotTableError::Pivot(_)), "{unknown_column:?}");
let foreign = sales_pivot().with_row_fields(vec!["Sales[Region]".into(), "Other[Region]".into()]).render(&model()).expect_err("foreign");
// `Other[Region]` does not bind at all without that table.
assert!(matches!(foreign, PivotTableError::Pivot(_)), "{foreign:?}");
let two_tables = DataModel {
tables: vec![
model().tables[0].clone(),
ModelTable { name: "Other".into(), columns: vec![ModelColumn { name: "Region".into(), data_type: None }], rows: Vec::new() },
],
..model()
};
let foreign = sales_pivot().with_row_fields(vec!["Sales[Region]".into(), "Other[Region]".into()]).render(&two_tables).expect_err("foreign");
assert!(matches!(foreign, PivotTableError::ForeignField { .. }), "{foreign:?}");
let bad_filter = sales_pivot().with_filter(PivotFilter::new("Sales[Nope]", [text("East")])).render(&model()).expect_err("bad filter");
assert!(matches!(bad_filter, PivotTableError::Pivot(_)), "{bad_filter:?}");
}
#[test]
fn rendering_is_bounded_by_max_cells() {
let pivot = sales_pivot().with_row_fields(vec!["Sales[Region]".into()]).with_max_cells(2);
let error = pivot.render(&model()).expect_err("over budget");
assert!(matches!(&error, PivotTableError::TooManyCells { limit: 2, .. }), "{error:?}");
let default_pivot = sales_pivot().with_row_fields(vec!["Sales[Region]".into()]);
assert_eq!(default_pivot.max_cells, DEFAULT_MAX_CELLS);
assert!(default_pivot.render(&model()).is_ok());
}
#[test]
fn pivot_cross_is_bounded_by_max_cells() {
// 1025 distinct values on each axis ask for 1,050,625 cells, over the default budget.
let rows = (0..1025).map(|index| vec![Scalar::Integer(index), Scalar::Integer(index), Scalar::Integer(1)]).collect::<Vec<_>>();
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "RowKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "ColumnKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows,
}],
relationships: Vec::new(),
measures: vec![Measure {
name: "Total Sales".into(),
formula: "SUM(Sales[Amount])".into(),
table: Some("Sales".into()),
format: None,
expr: None,
}],
};
model.parse_formulas().expect("model parses");
let row_fields = pivot_fields(&model, &["Sales[RowKey]".to_string()]).expect("row fields");
let column_fields = pivot_fields(&model, &["Sales[ColumnKey]".to_string()]).expect("column fields");
let error = pivot_cross(&model, "Total Sales", &row_fields, &column_fields).expect_err("over the limit");
let PivotError::Eval(error) = &error else {
panic!("expected an evaluation error, got {error:?}");
};
assert!(error.message.contains("1025 rows x 1025 columns"), "{error}");
assert!(error.message.contains(&DEFAULT_MAX_CELLS.to_string()), "{error}");
// Under the budget, the same axes evaluate normally.
let row_fields = pivot_fields(&model, &["Sales[RowKey]".to_string()]).expect("row fields");
let narrow = pivot_cross(&model, "Total Sales", &row_fields, &[]).expect("single-axis pivot stays within budget");
assert_eq!(narrow.rows.len(), 1025);
}
#[test]
fn a_dense_relationship_graph_reports_ambiguity_instead_of_searching_forever() {
// Fourteen tables with a forward lookup relationship between every pair, plus a table no
// relationship reaches. Enumerating every simple path to `Nowhere` would take hundreds of
// thousands of steps, so the path search spends its budget and the field is rejected as
// ambiguous instead of being bound to a partial (or empty) chain.
const TABLES: usize = 14;
let mut tables = (0..TABLES)
.map(|index| ModelTable {
name: format!("T{index}"),
columns: vec![ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) }],
rows: Vec::new(),
})
.collect::<Vec<_>>();
tables.push(ModelTable {
name: "Nowhere".into(),
columns: vec![ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) }],
rows: Vec::new(),
});
let relationships = (0..TABLES)
.flat_map(|from| {
((from + 1)..TABLES).map(move |to| Relationship {
from_table: format!("T{from}"),
from_column: "Key".into(),
to_table: format!("T{to}"),
to_column: "Key".into(),
bidirectional: false,
inactive: false,
})
})
.collect::<Vec<_>>();
let mut model = DataModel {
tables,
relationships,
measures: vec![Measure { name: "Rows".into(), formula: "COUNTROWS(T0)".into(), table: Some("T0".into()), format: None, expr: None }],
};
model.parse_formulas().expect("model parses");
let error = PivotTable::new("p", "Rows").with_row_fields(vec!["Nowhere[Key]".into()]).render(&model).expect_err("exhausted path search");
assert!(
matches!(&error, PivotTableError::AmbiguousFieldPath { field, table, source_table, .. } if field == "Key" && table == "Nowhere" && source_table == "T0"),
"{error:?}"
);
}
@@ -0,0 +1,164 @@
//! Circular-relationship detection tests.
//!
//! A cycle is reported by table name with the offending chain closed (`A -> B -> C -> A`), once per
//! distinct cycle, capped at [`MAX_REPORTED_CYCLES`], and the search is iterative so a long acyclic
//! chain cannot overflow the stack. These tests cover the plain cycle, the self relationship, the
//! edge a bidirectional relationship adds, the acyclic control, the cap and determinism.
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::storage::ModelStorage;
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{IntegrityCheck, IntegrityFinding, MAX_REPORTED_CYCLES, Severity, validate_model};
fn link_table(name: &str, key: i64) -> ModelTable {
ModelTable {
name: name.into(),
columns: vec![
ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Ref".into(), data_type: Some("Int64".into()) },
],
rows: vec![vec![Scalar::Integer(key), Scalar::Integer(key)]],
}
}
fn link(from_table: &str, to_table: &str) -> Relationship {
Relationship {
from_table: from_table.into(),
from_column: "Ref".into(),
to_table: to_table.into(),
to_column: "Key".into(),
bidirectional: false,
inactive: false,
}
}
fn model(tables: Vec<ModelTable>, relationships: Vec<Relationship>) -> DataModel {
DataModel { tables, relationships, measures: Vec::new() }
}
fn cycles(report: &gridcraft_dax::IntegrityReport) -> Vec<&IntegrityFinding> {
report.findings_for(IntegrityCheck::CircularRelationship).collect()
}
#[test]
fn a_three_table_cycle_is_reported_by_name() {
let report = validate_model(&model(
vec![link_table("A", 1), link_table("B", 1), link_table("C", 1)],
vec![link("A", "B"), link("B", "C"), link("C", "A")],
));
let found = cycles(&report);
assert_eq!(found.len(), 1, "findings: {:?}", report.findings);
let cycle = found.first().expect("one cycle");
assert_eq!(cycle.severity, Severity::Error);
assert_eq!(cycle.check, IntegrityCheck::CircularRelationship);
assert_eq!(cycle.table, "A");
assert_eq!(cycle.cycle, vec!["A".to_string(), "B".into(), "C".into(), "A".into()]);
assert_eq!(cycle.message, "circular relationship chain: A -> B -> C -> A");
assert_eq!(cycle.relationship, None);
assert!(cycle.rows.is_empty());
assert_eq!(cycle.total, 0);
let repeat = validate_model(&model(
vec![link_table("A", 1), link_table("B", 1), link_table("C", 1)],
vec![link("A", "B"), link("B", "C"), link("C", "A")],
));
assert_eq!(report.findings, repeat.findings, "the cycle report is deterministic");
}
#[test]
fn a_self_relationship_is_a_cycle() {
let report = validate_model(&model(vec![link_table("Node", 1)], vec![link("Node", "Node")]));
let found = cycles(&report);
assert_eq!(found.len(), 1, "findings: {:?}", report.findings);
let cycle = found.first().expect("one cycle");
assert_eq!(cycle.table, "Node");
assert_eq!(cycle.cycle, vec!["Node".to_string(), "Node".into()]);
assert_eq!(cycle.message, "circular relationship chain: Node -> Node");
// The materialized storage reports the same chain.
let storage = ModelStorage::from_model(&model(vec![link_table("Node", 1)], vec![link("Node", "Node")])).expect("storage");
assert_eq!(cycles(&storage.validate()), found);
}
#[test]
fn a_bidirectional_relationship_adds_the_reverse_edge() {
let tables = || vec![link_table("A", 1), link_table("B", 1), link_table("C", 1)];
// Without the flag, A -> B, A -> C and C -> B form no cycle.
let plain = validate_model(&model(tables(), vec![link("A", "B"), link("A", "C"), link("C", "B")]));
assert!(cycles(&plain).is_empty(), "findings: {:?}", plain.findings);
// The bidirectional link also offers the reverse edge A -> B, which closes A -> B -> C -> A.
let mut forward = link("A", "B");
forward.bidirectional = true;
let report = validate_model(&model(tables(), vec![forward, link("A", "C"), link("C", "B")]));
let found = cycles(&report);
assert_eq!(found.len(), 1, "findings: {:?}", report.findings);
let cycle = found.first().expect("one cycle");
assert_eq!(cycle.cycle, vec!["A".to_string(), "B".into(), "C".into(), "A".into()]);
assert_eq!(cycle.message, "circular relationship chain: A -> B -> C -> A");
}
#[test]
fn an_acyclic_star_has_no_cycle_finding() {
let report = validate_model(&model(
vec![link_table("Fact", 1), link_table("Dim1", 1), link_table("Dim2", 1)],
vec![link("Fact", "Dim1"), link("Fact", "Dim2")],
));
assert!(cycles(&report).is_empty(), "findings: {:?}", report.findings);
}
#[test]
fn a_long_acyclic_chain_is_walked_iteratively() {
// 500 tables in a straight line: guards against recursion on the path depth.
let tables: Vec<ModelTable> = (0..500).map(|index| link_table(&format!("T{index}"), 1)).collect();
let relationships: Vec<Relationship> = (0..499).map(|index| link(&format!("T{index}"), &format!("T{}", index + 1))).collect();
let report = validate_model(&model(tables, relationships));
assert!(cycles(&report).is_empty(), "findings: {:?}", report.findings);
}
#[test]
fn cycles_are_capped() {
// Nine independent two-table cycles; only the first eight are reported.
let mut tables = Vec::new();
let mut relationships = Vec::new();
for pair in 0..9 {
let left = format!("T{}", pair * 2);
let right = format!("T{}", pair * 2 + 1);
tables.push(link_table(&left, 1));
tables.push(link_table(&right, 1));
relationships.push(link(&left, &right));
relationships.push(link(&right, &left));
}
let report = validate_model(&model(tables, relationships));
let found = cycles(&report);
assert_eq!(found.len(), MAX_REPORTED_CYCLES);
let starts: Vec<&str> = found.iter().map(|finding| finding.table.as_str()).collect();
assert_eq!(starts, vec!["T0", "T2", "T4", "T6", "T8", "T10", "T12", "T14"]);
for finding in &found {
assert_eq!(finding.cycle.len(), 3, "chain names include the closing table");
assert_eq!(finding.cycle.first(), finding.cycle.last());
}
}
#[test]
fn an_inactive_relationship_cannot_close_a_chain() {
// One active and one inactive relationship between the same pair of tables: the inactive one
// is not part of the default filter propagation, so there is no cycle.
let mut inactive = link("B", "A");
inactive.inactive = true;
let report = validate_model(&model(vec![link_table("A", 1), link_table("B", 1)], vec![link("A", "B"), inactive]));
assert!(cycles(&report).is_empty(), "findings: {:?}", report.findings);
// Two active relationships between the same pair still are a cycle.
let report = validate_model(&model(vec![link_table("A", 1), link_table("B", 1)], vec![link("A", "B"), link("B", "A")]));
assert_eq!(cycles(&report).len(), 1, "findings: {:?}", report.findings);
}
#[test]
fn a_two_fact_model_with_shared_dimensions_has_no_cycle() {
// Sales and Returns both point at Product and Date, the usual star: filters flow from the
// dimensions to the facts, so there is no chain through the two facts.
let report = validate_model(&model(
vec![link_table("Sales", 1), link_table("Returns", 1), link_table("Product", 1), link_table("Date", 1)],
vec![link("Sales", "Product"), link("Returns", "Product"), link("Sales", "Date"), link("Returns", "Date")],
));
assert!(cycles(&report).is_empty(), "findings: {:?}", report.findings);
assert!(!report.has_errors(), "findings: {:?}", report.findings);
}
@@ -0,0 +1,447 @@
//! Referential-integrity report tests over deliberately hostile models.
//!
//! Every model here is built in code — duplicate one-side keys, orphan fact keys, blank keys,
//! unknown endpoints, duplicate table names, a target model larger than the report cap — and the
//! tests assert the report contents field by field, including the deterministic order and the
//! truncation counts. Both entry points are covered, and they are required to agree on a model the
//! store can materialize faithfully.
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::storage::ModelStorage;
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Cardinality, IntegrityCheck, IntegrityFinding, MAX_REPORTED_KEYS, MAX_REPORTED_ROWS, Severity, validate_model};
fn key_column(name: &str) -> ModelColumn {
ModelColumn { name: name.into(), data_type: Some("Int64".into()) }
}
fn text_column(name: &str) -> ModelColumn {
ModelColumn { name: name.into(), data_type: Some("String".into()) }
}
fn table(name: &str, columns: Vec<ModelColumn>, rows: Vec<Vec<Scalar>>) -> ModelTable {
ModelTable { name: name.into(), columns, rows }
}
fn relation(from_table: &str, from_column: &str, to_table: &str, to_column: &str, bidirectional: bool) -> Relationship {
Relationship {
from_table: from_table.into(),
from_column: from_column.into(),
to_table: to_table.into(),
to_column: to_column.into(),
bidirectional,
inactive: false,
}
}
/// `Product` has the one side's classic defects: key `1` twice and a blank key.
/// `Sales` has the many side's: an orphan key `7`, a blank key, and key `1` twice.
fn hostile_model() -> DataModel {
DataModel {
tables: vec![
table(
"Product",
vec![key_column("ProductKey"), text_column("Name")],
vec![
vec![Scalar::Integer(1), Scalar::String("One".into())],
vec![Scalar::Integer(2), Scalar::String("Two".into())],
vec![Scalar::Integer(3), Scalar::String("Three".into())],
vec![Scalar::Integer(1), Scalar::String("One again".into())],
vec![Scalar::Blank, Scalar::String("No key".into())],
],
),
table(
"Sales",
vec![key_column("ProductKey"), key_column("Amount")],
vec![
vec![Scalar::Integer(1), Scalar::Integer(10)],
vec![Scalar::Integer(2), Scalar::Integer(20)],
vec![Scalar::Integer(7), Scalar::Integer(30)],
vec![Scalar::Blank, Scalar::Integer(40)],
vec![Scalar::Integer(1), Scalar::Integer(50)],
],
),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
}
}
#[allow(clippy::too_many_arguments)] // One named argument per column of the expected finding row.
fn finding(
check: IntegrityCheck,
severity: Severity,
table: &str,
column: &str,
related_table: Option<&str>,
related_column: Option<&str>,
key: Option<Scalar>,
rows: Vec<usize>,
total: usize,
message: &str,
) -> IntegrityFinding {
IntegrityFinding {
check,
severity,
relationship: Some(0),
table: table.into(),
column: column.into(),
related_table: related_table.map(Into::into),
related_column: related_column.map(Into::into),
key,
rows,
total,
cycle: Vec::new(),
message: message.into(),
}
}
#[test]
fn hostile_model_reports_orphans_duplicates_blanks_and_invalid_cardinality() {
let model = hostile_model();
let report = validate_model(&model);
assert_eq!(report.tables, 2);
assert_eq!(report.rows, 10);
assert!(report.has_errors());
assert_eq!(report.errors().count(), 3, "orphan, duplicate key and many-to-many are errors");
assert_eq!(report.warnings().count(), 2, "both blank-key findings are warnings");
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.index, 0);
assert_eq!(check.from_table, "Sales");
assert_eq!(check.from_column, "ProductKey");
assert_eq!(check.to_table, "Product");
assert_eq!(check.to_column, "ProductKey");
assert_eq!(check.declared, Cardinality::OneToMany);
assert_eq!(check.actual, Cardinality::ManyToMany);
assert!(!check.is_valid());
assert_eq!(check.from_rows, 5);
assert_eq!(check.from_keys, 3);
assert_eq!(check.to_rows, 5);
assert_eq!(check.to_keys, 3);
assert_eq!(check.orphan_keys, 1);
assert_eq!(check.orphan_rows, 1);
assert_eq!(check.duplicate_to_keys, 1);
assert_eq!(check.blank_from_keys, 1);
assert_eq!(check.blank_to_keys, 1);
assert!(!check.bidirectional);
assert!(!check.inactive);
let expected = vec![
finding(
IntegrityCheck::OrphanRow,
Severity::Error,
"Sales",
"ProductKey",
Some("Product"),
Some("ProductKey"),
Some(Scalar::Integer(7)),
vec![2],
1,
"1 row(s) in `Sales[ProductKey]` have key 7 with no match in `Product[ProductKey]`",
),
finding(
IntegrityCheck::DuplicateKey,
Severity::Error,
"Product",
"ProductKey",
Some("Sales"),
Some("ProductKey"),
Some(Scalar::Integer(1)),
vec![0, 3],
2,
"key 1 appears in 2 row(s) of `Product[ProductKey]`, so the one side of the relationship is not unique",
),
finding(
IntegrityCheck::BlankKey,
Severity::Warning,
"Sales",
"ProductKey",
Some("Product"),
Some("ProductKey"),
Some(Scalar::Blank),
vec![3],
1,
"1 row(s) in `Sales[ProductKey]` have a blank relationship key",
),
finding(
IntegrityCheck::BlankKey,
Severity::Warning,
"Product",
"ProductKey",
Some("Sales"),
Some("ProductKey"),
Some(Scalar::Blank),
vec![4],
1,
"1 row(s) in `Product[ProductKey]` have a blank relationship key",
),
finding(
IntegrityCheck::InvalidCardinality,
Severity::Error,
"Sales",
"ProductKey",
Some("Product"),
Some("ProductKey"),
None,
Vec::new(),
0,
"relationship `Sales[ProductKey]` -> `Product[ProductKey]` declares one-to-many but both sides have duplicate keys (many-to-many); the one side must be unique",
),
];
assert_eq!(report.findings, expected);
assert_eq!(report.first_error(), Some("1 row(s) in `Sales[ProductKey]` have key 7 with no match in `Product[ProductKey]`"));
}
#[test]
fn the_storage_entry_point_agrees_with_the_model_entry_point() {
let model = hostile_model();
let storage = ModelStorage::from_model(&model).expect("hostile keys still materialize");
assert!(storage.is_faithful());
assert_eq!(storage.validate(), validate_model(&model));
}
#[test]
fn a_clean_star_schema_reports_nothing() {
let model = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)], vec![Scalar::Integer(3)]]),
table(
"Sales",
vec![key_column("ProductKey")],
vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)], vec![Scalar::Integer(2)], vec![Scalar::Integer(3)]],
),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&model);
assert!(report.is_clean(), "findings: {:?}", report.findings);
assert!(!report.has_errors());
assert!(report.first_error().is_none());
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.actual, Cardinality::OneToMany);
assert!(check.is_valid());
assert_eq!(check.orphan_keys, 0);
assert_eq!(check.blank_from_keys, 0);
assert!(storage_agrees(&model, &report));
}
fn storage_agrees(model: &DataModel, report: &gridcraft_dax::IntegrityReport) -> bool {
ModelStorage::from_model(model).is_ok_and(|storage| storage.validate() == *report)
}
#[test]
fn one_to_one_and_reversed_relationships_are_warnings_not_errors() {
let one_to_one = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)]]),
table("Sales", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)]]),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&one_to_one);
assert_eq!(report.findings.len(), 1);
let only = report.findings.first().expect("one finding");
assert_eq!(only.check, IntegrityCheck::InvalidCardinality);
assert_eq!(only.severity, Severity::Warning);
assert_eq!(report.relationships.first().map(|check| check.actual), Some(Cardinality::OneToOne));
assert!(!report.has_errors());
// The from side is unique and the to side repeats: the relationship points the wrong way.
let reversed = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)], vec![Scalar::Integer(2)]]),
table("Sales", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2)]]),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&reversed);
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.actual, Cardinality::ManyToOne);
assert_eq!(check.duplicate_to_keys, 1);
assert_eq!(report.findings_for(IntegrityCheck::DuplicateKey).count(), 1, "the repeated one-side key is still an error");
let cardinality: Vec<&IntegrityFinding> = report.findings_for(IntegrityCheck::InvalidCardinality).collect();
assert_eq!(cardinality.first().map(|finding| finding.severity), Some(Severity::Warning));
assert!(
cardinality.first().is_some_and(|finding| finding.message.contains("stored in the wrong direction")),
"{:?}",
cardinality.first().map(|finding| finding.message.as_str())
);
}
#[test]
fn unknown_endpoints_are_reported_instead_of_failing() {
let model = DataModel {
tables: vec![table("Sales", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)]])],
relationships: vec![relation("Sales", "ProductKey", "Missing", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&model);
assert!(report.relationships.is_empty(), "an unresolved relationship has no measured cardinality");
assert_eq!(report.findings.len(), 1);
let only = report.findings.first().expect("one finding");
assert_eq!(only.check, IntegrityCheck::UnknownEndpoint);
assert_eq!(only.severity, Severity::Error);
assert_eq!(only.table, "Missing");
assert_eq!(only.column, "ProductKey");
assert_eq!(only.related_table.as_deref(), Some("Sales"));
assert_eq!(only.related_column.as_deref(), Some("ProductKey"));
assert_eq!(only.relationship, Some(0));
assert_eq!(only.total, 0);
assert!(only.message.contains("which does not exist"), "{}", only.message);
// A relationship naming a column that does not exist is the same kind of finding.
let mut missing_column = model;
missing_column.relationships[0].to_table = "Sales".into();
missing_column.relationships[0].to_column = "Nope".into();
let report = validate_model(&missing_column);
assert_eq!(report.findings_for(IntegrityCheck::UnknownEndpoint).count(), 1);
let only = report.findings.first().expect("one finding");
assert_eq!(only.column, "Nope");
}
#[test]
fn duplicate_table_names_are_reported_first() {
let sales = table("Sales", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)]]);
let model = DataModel {
tables: vec![sales.clone(), sales],
relationships: vec![relation("Sales", "ProductKey", "Sales", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&model);
assert_eq!(report.tables, 2);
let first = report.findings.first().expect("one finding");
assert_eq!(first.check, IntegrityCheck::DuplicateTable);
assert_eq!(first.severity, Severity::Error);
assert_eq!(first.table, "Sales");
assert_eq!(first.column, "");
assert_eq!(first.relationship, None);
assert_eq!(
first.message,
"table `Sales` is defined more than once (first at position 0, duplicate at position 1); name-based lookups resolve to the first"
);
// The self relationship the duplicate resolution produces still gets measured.
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.from_table, "Sales");
assert_eq!(check.from_rows, 1);
}
#[test]
fn big_orphan_sets_are_capped_but_counted_in_full() {
// 31 orphan keys: key 10 appears 25 times, keys 11..=40 once each. The one side holds key 1.
let mut sales_rows = Vec::new();
for _ in 0..25 {
sales_rows.push(vec![Scalar::Integer(10)]);
}
for key in 11..=40 {
sales_rows.push(vec![Scalar::Integer(key)]);
}
let model = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)]]),
table("Sales", vec![key_column("ProductKey")], sales_rows),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&model);
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.orphan_keys, 31);
assert_eq!(check.orphan_rows, 55);
let orphans: Vec<&IntegrityFinding> = report.findings_for(IntegrityCheck::OrphanRow).collect();
assert_eq!(orphans.len(), MAX_REPORTED_KEYS, "key findings are capped");
let first = orphans.first().expect("first orphan");
assert_eq!(first.key, Some(Scalar::Integer(10)));
assert_eq!(first.total, 25, "the uncapped row count survives the cap");
assert_eq!(first.rows.len(), MAX_REPORTED_ROWS, "row ids are capped");
assert_eq!(first.rows.first().copied(), Some(0));
assert_eq!(first.rows.last().copied(), Some(MAX_REPORTED_ROWS - 1));
// The last captured key is still in ascending order and inside the cap.
let last = orphans.last().expect("last orphan");
assert_eq!(last.key, Some(Scalar::Integer(25)));
assert_eq!(last.total, 1);
// The many-to-one orientation of the capped report is unchanged.
assert_eq!(check.actual, Cardinality::OneToMany);
assert!(ModelStorage::from_model(&model).is_ok_and(|storage| storage.validate() == report));
}
#[test]
fn ragged_rows_treat_missing_cells_as_blank_keys_on_both_entry_points() {
let model = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)]]),
// Row 0 has no cells at all, so its key cell is missing (BLANK after blank extension).
table(
"Sales",
vec![key_column("ProductKey"), key_column("Amount")],
vec![vec![], vec![Scalar::Integer(1)], vec![Scalar::Integer(1), Scalar::Integer(5)]],
),
],
relationships: vec![relation("Sales", "ProductKey", "Product", "ProductKey", false)],
measures: Vec::new(),
};
let report = validate_model(&model);
let check = report.relationships.first().expect("one relationship");
assert_eq!(check.from_rows, 3);
assert_eq!(check.from_keys, 1);
assert_eq!(check.blank_from_keys, 1);
assert_eq!(check.orphan_keys, 0);
let blank: Vec<&IntegrityFinding> = report.findings_for(IntegrityCheck::BlankKey).collect();
assert_eq!(blank.len(), 1);
assert_eq!(blank.first().map(|finding| finding.rows.clone()), Some(vec![0]));
let storage = ModelStorage::from_model(&model).expect("ragged rows are blank-extended");
assert_eq!(storage.validate(), report);
}
#[test]
fn bidirectional_and_inactive_flags_are_reported_verbatim() {
let model = DataModel {
tables: vec![
table("Product", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)]]),
table("Sales", vec![key_column("ProductKey")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(1)]]),
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "ProductKey".into(),
to_table: "Product".into(),
to_column: "ProductKey".into(),
bidirectional: true,
inactive: true,
}],
measures: Vec::new(),
};
let report = validate_model(&model);
let check = report.relationships.first().expect("one relationship");
assert!(check.bidirectional);
assert!(check.inactive);
assert_eq!(check.declared, Cardinality::OneToMany);
assert_eq!(check.actual, Cardinality::OneToMany);
assert!(report.is_clean(), "{:?}", report.findings);
}
#[test]
fn report_accessors_group_the_findings() {
let report = validate_model(&hostile_model());
assert_eq!(report.findings_for(IntegrityCheck::OrphanRow).count(), 1);
assert_eq!(report.findings_for(IntegrityCheck::DuplicateKey).count(), 1);
assert_eq!(report.findings_for(IntegrityCheck::BlankKey).count(), 2);
assert_eq!(report.findings_for(IntegrityCheck::InvalidCardinality).count(), 1);
assert_eq!(report.findings_for(IntegrityCheck::CircularRelationship).count(), 0);
assert_eq!(report.findings_for(IntegrityCheck::UnknownEndpoint).count(), 0);
assert_eq!(report.findings_for(IntegrityCheck::DuplicateTable).count(), 0);
assert_eq!(IntegrityCheck::OrphanRow.name(), "orphanRow");
assert_eq!(Severity::Warning.name(), "warning");
assert_eq!(Cardinality::ManyToMany.name(), "manyToMany");
assert!(Severity::Warning < Severity::Error);
// The report serializes for the engine command's JSON payload.
let json = serde_json::to_value(&report).expect("report serializes");
assert_eq!(json["tables"], 2);
assert_eq!(json["relationships"][0]["actual"], "manyToMany");
assert_eq!(json["findings"][0]["check"], "orphanRow");
assert_eq!(json["findings"][0]["severity"], "error");
}
+112
View File
@@ -0,0 +1,112 @@
# DAX functions implemented in GridCraft
This list is generated from the `gridcraft-dax` catalog and evaluator. **Parsed** means the
function is in the catalog with arity/parameter validation and round-trips through the parser
and printer. **Evaluated** means the evaluator has a dispatch path for it.
- Catalogued (parsed and validated): **484**
- Evaluated by the scalar core in this crate: **the aggregations, the logical spine and the
relationship/table helpers listed in `crates/dax/README.md`**
- Everything else: **not implemented until its evaluator family is linked**
The per-category counts below are the catalog's. This crate links no evaluator family yet
(`eval::FAMILIES` is empty), so a catalogued function outside the scalar core returns
`not implemented`; each family PR adds its own dispatch and its own suite.
| Category | Catalogued | Evaluated |
| --- | ---: | ---: |
| Aggregation | 22 | 22 |
| Date and time | 24 | 24 |
| Filter | 29 | 29 |
| Financial | 51 | 51 |
| Information | 114 | 114 |
| Logical | 13 | 13 |
| Math and trig | 49 | 49 |
| Other | 16 | 16 |
| Parent and child | 5 | 5 |
| Relationships | 4 | 4 |
| Statistical | 43 | 43 |
| Table manipulation | 35 | 35 |
| Text | 23 | 23 |
| Time intelligence | 45 | 45 |
| Visual calculations | 11 | 11 |
## Evaluated functions
All 484 catalogued functions have an evaluator path. The catalog sections below are the complete
list, grouped by family; each family has an integration suite under `crates/dax/tests/eval_*.rs`,
and `crates/dax/tests/coverage.rs` asserts that every catalogued name binds and reaches an
implementation.
## Catalogued (parsed and validated)
### Aggregation
`APPROXIMATEDISTINCTCOUNT`, `AVERAGE`, `AVERAGEA`, `AVERAGEX`, `COUNT`, `COUNTA`, `COUNTAX`, `COUNTBLANK`, `COUNTROWS`, `COUNTX`, `DISTINCTCOUNT`, `DISTINCTCOUNTNOBLANK`, `MAX`, `MAXA`, `MAXX`, `MIN`, `MINA`, `MINX`, `PRODUCT`, `PRODUCTX`, `SUM`, `SUMX`
### Date and time
`CALENDAR`, `CALENDARAUTO`, `DATE`, `DATEDIFF`, `DATEVALUE`, `DAY`, `EDATE`, `EOMONTH`, `HOUR`, `MINUTE`, `MONTH`, `NETWORKDAYS`, `NOW`, `QUARTER`, `SECOND`, `TIME`, `TIMEVALUE`, `TODAY`, `UTCNOW`, `UTCTODAY`, `WEEKDAY`, `WEEKNUM`, `YEAR`, `YEARFRAC`
### Filter
`ALL`, `ALLCROSSFILTERED`, `ALLEXCEPT`, `ALLNOBLANKROW`, `ALLSELECTED`, `ALLSELECTEDAPPLY`, `ALLSELECTEDREMOVE`, `ALWAYSAPPLY`, `CALCULATE`, `CALCULATETABLE`, `DEPENDON`, `FILTER`, `FILTERCLUSTER`, `GROUPCROSSAPPLY`, `GROUPCROSSAPPLYTABLE`, `INDEX`, `KEEPFILTERS`, `LOOKUP`, `LOOKUPVALUE`, `LOOKUPWITHTOTALS`, `MATCHBY`, `NONFILTER`, `OFFSET`, `ORDERBY`, `PARTITIONBY`, `REMOVEFILTERS`, `SELECTEDVALUE`, `SHADOWCLUSTER`, `WINDOW`
### Financial
`ACCRINT`, `ACCRINTM`, `AMORDEGRC`, `AMORLINC`, `COUPDAYBS`, `COUPDAYS`, `COUPDAYSNC`, `COUPNCD`, `COUPNUM`, `COUPPCD`, `CUMIPMT`, `CUMPRINC`, `DB`, `DDB`, `DISC`, `DOLLARDE`, `DOLLARFR`, `DURATION`, `EFFECT`, `FV`, `INTRATE`, `IPMT`, `ISPMT`, `MDURATION`, `NOMINAL`, `NPER`, `ODDFPRICE`, `ODDFYIELD`, `ODDLPRICE`, `ODDLYIELD`, `PDURATION`, `PMT`, `PPMT`, `PRICE`, `PRICEDISC`, `PRICEMAT`, `PV`, `RATE`, `RECEIVED`, `RRI`, `SLN`, `SYD`, `TBILLEQ`, `TBILLPRICE`, `TBILLYIELD`, `VDB`, `XIRR`, `XNPV`, `YIELD`, `YIELDDISC`, `YIELDMAT`
### Information
`COLUMNSTATISTICS`, `CONTAINS`, `CONTAINSROW`, `CONTAINSSTRING`, `CONTAINSSTRINGEXACT`, `CUSTOMDATA`, `EVALUATEANDLOG`, `HASONEFILTER`, `HASONEVALUE`, `INFO.VIEW.COLUMNS`, `INFO.VIEW.MEASURES`, `INFO.VIEW.RELATIONSHIPS`, `INFO.VIEW.TABLES`, `ISAFTER`, `ISBLANK`, `ISBOOLEAN`, `ISCROSSFILTERED`, `ISDATETIME`, `ISDECIMAL`, `ISDOUBLE`, `ISEMPTY`, `ISERROR`, `ISEVEN`, `ISFILTERED`, `ISINSCOPE`, `ISINT64`, `ISLOGICAL`, `ISNONTEXT`, `ISNUMBER`, `ISNUMERIC`, `ISODD`, `ISONORAFTER`, `ISSELECTEDMEASURE`, `ISSTRING`, `ISSUBTOTAL`, `ISTEXT`, `NAMEOF`, `SELECTEDMEASURE`, `SELECTEDMEASUREFORMATSTRING`, `SELECTEDMEASURENAME`, `TABLEOF`, `TEXTCONTAINS`, `TEXTSIMILARITY`, `USERCULTURE`, `USERNAME`, `USEROBJECTID`, `USERPRINCIPALNAME`, `INFO.ALTERNATEOFDEFINITIONS`, `INFO.ANNOTATIONS`, `INFO.ATTRIBUTEHIERARCHIES`, `INFO.ATTRIBUTEHIERARCHYSTORAGES`, `INFO.CALCDEPENDENCY`, `INFO.CALCULATIONGROUPS`, `INFO.CALCULATIONITEMS`, `INFO.CALENDARCOLUMNGROUPS`, `INFO.CALENDARCOLUMNREFERENCES`, `INFO.CALENDARS`, `INFO.CATALOGS`, `INFO.CHANGEDPROPERTIES`, `INFO.COLUMNPARTITIONSTORAGES`, `INFO.COLUMNPERMISSIONS`, `INFO.COLUMNS`, `INFO.COLUMNSTORAGES`, `INFO.CSDLMETADATA`, `INFO.CULTURES`, `INFO.DATACOVERAGEDEFINITIONS`, `INFO.DATASOURCES`, `INFO.DELTATABLEMETADATASTORAGES`, `INFO.DEPENDENCIES`, `INFO.DETAILROWSDEFINITIONS`, `INFO.DICTIONARYSTORAGES`, `INFO.EXCLUDEDARTIFACTS`, `INFO.EXPRESSIONS`, `INFO.EXTENDEDPROPERTIES`, `INFO.FORMATSTRINGDEFINITIONS`, `INFO.FUNCTIONS`, `INFO.GENERALSEGMENTMAPSEGMENTMETADATASTORAGES`, `INFO.GROUPBYCOLUMNS`, `INFO.HIERARCHIES`, `INFO.HIERARCHYSTORAGES`, `INFO.KPIS`, `INFO.LEVELS`, `INFO.LINGUISTICMETADATA`, `INFO.MEASURES`, `INFO.MODEL`, `INFO.OBJECTTRANSLATIONS`, `INFO.PARQUETFILESTORAGES`, `INFO.PARTITIONS`, `INFO.PARTITIONSTORAGES`, `INFO.PERSPECTIVECOLUMNS`, `INFO.PERSPECTIVEHIERARCHIES`, `INFO.PERSPECTIVEMEASURES`, `INFO.PERSPECTIVES`, `INFO.PERSPECTIVETABLES`, `INFO.PROPERTIES`, `INFO.QUERYGROUPS`, `INFO.REFRESHPOLICIES`, `INFO.RELATEDCOLUMNDETAILS`, `INFO.RELATIONSHIPINDEXSTORAGES`, `INFO.RELATIONSHIPS`, `INFO.RELATIONSHIPSTORAGES`, `INFO.ROLEMEMBERSHIPS`, `INFO.ROLES`, `INFO.SEGMENTMAPSTORAGES`, `INFO.SEGMENTSTORAGES`, `INFO.STORAGEFILES`, `INFO.STORAGEFOLDERS`, `INFO.STORAGETABLECOLUMNS`, `INFO.STORAGETABLECOLUMNSEGMENTS`, `INFO.TABLEPERMISSIONS`, `INFO.TABLES`, `INFO.TABLESTORAGES`, `INFO.USERDEFINEDFUNCTIONS`, `INFO.VARIATIONS`
### Logical
`AND`, `BITAND`, `BITOR`, `BITXOR`, `COALESCE`, `FALSE`, `IF`, `IF.EAGER`, `IFERROR`, `NOT`, `OR`, `SWITCH`, `TRUE`
### Math and trig
`ABS`, `ACOS`, `ACOSH`, `ACOT`, `ACOTH`, `ASIN`, `ASINH`, `ATAN`, `ATANH`, `CEILING`, `CONVERT`, `COS`, `COSH`, `COT`, `COTH`, `CURRENCY`, `DEGREES`, `DIVIDE`, `EVEN`, `EXP`, `FACT`, `FLOOR`, `GCD`, `INT`, `ISO.CEILING`, `LCM`, `LN`, `LOG`, `LOG10`, `MOD`, `MROUND`, `ODD`, `PI`, `POWER`, `QUOTIENT`, `RADIANS`, `RAND`, `RANDBETWEEN`, `ROUND`, `ROUNDDOWN`, `ROUNDUP`, `SIGN`, `SIN`, `SINH`, `SQRT`, `SQRTPI`, `TAN`, `TANH`, `TRUNC`
### Other
`BITLSHIFT`, `BITRSHIFT`, `BLANK`, `EARLIER`, `EARLIEST`, `ERROR`, `EXTERNALMEASURE`, `HASH`, `INFO.STORAGETABLES`, `ISATLEVEL`, `ISCURRENCY`, `ISINTEGER`, `KEYWORDMATCH`, `RANK`, `ROWNUMBER`, `SAMPLECARTESIANPOINTSBYCOVER`
### Parent and child
`PATH`, `PATHCONTAINS`, `PATHITEM`, `PATHITEMREVERSE`, `PATHLENGTH`
### Relationships
`CROSSFILTER`, `RELATED`, `RELATEDTABLE`, `USERELATIONSHIP`
### Statistical
`BETA.DIST`, `BETA.INV`, `CHISQ.DIST`, `CHISQ.DIST.RT`, `CHISQ.INV`, `CHISQ.INV.RT`, `COMBIN`, `COMBINA`, `CONFIDENCE.NORM`, `CONFIDENCE.T`, `EXPON.DIST`, `GEOMEAN`, `GEOMEANX`, `LINEST`, `LINESTX`, `MEDIAN`, `MEDIANX`, `NORM.DIST`, `NORM.INV`, `NORM.S.DIST`, `NORM.S.INV`, `PERCENTILE.EXC`, `PERCENTILE.INC`, `PERCENTILEX.EXC`, `PERCENTILEX.INC`, `PERMUT`, `POISSON.DIST`, `RANK.EQ`, `RANKX`, `SAMPLE`, `STDEV.P`, `STDEV.S`, `STDEVX.P`, `STDEVX.S`, `T.DIST`, `T.DIST.2T`, `T.DIST.RT`, `T.INV`, `T.INV.2T`, `VAR.P`, `VAR.S`, `VARX.P`, `VARX.S`
### Table manipulation
`ADDCOLUMNS`, `ADDMISSINGITEMS`, `CROSSJOIN`, `CURRENTGROUP`, `DATATABLE`, `DETAILROWS`, `DISTINCT`, `EXCEPT`, `FILTERS`, `GENERATE`, `GENERATEALL`, `GENERATESERIES`, `GROUPBY`, `IGNORE`, `INTERSECT`, `NATURALINNERJOIN`, `NATURALJOINUSAGE`, `NATURALLEFTOUTERJOIN`, `NONVISUAL`, `ROLLUP`, `ROLLUPADDISSUBTOTAL`, `ROLLUPGROUP`, `ROLLUPISSUBTOTAL`, `ROW`, `SAMPLEAXISWITHLOCALMINMAX`, `SELECTCOLUMNS`, `SUBSTITUTEWITHINDEX`, `SUMMARIZE`, `SUMMARIZECOLUMNS`, `TOPN`, `TOPNPERLEVEL`, `TOPNSKIP`, `TREATAS`, `UNION`, `VALUES`
### Text
`COMBINEVALUES`, `CONCATENATE`, `CONCATENATEX`, `EXACT`, `FIND`, `FIXED`, `FORMAT`, `LEFT`, `LEN`, `LOWER`, `MID`, `REPLACE`, `REPT`, `RIGHT`, `SEARCH`, `SUBSTITUTE`, `TOCSV`, `TOJSON`, `TRIM`, `UNICHAR`, `UNICODE`, `UPPER`, `VALUE`
### Time intelligence
`CLOSINGBALANCEMONTH`, `CLOSINGBALANCEQUARTER`, `CLOSINGBALANCEWEEK`, `CLOSINGBALANCEYEAR`, `DATEADD`, `DATESBETWEEN`, `DATESINPERIOD`, `DATESMTD`, `DATESQTD`, `DATESWTD`, `DATESYTD`, `ENDOFMONTH`, `ENDOFQUARTER`, `ENDOFWEEK`, `ENDOFYEAR`, `FIRSTDATE`, `FIRSTNONBLANK`, `FIRSTNONBLANKVALUE`, `LASTDATE`, `LASTNONBLANK`, `LASTNONBLANKVALUE`, `NEXTDAY`, `NEXTMONTH`, `NEXTQUARTER`, `NEXTWEEK`, `NEXTYEAR`, `OPENINGBALANCEMONTH`, `OPENINGBALANCEQUARTER`, `OPENINGBALANCEWEEK`, `OPENINGBALANCEYEAR`, `PARALLELPERIOD`, `PREVIOUSDAY`, `PREVIOUSMONTH`, `PREVIOUSQUARTER`, `PREVIOUSWEEK`, `PREVIOUSYEAR`, `SAMEPERIODLASTYEAR`, `STARTOFMONTH`, `STARTOFQUARTER`, `STARTOFWEEK`, `STARTOFYEAR`, `TOTALMTD`, `TOTALQTD`, `TOTALWTD`, `TOTALYTD`
### Visual calculations
`COLLAPSE`, `COLLAPSEALL`, `EXPAND`, `EXPANDALL`, `FIRST`, `LAST`, `MOVINGAVERAGE`, `NEXT`, `PREVIOUS`, `RANGE`, `RUNNINGSUM`
## Notes
- `Evaluated` means a dispatch arm exists in one of the family modules under
`crates/dax/src/eval/`; table-valued functions are counted when they have a `call_table` path.
- Engine-only functions (internal filter clusters, `INFO.*` storage views, visual calculations)
use bounded equivalents of their documented behaviour, described in the module that implements
them; `MS Learn` and dax.guide are the semantic references for everything else.
- The catalog is the dax.guide aggregation/data-type/statement/operator surface plus every
function category in `crates/dax/src/functions/`; see `docs/parity-checklist.md` for the
GridCraft command surface.