Skip to main content

schema_sql_generator/common/
aggregation_sql.rs

1use schema_model::model::aggregation::{Aggregation, AggregationColumn, AggregationType};
2use schema_model::model::table::Table;
3use schema_model::model::types::DatabaseType;
4
5/// Schema-qualifies an aggregation's destination table with the source table's schema when
6/// the XML names it bare; a name that already contains a `.` is used as written.
7pub fn destination_table_name(
8    database_type: DatabaseType,
9    table: &Table,
10    aggregation: &Aggregation,
11) -> String {
12    let destination = aggregation.destination_table();
13    if destination.contains('.') {
14        destination.to_string()
15    } else {
16        database_type.qualified_name(table.schema_name(), destination)
17    }
18}
19
20/// The value a source row contributes to an aggregation column: a count contributes `1`
21/// per row, a sum contributes the (null-as-zero) source column.
22pub fn row_value(column: &AggregationColumn) -> String {
23    match column.aggregation_type() {
24        AggregationType::Count => "1".to_string(),
25        AggregationType::Sum => format!("coalesce({}, 0)", column.source_column()),
26    }
27}
28
29/// The criteria as a parenthesised predicate, or `None` when absent/blank.
30pub fn criteria_predicate(aggregation: &Aggregation) -> Option<String> {
31    aggregation
32        .criteria()
33        .map(str::trim)
34        .filter(|c| !c.is_empty())
35        .map(|c| format!("({})", c))
36}
37
38/// Source columns whose change can alter an aggregation's contribution, or `None` when that
39/// can't be known (the free-form criteria may read any column), in which case an update must
40/// always be re-aggregated. A group's `sourceDerivedFrom` names the column its (possibly
41/// expression-valued) `source` is derived from.
42pub fn watched_columns(aggregation: &Aggregation) -> Option<Vec<String>> {
43    if criteria_predicate(aggregation).is_some() {
44        return None;
45    }
46
47    let mut columns: Vec<String> = Vec::new();
48    for column in aggregation.aggregation_columns() {
49        if column.aggregation_type() == AggregationType::Sum {
50            columns.push(column.source_column().to_string());
51        }
52    }
53    for group in aggregation.aggregation_groups() {
54        match group.source_derived_from().map(str::trim) {
55            Some(derived) if !derived.is_empty() => columns.push(derived.to_string()),
56            _ => columns.push(group.source().to_string()),
57        }
58    }
59    columns.push(aggregation.date_column().to_string());
60    Some(columns)
61}