solidb 1.0.2

A lightweight, high-performance structured database server written in Rust.
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Aggregation functions for SDBQL executor.
//!
//! This module contains aggregation logic:
//! - compute_aggregate: Compute aggregate functions (COUNT, SUM, AVG, etc.)
//! - try_columnar_aggregation: Optimized columnar aggregation path

use serde_json::Value;

use super::types::Context;
use super::QueryExecutor;
use crate::error::{DbError, DbResult};
use crate::sdbql::ast::*;
use crate::storage::{AggregateOp, ColumnarCollection};

impl<'a> QueryExecutor<'a> {
    pub(super) fn try_columnar_aggregation(
        &self,
        query: &Query,
        _initial_bindings: &Context,
    ) -> DbResult<Option<Vec<Value>>> {
        // Must have a database context
        let db_name = match &self.database {
            Some(name) => name,
            None => return Ok(None),
        };

        // Get database to check if collection is columnar
        let database = match self.storage.get_database(db_name) {
            Ok(db) => db,
            Err(_) => return Ok(None),
        };

        // Check pattern: FOR clause on collection, COLLECT with AGGREGATE, RETURN
        if query.body_clauses.len() != 2 {
            return Ok(None);
        }

        // First clause must be FOR on a collection
        let for_clause = match &query.body_clauses[0] {
            BodyClause::For(fc) if fc.source_expression.is_none() => fc,
            _ => return Ok(None),
        };

        // Check if collection is columnar
        let collection_name = &for_clause.collection;
        if !database.is_columnar_collection(collection_name) {
            return Ok(None);
        }

        // Second clause must be COLLECT with AGGREGATE
        let collect_clause = match &query.body_clauses[1] {
            BodyClause::Collect(cc) if !cc.aggregates.is_empty() => cc,
            _ => return Ok(None),
        };

        // Must have a return clause
        if query.return_clause.is_none() {
            return Ok(None);
        }

        // Load columnar collection
        let columnar =
            match ColumnarCollection::load(collection_name.clone(), db_name, database.db_arc()) {
                Ok(c) => c,
                Err(_) => return Ok(None),
            };

        // Extract group by columns (from COLLECT var1 = x.field1, var2 = x.field2)
        use crate::storage::columnar::GroupByColumn;

        // Helper to extract grouping definition definition
        let parse_group_expr = |expr: &Expression| -> Option<GroupByColumn> {
            match expr {
                Expression::FieldAccess(base, field) => {
                    if let Expression::Variable(var) = base.as_ref() {
                        if var == &for_clause.variable {
                            return Some(GroupByColumn::Simple(field.clone()));
                        }
                    }
                    None
                }
                Expression::FunctionCall { name, args } if name == "TIME_BUCKET" => {
                    if args.len() == 2 {
                        // Arg 0 must be field access
                        let col = if let Expression::FieldAccess(base, field) = &args[0] {
                            if let Expression::Variable(var) = base.as_ref() {
                                if var == &for_clause.variable {
                                    Some(field.clone())
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        } else {
                            None
                        }?;

                        // Arg 1 must be literal string (interval)
                        let interval = if let Expression::Literal(Value::String(s)) = &args[1] {
                            Some(s.clone())
                        } else {
                            None
                        }?;

                        Some(GroupByColumn::TimeBucket(col, interval))
                    } else {
                        None
                    }
                }
                _ => None,
            }
        };

        let group_defs: Vec<GroupByColumn> = collect_clause
            .group_vars
            .iter()
            .filter_map(|(_, expr)| parse_group_expr(expr))
            .collect();

        // If we couldn't parse all group vars, abort optimization
        if group_defs.len() != collect_clause.group_vars.len() {
            return Ok(None);
        }

        // Process aggregations
        let mut result_obj: serde_json::Map<String, Value> = serde_json::Map::new();
        // Grouped results, merged across aggregates by group key.
        let mut grouped: std::collections::BTreeMap<String, serde_json::Map<String, Value>> =
            std::collections::BTreeMap::new();

        for agg in &collect_clause.aggregates {
            let var_name = &agg.variable;
            let func_name = &agg.function;

            // Extract field from argument
            let field = match &agg.argument {
                Some(Expression::FieldAccess(base, field)) => {
                    if let Expression::Variable(var) = base.as_ref() {
                        if var == &for_clause.variable {
                            field.clone()
                        } else {
                            return Ok(None);
                        }
                    } else {
                        return Ok(None);
                    }
                }
                Some(Expression::Variable(_)) | None => {
                    // COUNT(*) style - use special handling
                    "_count".to_string()
                }
                _ => return Ok(None),
            };

            // Map function name to AggregateOp
            let op = match func_name.to_uppercase().as_str() {
                "SUM" => AggregateOp::Sum,
                "AVG" | "AVERAGE" => AggregateOp::Avg,
                "COUNT" | "LENGTH" => AggregateOp::Count,
                "MIN" | "MINIMUM" => AggregateOp::Min,
                "MAX" | "MAXIMUM" => AggregateOp::Max,
                "COUNT_DISTINCT" | "COUNT_UNIQUE" | "UNIQUE" => AggregateOp::CountDistinct,
                _ => return Ok(None), // Unknown aggregate
            };

            // Execute aggregation
            if group_defs.is_empty() {
                // Simple aggregation without grouping
                match columnar.aggregate(&field, op) {
                    Ok(value) => {
                        result_obj.insert(var_name.clone(), value);
                    }
                    Err(_) => return Ok(None),
                }
            } else {
                // Grouped aggregation. Each aggregate is a separate column-native
                // pass; merge them on the group key.
                //
                // This used to `return` inside the loop with the raw storage
                // rows, which meant every aggregate after the first was
                // silently dropped and the column was reported under storage's
                // internal `_agg` name instead of the COLLECT variable.
                let rows = match columnar.group_by(&group_defs, &field, op) {
                    Ok(rows) => rows,
                    Err(_) => return Ok(None),
                };

                for row in rows {
                    let Some(obj) = row.as_object() else {
                        return Ok(None);
                    };
                    let key = group_key_of(obj, &group_defs);
                    let entry = grouped.entry(key).or_default();

                    // Group columns are keyed by column name; re-key them to the
                    // COLLECT variable, which is what the RETURN clause refers to
                    // (`COLLECT h = m.host` binds `h`, not `host`).
                    for ((collect_var, _), col_def) in
                        collect_clause.group_vars.iter().zip(group_defs.iter())
                    {
                        if let Some(v) = obj.get(col_def.name()) {
                            entry.insert(collect_var.clone(), v.clone());
                        }
                    }
                    if let Some(v) = obj.get("_agg") {
                        entry.insert(var_name.clone(), v.clone());
                    }
                }
            }
        }

        // Build the rows this optimization produces, then run them through the
        // query's RETURN clause. Returning the aggregate rows directly ignored
        // RETURN entirely: `RETURN {sum: total}` came back as `{"total": ...}`
        // and `RETURN total` came back as an object instead of a scalar.
        let rows: Vec<serde_json::Map<String, Value>> = if group_defs.is_empty() {
            vec![result_obj]
        } else {
            grouped.into_values().collect()
        };

        let return_expr = &query
            .return_clause
            .as_ref()
            .expect("checked above")
            .expression;

        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            let mut ctx: Context = _initial_bindings.clone();
            for (k, v) in row {
                ctx.insert(k, v);
            }
            out.push(self.evaluate_expr_with_context(return_expr, &ctx)?);
        }
        Ok(Some(out))
    }

    /// Execute query and return results only (backwards compatible)
    pub(super) fn compute_aggregate(
        &self,
        function: &str,
        argument: &Option<Expression>,
        group_docs: &[Context],
    ) -> DbResult<Value> {
        match function {
            "COUNT" => {
                if argument.is_none() {
                    // COUNT() - count all rows
                    Ok(Value::Number((group_docs.len() as i64).into()))
                } else {
                    // COUNT(expr) - count non-null values
                    let mut count = 0i64;
                    for ctx in group_docs {
                        if let Some(expr) = argument {
                            let val = self.evaluate_expr_with_context(expr, ctx)?;
                            if !val.is_null() {
                                count += 1;
                            }
                        }
                    }
                    Ok(Value::Number(count.into()))
                }
            }
            "SUM" => {
                let mut sum = 0.0f64;
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        if let Some(n) = val.as_f64() {
                            sum += n;
                        } else if let Some(n) = val.as_i64() {
                            sum += n as f64;
                        }
                    }
                }
                Ok(Value::Number(
                    serde_json::Number::from_f64(sum).unwrap_or_else(|| (sum as i64).into()),
                ))
            }
            "AVG" => {
                let mut sum = 0.0f64;
                let mut count = 0i64;
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        if let Some(n) = val.as_f64() {
                            sum += n;
                            count += 1;
                        } else if let Some(n) = val.as_i64() {
                            sum += n as f64;
                            count += 1;
                        }
                    }
                }
                if count == 0 {
                    Ok(Value::Null)
                } else {
                    let avg = sum / (count as f64);
                    Ok(Value::Number(
                        serde_json::Number::from_f64(avg).unwrap_or_else(|| (avg as i64).into()),
                    ))
                }
            }
            "MIN" => {
                let mut min: Option<Value> = None;
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        if val.is_null() {
                            continue;
                        }

                        if min.is_none() {
                            min = Some(val);
                        } else if let (Some(cur), Some(new)) =
                            (min.as_ref().and_then(|v| v.as_f64()), val.as_f64())
                        {
                            if new < cur {
                                min = Some(val);
                            }
                        } else if let (Some(cur_str), Some(new_str)) =
                            (min.as_ref().and_then(|v| v.as_str()), val.as_str())
                        {
                            if new_str < cur_str {
                                min = Some(val);
                            }
                        }
                    }
                }
                Ok(min.unwrap_or(Value::Null))
            }
            "MAX" => {
                let mut max: Option<Value> = None;
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        if val.is_null() {
                            continue;
                        }

                        if max.is_none() {
                            max = Some(val);
                        } else if let (Some(cur), Some(new)) =
                            (max.as_ref().and_then(|v| v.as_f64()), val.as_f64())
                        {
                            if new > cur {
                                max = Some(val);
                            }
                        } else if let (Some(cur_str), Some(new_str)) =
                            (max.as_ref().and_then(|v| v.as_str()), val.as_str())
                        {
                            if new_str > cur_str {
                                max = Some(val);
                            }
                        }
                    }
                }
                Ok(max.unwrap_or(Value::Null))
            }
            "LENGTH" | "COUNT_DISTINCT" => {
                use std::collections::HashSet;
                let mut seen: HashSet<String> = HashSet::new();
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        seen.insert(serde_json::to_string(&val).unwrap_or_default());
                    }
                }
                Ok(Value::Number((seen.len() as i64).into()))
            }
            "COLLECT_LIST" | "COLLECT" => {
                let mut list = Vec::new();
                if let Some(expr) = argument {
                    for ctx in group_docs {
                        let val = self.evaluate_expr_with_context(expr, ctx)?;
                        list.push(val);
                    }
                }
                Ok(Value::Array(list))
            }
            _ => Err(DbError::ExecutionError(format!(
                "Unknown aggregate function: {}",
                function
            ))),
        }
    }
}

/// Stable identity for a group across per-aggregate passes.
///
/// Each aggregate is computed in its own `group_by` call, so their rows have to
/// be merged. The group columns are what identify a group; `_agg` is the value
/// being merged in and is deliberately excluded.
fn group_key_of(
    obj: &serde_json::Map<String, Value>,
    group_defs: &[crate::storage::columnar::GroupByColumn],
) -> String {
    group_defs
        .iter()
        .map(|d| match obj.get(d.name()) {
            Some(Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
            None => String::new(),
        })
        .collect::<Vec<_>>()
        .join("\u{1}")
}