From 40350bad7a6b7b268fe32a3fb49da2d673071c6e Mon Sep 17 00:00:00 2001 From: alosslessdev Date: Thu, 5 Nov 2026 02:12:24 -0500 Subject: [PATCH] dax: fix the evaluator core's rounding, aggregation types, blank member and IN semantics (#2228) --- crates/dax/src/eval.rs | 244 ++++++++++++++---- crates/dax/src/eval/support.rs | 118 ++++++++- crates/dax/src/pivot_table.rs | 16 +- crates/dax/src/storage.rs | 45 ++-- crates/dax/src/value.rs | 25 +- crates/dax/tests/binder.rs | 30 +++ crates/dax/tests/eval_storage_differential.rs | 76 +++++- crates/dax/tests/eval_storage_fallback.rs | 8 +- crates/dax/tests/evaluator.rs | 84 ++++++ 9 files changed, 559 insertions(+), 87 deletions(-) diff --git a/crates/dax/src/eval.rs b/crates/dax/src/eval.rs index 0338ca6e1..6f17f58cf 100644 --- a/crates/dax/src/eval.rs +++ b/crates/dax/src/eval.rs @@ -35,6 +35,7 @@ mod support; + use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; @@ -43,7 +44,7 @@ use crate::ast::{BinaryOp, Literal, UnaryOp}; use crate::binder::{BindError, Binder, BoundExpr}; use crate::model::DataModel; use crate::storage::{ColumnKind, ModelStorage, StorageError, TableStorage}; -use crate::value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue}; +use crate::value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue, distinct_key}; use support::*; @@ -93,14 +94,50 @@ pub fn linked_families() -> impl Iterator { FAMILIES.iter().map(|family| family.name) } +/// How filters pass across one relationship under the current filter context. +/// +/// DAX's default is the one-to-many direction: a filter on the one side (`to_table`, the lookup +/// table) restricts the many side (`from_table`, the fact table). `CROSSFILTER` can add the +/// reverse direction (`BOTH`/`TWOWAY`), turn propagation off (`NONE`), or name a single direction +/// (`ONEWAY_LEFTFILTERSRIGHT`/`ONEWAY_RIGHTFILTERSLEFT`), which is why both directions are flags. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RelationshipFlow { + /// Filters pass from the one side to the many side (the default direction). + pub one_to_many: bool, + /// Filters pass from the many side back to the one side. + pub many_to_one: bool, +} + +impl RelationshipFlow { + /// No propagation: `CROSSFILTER ( ..., NONE )` or an inactive relationship. + pub const NONE: Self = Self { one_to_many: false, many_to_one: false }; + /// The default direction: one side filters the many side. + pub const ONE_TO_MANY: Self = Self { one_to_many: true, many_to_one: false }; + /// The reverse direction only: many side filters the one side. + pub const MANY_TO_ONE: Self = Self { one_to_many: false, many_to_one: true }; + /// Both directions: `CROSSFILTER ( ..., BOTH )` or a bidirectional relationship. + pub const BOTH: Self = Self { one_to_many: true, many_to_one: true }; + + /// The flow of a relationship without a `USERELATIONSHIP`/`CROSSFILTER` modifier. + fn from_flags(inactive: bool, bidirectional: bool) -> Self { + if inactive { + Self::NONE + } else if bidirectional { + Self::BOTH + } else { + Self::ONE_TO_MANY + } + } +} + /// A set of column-value filters. A column with several keys is an OR; different columns are /// ANDed. #[derive(Clone, Debug, Default, PartialEq)] pub struct FilterContext { pub filters: BTreeMap<(usize, usize), BTreeSet>, /// Relationship behaviour set by `USERELATIONSHIP`/`CROSSFILTER` inside CALCULATE: - /// relationship index -> `(active, bidirectional)`. - pub relationships: BTreeMap, + /// relationship index -> [`RelationshipFlow`]. + pub relationships: BTreeMap, } impl FilterContext { @@ -497,14 +534,23 @@ impl<'a> Evaluator<'a> { let mut rows = rows.unwrap_or_else(|| (0..table_storage.row_count()).collect()); for (index, relationship) in storage.relationships().iter().enumerate() { - let (active, bidirectional) = filters.relationships.get(&index).copied().unwrap_or((!relationship.inactive, relationship.bidirectional)); - if !active { - continue; - } - let (other, self_column, other_column) = if relationship.from_table == table { - (relationship.to_table, relationship.from_column, relationship.to_column) - } else if bidirectional && relationship.to_table == table { - (relationship.from_table, relationship.to_column, relationship.from_column) + let flow = filters + .relationships + .get(&index) + .copied() + .unwrap_or_else(|| RelationshipFlow::from_flags(relationship.inactive, relationship.bidirectional)); + // `other` is the side whose filters reach `table`: the one side when filters flow + // one-to-many (this table is the many side), the many side for the reverse direction. + let (other, self_column, other_column, one_to_many) = if relationship.from_table == table { + if !flow.one_to_many { + continue; + } + (relationship.to_table, relationship.from_column, relationship.to_column, true) + } else if relationship.to_table == table { + if !flow.many_to_one { + continue; + } + (relationship.from_table, relationship.to_column, relationship.from_column, false) } else { continue; }; @@ -516,11 +562,17 @@ impl<'a> Evaluator<'a> { self.bump(|counters| &counters.relationship_lookups); let keys: BTreeSet = other_rows.iter().filter_map(|row| storage.value(other, other_column, *row)).map(|value| ScalarKey::from(&value)).collect(); + // A one-side filter that selects BLANK also selects the rows that do not join it at + // all: DAX's BLANK member carries the orphan keys, so the BLANK cell of a pivot counts + // its fact rows instead of hiding them. + let blank_member = one_to_many && self.selects_blank_member(other, filters, &mut visited.clone()); + let index_of = |key: &ScalarKey| relationship.rows_to(key); let mut retained = Vec::with_capacity(rows.len()); for row in rows { - if let Some(value) = storage.value(table, self_column, row) - && keys.contains(&ScalarKey::from(&value)) - { + let Some(value) = storage.value(table, self_column, row) else { continue }; + let key = ScalarKey::from(&value); + let orphan = key == ScalarKey::Blank || index_of(&key).is_empty(); + if keys.contains(&key) || (blank_member && orphan) { retained.push(row); } } @@ -560,10 +612,19 @@ impl<'a> Evaluator<'a> { let mut rows: Vec> = model_table .rows .iter() + // A caller-built row can be shorter than the declared columns. Pad it first, so the + // filter and every later column read see the missing cells as BLANK — the storage + // path and the integrity check already treat them that way. + .map(|row| { + let mut padded = row.clone(); + if padded.len() < model_table.columns.len() { + padded.resize(model_table.columns.len(), Scalar::Blank); + } + padded + }) .filter(|row| { model_table.columns.iter().enumerate().all(|(column, _)| row.get(column).is_none_or(|value| filters.matches(table, column, value))) }) - .cloned() .collect(); // Propagate filters across active relationships: a filtered related table restricts this @@ -574,14 +635,21 @@ impl<'a> Evaluator<'a> { let (Some(from), Some(to)) = (self.model.table_index(&relationship.from_table), self.model.table_index(&relationship.to_table)) else { continue; }; - let (active, bidirectional) = filters.relationships.get(&index).copied().unwrap_or((!relationship.inactive, relationship.bidirectional)); - if !active { - continue; - } - let (other, self_column, other_column) = if from == table { - (to, &relationship.from_column, &relationship.to_column) - } else if bidirectional && to == table { - (from, &relationship.to_column, &relationship.from_column) + let flow = filters + .relationships + .get(&index) + .copied() + .unwrap_or_else(|| RelationshipFlow::from_flags(relationship.inactive, relationship.bidirectional)); + let (other, self_column, other_column, one_to_many) = if from == table { + if !flow.one_to_many { + continue; + } + (to, &relationship.from_column, &relationship.to_column, true) + } else if to == table { + if !flow.many_to_one { + continue; + } + (from, &relationship.to_column, &relationship.from_column, false) } else { continue; }; @@ -599,7 +667,23 @@ impl<'a> Evaluator<'a> { }; let keys: BTreeSet = self.table_inner(other, filters, visited).rows.iter().filter_map(|row| row.get(other_col)).map(ScalarKey::from).collect(); - rows.retain(|row| row.get(self_col).is_some_and(|value| keys.contains(&ScalarKey::from(value)))); + // As on the storage path, a one-side filter that selects BLANK also selects the rows + // whose key has no related row: DAX's BLANK member carries the orphan keys. + let blank_member = one_to_many && self.selects_blank_member(other, filters, &mut visited.clone()); + let known: BTreeSet = if blank_member { + self.model + .tables + .get(other) + .map(|table| table.rows.iter().filter_map(|row| row.get(other_col)).map(ScalarKey::from).collect()) + .unwrap_or_default() + } else { + BTreeSet::new() + }; + rows.retain(|row| { + let Some(value) = row.get(self_col) else { return false }; + let key = ScalarKey::from(value); + keys.contains(&key) || (blank_member && (key == ScalarKey::Blank || !known.contains(&key))) + }); } visited.remove(&table); @@ -616,17 +700,18 @@ impl<'a> Evaluator<'a> { return true; } for (index, relationship) in self.model.relationships.iter().enumerate() { - let (active, bidirectional) = filters.relationships.get(&index).copied().unwrap_or((!relationship.inactive, relationship.bidirectional)); - if !active { - continue; - } + let flow = filters + .relationships + .get(&index) + .copied() + .unwrap_or_else(|| RelationshipFlow::from_flags(relationship.inactive, relationship.bidirectional)); let (Some(from), Some(to)) = (self.model.table_index(&relationship.from_table), self.model.table_index(&relationship.to_table)) else { continue; }; let next = if from == table { - Some(to) - } else if bidirectional && to == table { - Some(from) + flow.one_to_many.then_some(to) + } else if to == table { + flow.many_to_one.then_some(from) } else { None }; @@ -640,6 +725,38 @@ impl<'a> Evaluator<'a> { false } + /// Whether the current filters select the BLANK member of `table`. + /// + /// A filter that names BLANK on any of the table's columns selects it, and so does a filter + /// that reaches `table` from a further dimension over an active one-to-many relationship: DAX + /// represents the rows that do not join a dimension by the dimension's BLANK member, so the + /// whole chain is in the BLANK member. That member is what makes an orphan key belong to the + /// BLANK group of a pivot instead of falling out of the filter. + fn selects_blank_member(&self, table: usize, filters: &FilterContext, visited: &mut BTreeSet) -> bool { + if !visited.insert(table) { + return false; + } + if filters.filters.iter().any(|((filtered, _), keys)| *filtered == table && keys.contains(&ScalarKey::Blank)) { + return true; + } + for (index, relationship) in self.model.relationships.iter().enumerate() { + let flow = filters + .relationships + .get(&index) + .copied() + .unwrap_or_else(|| RelationshipFlow::from_flags(relationship.inactive, relationship.bidirectional)); + let (Some(from), Some(to)) = (self.model.table_index(&relationship.from_table), self.model.table_index(&relationship.to_table)) else { + continue; + }; + // `table` is the many side of this relationship, so `to` is the dimension whose + // filters reach it. + if from == table && flow.one_to_many && to != table && self.selects_blank_member(to, filters, visited) { + return true; + } + } + false + } + pub(crate) fn eval_table(&self, expr: &BoundExpr, ctx: &mut Context) -> Result { match expr { BoundExpr::Table(table) => Ok(self.table(*table, &ctx.filters)), @@ -659,7 +776,9 @@ impl<'a> Evaluator<'a> { _ => vec![self.eval(left, ctx)?], }; let table = self.eval_table(right, ctx)?; - let found = table.rows.iter().any(|row| row.len() == left.len() && row.iter().zip(&left).all(|(a, b)| a.strict_eq(b))); + // `IN` is DAX equality, not representation equality: `2 IN {2.0}` and `"a" IN {"A"}` are + // TRUE, which `strict_eq`'s variant comparison would miss. BLANK still matches only BLANK. + let found = table.rows.iter().any(|row| row.len() == left.len() && row.iter().zip(&left).all(|(a, b)| in_equals(a, b))); Ok(Scalar::Boolean(found)) } @@ -1223,7 +1342,17 @@ impl<'a> Evaluator<'a> { let rows = self.filtered_row_ids(table, filters)?; let aggregate = name.to_ascii_uppercase(); let scalar = match aggregate.as_str() { - "SUM" | "AVERAGE" | "PRODUCT" | "MIN" | "MAX" => { + "MIN" | "MAX" => { + // The winning value keeps its own type, so a DateTime column answers a DateTime + // and an integer column an Integer. Only numbers compete: text and logicals are + // not observations, and a promoted column keeps the row path where that rule + // lives. + if !matches!(kind, ColumnKind::Integer | ColumnKind::Currency | ColumnKind::Decimal | ColumnKind::DateTime) { + return None; + } + if aggregate == "MIN" { table_storage.min(column, &rows).ok()? } else { table_storage.max(column, &rows).ok()? } + } + "SUM" | "AVERAGE" | "PRODUCT" => { // These read numbers only: booleans and text contribute nothing, so a logical or // promoted-to-text column keeps the row path where that rule lives. if !matches!(kind, ColumnKind::Integer | ColumnKind::Currency | ColumnKind::Decimal | ColumnKind::DateTime) { @@ -1231,8 +1360,6 @@ impl<'a> Evaluator<'a> { } let numbers = table_storage.numeric_values(column, &rows).ok()?; match aggregate.as_str() { - "MIN" => numbers.iter().copied().reduce(f64::min).map(Scalar::Decimal).unwrap_or(Scalar::Blank), - "MAX" => numbers.iter().copied().reduce(f64::max).map(Scalar::Decimal).unwrap_or(Scalar::Blank), "SUM" if numbers.is_empty() => Scalar::Blank, "SUM" => Scalar::Decimal(numbers.iter().sum()), "PRODUCT" if numbers.is_empty() => Scalar::Blank, @@ -1539,7 +1666,10 @@ impl<'a> Evaluator<'a> { let same_pair = (same(&other.from_table, &relationship.from_table) && same(&other.to_table, &relationship.to_table)) || (same(&other.from_table, &relationship.to_table) && same(&other.to_table, &relationship.from_table)); if same_pair { - filters.relationships.insert(other_index, (other_index == index, other.bidirectional)); + // Activating this one enables it whatever the model marked it as; the other + // links between the same pair stop filtering. + let flow = if other_index == index { RelationshipFlow::from_flags(false, other.bidirectional) } else { RelationshipFlow::NONE }; + filters.relationships.insert(other_index, flow); } } return Ok(()); @@ -1548,13 +1678,24 @@ impl<'a> Evaluator<'a> { Some(BoundExpr::Keyword(word)) | Some(BoundExpr::Literal(Literal::String(word))) => word.to_ascii_uppercase(), _ => return Err(EvalError::new("CROSSFILTER needs ONE, BOTH or NONE")), }; - let state = match direction.as_str() { - "ONE" | "ONEWAY" => (true, false), - "BOTH" | "TWOWAY" => (true, true), - "NONE" => (false, false), - _ => return Err(EvalError::new("CROSSFILTER direction must be ONE, ONEWAY, BOTH, TWOWAY or NONE")), + let flow = match direction.as_str() { + "ONE" | "ONEWAY" => RelationshipFlow::ONE_TO_MANY, + "BOTH" | "TWOWAY" => RelationshipFlow::BOTH, + "NONE" => RelationshipFlow::NONE, + "ONEWAY_LEFTFILTERSRIGHT" | "ONEWAY_RIGHTFILTERSLEFT" => { + // LEFT and RIGHT name the first and second column argument, so which way this is + // depends on whether the first argument named the many or the one side. + let first_is_one_side = same(&relationship.to_table, &table_a_name) && same(&relationship.to_column, &name_a); + let left_filters_right = direction == "ONEWAY_LEFTFILTERSRIGHT"; + if left_filters_right == first_is_one_side { RelationshipFlow::ONE_TO_MANY } else { RelationshipFlow::MANY_TO_ONE } + } + _ => { + return Err(EvalError::new( + "CROSSFILTER direction must be NONE, ONEWAY, BOTH, TWOWAY, ONEWAY_LEFTFILTERSRIGHT or ONEWAY_RIGHTFILTERSLEFT", + )); + } }; - filters.relationships.insert(index, state); + filters.relationships.insert(index, flow); Ok(()) } @@ -1769,6 +1910,16 @@ fn unary(op: UnaryOp, value: Scalar) -> Result { } } +/// Equality for `IN`: BLANK equals only BLANK, and every other pair follows [`Scalar::compare`], +/// so numbers compare by value across variants and text ignores case. +fn in_equals(left: &Scalar, right: &Scalar) -> bool { + match (left.is_blank(), right.is_blank()) { + (true, true) => true, + (true, false) | (false, true) => false, + (false, false) => left.compare(right) == Some(Ordering::Equal), + } +} + fn binary(op: BinaryOp, left: Scalar, right: Scalar) -> Result { match op { BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow => { @@ -1952,8 +2103,13 @@ fn scalar_function(name: &str, args: &[Scalar]) -> Result { } } "UNICHAR" => Ok(char::from_u32(number(0)?.max(0.0) as u32).map(|c| Scalar::String(c.to_string())).unwrap_or(Scalar::Blank)), - "GCD" => Ok(Scalar::Integer(gcd(number(0)? as i64, number(1)? as i64))), - "LCM" => Ok(Scalar::Integer(lcm(number(0)? as i64, number(1)? as i64))), + "GCD" => { + let value = gcd(number(0)? as i64, number(1)? as i64); + // Excel answers `#NUM!` when the divisor does not fit the integer type. + let value = i64::try_from(value).map_err(|_| EvalError::new("GCD result is out of range"))?; + Ok(Scalar::Integer(value)) + } + "LCM" => lcm(number(0)? as i64, number(1)? as i64).map(Scalar::Integer).ok_or_else(|| EvalError::new("LCM result is out of range")), "PI" => Ok(Scalar::Decimal(std::f64::consts::PI)), "DEGREES" => Ok(Scalar::Decimal(number(0)?.to_degrees())), "RADIANS" => Ok(Scalar::Decimal(number(0)?.to_radians())), diff --git a/crates/dax/src/eval/support.rs b/crates/dax/src/eval/support.rs index 010d12c51..896f370ed 100644 --- a/crates/dax/src/eval/support.rs +++ b/crates/dax/src/eval/support.rs @@ -310,6 +310,16 @@ pub(crate) fn utc_today_serial() -> f64 { utc_now_serial().floor() } +/// Rounds `value` to 15 significant digits, the precision Excel and DAX compute with. +/// +/// `value * 10^digits` carries the binary representation error of its factors, and a directed +/// rounding makes that error visible: `0.29 * 100` is `28.999999999999996`, so `ROUNDDOWN ( 0.29, +/// 2 )` would truncate to `0.28` and `ROUNDUP ( 0.07, 2 )` would ceil `7.000000000000001` to +/// `0.08`. Snap that noise away before rounding, exactly as `to_dax_text` does when it prints. +fn excel_precision(value: f64) -> f64 { + format!("{value:.14e}").parse().unwrap_or(value) +} + pub(crate) fn round_to(value: f64, digits: i32) -> f64 { // The scale factor overflows or underflows outside f64's exponent range: past +308 digits the // value cannot change, past -308 every digit is rounded away. @@ -320,7 +330,7 @@ pub(crate) fn round_to(value: f64, digits: i32) -> f64 { return 0.0; } let factor = 10f64.powi(digits); - let scaled = value * factor; + let scaled = excel_precision(value * factor); if !scaled.is_finite() { return value; } @@ -340,7 +350,7 @@ pub(crate) fn round_direction(value: f64, digits: i32, up: bool) -> f64 { return if up && value != 0.0 { f64::INFINITY.copysign(value) } else { 0.0 }; } let factor = 10f64.powi(digits); - let scaled = value * factor; + let scaled = excel_precision(value * factor); if !scaled.is_finite() { return value; } @@ -348,9 +358,10 @@ pub(crate) fn round_direction(value: f64, digits: i32, up: bool) -> f64 { rounded / factor } -pub(crate) fn gcd(mut a: i64, mut b: i64) -> i64 { - a = a.abs(); - b = b.abs(); +/// The greatest common divisor of the two magnitudes, so `i64::MIN` is represented without +/// overflowing the way `i64::abs` would. +pub(crate) fn gcd(a: i64, b: i64) -> u64 { + let (mut a, mut b) = (a.unsigned_abs(), b.unsigned_abs()); while b != 0 { let t = a % b; a = b; @@ -359,8 +370,12 @@ pub(crate) fn gcd(mut a: i64, mut b: i64) -> i64 { a } -pub(crate) fn lcm(a: i64, b: i64) -> i64 { - if a == 0 || b == 0 { 0 } else { (a / gcd(a, b) * b).abs() } +/// The least common multiple, or `None` when it does not fit in an `i64` (Excel answers `#NUM!`). +pub(crate) fn lcm(a: i64, b: i64) -> Option { + if a == 0 || b == 0 { + return Some(0); + } + (a.unsigned_abs() / gcd(a, b)).checked_mul(b.unsigned_abs()).and_then(|value| i64::try_from(value).ok()) } /// Applies a scalar aggregation over already-evaluated values. @@ -394,8 +409,23 @@ pub(crate) fn aggregate_values(name: &str, values: &[Scalar]) -> Result Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().product()) }), - "MIN" => Ok(numbers.iter().copied().reduce(f64::min).map(Scalar::Decimal).unwrap_or(Scalar::Blank)), - "MAX" => Ok(numbers.iter().copied().reduce(f64::max).map(Scalar::Decimal).unwrap_or(Scalar::Blank)), + "MIN" | "MAX" => { + // The winner keeps its own type — a date column answers a DateTime and an integer + // column an Integer — so this cannot read the `f64` projection the sum-like + // aggregations use. Only numbers compete: text and logicals are not observations. + let want = if name.eq_ignore_ascii_case("MIN") { Ordering::Less } else { Ordering::Greater }; + let mut best: Option<&Scalar> = None; + for value in + values.iter().filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_))) + { + match best { + None => best = Some(value), + Some(current) if value.compare(current) == Some(want) => best = Some(value), + Some(_) => {} + } + } + Ok(best.cloned().unwrap_or(Scalar::Blank)) + } "MINA" => Ok(values .iter() .filter(|value| !value.is_blank()) @@ -428,11 +458,11 @@ pub(crate) fn aggregate_values(name: &str, values: &[Scalar]) -> Result Ok(Scalar::Integer(values.iter().filter(|v| v.is_blank() || v.to_text().is_empty()).count() as i64)), "DISTINCTCOUNT" | "APPROXIMATEDISTINCTCOUNT" => { - let distinct: BTreeSet = values.iter().map(ScalarKey::from).collect(); + let distinct: BTreeSet = values.iter().map(distinct_key).collect(); Ok(if values.is_empty() { Scalar::Blank } else { Scalar::Integer(distinct.len() as i64) }) } "DISTINCTCOUNTNOBLANK" => { - let distinct: BTreeSet = values.iter().filter(|value| !value.is_blank()).map(ScalarKey::from).collect(); + let distinct: BTreeSet = values.iter().filter(|value| !value.is_blank()).map(distinct_key).collect(); Ok(Scalar::Integer(distinct.len() as i64)) } _ => Err(EvalError::not_implemented(name)), @@ -481,12 +511,32 @@ pub(crate) fn parse_date_text(text: &str) -> Option { let (hour, minute, second) = match time.map(str::trim).filter(|time| !time.is_empty()) { None => (0, 0, 0), Some(time) => { + // `datetime_text` prints a date as `M/D/YYYY H:MM:SS AM/PM`, so the form the crate + // itself writes has to parse back. The suffix decides the half of the day and the + // hour is then 1-12; without it the hour is 0-23. + let (clock, meridiem) = match time.rsplit_once(' ') { + Some((clock, suffix)) if suffix.eq_ignore_ascii_case("AM") || suffix.eq_ignore_ascii_case("PM") => { + (clock.trim(), Some(suffix.eq_ignore_ascii_case("PM"))) + } + _ => (time, None), + }; // A present time must parse and be in range: `25:00:00` is rejected rather than // rolled into the next day, like an impossible date. - let parts: Vec<&str> = time.split(':').collect(); + let parts: Vec<&str> = clock.split(':').collect(); let hour: i64 = parts.first()?.trim().parse().ok()?; let minute: i64 = parts.get(1).unwrap_or(&"0").trim().parse().ok()?; let second: i64 = parts.get(2).unwrap_or(&"0").trim().parse().ok()?; + let hour = match meridiem { + // 12 AM is midnight and 12 PM is noon; the other PM hours move to the afternoon. + Some(pm) if (1..=12).contains(&hour) => match (hour, pm) { + (12, false) => 0, + (12, true) => 12, + (hour, true) => hour + 12, + (hour, false) => hour, + }, + Some(_) => return None, + None => hour, + }; if !(0..24).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) { return None; } @@ -593,9 +643,14 @@ mod tests { ]; assert_eq!(aggregate_values("SUM", &values).expect("SUM"), Scalar::Decimal(14.0)); assert_eq!(aggregate_values("AVERAGE", &values).expect("AVERAGE"), Scalar::Decimal(3.5)); + // MIN/MAX return the winning value itself: its type survives, so the 10.0 date stays a + // DateTime rather than becoming a decimal serial. assert_eq!(aggregate_values("MIN", &values).expect("MIN"), Scalar::Decimal(0.5)); - assert_eq!(aggregate_values("MAX", &values).expect("MAX"), Scalar::Decimal(10.0)); + assert_eq!(aggregate_values("MAX", &values).expect("MAX"), Scalar::DateTime(10.0)); assert_eq!(aggregate_values("PRODUCT", &values).expect("PRODUCT"), Scalar::Decimal(15.0)); + let integers = [Scalar::Integer(7), Scalar::Integer(3), Scalar::Blank]; + assert_eq!(aggregate_values("MIN", &integers).expect("MIN"), Scalar::Integer(3)); + assert_eq!(aggregate_values("MAX", &integers).expect("MAX"), Scalar::Integer(7)); // A column holding only text, logicals and blanks has no numeric observations at all. let non_numeric = [Scalar::String("5".into()), Scalar::Boolean(false), Scalar::Blank]; assert_eq!(aggregate_values("SUM", &non_numeric).expect("SUM"), Scalar::Blank); @@ -621,4 +676,41 @@ mod tests { assert_eq!(parse_date_text("1/8"), None); assert_eq!(parse_date_text(""), None); } + + #[test] + fn date_text_round_trips_the_ampm_form_the_crate_prints() { + // `datetime_text` writes `M/D/YYYY H:MM:SS AM/PM`, so the same text has to parse back: + // 12 AM is midnight and 12 PM is noon, and the other PM hours move to the afternoon. + assert_eq!(parse_date_text("1/2/2024 12:00:00 AM"), Some(date_serial(2024, 1, 2, 0, 0, 0))); + assert_eq!(parse_date_text("1/2/2024 12:00:00 PM"), Some(date_serial(2024, 1, 2, 12, 0, 0))); + assert_eq!(parse_date_text("1/2/2024 1:30:15 PM"), Some(date_serial(2024, 1, 2, 13, 30, 15))); + assert_eq!(parse_date_text("1/2/2024 1:30:15 AM"), Some(date_serial(2024, 1, 2, 1, 30, 15))); + // A suffixed hour is 1-12, so 13 PM and 0 AM are impossible rather than 13:00 and 00:00. + assert_eq!(parse_date_text("1/2/2024 13:00:00 PM"), None); + assert_eq!(parse_date_text("1/2/2024 0:00:00 AM"), None); + } + + #[test] + fn rounding_snaps_binary_noise_at_fifteen_digits() { + // `value * 100` carries the binary error of the input, and a directed rounding exposes it. + assert_eq!(round_to(1.005, 2), 1.01); + assert_eq!(round_direction(0.29, 2, false), 0.29); + assert_eq!(round_direction(0.07, 2, true), 0.07); + // The ordinary cases still behave: sign-aware directed rounding and half away from zero. + assert_eq!(round_direction(-2.9, 0, false), -2.0); + assert_eq!(round_direction(-2.1, 0, true), -3.0); + assert_eq!(round_to(2.5, 0), 3.0); + assert_eq!(round_to(2.345, 2), 2.35); + } + + #[test] + fn gcd_and_lcm_report_results_that_do_not_fit() { + assert_eq!(gcd(12, 18), 6); + // `i64::MIN` has no positive counterpart: the magnitudes are used instead of `abs`. + assert_eq!(gcd(i64::MIN, 2), 2); + assert_eq!(lcm(4, 6), Some(12)); + assert_eq!(lcm(0, 7), Some(0)); + // Coprime operands above 2^32 overflow the product, which Excel answers with `#NUM!`. + assert_eq!(lcm(1 << 40, (1 << 40) + 1), None); + } } diff --git a/crates/dax/src/pivot_table.rs b/crates/dax/src/pivot_table.rs index c4ac5689b..c754eb9dd 100644 --- a/crates/dax/src/pivot_table.rs +++ b/crates/dax/src/pivot_table.rs @@ -45,9 +45,10 @@ //! rejected ([`PivotTableError::ForeignField`]). //! * A cell of a related field's group is evaluated with the group value as a filter on the //! *related table*, so the evaluator's own relationship propagation (through the same indexes, -//! over any number of hops) restricts the source table. A group value the relationship cannot -//! resolve — an orphan key, shown as `(Blank)` — therefore selects no source rows and the -//! measure returns its empty-set value (BLANK for `SUM`), the model's inner-join semantics. +//! over any number of hops) restricts the source table. A source row whose key has no related +//! row — an orphan key, shown as `(Blank)` — belongs to the related table's BLANK member, so the +//! `(Blank)` cell counts it and the leaf rows still add up to the grand total. A BLANK foreign +//! key is an orphan as well: a relationship never joins one. //! A label column of a related field is named `Table[Column]`, so two dimensions with a column //! of the same name stay distinguishable; source-table fields keep the bare column name. //! @@ -998,6 +999,11 @@ fn column_field_value(storage: &ModelStorage, table: usize, row: usize, field: & for hop in &field.hops { let key = storage.value(current_table, hop.from_column, current_row).unwrap_or(Scalar::Blank); let key = ScalarKey::from(&key); + // A BLANK key never joins, even when the related table has its own BLANK key row: DAX + // treats it as an orphan, and `model_field_value` groups it as one too. + if key == ScalarKey::Blank { + return Scalar::Blank; + } let Some(next) = storage.relationships().get(hop.relationship).and_then(|relationship| relationship.rows_to(&key).first().copied()) else { return Scalar::Blank; }; @@ -1016,8 +1022,8 @@ fn model_field_value(model: &DataModel, row: &[Scalar], field: &BoundField) -> S let mut current = row; for hop in &field.hops { let key = ScalarKey::from(¤t.get(hop.from_column).cloned().unwrap_or(Scalar::Blank)); - // The relationship index never matches a BLANK key, so a blank foreign key is an orphan - // here too; otherwise both paths would group the same row differently. + // A BLANK key is an orphan here too — a relationship never joins one, even when the + // related table has a BLANK key row of its own — so both paths group the row the same way. if key == ScalarKey::Blank { return Scalar::Blank; } diff --git a/crates/dax/src/storage.rs b/crates/dax/src/storage.rs index 3be56f31e..41610f2f3 100644 --- a/crates/dax/src/storage.rs +++ b/crates/dax/src/storage.rs @@ -92,7 +92,7 @@ use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use crate::model::DataModel; -use crate::value::{Scalar, ScalarKey}; +use crate::value::{Scalar, ScalarKey, distinct_key}; /// A bitset used for column blank/null bitmaps. /// @@ -966,20 +966,19 @@ impl TableStorage { /// `DISTINCTCOUNT` over the selected rows. BLANK counts as a distinct value, as in DAX. /// /// A dictionary-encoded column counts distinct codes instead of decoding a value per row, so - /// each label is compared once whatever the row count. + /// each label is compared once whatever the row count. Labels fold to lower case, the model + /// collation, so `"A"` and `"a"` are one distinct value — the same key the row-scan path + /// builds and the same folding the filter context uses. pub fn distinct_count(&self, column: usize, rows: &[usize]) -> Result { let storage = self.column_checked(column)?; self.check_rows(storage, rows)?; if let Some((dictionary, nulls)) = storage.data().string_parts() { let mut seen = vec![false; dictionary.len()]; - let mut distinct: usize = 0; let mut seen_blank = false; + let mut folded: BTreeSet = BTreeSet::new(); for &row in rows { if nulls.get(row) { - if !seen_blank { - seen_blank = true; - distinct += 1; - } + seen_blank = true; continue; } if let Some(code) = storage.data().code_at(row).and_then(|code| usize::try_from(code).ok()) @@ -987,16 +986,19 @@ impl TableStorage { && !*seen { *seen = true; - distinct += 1; + if let Some(label) = dictionary.get(code) { + folded.insert(label.to_lowercase()); + } } } + let distinct = folded.len() + usize::from(seen_blank); return Ok(Scalar::Integer(i64::try_from(distinct).unwrap_or(i64::MAX))); } let data = storage.data(); let mut keys = BTreeSet::new(); for &row in rows { if let Some(value) = data.value(row) { - keys.insert(ScalarKey::from(&value)); + keys.insert(distinct_key(&value)); } } Ok(Scalar::Integer(i64::try_from(keys.len()).unwrap_or(i64::MAX))) @@ -1026,8 +1028,8 @@ impl TableStorage { /// The numeric values of `column` over `rows`, in row order, using DAX coercion. /// - /// This is the observation list `SUM`, `AVERAGE`, `PRODUCT`, `MIN`, `MAX` and the variance - /// family aggregate: blanks, booleans and text contribute nothing (BLANK is skipped, + /// This is the observation list `SUM`, `AVERAGE`, `PRODUCT` and the variance family + /// aggregate: blanks, booleans and text contribute nothing (BLANK is skipped, /// booleans and text are not numbers here even when Excel would coerce them), integers are /// read as `f64`, currency in major units and date/time serials unchanged. Non-finite values /// are kept; callers that need finite observations filter them. @@ -1084,7 +1086,8 @@ impl TableStorage { /// The distinct values of `column` over `rows`, in first-occurrence row order. /// /// BLANK is a value of its own. A dictionary-encoded column compares each label once through - /// its dictionary instead of decoding a value per row. + /// its dictionary instead of decoding a value per row, and text folds to lower case — the + /// model collation — so `"A"` and `"a"` are one value, reported with the first spelling seen. pub fn distinct_values(&self, column: usize, rows: &[usize]) -> Result, StorageError> { let storage = self.column_checked(column)?; self.check_rows(storage, rows)?; @@ -1093,6 +1096,10 @@ impl TableStorage { if let Some((dictionary, nulls)) = data.string_parts() { let mut seen = vec![false; dictionary.len()]; let mut seen_blank = false; + // Labels fold to lower case, the model collation, so `"A"` and `"a"` are one value — + // the same key `DISTINCTCOUNT` counts and the filter context filters on. The first + // spelling encountered is the one reported. + let mut labels: BTreeSet = BTreeSet::new(); for &row in rows { if nulls.get(row) { if !seen_blank { @@ -1107,10 +1114,14 @@ impl TableStorage { let Some(label) = dictionary.get(code) else { continue; }; - if let Some(seen) = seen.get_mut(code) - && !*seen - { - *seen = true; + let Some(seen) = seen.get_mut(code) else { + continue; + }; + if *seen { + continue; + } + *seen = true; + if labels.insert(label.to_lowercase()) { values.push(Scalar::String(label.clone())); } } @@ -1120,7 +1131,7 @@ impl TableStorage { let Some(value) = data.value(row) else { continue; }; - if seen.insert(ScalarKey::from(&value)) { + if seen.insert(distinct_key(&value)) { values.push(value); } } diff --git a/crates/dax/src/value.rs b/crates/dax/src/value.rs index 95292fbec..4546455a0 100644 --- a/crates/dax/src/value.rs +++ b/crates/dax/src/value.rs @@ -171,6 +171,11 @@ impl Scalar { } /// Comparison with DAX's blank coercion for `=`/ordering and case-insensitive strings. + /// + /// `None` means the types are not comparable: text against a number or a logical, and any + /// pair with NaN. Text is never coerced to a number here — arithmetic coerces numeric text + /// (`to_number`), comparison does not — so the caller decides what an incomparable pair means + /// (the evaluator maps it to FALSE for `=`/ordering and to an error where DAX raises one). pub fn compare(&self, other: &Scalar) -> Option { match (self, other) { (Scalar::Blank, Scalar::Blank) => Some(Ordering::Equal), @@ -179,6 +184,7 @@ impl Scalar { (Scalar::Blank, Scalar::String(b)) => Some(String::new().cmp(&b.to_lowercase())), (Scalar::String(a), Scalar::Blank) => Some(a.to_lowercase().cmp(&String::new())), (Scalar::String(a), Scalar::String(b)) => Some(a.to_lowercase().cmp(&b.to_lowercase())), + (Scalar::String(_), _) | (_, Scalar::String(_)) => None, (Scalar::Boolean(a), Scalar::Boolean(b)) => Some(a.cmp(b)), _ => self.to_number()?.partial_cmp(&other.to_number()?), } @@ -193,7 +199,12 @@ impl Scalar { } } -/// A comparable/hashable key used for filter context values. +/// A comparable/hashable key used for filter context values, relationship joins and dictionary +/// lookups. +/// +/// Keys keep the exact spelling: they double as the reported key in integrity findings. Where DAX +/// compares values for *distinctness* instead of identity — `DISTINCTCOUNT`, `VALUES`/`DISTINCT` +/// — the text folds through [`distinct_key`], which is the model's case-insensitive collation. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ScalarKey { Blank, @@ -219,6 +230,18 @@ impl From<&Scalar> for ScalarKey { } } +/// The key a distinctness comparison uses: text folds to lower case, the model collation, so `"A"` +/// and `"a"` are one value. Every other type keeps its exact key. +/// +/// `DISTINCTCOUNT`, `DISTINCTCOUNTNOBLANK`, `VALUES`/`DISTINCT` and the storage dictionary all use +/// this, so a faithful model and a row-scanned one count the same values. +pub(crate) fn distinct_key(value: &Scalar) -> ScalarKey { + match value { + Scalar::String(text) => ScalarKey::String(text.to_lowercase()), + other => ScalarKey::from(other), + } +} + /// Maps an `f64` to a `u64` whose unsigned order matches numeric order. `-0.0` and `0.0` map to /// the same key, so `Ord` on [`ScalarKey`] sorts pivot groups numerically. fn order_bits(value: f64) -> u64 { diff --git a/crates/dax/tests/binder.rs b/crates/dax/tests/binder.rs index c40648d5e..95bb5100d 100644 --- a/crates/dax/tests/binder.rs +++ b/crates/dax/tests/binder.rs @@ -203,3 +203,33 @@ fn model_json_deserializes_and_parses_measures() { model.parse_formulas().expect("model parses"); assert!(model.measures[0].expr.is_some()); } + +#[test] +fn documented_keyword_arguments_bind_instead_of_resolving_as_names() { + let model = sample_model(); + // CROSSFILTER's direction words are documented enum values, including the two directional + // spellings; none of them may be resolved as a model name. + for direction in ["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"] { + let formula = format!("CROSSFILTER ( Sales[Region], Date[Date], {direction} )"); + match bind(&model, &formula) { + BoundExpr::Call { args, .. } => { + assert!(matches!(&args[2], BoundExpr::Keyword(word) if word.eq_ignore_ascii_case(direction)), "{direction}: {:?}", args[2]); + } + other => panic!("expected a call for {direction}, got {other:?}"), + } + } + // RANK/ROWNUMBER's Reset argument takes the same three words at the documented position. + for reset in ["NONE", "LOWESTPARENT", "HIGHESTPARENT"] { + let rank = + format!("RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )"); + assert!(matches!(bind(&model, &rank), BoundExpr::Call { .. }), "RANK should bind {reset}"); + let rownumber = + format!("ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )"); + assert!(matches!(bind(&model, &rownumber), BoundExpr::Call { .. }), "ROWNUMBER should bind {reset}"); + } + // RANKX's Order argument is `ASC`/`DESC`, not a name. + match bind(&model, "RANKX ( Sales, Sales[Amount], 42, DESC )") { + BoundExpr::Call { args, .. } => assert!(matches!(args[3], BoundExpr::Keyword(ref word) if word == "DESC"), "{:?}", args[3]), + other => panic!("expected a call, got {other:?}"), + } +} diff --git a/crates/dax/tests/eval_storage_differential.rs b/crates/dax/tests/eval_storage_differential.rs index 0b3e3579b..bbe6b2a0d 100644 --- a/crates/dax/tests/eval_storage_differential.rs +++ b/crates/dax/tests/eval_storage_differential.rs @@ -153,16 +153,20 @@ fn column_aggregates_match_documented_values() { assert_eq!(value, Scalar::Integer(7)); assert!(stats.aggregates > 0); - assert_eq!(eval(&model, "MIN(Sales[Amount])").0, Scalar::Decimal(10.0)); - assert_eq!(eval(&model, "MAX(Sales[Amount])").0, Scalar::Decimal(100.0)); + // MIN/MAX answer the winning value, so an Int64 column keeps its Integer type. + let (value, stats) = eval(&model, "MIN(Sales[Amount])"); + assert_eq!(value, Scalar::Integer(10)); + assert!(stats.aggregates > 0, "MIN must be served by storage, got {stats:?}"); + assert_eq!(eval(&model, "MAX(Sales[Amount])").0, Scalar::Integer(100)); // 100 * 50 * 30 * 70 * 20 * 10 = 2,100,000,000. assert_eq!(eval(&model, "PRODUCT(Sales[Amount])").0, Scalar::Decimal(2_100_000_000.0)); - // Currency is read in major units: MIN is 0.75 and MAX is 20.00 (Excel agrees). + // Currency is read in major units: MIN is 0.75 and MAX is 20.00 (Excel agrees), and the + // result stays currency — 7,500 and 200,000 in the internal ten-thousandths scale. let (value, stats) = eval(&model, "MIN(Product[UnitPrice])"); - assert_eq!(value, Scalar::Decimal(0.75)); + assert_eq!(value, Scalar::Currency(7_500)); assert!(stats.aggregates > 0); - assert_eq!(eval(&model, "MAX(Product[UnitPrice])").0, Scalar::Decimal(20.0)); + assert_eq!(eval(&model, "MAX(Product[UnitPrice])").0, Scalar::Currency(200_000)); } #[test] @@ -327,3 +331,65 @@ fn measures_evaluate_through_storage() { // derived iterator expressions stay row-based, so `iterators` is zero here). assert!(stats.aggregates >= 2 && stats.count_rows == 1 && stats.related > 0 && stats.related_table > 0, "{stats:?}"); } + +#[test] +fn pivot_blank_group_counts_orphan_fact_rows() { + // `Product` has an "Unknown" row whose key is BLANK. `Sales` has a row matching `Widget`, a + // row whose key has no `Product` at all, and a row whose key is BLANK. A relationship never + // joins a BLANK key, so the last two are orphans: they group as `(Blank)` and the BLANK cell + // must count them instead of showing zero. + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Product".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Name".into(), data_type: Some("String".into()) }, + ], + rows: vec![vec![Scalar::Integer(1), text("Widget")], vec![Scalar::Blank, text("Unknown")]], + }, + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(1), Scalar::Integer(10)], + vec![Scalar::Integer(99), Scalar::Integer(20)], + vec![Scalar::Blank, Scalar::Integer(40)], + ], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "ProductKey".into(), + to_table: "Product".into(), + to_column: "ProductKey".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![Measure { + name: "Total Amount".into(), + formula: "SUM(Sales[Amount])".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }], + }; + model.parse_formulas().expect("model parses"); + + let pivot = PivotTable::new("Sales by product", "Total Amount") + .with_row_fields(vec!["Product[Name]".into()]) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let (table, stats) = pivot.render_with_stats(&model).expect("render pivot"); + + // (Blank) 60 = the orphan key 99 (20) plus the BLANK key (40); Widget 10; total 70. + assert_eq!(table.rows.len(), 3, "{:?}", table.rows); + assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Decimal(60.0)]); + assert_eq!(table.rows[1], vec![text("Widget"), Scalar::Decimal(10.0)]); + assert_eq!(table.rows[2], vec![text("Grand Total"), Scalar::Decimal(70.0)]); + // Every cell was answered from the columns, so both sides read the same relationship indexes. + assert!(stats.aggregates > 0, "each pivot cell is a storage aggregate, got {stats:?}"); +} diff --git a/crates/dax/tests/eval_storage_fallback.rs b/crates/dax/tests/eval_storage_fallback.rs index 7b57712f1..37dbf8e73 100644 --- a/crates/dax/tests/eval_storage_fallback.rs +++ b/crates/dax/tests/eval_storage_fallback.rs @@ -30,7 +30,8 @@ fn single_table(name: &str, columns: &[(&str, &str)], rows: Vec>) -> #[test] fn ragged_rows_keep_the_row_scan_semantics() { - // Row 0 only supplies A; the missing B cell is a row the columnar copy would blank-extend. + // Row 0 only supplies A; the missing B cell is padded to BLANK, the same value the columnar + // copy and the integrity check read, so both paths agree. let model = single_table("Sales", &[("A", "Int64"), ("B", "Int64")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2), Scalar::Integer(3)]]); let evaluator = Evaluator::new(&model).expect("evaluator"); @@ -39,9 +40,12 @@ fn ragged_rows_keep_the_row_scan_semantics() { let expr = parse_expression("SUM(Sales[B])").expect("parse"); let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); - // `TableValue::column` skips a row shorter than the requested column, so only row 1 counts. + // BLANK contributes nothing to SUM, so only row 1 counts. assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(3.0)); assert_eq!(eval(&model, "COUNTROWS(Sales)"), Scalar::Integer(2)); + // The padded cell is a real BLANK for the filter and for `VALUES`, instead of vanishing. + assert_eq!(eval(&model, "CALCULATE(COUNTROWS(Sales), Sales[B] = 3)"), Scalar::Integer(1)); + assert_eq!(eval(&model, "COUNTROWS(VALUES(Sales[B]))"), Scalar::Integer(2)); assert!(evaluator.storage_stats().row_scan_fallbacks > 0, "{:?}", evaluator.storage_stats()); } diff --git a/crates/dax/tests/evaluator.rs b/crates/dax/tests/evaluator.rs index c331b1c69..d99fb5f36 100644 --- a/crates/dax/tests/evaluator.rs +++ b/crates/dax/tests/evaluator.rs @@ -539,3 +539,87 @@ fn pivot_cross_puts_column_groups_in_columns() { assert_eq!(table.rows[0][1], Scalar::Blank); assert_eq!(table.rows[0][2], Scalar::Decimal(40.0)); } + +#[test] +fn text_is_not_compared_with_numbers() { + // DAX refuses to compare text with a number, so `=` answers FALSE instead of coercing "3". + assert_eq!(eval("\"3\" = 3"), Scalar::Boolean(false)); + assert_eq!(eval("\"3\" = \"3\""), Scalar::Boolean(true)); + // `IN` is DAX equality rather than representation equality: numbers compare by value across + // variants and text ignores case, while BLANK still matches only BLANK. + assert_eq!(eval("2 IN {2.0}"), Scalar::Boolean(true)); + assert_eq!(eval("\"a\" IN {\"A\"}"), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() IN {BLANK()}"), Scalar::Boolean(true)); + assert_eq!(eval("1 IN {2.0, 3.0}"), Scalar::Boolean(false)); +} + +#[test] +fn distinct_count_folds_text_case() { + let mut model = DataModel { + tables: vec![ModelTable { + name: "Labels".into(), + columns: vec![ModelColumn { name: "Name".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("a".into())], vec![Scalar::String("B".into())], vec![Scalar::Blank]], + }], + ..DataModel::default() + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let evaluate = |src: &str| { + let bound = Binder::new(&model).bind_expression(&parse_expression(src).expect("parse")).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") + }; + // The model collation is case-insensitive: A/a are one value, and BLANK counts as one more. + assert_eq!(evaluate("DISTINCTCOUNT(Labels[Name])"), Scalar::Integer(3)); + // VALUES reports the same distinct set, keeping the first spelling it saw. + let bound = Binder::new(&model).bind_expression(&parse_expression("VALUES(Labels[Name])").expect("parse")).expect("bind"); + let table = evaluator.evaluate_table(&bound).expect("values"); + assert_eq!(table.rows, vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())], vec![Scalar::Blank]]); +} + +#[test] +fn the_blank_member_keeps_orphan_fact_rows() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(10), Scalar::String("A".into())], + // No Products row: an orphan key belongs to Products' BLANK member. + vec![Scalar::Integer(20), Scalar::String("Orphan".into())], + ], + }, + ModelTable { + name: "Products".into(), + columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("A".into())]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Product".into(), + to_table: "Products".into(), + to_column: "Product".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }], + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let bound = Binder::new(&model).bind_expression(&parse_expression("[Total]").expect("parse")).expect("bind"); + + // The BLANK member of Products carries the rows that do not join, so the total is 20, not 0. + let mut filters = FilterContext::default(); + filters.set(1, 0, [gridcraft_dax::ScalarKey::Blank]); + assert_eq!(evaluator.evaluate_with(&bound, filters).expect("blank member"), Scalar::Decimal(20.0)); + + // A concrete member still sees only its own rows: the orphan stays out of `"A"`. + let mut filters = FilterContext::default(); + filters.set(1, 0, [gridcraft_dax::ScalarKey::String("A".into())]); + assert_eq!(evaluator.evaluate_with(&bound, filters).expect("matched member"), Scalar::Decimal(10.0)); +}