qualia_core_db/sparql_library/
sparql_aggregates.rs1use crate::sparql_ast::*;
6
7#[repr(C)]
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum AggregateFunction {
11 Count,
12 Sum,
13 Avg,
14 Min,
15 Max,
16}
17
18#[repr(C)]
20#[derive(Debug, Clone, Copy)]
21pub struct AggregateAccumulator {
22 pub func: AggregateFunction,
23 pub count: u64,
24 pub sum: u64,
25 pub min: u64,
26 pub max: u64,
27 pub initialized: bool,
28}
29
30impl AggregateAccumulator {
31 pub fn new(func: AggregateFunction) -> Self {
33 Self {
34 func,
35 count: 0,
36 sum: 0,
37 min: u64::MAX,
38 max: 0,
39 initialized: false,
40 }
41 }
42
43 pub fn add_value(&mut self, value: u64) {
45 self.count += 1;
46
47 match self.func {
48 AggregateFunction::Count => {
49 }
51 AggregateFunction::Sum => {
52 self.sum = self.sum.wrapping_add(value);
53 }
54 AggregateFunction::Avg => {
55 self.sum = self.sum.wrapping_add(value);
56 }
57 AggregateFunction::Min => {
58 if !self.initialized || value < self.min {
59 self.min = value;
60 self.initialized = true;
61 }
62 }
63 AggregateFunction::Max => {
64 if !self.initialized || value > self.max {
65 self.max = value;
66 self.initialized = true;
67 }
68 }
69 }
70 }
71
72 pub fn get_result(&self) -> Option<u64> {
74 if self.count == 0 {
75 return None;
76 }
77
78 match self.func {
79 AggregateFunction::Count => Some(self.count),
80 AggregateFunction::Sum => Some(self.sum),
81 AggregateFunction::Avg => {
82 if self.count > 0 {
83 Some(self.sum / self.count)
84 } else {
85 None
86 }
87 }
88 AggregateFunction::Min => {
89 if self.initialized {
90 Some(self.min)
91 } else {
92 None
93 }
94 }
95 AggregateFunction::Max => {
96 if self.initialized {
97 Some(self.max)
98 } else {
99 None
100 }
101 }
102 }
103 }
104}
105
106#[repr(C)]
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub struct GroupKey {
110 pub values: [u64; MAX_VARIABLES],
111 pub var_count: u8,
112}
113
114impl GroupKey {
115 pub fn new() -> Self {
117 Self {
118 values: [0; MAX_VARIABLES],
119 var_count: 0,
120 }
121 }
122
123 pub fn set(&mut self, var_id: VariableId, value: u64) {
125 if (var_id as usize) < MAX_VARIABLES {
126 self.values[var_id as usize] = value;
127 self.var_count = self.var_count.max(var_id + 1);
128 }
129 }
130}
131
132impl Default for GroupKey {
133 fn default() -> Self {
134 Self::new()
135 }
136}
137
138#[repr(C)]
140pub struct AggregationContext {
141 pub groups: [(GroupKey, [AggregateAccumulator; 16]); 64], pub group_count: u8,
143 pub aggregates_spec: [crate::sparql_planner::AggregateSpec; 16],
144 pub aggregate_count: u8,
145}
146
147impl AggregationContext {
148 pub fn new(
150 aggregates_spec: &[crate::sparql_planner::AggregateSpec],
151 aggregate_count: u8,
152 ) -> Self {
153 let mut default_accumulators = [AggregateAccumulator::new(AggregateFunction::Count); 16];
154 for i in 0..aggregate_count as usize {
155 let func = match aggregates_spec[i].func {
156 0 => AggregateFunction::Count,
157 1 => AggregateFunction::Sum,
158 2 => AggregateFunction::Avg,
159 3 => AggregateFunction::Min,
160 4 => AggregateFunction::Max,
161 _ => AggregateFunction::Count,
162 };
163 default_accumulators[i] = AggregateAccumulator::new(func);
164 }
165
166 let mut specs = [crate::sparql_planner::AggregateSpec {
167 func: 0,
168 input_var: 0,
169 output_var: 0,
170 }; 16];
171 if aggregate_count > 0 {
172 specs[..aggregate_count as usize]
173 .copy_from_slice(&aggregates_spec[..aggregate_count as usize]);
174 }
175
176 Self {
177 groups: [(GroupKey::new(), default_accumulators); 64],
178 group_count: 0,
179 aggregates_spec: specs,
180 aggregate_count,
181 }
182 }
183
184 pub fn find_or_create_group(&mut self, key: GroupKey) -> Result<usize, String> {
186 for i in 0..self.group_count as usize {
188 if self.groups[i].0 == key {
189 return Ok(i);
190 }
191 }
192
193 if self.group_count >= 64 {
194 return Err("Group overflow".to_string());
195 }
196
197 let idx = self.group_count as usize;
198 let mut accumulators = [AggregateAccumulator::new(AggregateFunction::Count); 16];
199 for i in 0..self.aggregate_count as usize {
200 let func = match self.aggregates_spec[i].func {
201 0 => AggregateFunction::Count,
202 1 => AggregateFunction::Sum,
203 2 => AggregateFunction::Avg,
204 3 => AggregateFunction::Min,
205 4 => AggregateFunction::Max,
206 _ => AggregateFunction::Count,
207 };
208 accumulators[i] = AggregateAccumulator::new(func);
209 }
210 self.groups[idx] = (key, accumulators);
211 self.group_count += 1;
212 Ok(idx)
213 }
214
215 pub fn add_values_to_group(&mut self, group_idx: usize, row: &BindingRow) {
217 for i in 0..self.aggregate_count as usize {
218 let spec = &self.aggregates_spec[i];
219 if spec.func == 0 {
220 self.groups[group_idx].1[i].add_value(0);
222 } else if let Some(val) = row.get(spec.input_var) {
223 self.groups[group_idx].1[i].add_value(val);
224 }
225 }
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn test_count_aggregate() {
235 let mut agg = AggregateAccumulator::new(AggregateFunction::Count);
236 agg.add_value(1);
237 agg.add_value(2);
238 agg.add_value(3);
239
240 assert_eq!(agg.get_result(), Some(3));
241 }
242
243 #[test]
244 fn test_sum_aggregate() {
245 let mut agg = AggregateAccumulator::new(AggregateFunction::Sum);
246 agg.add_value(1);
247 agg.add_value(2);
248 agg.add_value(3);
249
250 assert_eq!(agg.get_result(), Some(6));
251 }
252
253 #[test]
254 fn test_avg_aggregate() {
255 let mut agg = AggregateAccumulator::new(AggregateFunction::Avg);
256 agg.add_value(1);
257 agg.add_value(2);
258 agg.add_value(3);
259
260 assert_eq!(agg.get_result(), Some(2));
261 }
262
263 #[test]
264 fn test_min_aggregate() {
265 let mut agg = AggregateAccumulator::new(AggregateFunction::Min);
266 agg.add_value(5);
267 agg.add_value(2);
268 agg.add_value(8);
269
270 assert_eq!(agg.get_result(), Some(2));
271 }
272
273 #[test]
274 fn test_max_aggregate() {
275 let mut agg = AggregateAccumulator::new(AggregateFunction::Max);
276 agg.add_value(5);
277 agg.add_value(2);
278 agg.add_value(8);
279
280 assert_eq!(agg.get_result(), Some(8));
281 }
282
283 #[test]
284 fn test_group_key() {
285 let mut key = GroupKey::new();
286 key.set(0, 42);
287 key.set(1, 43);
288
289 assert_eq!(key.values[0], 42);
290 assert_eq!(key.values[1], 43);
291 assert_eq!(key.var_count, 2);
292 }
293
294 #[test]
295 fn test_aggregation_context() {
296 let spec = [crate::sparql_planner::AggregateSpec {
297 func: 0,
298 input_var: 0,
299 output_var: 1,
300 }];
301 let mut ctx = AggregationContext::new(&spec, 1);
302 let mut key = GroupKey::new();
303 key.set(0, 42);
304
305 let idx = ctx.find_or_create_group(key).unwrap();
306 let row = BindingRow::new();
307 ctx.add_values_to_group(idx, &row);
308 ctx.add_values_to_group(idx, &row);
309
310 assert_eq!(ctx.groups[idx].1[0].get_result(), Some(2));
311 }
312}