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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Aggregation Result Projector
//!
//! Projects SQL aggregate results to GraphQL JSON responses.
//!
//! # SQL Result Format
//!
//! SQL returns rows as `Vec<HashMap<String, Value>>`:
//! ```json
//! [
//! {
//! "category": "Electronics",
//! "occurred_at_day": "2025-01-01T00:00:00Z",
//! "count": 42,
//! "revenue_sum": 5280.50,
//! "revenue_avg": 125.73
//! }
//! ]
//! ```
//!
//! # GraphQL Response Format
//!
//! Projected to GraphQL response:
//! ```json
//! {
//! "data": {
//! "sales_aggregate": [
//! {
//! "category": "Electronics",
//! "occurred_at_day": "2025-01-01T00:00:00Z",
//! "count": 42,
//! "revenue_sum": 5280.50,
//! "revenue_avg": 125.73
//! }
//! ]
//! }
//! }
//! ```
use std::collections::HashMap;
use serde_json::{Value, json};
#[allow(unused_imports)] // Reason: used only in doc links for `# Errors` sections
use crate::error::FraiseQLError;
use crate::{compiler::aggregation::AggregationPlan, error::Result};
/// Aggregation result projector
pub struct AggregationProjector;
impl AggregationProjector {
/// Project SQL aggregate results to GraphQL JSON.
///
/// # Arguments
///
/// * `rows` - SQL result rows as `HashMaps`
/// * `plan` - Aggregation execution plan (for metadata)
///
/// # Returns
///
/// GraphQL-compatible JSON response
///
/// # Errors
///
/// Currently infallible; reserved for future extension (e.g., type coercion failures).
///
/// # Example
///
/// ```no_run
/// // Requires: an AggregationPlan built from compiled schema metadata.
/// // See: tests/integration/ for runnable examples.
/// use std::collections::HashMap;
/// use serde_json::{json, Value};
/// # use fraiseql_core::runtime::AggregationProjector;
///
/// let mut row = HashMap::new();
/// row.insert("category".to_string(), json!("Electronics"));
/// row.insert("count".to_string(), json!(42));
/// row.insert("revenue_sum".to_string(), json!(5280.50));
/// let rows = vec![row];
/// // let result = AggregationProjector::project(rows, &plan)?;
/// // result: [{"category": "Electronics", "count": 42, "revenue_sum": 5280.50}]
/// ```
///
/// # Errors
///
/// Returns [`FraiseQLError::Internal`] if JSON serialization of the projected
/// rows fails (should not occur for well-formed input).
pub fn project(rows: Vec<HashMap<String, Value>>, _plan: &AggregationPlan) -> Result<Value> {
// For simple projection: just convert rows to JSON array
// Future improvements could include:
// - Type coercion (ensure numbers are numbers, not strings)
// - Null handling
// - Nested object construction
// - Date formatting
let projected_rows: Vec<Value> = rows
.into_iter()
.map(|row| {
// Convert HashMap to JSON object
let mut obj = serde_json::Map::new();
for (key, value) in row {
obj.insert(key, value);
}
Value::Object(obj)
})
.collect();
Ok(Value::Array(projected_rows))
}
/// Wrap projected results in GraphQL data envelope.
///
/// # Arguments
///
/// * `projected` - Projected result array
/// * `query_name` - GraphQL query field name (e.g., "`sales_aggregate`")
///
/// # Returns
///
/// Complete GraphQL response with `{"data": {...}}` wrapper
///
/// # Example
///
/// ```rust
/// # use fraiseql_core::runtime::AggregationProjector;
/// # use serde_json::json;
/// let projected = json!([{"count": 42}]);
/// let response = AggregationProjector::wrap_in_data_envelope(projected, "sales_aggregate");
/// // response: {"data": {"sales_aggregate": [{"count": 42}]}}
/// assert!(response.get("data").is_some());
/// ```
#[allow(clippy::needless_pass_by_value)] // Reason: projected is moved into serde_json::json! and consumed by value
pub fn wrap_in_data_envelope(projected: Value, query_name: &str) -> Value {
json!({
"data": {
query_name: projected
}
})
}
/// Project a single aggregate result (no GROUP BY).
///
/// When there's no GROUP BY, the result is a single object, not an array.
///
/// # Errors
///
/// Currently infallible; reserved for future extension (e.g., type coercion failures).
///
/// # Example
///
/// ```no_run
/// // Requires: an AggregationPlan built from compiled schema metadata.
/// // See: tests/integration/ for runnable examples.
/// use std::collections::HashMap;
/// use serde_json::json;
/// # use fraiseql_core::runtime::AggregationProjector;
///
/// let mut row = HashMap::new();
/// row.insert("count".to_string(), json!(100));
/// row.insert("revenue_sum".to_string(), json!(5000.0));
/// // let result = AggregationProjector::project_single(row, &plan)?;
/// // result: {"count": 100, "revenue_sum": 5000.0}
/// ```
pub fn project_single(row: HashMap<String, Value>, _plan: &AggregationPlan) -> Result<Value> {
// Convert HashMap to JSON object
let mut obj = serde_json::Map::new();
for (key, value) in row {
obj.insert(key, value);
}
Ok(Value::Object(obj))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
use super::*;
use crate::compiler::{
aggregate_types::AggregateFunction,
aggregation::{
AggregateExpression, AggregateSelection, AggregationRequest, GroupByExpression,
GroupBySelection,
},
fact_table::{DimensionColumn, FactTableMetadata, FilterColumn, MeasureColumn, SqlType},
};
fn create_test_plan() -> AggregationPlan {
use crate::compiler::fact_table::DimensionPath;
let metadata = FactTableMetadata {
table_name: "tf_sales".to_string(),
measures: vec![MeasureColumn {
name: "revenue".to_string(),
sql_type: SqlType::Decimal,
nullable: false,
}],
dimensions: DimensionColumn {
name: "dimensions".to_string(),
paths: vec![DimensionPath {
name: "category".to_string(),
json_path: "data->>'category'".to_string(),
data_type: "text".to_string(),
}],
},
denormalized_filters: vec![FilterColumn {
name: "occurred_at".to_string(),
sql_type: SqlType::Timestamp,
indexed: true,
}],
calendar_dimensions: vec![],
};
let request = AggregationRequest {
table_name: "tf_sales".to_string(),
where_clause: None,
group_by: vec![GroupBySelection::Dimension {
path: "category".to_string(),
alias: "category".to_string(),
}],
aggregates: vec![
AggregateSelection::Count {
alias: "count".to_string(),
},
AggregateSelection::MeasureAggregate {
measure: "revenue".to_string(),
function: AggregateFunction::Sum,
alias: "revenue_sum".to_string(),
},
],
having: vec![],
order_by: vec![],
limit: None,
offset: None,
};
AggregationPlan {
metadata,
request,
group_by_expressions: vec![GroupByExpression::JsonbPath {
jsonb_column: "data".to_string(),
path: "category".to_string(),
alias: "category".to_string(),
}],
aggregate_expressions: vec![
AggregateExpression::Count {
alias: "count".to_string(),
},
AggregateExpression::MeasureAggregate {
column: "revenue".to_string(),
function: AggregateFunction::Sum,
alias: "revenue_sum".to_string(),
},
],
having_conditions: vec![],
}
}
#[test]
fn test_project_simple_result() {
let plan = create_test_plan();
let rows = vec![
{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("count".to_string(), json!(42));
row.insert("revenue_sum".to_string(), json!(5280.50));
row
},
{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Books"));
row.insert("count".to_string(), json!(15));
row.insert("revenue_sum".to_string(), json!(450.25));
row
},
];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr.len(), 2);
assert_eq!(arr[0]["category"], "Electronics");
assert_eq!(arr[0]["count"], 42);
assert_eq!(arr[0]["revenue_sum"], 5280.50);
assert_eq!(arr[1]["category"], "Books");
assert_eq!(arr[1]["count"], 15);
assert_eq!(arr[1]["revenue_sum"], 450.25);
}
#[test]
fn test_project_empty_result() {
let plan = create_test_plan();
let rows = vec![];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr.len(), 0);
}
#[test]
fn test_wrap_in_data_envelope() {
let projected = json!([
{"category": "Electronics", "count": 42}
]);
let response = AggregationProjector::wrap_in_data_envelope(projected, "sales_aggregate");
assert!(response.get("data").is_some());
assert!(response["data"].get("sales_aggregate").is_some());
assert!(response["data"]["sales_aggregate"].is_array());
assert_eq!(response["data"]["sales_aggregate"][0]["category"], "Electronics");
}
#[test]
fn test_project_single() {
let plan = create_test_plan();
let mut row = HashMap::new();
row.insert("count".to_string(), json!(100));
row.insert("revenue_sum".to_string(), json!(10000.0));
let result = AggregationProjector::project_single(row, &plan).unwrap();
assert!(result.is_object());
assert_eq!(result["count"], 100);
assert_eq!(result["revenue_sum"], 10000.0);
}
#[test]
fn test_project_with_temporal_bucket() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("occurred_at_day".to_string(), json!("2025-01-01"));
row.insert("count".to_string(), json!(25));
row.insert("revenue_sum".to_string(), json!(3000.0));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["occurred_at_day"], "2025-01-01");
}
#[test]
fn test_project_with_null_values() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), Value::Null);
row.insert("count".to_string(), json!(10));
row.insert("revenue_sum".to_string(), json!(500.0));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], Value::Null);
assert_eq!(arr[0]["count"], 10);
}
// ========================================
// Advanced Aggregates Projection Tests
// ========================================
#[test]
fn test_project_array_agg_result() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("count".to_string(), json!(10));
// PostgreSQL ARRAY_AGG result
row.insert("products".to_string(), json!(["prod_1", "prod_2", "prod_3"]));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], "Electronics");
assert_eq!(arr[0]["products"], json!(["prod_1", "prod_2", "prod_3"]));
}
#[test]
fn test_project_json_agg_result() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("count".to_string(), json!(10));
// PostgreSQL JSON_AGG result
row.insert(
"items".to_string(),
json!([
{"product": "prod_1", "revenue": 1500},
{"product": "prod_2", "revenue": 1200}
]),
);
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], "Electronics");
assert!(arr[0]["items"].is_array());
let items = arr[0]["items"].as_array().unwrap();
assert_eq!(items.len(), 2);
assert_eq!(items[0]["product"], "prod_1");
assert_eq!(items[0]["revenue"], 1500);
}
#[test]
fn test_project_string_agg_result() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("count".to_string(), json!(10));
// PostgreSQL STRING_AGG result
row.insert("product_names".to_string(), json!("Laptop, Phone, Tablet"));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], "Electronics");
assert_eq!(arr[0]["product_names"], "Laptop, Phone, Tablet");
}
#[test]
fn test_project_bool_agg_result() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
row.insert("count".to_string(), json!(10));
// PostgreSQL BOOL_AND result
row.insert("all_active".to_string(), json!(true));
// PostgreSQL BOOL_OR result
row.insert("any_discounted".to_string(), json!(false));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], "Electronics");
assert_eq!(arr[0]["all_active"], true);
assert_eq!(arr[0]["any_discounted"], false);
}
#[test]
fn test_project_mixed_aggregates() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Electronics"));
// Basic aggregates
row.insert("count".to_string(), json!(42));
row.insert("revenue_sum".to_string(), json!(5280.50));
row.insert("revenue_avg".to_string(), json!(125.73));
// Advanced aggregates
row.insert("products".to_string(), json!(["prod_1", "prod_2"]));
row.insert("product_names".to_string(), json!("Laptop, Phone"));
row.insert("all_active".to_string(), json!(true));
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
// Verify basic aggregates
assert_eq!(arr[0]["count"], 42);
assert_eq!(arr[0]["revenue_sum"], 5280.50);
// Verify advanced aggregates
assert_eq!(arr[0]["products"], json!(["prod_1", "prod_2"]));
assert_eq!(arr[0]["product_names"], "Laptop, Phone");
assert_eq!(arr[0]["all_active"], true);
}
#[test]
fn test_project_empty_array_agg() {
let plan = create_test_plan();
let rows = vec![{
let mut row = HashMap::new();
row.insert("category".to_string(), json!("Empty"));
row.insert("count".to_string(), json!(0));
// Empty ARRAY_AGG result (NULL in PostgreSQL, [] in others)
row.insert("products".to_string(), Value::Null);
row
}];
let result = AggregationProjector::project(rows, &plan).unwrap();
assert!(result.is_array());
let arr = result.as_array().unwrap();
assert_eq!(arr[0]["category"], "Empty");
assert!(arr[0]["products"].is_null());
}
}