graphlite 0.0.1

GraphLite - A lightweight ISO GQL Graph Database
Documentation
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
410
// Copyright (c) 2024-2025 DeepGraph Inc.
// SPDX-License-Identifier: Apache-2.0
//
//! Consolidated aggregate function implementations
//!
//! This module contains all aggregate/statistical functions:
//! - COUNT: Counts rows or non-null values
//! - AVERAGE: Calculates arithmetic mean
//! - SUM: Calculates sum of numeric values
//! - MIN: Finds minimum value
//! - MAX: Finds maximum value

use super::function_trait::{Function, FunctionContext, FunctionError, FunctionResult};
use crate::storage::Value;

// ==============================================================================
// COUNT FUNCTION
// ==============================================================================

/// COUNT function - counts rows or non-null values
#[derive(Debug)]
pub struct CountFunction;

impl CountFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for CountFunction {
    fn name(&self) -> &str {
        "COUNT"
    }

    fn description(&self) -> &str {
        "Counts the number of non-null values in a column or all rows if no column specified"
    }

    fn argument_count(&self) -> usize {
        0 // COUNT() or COUNT(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        // If no arguments, count all rows
        if context.argument_count() == 0 {
            return Ok(Value::Number(context.rows.len() as f64));
        }

        // If argument provided, count non-null values in that column
        let column_name = context.get_argument(0)?.as_string().ok_or_else(|| {
            FunctionError::InvalidArgumentType {
                message: "COUNT argument must be a string column name".to_string(),
            }
        })?;

        // Special case: COUNT(*) should count all rows
        if column_name == "*" {
            return Ok(Value::Number(context.rows.len() as f64));
        }

        let mut count = 0;
        for row in &context.rows {
            if let Some(value) = row.values.get(column_name) {
                if !value.is_null() {
                    count += 1;
                }
            }
        }
        Ok(Value::Number(count as f64))
    }

    fn return_type(&self) -> &str {
        "Number"
    }
}

// ==============================================================================
// AVERAGE FUNCTION
// ==============================================================================

/// AVERAGE function - calculates arithmetic mean
#[derive(Debug)]
pub struct AverageFunction;

impl AverageFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for AverageFunction {
    fn name(&self) -> &str {
        "AVERAGE"
    }

    fn description(&self) -> &str {
        "Calculates the arithmetic mean of numeric values in a column"
    }

    fn argument_count(&self) -> usize {
        1 // AVERAGE(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        context.validate_argument_count(1)?;

        let arg = context.get_argument(0)?;

        // Handle both aggregation path (string column name) and regular function path (numeric value)
        match arg {
            // Aggregation path: receive column name as string, process all rows
            Value::String(column_name) => {
                let mut sum = 0.0;
                let mut count = 0;

                for row in &context.rows {
                    if let Some(value) = row.values.get(column_name) {
                        if !value.is_null() {
                            let number = value.as_number().ok_or_else(|| {
                                FunctionError::InvalidArgumentType {
                                    message: format!(
                                        "Cannot convert {} to number for AVERAGE",
                                        value.type_name()
                                    ),
                                }
                            })?;

                            sum += number;
                            count += 1;
                        }
                    }
                }

                if count == 0 {
                    log::debug!(
                        "DEBUG: AverageFunction::execute - returning NULL (no values found)"
                    );
                    Ok(Value::Null)
                } else {
                    let avg = sum / count as f64;
                    log::debug!("DEBUG: AverageFunction::execute - returning Number({}) from sum={}, count={}", avg, sum, count);
                    Ok(Value::Number(avg))
                }
            }

            // Regular function path: receive individual numeric values
            // This handles the case where AVERAGE is called as a regular function instead of aggregate
            Value::Number(num) => {
                // For single values, just return the value (average of one number is itself)
                Ok(Value::Number(*num))
            }

            _ => Err(FunctionError::InvalidArgumentType {
                message: "AVERAGE argument must be a string column name or numeric value"
                    .to_string(),
            }),
        }
    }

    fn return_type(&self) -> &str {
        "Number"
    }
}

// ==============================================================================
// SUM FUNCTION
// ==============================================================================

/// SUM function - calculates the sum of numeric values in a column
#[derive(Debug)]
pub struct SumFunction;

impl SumFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for SumFunction {
    fn name(&self) -> &str {
        "SUM"
    }

    fn description(&self) -> &str {
        "Calculates the sum of numeric values in a column"
    }

