Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/native-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ At least one of `table`, `sql`, or `source_uri` should be present unless the mod
| `required_filters` | No | Fields that every query using the model must filter. Enforced by Python-hosted clients before Python or Rust compilation. |
| `required_filters_or_groups` | No | Fields that every query using the model must filter or group by, independently for each listed field. |
| `pre_aggregations` | No | List of pre-aggregation definitions. |
| `default_time_dimension` | No | Time dimension the Python generator adds to every query of this model's metrics that does not already group by one of the model's time dimensions. |
| `default_time_dimension` | No | Time dimension a structured query is grouped by when it selects metrics and no dimensions, and the time axis of cumulative, time-comparison and offset-ratio metrics that select none. Ordinary aggregates in a query with its own dimensions, or in a SQL `SELECT`, are never grouped by it. |
| `default_grain` | No | Default time grain for the default time dimension. |
| `freshness` | No | Source freshness policy for live chart/dashboard runtimes. |
| `security` | No | Row/access `SecurityPolicy` (`access` gate + `row_filters`) enforced per query when `user_attributes` are supplied. See [Security](security.md). |
Expand Down
9 changes: 9 additions & 0 deletions sidemantic-rs/src/core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,15 @@ impl Metric {
pub fn is_simple_aggregation(&self) -> bool {
self.r#type == MetricType::Simple && self.agg.is_some()
}

/// Whether this metric can only be evaluated over a time dimension in the
/// grouping: running totals, period comparisons and offset ratios.
pub fn requires_time_axis(&self) -> bool {
matches!(
self.r#type,
MetricType::Cumulative | MetricType::TimeComparison
) || (self.r#type == MetricType::Ratio && self.offset_window.is_some())
}
}

/// Relationship type between models
Expand Down
23 changes: 22 additions & 1 deletion sidemantic-rs/src/semantic_input/policies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,28 @@ fn check_visibility(
}
}
}
if !query.skip_default_time_dimensions {
// A query that names its own grain receives a default time dimension only
// for metrics needing a time axis. Stay conservative: once any selected
// metric needs one, check every metric model's default.
let grain_is_explicit = query.explicit_projection || !query.dimensions.is_empty();
let selects_time_axis_metric = || {
query.metrics.iter().any(|reference| {
if let Some(metric) = graph.get_metric(reference) {
return metric.requires_time_axis();
}
let (owners, name): (Vec<&str>, &str) = match reference.split_once('.') {
Some((model, name)) => (vec![model], name),
None => (candidates.iter().map(String::as_str).collect(), reference),
};
owners.into_iter().any(|model| {
graph
.get_model(model)
.and_then(|model| model.get_metric(name))
.is_some_and(|metric| metric.requires_time_axis())
})
})
};
if !query.skip_default_time_dimensions && (!grain_is_explicit || selects_time_axis_metric()) {
for model in metric_models {
if let Some(default_time) = graph
.get_model(model)
Expand Down
116 changes: 98 additions & 18 deletions sidemantic-rs/src/sql/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ pub struct SemanticQuery {
pub preagg_database: Option<String>,
pub preagg_schema: Option<String>,
pub skip_default_time_dimensions: bool,
/// The caller's projection is complete, as in a SQL SELECT list. A model's
/// default time dimension is then added only for a metric that needs a
/// time axis, never as a grouping key for ordinary aggregates.
pub explicit_projection: bool,
pub aliases: HashMap<String, String>,
pub timezone: Option<String>,
pub with_totals: bool,
Expand Down Expand Up @@ -274,7 +278,11 @@ impl<'a> SqlGenerator<'a> {
let effective_dimensions = if query.skip_default_time_dimensions {
query.dimensions.clone()
} else {
self.apply_default_time_dimensions(&query.metrics, &query.dimensions)?
self.apply_default_time_dimensions(
&query.metrics,
&query.dimensions,
query.explicit_projection,
)?
};

// Parse all references
Expand Down Expand Up @@ -1165,7 +1173,11 @@ impl<'a> SqlGenerator<'a> {
let effective_dimensions = if query.skip_default_time_dimensions {
query.dimensions.clone()
} else {
self.apply_default_time_dimensions(&query.metrics, &query.dimensions)?
self.apply_default_time_dimensions(
&query.metrics,
&query.dimensions,
query.explicit_projection,
)?
};
let dimension_refs = self.parse_dimension_refs(&effective_dimensions)?;
let metric_refs = self.parse_metric_refs(&query.metrics)?;
Expand Down Expand Up @@ -4397,11 +4409,21 @@ impl<'a> SqlGenerator<'a> {
value.replace('\'', "''")
}

/// Add each selected metric model's default time dimension, at its default
/// grain, unless a time dimension of that model is already selected.
///
/// A metrics-only query takes its grain from the default. A query that
/// names its own dimensions, or whose projection is fixed by the caller
/// (`explicit_projection`), keeps exactly that grain for ordinary
/// aggregates: grouping them by a time dimension nobody selected splits
/// their totals. Metrics that need a time axis always receive it.
fn apply_default_time_dimensions(
&self,
metrics: &[String],
dimensions: &[String],
explicit_projection: bool,
) -> Result<Vec<String>> {
let grain_is_explicit = explicit_projection || !dimensions.is_empty();
let mut result = dimensions.to_vec();
let mut models_with_time_dims: HashSet<String> = HashSet::new();

Expand All @@ -4425,22 +4447,34 @@ impl<'a> SqlGenerator<'a> {
// Graph calculations are scalar unless dimensions were requested.
// Only cumulative graph metrics inherit a dependency's time grain
// because their window needs an ordering dimension.
if self
.graph
.get_metric(metric_ref)
.is_some_and(|metric| metric.r#type != MetricType::Cumulative)
{
let graph_metric = self.graph.get_metric(metric_ref);
if graph_metric.is_some_and(|metric| metric.r#type != MetricType::Cumulative) {
continue;
}
let model_name =
if let Some((model_name, _, _)) = self.exact_metric_reference(metric_ref)? {
model_name
} else {
if !metric_ref.contains('.') {
continue;
}
self.graph.parse_reference(metric_ref)?.0
};
let (model_name, metric_name) = if let Some((model_name, metric_name, _)) =
self.exact_metric_reference(metric_ref)?
{
(model_name, metric_name)
} else {
if !metric_ref.contains('.') {
continue;
}
let (model_name, metric_name, _) = self.graph.parse_reference(metric_ref)?;
(model_name, metric_name)
};

// Checked per metric, before the model is marked as handled: an
// ordinary aggregate must not hide a sibling that needs the axis.
if grain_is_explicit {
let metric = graph_metric.or_else(|| {
self.graph
.get_model(&model_name)
.and_then(|model| model.get_metric(&metric_name))
});
if !metric.is_some_and(Metric::requires_time_axis) {
continue;
}
}

if !seen_models.insert(model_name.clone()) {
continue;
Expand Down Expand Up @@ -7148,12 +7182,12 @@ mod tests {
graph.set_metric_scopes(HashMap::new()).unwrap();
let generator = SqlGenerator::new(&graph);
assert!(generator
.apply_default_time_dimensions(&["total_revenue".into()], &[])
.apply_default_time_dimensions(&["total_revenue".into()], &[], false)
.unwrap()
.is_empty());
assert_eq!(
generator
.apply_default_time_dimensions(&["orders.revenue".into()], &[])
.apply_default_time_dimensions(&["orders.revenue".into()], &[], false)
.unwrap(),
vec!["orders.day__day"]
);
Expand All @@ -7164,6 +7198,52 @@ mod tests {
assert!(!sql.contains("DATE_TRUNC"), "{sql}");
}

#[test]
fn default_time_dimension_never_regroups_an_explicit_grain() {
let mut graph = SemanticGraph::new();
let mut model = Model::new("orders", "id")
.with_table("orders")
.with_dimension(Dimension::time("day"))
.with_dimension(Dimension::categorical("status"))
.with_metric(Metric::sum("revenue", "amount"))
.with_metric(Metric::cumulative("running_revenue", "revenue"));
model.default_time_dimension = Some("day".into());
graph.add_model(model).unwrap();
let generator = SqlGenerator::new(&graph);
let status = vec!["orders.status".to_string()];
let defaults = |metrics: &[&str], dimensions: &[String], explicit_projection| {
let metrics: Vec<String> = metrics.iter().map(|metric| metric.to_string()).collect();
generator
.apply_default_time_dimensions(&metrics, dimensions, explicit_projection)
.unwrap()
};

// Selected dimensions are the whole grain of an ordinary aggregate.
assert_eq!(defaults(&["orders.revenue"], &status, false), status);
// A SQL projection is complete even when it lists no dimension.
assert!(defaults(&["orders.revenue"], &[], true).is_empty());
// A running total still needs its time axis, also behind a sibling.
for metrics in [
vec!["orders.running_revenue"],
vec!["orders.revenue", "orders.running_revenue"],
] {
assert_eq!(
defaults(&metrics, &status, false),
vec!["orders.status", "orders.day"]
);
assert_eq!(defaults(&metrics, &[], true), vec!["orders.day"]);
}

let sql = generator
.generate(
&SemanticQuery::new()
.with_metrics(vec!["orders.revenue".into()])
.with_dimensions(status),
)
.unwrap();
assert!(!sql.contains("day"), "{sql}");
}

#[test]
fn computed_time_key_projection_applies_grain_and_timezone() {
let mut dimension = Dimension::time("event_time").with_sql("CAST(raw_time AS TIMESTAMP)");
Expand Down
11 changes: 8 additions & 3 deletions sidemantic-rs/src/sql/generator/aggregate_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,8 +681,11 @@ pub(super) fn try_generate(
// Defaults belong to selected model metric references, not every source
// discovered while expanding graph calculations. Resolve them once for
// the whole query before creating independent aggregate children.
effective_query.dimensions =
generator.apply_default_time_dimensions(&query.metrics, &query.dimensions)?;
effective_query.dimensions = generator.apply_default_time_dimensions(
&query.metrics,
&query.dimensions,
query.explicit_projection,
)?;
effective_query.skip_default_time_dimensions = true;
&effective_query
} else {
Expand Down Expand Up @@ -1778,12 +1781,14 @@ mod tests {
true,
true,
),
// Selected dimensions are the whole grain: no other source's
// default joins them.
(
vec!["orders.revenue", "customers.customer_count"],
vec!["orders.ordered_at__day"],
false,
false,
true,
false,
),
(
vec!["orders.revenue", "customers.customer_count"],
Expand Down
6 changes: 5 additions & 1 deletion sidemantic-rs/src/sql/generator/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ impl SqlGenerator<'_> {
}
default_metrics.push(reference.clone());
}
self.apply_default_time_dimensions(&default_metrics, &query.dimensions)?
self.apply_default_time_dimensions(
&default_metrics,
&query.dimensions,
query.explicit_projection,
)?
};
let mut fields = Vec::new();
for (reference, dimension) in dimensions
Expand Down
6 changes: 5 additions & 1 deletion sidemantic-rs/src/sql/generator/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,11 @@ pub(super) fn try_generate(
let dimensions = if query.skip_default_time_dimensions {
query.dimensions.clone()
} else {
generator.apply_default_time_dimensions(&query.metrics, &query.dimensions)?
generator.apply_default_time_dimensions(
&query.metrics,
&query.dimensions,
query.explicit_projection,
)?
};
let output_dimensions = generator.parse_dimension_refs(&dimensions)?;
let mut raw_dimensions = dimensions.clone();
Expand Down
27 changes: 27 additions & 0 deletions sidemantic-rs/src/sql/rewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,33 @@ mod tests {
assert!(rewritten.contains("GROUP BY"));
}

#[test]
fn default_time_dimension_is_not_a_hidden_group_key() {
let mut graph = SemanticGraph::new();
let mut orders = Model::new("orders", "order_id")
.with_table("public.orders")
.with_dimension(Dimension::categorical("status"))
.with_dimension(Dimension::time("order_date").with_sql("created_at"))
.with_metric(Metric::sum("revenue", "amount"));
orders.default_time_dimension = Some("order_date".into());
graph.add_model(orders).unwrap();
let rewriter = QueryRewriter::new(&graph);

// The SELECT list is the whole projection, so neither query may be
// grouped by a default time dimension that it does not return.
let scalar = rewriter
.rewrite("SELECT orders.revenue FROM orders")
.unwrap();
assert!(!scalar.contains("GROUP BY"), "{scalar}");
assert!(!scalar.contains("created_at"), "{scalar}");

let grouped = rewriter
.rewrite("SELECT orders.status, orders.revenue FROM orders")
.unwrap();
assert!(grouped.contains("GROUP BY"), "{grouped}");
assert!(!grouped.contains("created_at"), "{grouped}");
}

#[test]
fn source_normalization_and_rewrite_work_on_standard_test_stack() {
// This test deliberately uses the ordinary harness thread. The input
Expand Down
8 changes: 7 additions & 1 deletion sidemantic-rs/src/sql/rewriter/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,9 +465,15 @@ impl QueryRewriter<'_> {
vec![(base.clone(), alias.unwrap_or_else(|| base.clone()))]
});
let join_filters = self.bind_explicit_joins(&select.joins, &mut sources)?;
// The SELECT list is the whole projection; a model's default time
// dimension must not become a grouping key the result never shows.
let query = SemanticQuery {
explicit_projection: true,
..SemanticQuery::new()
};
let mut bindings = Bindings {
graph: self.graph.clone(),
query: SemanticQuery::new(),
query,
sources,
base,
references: HashMap::new(),
Expand Down
Loading
Loading