gitql_std/
aggregation.rs

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::cmp::Ordering;
use std::collections::HashMap;
use std::sync::OnceLock;

use gitql_ast::types::any::AnyType;
use gitql_ast::types::boolean::BoolType;
use gitql_ast::types::date::DateType;
use gitql_ast::types::datetime::DateTimeType;
use gitql_ast::types::dynamic::DynamicType;
use gitql_ast::types::float::FloatType;
use gitql_ast::types::integer::IntType;
use gitql_ast::types::null::NullType;
use gitql_ast::types::optional::OptionType;
use gitql_ast::types::text::TextType;
use gitql_ast::types::time::TimeType;
use gitql_ast::types::varargs::VarargsType;
use gitql_ast::types::variant::VariantType;
use gitql_core::signature::AggregationFunction;
use gitql_core::signature::Signature;
use gitql_core::values::array::ArrayValue;
use gitql_core::values::base::Value;
use gitql_core::values::boolean::BoolValue;
use gitql_core::values::integer::IntValue;
use gitql_core::values::null::NullValue;
use gitql_core::values::text::TextValue;

use crate::meta_types::array_of_type;
use crate::meta_types::first_element_type;

pub fn aggregation_functions() -> &'static HashMap<&'static str, AggregationFunction> {
    static HASHMAP: OnceLock<HashMap<&'static str, AggregationFunction>> = OnceLock::new();
    HASHMAP.get_or_init(|| {
        let mut map: HashMap<&'static str, AggregationFunction> = HashMap::new();
        map.insert("max", aggregation_max);
        map.insert("min", aggregation_min);
        map.insert("sum", aggregation_sum);
        map.insert("avg", aggregation_average);
        map.insert("count", aggregation_count);
        map.insert("group_concat", aggregation_group_concat);
        map.insert("bool_and", aggregation_bool_and);
        map.insert("bool_or", aggregation_bool_or);
        map.insert("bit_and", aggregation_bit_and);
        map.insert("bit_or", aggregation_bit_or);
        map.insert("bit_xor", aggregation_bit_xor);
        map.insert("array_agg", aggregation_array_agg);
        map
    })
}