    fn argument_count(&self) -> usize {
        1 // SUM(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        // Get the column name argument
        let column_name = context.get_argument(0)?.as_string().ok_or_else(|| {
            FunctionError::InvalidArgumentType {
                message: "SUM argument must be a string column name".to_string(),
            }
        })?;

        let mut sum = 0.0;
        let mut has_values = false;

        for row in &context.rows {
            if let Some(value) = row.values.get(column_name) {
                if !value.is_null() {
                    if let Some(num) = value.as_number() {
                        sum += num;
                        has_values = true;
                    }
                }
            }
        }

        // Return NULL if no numeric values found (ISO GQL behavior)
        if !has_values {
            return Ok(Value::Null);
        }

        Ok(Value::Number(sum))
    }

    fn return_type(&self) -> &str {
        "Number"
    }
}

// ==============================================================================
// MIN FUNCTION
// ==============================================================================

/// MIN function - finds the minimum numeric value in a column
#[derive(Debug)]
pub struct MinFunction;

impl MinFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for MinFunction {
    fn name(&self) -> &str {
        "MIN"
    }

    fn description(&self) -> &str {
        "Finds the minimum numeric value in a column"
    }

    fn argument_count(&self) -> usize {
        1 // MIN(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        // Get the column name argument
        let column_name = context.get_argument(0)?.as_string().ok_or_else(|| {
            FunctionError::InvalidArgumentType {
                message: "MIN argument must be a string column name".to_string(),
            }
        })?;

        let mut min_value: Option<f64> = None;

        for row in &context.rows {
            if let Some(value) = row.values.get(column_name) {
                if !value.is_null() {
                    if let Some(num) = value.as_number() {
                        match min_value {
                            None => min_value = Some(num),
                            Some(current_min) => {
                                if num < current_min {
                                    min_value = Some(num);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Return null if no numeric values found
        match min_value {
            Some(min) => Ok(Value::Number(min)),
            None => Ok(Value::Null),
        }
    }

    fn return_type(&self) -> &str {
        "Number"
    }
}

// ==============================================================================
// MAX FUNCTION
// ==============================================================================

/// MAX function - finds the maximum numeric value in a column
#[derive(Debug)]
pub struct MaxFunction;

impl MaxFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for MaxFunction {
    fn name(&self) -> &str {
        "MAX"
    }

    fn description(&self) -> &str {
        "Finds the maximum numeric value in a column"
    }

    fn argument_count(&self) -> usize {
        1 // MAX(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        // Get the column name argument
        let column_name = context.get_argument(0)?.as_string().ok_or_else(|| {
            FunctionError::InvalidArgumentType {
                message: "MAX argument must be a string column name".to_string(),
            }
        })?;

        let mut max_value: Option<f64> = None;

        for row in &context.rows {
            if let Some(value) = row.values.get(column_name) {
                if !value.is_null() {
                    if let Some(num) = value.as_number() {
                        match max_value {
                            None => max_value = Some(num),
                            Some(current_max) => {
                                if num > current_max {
                                    max_value = Some(num);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Return null if no numeric values found
        match max_value {
            Some(max) => Ok(Value::Number(max)),
            None => Ok(Value::Null),
        }
    }

    fn return_type(&self) -> &str {
        "Number"
    }
}

// ==============================================================================
// COLLECT FUNCTION
// ==============================================================================

/// COLLECT function - collects values into a list/array
#[derive(Debug)]
pub struct CollectFunction;

impl CollectFunction {
    pub fn new() -> Self {
        Self
    }
}

impl Function for CollectFunction {
    fn name(&self) -> &str {
        "COLLECT"
    }

    fn description(&self) -> &str {
        "Collects values from a column into a list/array"
    }

    fn argument_count(&self) -> usize {
        1 // COLLECT(column)
    }

    fn execute(&self, context: &FunctionContext) -> FunctionResult<Value> {
        // Get the column name argument
        let column_name = context.get_argument(0)?.as_string().ok_or_else(|| {
            FunctionError::InvalidArgumentType {
                message: "COLLECT argument must be a string column name".to_string(),
            }
        })?;

        let mut collected_values = Vec::new();

        for row in &context.rows {
            if let Some(value) = row.values.get(column_name) {
                // Include all values, including nulls, to match ISO GQL behavior
                collected_values.push(value.clone());
            }
        }

        // Return as List type for ISO GQL compatibility
        Ok(Value::List(collected_values))
    }

    fn return_type(&self) -> &str {
        "List"
    }
}