1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use crate::{
    join_utils::{compute_aggr_join, AggregationType, AliasedJoin},
    Context,
};
use quaint::prelude::*;
use query_structure::VirtualSelection;

#[derive(Debug)]
pub(crate) struct RelAggregationJoins {
    // Joins necessary to perform the relation aggregations
    pub(crate) joins: Vec<AliasedJoin>,
    // Aggregator columns
    pub(crate) columns: Vec<Expression<'static>>,
}

pub(crate) fn build<'a>(
    virtual_selections: impl IntoIterator<Item = &'a VirtualSelection>,
    ctx: &Context<'_>,
) -> RelAggregationJoins {
    let mut joins = vec![];
    let mut columns: Vec<Expression<'static>> = vec![];

    for (index, selection) in virtual_selections.into_iter().enumerate() {
        match selection {
            VirtualSelection::RelationCount(rf, filter) => {
                let join_alias = format!("aggr_selection_{index}");
                let aggregator_alias = selection.db_alias();
                let join = compute_aggr_join(
                    rf,
                    AggregationType::Count,
                    filter.clone(),
                    aggregator_alias.as_str(),
                    join_alias.as_str(),
                    None,
                    ctx,
                );

                columns.push(Column::from((join.alias.clone(), aggregator_alias)).into());
                joins.push(join);
            }
        }
    }

    RelAggregationJoins { joins, columns }
}