pub fn aggregation_function_signatures() -> HashMap<&'static str, Signature> {
    let mut map: HashMap<&'static str, Signature> = HashMap::new();
    map.insert(
        "max",
        Signature {
            parameters: vec![Box::new(VariantType {
                variants: vec![
                    Box::new(IntType),
                    Box::new(FloatType),
                    Box::new(TextType),
                    Box::new(DateType),
                    Box::new(TimeType),
                    Box::new(DateTimeType),
                ],
            })],
            return_type: Box::new(DynamicType {
                function: first_element_type,
            }),
        },
    );
    map.insert(
        "min",
        Signature {
            parameters: vec![Box::new(VariantType {
                variants: vec![
                    Box::new(IntType),
                    Box::new(FloatType),
                    Box::new(TextType),
                    Box::new(DateType),
                    Box::new(TimeType),
                    Box::new(DateTimeType),
                ],
            })],
            return_type: Box::new(DynamicType {
                function: first_element_type,
            }),
        },
    );
    map.insert(
        "sum",
        Signature {
            parameters: vec![Box::new(IntType)],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "avg",
        Signature {
            parameters: vec![Box::new(IntType)],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "count",
        Signature {
            parameters: vec![Box::new(OptionType {
                base: Some(Box::new(AnyType)),
            })],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "group_concat",
        Signature {
            parameters: vec![Box::new(VarargsType {
                base: Box::new(AnyType),
            })],
            return_type: Box::new(TextType),
        },
    );
    map.insert(
        "bool_and",
        Signature {
            parameters: vec![Box::new(BoolType)],
            return_type: Box::new(BoolType),
        },
    );
    map.insert(
        "bool_or",
        Signature {
            parameters: vec![Box::new(BoolType)],
            return_type: Box::new(BoolType),
        },
    );
    map.insert(
        "bit_and",
        Signature {
            parameters: vec![Box::new(IntType)],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "bit_or",
        Signature {
            parameters: vec![Box::new(IntType)],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "bit_xor",
        Signature {
            parameters: vec![Box::new(IntType)],
            return_type: Box::new(IntType),
        },
    );
    map.insert(
        "array_agg",
        Signature {
            parameters: vec![Box::new(AnyType)],
            return_type: Box::new(DynamicType {
                function: |elements| array_of_type(first_element_type(elements)),
            }),
        },
    );
    map
}

pub fn aggregation_max(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut max_value = &group_values[0][0];
    for row_values in group_values {
        let single_value = &row_values[0];
        if max_value.compare(single_value) == Some(Ordering::Less) {
            max_value = single_value;
        }
    }
    max_value.clone()
}

pub fn aggregation_min(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut min_value = &group_values[0][0];
    for row_values in group_values {
        let single_value = &row_values[0];
        if min_value.compare(single_value) == Some(Ordering::Greater) {
            min_value = single_value;
        }
    }
    min_value.clone()
}

pub fn aggregation_sum(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut sum: i64 = 0;
    for row_values in group_values {
        if let Some(int_value) = row_values[0].as_any().downcast_ref::<IntValue>() {
            sum += int_value.value;
        }
    }
    Box::new(IntValue { value: sum })
}

pub fn aggregation_average(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut sum: i64 = 0;
    for row_values in group_values {
        if let Some(int_value) = row_values[0].as_any().downcast_ref::<IntValue>() {
            sum += int_value.value;
        }
    }
    let count: i64 = group_values[0].len().try_into().unwrap();
    Box::new(IntValue { value: sum / count })
}

pub fn aggregation_count(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    Box::new(IntValue {
        value: group_values.len() as i64,
    })
}

pub fn aggregation_group_concat(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut string_values: Vec<String> = vec![];
    for row_values in group_values {
        for value in row_values {
            string_values.push(value.literal());
        }
    }
    Box::new(TextValue {
        value: string_values.concat(),
    })
}

pub fn aggregation_bool_and(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    for row_values in group_values {
        if let Some(bool_value) = row_values[0].as_any().downcast_ref::<BoolValue>() {
            if !bool_value.value {
                return Box::new(BoolValue { value: false });
            }
        }
    }
    Box::new(BoolValue { value: true })
}

pub fn aggregation_bool_or(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    for row_values in group_values {
        if let Some(bool_value) = row_values[0].as_any().downcast_ref::<BoolValue>() {
            if bool_value.value {
                return Box::new(BoolValue { value: true });
            }
        }
    }
    Box::new(BoolValue { value: false })
}

pub fn aggregation_bit_and(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut value: i64 = 1;
    let mut has_non_null = false;
    for row_values in group_values {
        if row_values[0].data_type().is_null() {
            continue;
        }

        if let Some(int_value) = row_values[0].as_any().downcast_ref::<IntValue>() {
            value &= int_value.value;
            has_non_null = true;
        }
    }

    if has_non_null {
        Box::new(IntValue { value })
    } else {
        Box::new(NullValue)
    }
}

pub fn aggregation_bit_or(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut value: i64 = 0;
    let mut has_non_null = false;
    for row_values in group_values {
        if row_values[0].data_type().is_null() {
            continue;
        }

        if let Some(int_value) = row_values[0].as_any().downcast_ref::<IntValue>() {
            value |= int_value.value;
            has_non_null = true;
        }
    }

    if has_non_null {
        Box::new(IntValue { value })
    } else {
        Box::new(NullValue)
    }
}

pub fn aggregation_bit_xor(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut value: i64 = 0;
    let mut has_non_null = false;
    for row_values in group_values {
        if row_values[0].data_type().is_null() {
            continue;
        }

        if let Some(int_value) = row_values[0].as_any().downcast_ref::<IntValue>() {
            value ^= int_value.value;
            has_non_null = true;
        }
    }

    if has_non_null {
        Box::new(IntValue { value })
    } else {
        Box::new(NullValue)
    }
}

pub fn aggregation_array_agg(group_values: &[Vec<Box<dyn Value>>]) -> Box<dyn Value> {
    let mut array: Vec<Box<dyn Value>> = vec![];
    for row_values in group_values {
        array.push(row_values[0].clone());
    }

    let element_type = if array.is_empty() {
        Box::new(NullType)
    } else {
        array[0].data_type()
    };

    Box::new(ArrayValue {
        values: array,
        base_type: element_type,
    })
}