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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Aggregation Execution Plan Module
//!
//! This module generates execution plans for GROUP BY queries with aggregations.
//!
//! # Execution Plan Flow
//!
//! ```text
//! GraphQL Query
//! ↓
//! AggregationRequest (parsed)
//! ↓
//! AggregationPlan (validated, optimized)
//! ↓
//! SQL Generation (database-specific)
//! ↓
//! Query Execution
//! ```
//!
//! # Example
//!
//! ```graphql
//! query {
//! sales_aggregate(
//! where: { customer_id: { _eq: "uuid-123" } }
//! groupBy: { category: true, occurred_at_day: true }
//! having: { revenue_sum_gt: 1000 }
//! ) {
//! category
//! occurred_at_day
//! count
//! revenue_sum
//! revenue_avg
//! }
//! }
//! ```
//!
//! Generates:
//!
//! ```sql
//! SELECT
//! data->>'category' AS category,
//! DATE_TRUNC('day', occurred_at) AS occurred_at_day,
//! COUNT(*) AS count,
//! SUM(revenue) AS revenue_sum,
//! AVG(revenue) AS revenue_avg
//! FROM tf_sales
//! WHERE customer_id = $1
//! GROUP BY data->>'category', DATE_TRUNC('day', occurred_at)
//! HAVING SUM(revenue) > $2
//! ```
use serde::{Deserialize, Serialize};
pub use crate::types::{OrderByClause, OrderDirection};
use crate::{
backend::where_clause::WhereClause,
compiler::{
aggregate_types::{AggregateFunction, HavingOperator, TemporalBucket},
fact_table::FactTableMetadata,
},
error::{FraiseQLError, Result},
};
/// Aggregation request from GraphQL query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AggregationRequest {
/// Fact table name
pub table_name: String,
/// WHERE clause filters (applied before GROUP BY)
pub where_clause: Option<WhereClause>,
/// GROUP BY selections
pub group_by: Vec<GroupBySelection>,
/// Aggregate selections (what to compute)
pub aggregates: Vec<AggregateSelection>,
/// HAVING clause filters (applied after GROUP BY)
pub having: Vec<HavingCondition>,
/// ORDER BY clauses
pub order_by: Vec<OrderByClause>,
/// LIMIT
pub limit: Option<u32>,
/// OFFSET
pub offset: Option<u32>,
}
/// GROUP BY selection
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GroupBySelection {
/// Group by JSONB dimension
Dimension {
/// JSONB path (e.g., "category")
path: String,
/// Alias for result
alias: String,
},
/// Group by temporal bucket
TemporalBucket {
/// Column name (e.g., "`occurred_at`")
column: String,
/// Bucket type
bucket: TemporalBucket,
/// Alias for result
alias: String,
},
/// Group by pre-computed calendar dimension
CalendarDimension {
/// Source timestamp column (e.g., "`occurred_at`")
source_column: String,
/// Calendar JSONB column (e.g., "`date_info`")
calendar_column: String,
/// JSON key within calendar column (e.g., "month")
json_key: String,
/// Temporal bucket type
bucket: TemporalBucket,
/// Alias for result
alias: String,
},
/// Group by a level or the depth of an `ltree` path column (#1498): `{"path":
/// {"level": n}}` rolls each path up to its first `n` labels, `{"path": "depth"}`
/// groups by the number of labels.
TreeLevel {
/// The denormalized filter column holding the path.
column: String,
/// Which part of the tree to group by.
grouping: TreeGrouping,
/// Alias for result
alias: String,
},
/// Group by a native SQL column (not JSONB-extracted).
///
/// Produced by [`crate::runtime::AggregateQueryParser`] when the GROUP BY field
/// matches an entry in the query's `native_columns` map.
NativeDimension {
/// Column name as it appears in the CREATE VIEW DDL.
column: String,
/// PostgreSQL type for cast expressions (e.g. `"int8"`).
pg_cast: String,
/// The key the request grouped by, which the result answers under: the column's
/// own name, or the dimension a `native_dimension_mapping` maps to it (#1231).
alias: String,
},
}
/// What a tree grouping keeps of an `ltree` path (#1498).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum TreeGrouping {
/// The first `n` labels (`subpath(path, 0, n)`); a shorter path is kept whole.
Level(u32),
/// The number of labels (`nlevel(path)`).
Depth,
}
impl GroupBySelection {
/// Get the result alias for this selection
#[must_use]
pub fn alias(&self) -> &str {
match self {
Self::Dimension { alias, .. }
| Self::TemporalBucket { alias, .. }
| Self::CalendarDimension { alias, .. }
| Self::TreeLevel { alias, .. }
| Self::NativeDimension { alias, .. } => alias,
}
}
}
/// Aggregate selection (what to compute)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AggregateSelection {
/// COUNT(*)
Count {
/// Alias for result
alias: String,
},
/// COUNT(DISTINCT field)
CountDistinct {
/// Field to count
field: String,
/// Alias for result
alias: String,
},
/// Aggregate function on a measure
MeasureAggregate {
/// Measure column name
measure: String,
/// Aggregate function
function: AggregateFunction,
/// Alias for result
alias: String,
},
/// Boolean aggregate
BoolAggregate {
/// Field to aggregate
field: String,
/// Boolean aggregate function
function: crate::compiler::aggregate_types::BoolAggregateFunction,
/// Alias for result
alias: String,
},
}
impl AggregateSelection {
/// Get the result alias for this selection
#[must_use]
pub fn alias(&self) -> &str {
match self {
Self::Count { alias }
| Self::CountDistinct { alias, .. }
| Self::MeasureAggregate { alias, .. }
| Self::BoolAggregate { alias, .. } => alias,
}
}
}
/// HAVING condition (post-aggregation filter)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HavingCondition {
/// Aggregate to filter on
pub aggregate: AggregateSelection,
/// Comparison operator
pub operator: HavingOperator,
/// Value to compare against
pub value: serde_json::Value,
}
/// Validated and optimized aggregation execution plan
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AggregationPlan {
/// Fact table metadata
pub metadata: FactTableMetadata,
/// Original request
pub request: AggregationRequest,
/// Validated GROUP BY expressions
pub group_by_expressions: Vec<GroupByExpression>,
/// Validated aggregate expressions
pub aggregate_expressions: Vec<AggregateExpression>,
/// Validated HAVING conditions
pub having_conditions: Vec<ValidatedHavingCondition>,
/// The per-entity, per-bucket reduction run before the requested functions, when the
/// request reads a measure not additive over time (#1459).
#[serde(default)]
pub time_reduction: Option<super::time_reduction::TimeReduction>,
}
/// Validated GROUP BY expression
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GroupByExpression {
/// JSONB dimension extraction
JsonbPath {
/// JSONB column name (usually "data")
jsonb_column: String,
/// JSON keys to extract, outermost first (e.g. `["category"]`, or a declared
/// path's `["machine", "model"]`, #1517)
path: Vec<String>,
/// Result alias
alias: String,
/// The request locale's fallback chain when the dimension is a localized field
/// (#1524): it groups by the label read through it, not by the stored locale map.
localized: Option<Vec<String>>,
},
/// Temporal bucket with `DATE_TRUNC`
TemporalBucket {
/// Timestamp column name
column: String,
/// Bucket type
bucket: TemporalBucket,
/// Result alias
alias: String,
},
/// Pre-computed calendar dimension extraction
CalendarPath {
/// Calendar JSONB column (e.g., "`date_info`")
calendar_column: String,
/// JSON key within calendar column (e.g., "month")
json_key: String,
/// Result alias
alias: String,
},
/// A level or the depth of an `ltree` path column (#1498).
TreeLevel {
/// The path column.
column: String,
/// Which part of the tree to group by.
grouping: TreeGrouping,
/// Result alias
alias: String,
},
/// A native SQL column on the view/fact table — referenced directly,
/// not via JSONB extraction. Generates a dialect-quoted column reference in
/// GROUP BY / SELECT, enabling btree index usage.
NativeColumn {
/// Column name as it appears in the CREATE VIEW DDL.
column: String,
/// PostgreSQL type suffix for casting (e.g. `"uuid"`, `"int8"`, `""`).
pg_cast: String,
/// Alias used in SELECT and referenced by ORDER BY.
alias: String,
},
}
/// Validated aggregate expression
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AggregateExpression {
/// COUNT(*)
Count {
/// Result alias
alias: String,
},
/// COUNT(DISTINCT field)
CountDistinct {
/// Column to count
column: String,
/// Result alias
alias: String,
},
/// Aggregate function on measure column
MeasureAggregate {
/// Measure column name
column: String,
/// Aggregate function
function: AggregateFunction,
/// Result alias
alias: String,
/// Whether the column is a native SQL column (not JSONB-extracted).
///
/// When `true`, the SQL generator quotes the column identifier and skips
/// any `::numeric` cast that would otherwise be needed for JSONB text values.
#[serde(default)]
native: bool,
},
/// Advanced aggregate with optional parameters
AdvancedAggregate {
/// Column to aggregate
column: String,
/// Aggregate function
function: AggregateFunction,
/// Result alias
alias: String,
/// Optional delimiter for `STRING_AGG`
delimiter: Option<String>,
/// Optional ORDER BY for `ARRAY_AGG/STRING_AGG`
order_by: Option<Vec<OrderByClause>>,
},
/// Boolean aggregate (`BOOL_AND/BOOL_OR`)
BoolAggregate {
/// Column to aggregate (boolean expression)
column: String,
/// Boolean aggregate function
function: crate::compiler::aggregate_types::BoolAggregateFunction,
/// Result alias
alias: String,
},
}
/// Validated HAVING condition
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidatedHavingCondition {
/// Aggregate expression to filter on
pub aggregate: AggregateExpression,
/// Comparison operator
pub operator: HavingOperator,
/// Value to compare against
pub value: serde_json::Value,
}
impl AggregationPlan {
/// Returns the set of alias strings that correspond to native SQL column
/// `GROUP BY` expressions (not JSONB-derived aliases).
///
/// Used by the ORDER BY clause builder to document that native columns are
/// referenced by alias rather than JSONB path, preventing accidental regressions
/// if the ORDER BY logic is ever refactored.
#[must_use]
pub fn native_aliases(&self) -> std::collections::HashSet<&str> {
self.group_by_expressions
.iter()
.filter_map(|e| {
if let GroupByExpression::NativeColumn { alias, .. } = e {
Some(alias.as_str())
} else {
None
}
})
.collect()
}
}
/// Aggregation plan generator
pub struct AggregationPlanner;
impl AggregationPlanner {
/// Generate execution plan from request
///
/// # Arguments
///
/// * `request` - Aggregation request from GraphQL
/// * `metadata` - Fact table metadata
///
/// # Errors
///
/// Returns error if:
/// - Request references non-existent measures or dimensions
/// - GROUP BY selections are invalid
/// - HAVING conditions reference non-computed aggregates
pub fn plan(
request: AggregationRequest,
metadata: FactTableMetadata,
) -> Result<AggregationPlan> {
// SECURITY (#795): the relation is determined by the GraphQL root field, which
// already resolved `metadata`. The request's `table` key was a second, unchecked
// channel selecting the same thing, so it could name any relation — or a whole
// subquery — and the RLS policy, looked up by that same name
// (`runners/aggregate.rs` `policy.evaluate(ctx, &request.table_name)`), returned
// `None` for an unpolicied table and composed no WHERE clause at all.
if request.table_name != metadata.table_name {
return Err(FraiseQLError::Validation {
message: format!(
"aggregate query 'table' ({}) does not match the fact table resolved from \
the query field ({}); the relation is determined by the schema, not the \
request",
request.table_name, metadata.table_name
),
path: None,
});
}
// Validate and convert GROUP BY selections
let group_by_expressions = Self::validate_group_by(&request.group_by, &metadata)?;
// Validate and convert aggregate selections
let aggregate_expressions = Self::validate_aggregates(&request.aggregates, &metadata)?;
// Validate HAVING conditions
let having_conditions = Self::validate_having(&request.having, &aggregate_expressions)?;
// #1459: a measure not additive over time is reduced per entity and bucket first, or
// the request is refused.
let time_reduction = super::time_reduction::plan_time_reduction(&request, &metadata)?;
Ok(AggregationPlan {
metadata,
request,
group_by_expressions,
aggregate_expressions,
having_conditions,
time_reduction,
})
}
/// Validate GROUP BY selections
fn validate_group_by(
selections: &[GroupBySelection],
metadata: &FactTableMetadata,
) -> Result<Vec<GroupByExpression>> {
let mut expressions = Vec::new();
for selection in selections {
match selection {
GroupBySelection::Dimension { path, alias } => {
// When the schema declares dimension paths, validate against the allowlist.
// This prevents unrecognised paths from reaching `jsonb_extract_sql` even
// after SQL-level escaping (defence in depth). If no paths are declared,
// all paths are accepted — escaping in the runtime layer still applies.
//
// A declared path is read where it says it is (#1517), not at a
// top-level key named after it.
let location = match metadata.declared_dimension_segments(path) {
Some(segments) => segments?,
None if metadata.dimensions.paths.is_empty() => vec![path.clone()],
None => {
return Err(FraiseQLError::Validation {
message: format!(
"Dimension '{}' not found in fact table '{}'",
path, metadata.table_name
),
path: None,
});
},
};
expressions.push(GroupByExpression::JsonbPath {
jsonb_column: metadata.dimensions.name.clone(),
path: location,
alias: alias.clone(),
// Set by the runner, which knows the type and the request locale.
localized: None,
});
},
GroupBySelection::TemporalBucket {
column,
bucket,
alias,
} => {
// Validate column exists in denormalized filters
let filter_exists =
metadata.denormalized_filters.iter().any(|f| f.name == *column);
if !filter_exists {
return Err(FraiseQLError::Validation {
message: format!(
"Column '{}' not found in fact table '{}'",
column, metadata.table_name
),
path: None,
});
}
expressions.push(GroupByExpression::TemporalBucket {
column: column.clone(),
bucket: *bucket,
alias: alias.clone(),
});
},
GroupBySelection::CalendarDimension {
calendar_column,
json_key,
alias,
..
} => {
// Calendar dimension - use pre-computed JSONB field
expressions.push(GroupByExpression::CalendarPath {
calendar_column: calendar_column.clone(),
json_key: json_key.clone(),
alias: alias.clone(),
});
},
GroupBySelection::TreeLevel {
column,
grouping,
alias,
} => {
let filter = metadata.denormalized_filters.iter().find(|f| f.name == *column);
if filter.map(|f| &f.sql_type) != Some(&super::fact_table::SqlType::Ltree) {
return Err(FraiseQLError::Validation {
message: format!(
"Grouping '{column}' by a tree level or depth needs an ltree \
denormalized filter column on fact table '{}'",
metadata.table_name
),
path: None,
});
}
expressions.push(GroupByExpression::TreeLevel {
column: column.clone(),
grouping: *grouping,
alias: alias.clone(),
});
},
GroupBySelection::NativeDimension {
column,
pg_cast,
alias,
} => {
expressions.push(GroupByExpression::NativeColumn {
alias: alias.clone(),
column: column.clone(),
pg_cast: pg_cast.clone(),
});
},
}
}
Ok(expressions)
}
/// Validate aggregate selections
fn validate_aggregates(
selections: &[AggregateSelection],
metadata: &FactTableMetadata,
) -> Result<Vec<AggregateExpression>> {
let mut expressions = Vec::new();
for selection in selections {
match selection {
AggregateSelection::Count { alias } => {
expressions.push(AggregateExpression::Count {
alias: alias.clone(),
});
},
AggregateSelection::CountDistinct { field, alias } => {
// Validate field is a measure
let measure_exists = metadata.measures.iter().any(|m| m.name == *field);
if !measure_exists {
return Err(FraiseQLError::Validation {
message: format!(
"Measure '{}' not found in fact table '{}'",
field, metadata.table_name
),
path: None,
});
}
expressions.push(AggregateExpression::CountDistinct {
column: field.clone(),
alias: alias.clone(),
});
},
AggregateSelection::MeasureAggregate {
measure,
function,
alias,
} => {
// Validate measure exists (or is a dimension path, filter, or native measure)
let measure_exists = metadata.measures.iter().any(|m| m.name == *measure);
let is_dimension = metadata.dimensions.paths.iter().any(|p| p.name == *measure);
let is_filter =
metadata.denormalized_filters.iter().any(|f| f.name == *measure);
let is_native_measure = metadata.native_measures.contains_key(measure.as_str());
if !measure_exists && !is_dimension && !is_filter && !is_native_measure {
return Err(FraiseQLError::Validation {
message: format!(
"Measure or field '{}' not found in fact table '{}'",
measure, metadata.table_name
),
path: None,
});
}
// For advanced aggregates, create AdvancedAggregate variant
if matches!(
function,
AggregateFunction::ArrayAgg
| AggregateFunction::JsonAgg
| AggregateFunction::JsonbAgg
| AggregateFunction::StringAgg
) {
expressions.push(AggregateExpression::AdvancedAggregate {
column: measure.clone(),
function: *function,
alias: alias.clone(),
delimiter: if *function == AggregateFunction::StringAgg {
Some(", ".to_string())
} else {
None
},
order_by: None,
});
} else {
// Check if the measure references a native measure mapping
let (resolved_column, is_native) = if let Some(native_col) =
metadata.native_measures.get(measure.as_str())
{
(native_col.clone(), true)
} else {
(measure.clone(), false)
};
expressions.push(AggregateExpression::MeasureAggregate {
column: resolved_column,
function: *function,
alias: alias.clone(),
native: is_native,
});
}
},
AggregateSelection::BoolAggregate {
field,
function,
alias,
} => {
// Validate field exists
let field_exists = metadata.dimensions.paths.iter().any(|p| p.name == *field)
|| metadata.denormalized_filters.iter().any(|f| f.name == *field);
if !field_exists {
return Err(FraiseQLError::Validation {
message: format!(
"Boolean field '{}' not found in fact table '{}'",
field, metadata.table_name
),
path: None,
});
}
expressions.push(AggregateExpression::BoolAggregate {
column: field.clone(),
function: *function,
alias: alias.clone(),
});
},
}
}
Ok(expressions)
}
/// Validate HAVING conditions
fn validate_having(
conditions: &[HavingCondition],
_aggregate_expressions: &[AggregateExpression],
) -> Result<Vec<ValidatedHavingCondition>> {
let mut validated = Vec::new();
for condition in conditions {
// Convert the aggregate selection to an expression
let aggregate_expr = match &condition.aggregate {
AggregateSelection::Count { alias } => AggregateExpression::Count {
alias: alias.clone(),
},
AggregateSelection::CountDistinct { field, alias } => {
AggregateExpression::CountDistinct {
column: field.clone(),
alias: alias.clone(),
}
},
AggregateSelection::MeasureAggregate {
measure,
function,
alias,
} => {
// For advanced aggregates in HAVING, create AdvancedAggregate variant
if matches!(
function,
AggregateFunction::ArrayAgg
| AggregateFunction::JsonAgg
| AggregateFunction::JsonbAgg
| AggregateFunction::StringAgg
) {
AggregateExpression::AdvancedAggregate {
column: measure.clone(),
function: *function,
alias: alias.clone(),
delimiter: if *function == AggregateFunction::StringAgg {
Some(", ".to_string())
} else {
None
},
order_by: None,
}
} else {
AggregateExpression::MeasureAggregate {
column: measure.clone(),
function: *function,
alias: alias.clone(),
native: false,
}
}
},
AggregateSelection::BoolAggregate {
field,
function,
alias,
} => AggregateExpression::BoolAggregate {
column: field.clone(),
function: *function,
alias: alias.clone(),
},
};
// Note: We don't strictly require the aggregate to be in the SELECT list
// Some databases allow filtering on aggregates not in SELECT
validated.push(ValidatedHavingCondition {
aggregate: aggregate_expr,
operator: condition.operator,
value: condition.value.clone(),
});
}
Ok(validated)
}
}