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
//! SELECT, GROUP BY, and aggregate expression SQL generation.
use super::{
AggregateExpression, AggregateFunction, AggregationSqlGenerator, DatabaseType,
GroupByExpression, OrderByClause, OrderDirection, Result, TemporalBucket,
};
use crate::compiler::aggregation::TreeGrouping;
impl AggregationSqlGenerator {
/// Build SELECT clause.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] if an unrecognised aggregate function
/// or GROUP BY expression cannot be converted to SQL.
pub(super) fn build_select_clause(
&self,
group_by_expressions: &[GroupByExpression],
aggregate_expressions: &[AggregateExpression],
) -> Result<String> {
let mut columns = Vec::new();
// Add GROUP BY columns to SELECT
for expr in group_by_expressions {
let column = self.group_by_expression_to_sql(expr)?;
let alias = match expr {
GroupByExpression::JsonbPath { alias, .. }
| GroupByExpression::TemporalBucket { alias, .. }
| GroupByExpression::CalendarPath { alias, .. }
| GroupByExpression::TreeLevel { alias, .. }
| GroupByExpression::NativeColumn { alias, .. } => alias,
};
columns.push(format!("{} AS {}", column, alias));
}
// Add aggregate columns to SELECT
for expr in aggregate_expressions {
let column = self.aggregate_expression_to_sql(expr)?;
let alias = match expr {
AggregateExpression::Count { alias }
| AggregateExpression::CountDistinct { alias, .. }
| AggregateExpression::MeasureAggregate { alias, .. }
| AggregateExpression::AdvancedAggregate { alias, .. }
| AggregateExpression::BoolAggregate { alias, .. } => alias,
};
columns.push(format!("{} AS {}", column, alias));
}
Ok(format!("SELECT\n {}", columns.join(",\n ")))
}
/// Convert GROUP BY expression to SQL.
///
/// # Errors
///
/// Currently infallible; reserved for future expression types that may
/// require validation (e.g., computed GROUP BY expressions).
pub(super) fn group_by_expression_to_sql(&self, expr: &GroupByExpression) -> Result<String> {
match expr {
GroupByExpression::JsonbPath {
jsonb_column, path, ..
} => Ok(self.jsonb_extract_sql(jsonb_column, path)),
GroupByExpression::TemporalBucket { column, bucket, .. } => {
Ok(self.temporal_bucket_sql(column, *bucket))
},
GroupByExpression::CalendarPath {
calendar_column,
json_key,
..
} => {
// Calendar dimension: reuse JSONB extraction for all 4 databases
Ok(self.jsonb_extract_sql(calendar_column, json_key))
},
GroupByExpression::TreeLevel {
column, grouping, ..
} => {
let col = self.quote_identifier(column);
Ok(match grouping {
// A length past the path's end keeps the whole path, so a path
// shallower than the level groups as itself.
TreeGrouping::Level(n) => format!("subpath({col}, 0, {n})"),
TreeGrouping::Depth => format!("nlevel({col})"),
})
},
GroupByExpression::NativeColumn { column, .. } => {
// Direct column reference, dialect-quoted to handle reserved words
Ok(self.quote_identifier(column))
},
}
}
/// Generate temporal bucket SQL
pub(super) fn temporal_bucket_sql(&self, column: &str, bucket: TemporalBucket) -> String {
match self.database_type {
DatabaseType::PostgreSQL => {
format!("DATE_TRUNC('{}', {})", bucket.postgres_arg(), column)
},
}
}
/// Convert aggregate expression to SQL.
///
/// # Errors
///
/// Returns `FraiseQLError::Validation` when an advanced aggregate function
/// (e.g., `STRING_AGG`) is not supported by the target database dialect.
pub(super) fn aggregate_expression_to_sql(&self, expr: &AggregateExpression) -> Result<String> {
match expr {
AggregateExpression::Count { .. } => Ok("COUNT(*)".to_string()),
AggregateExpression::CountDistinct { column, .. } => {
Ok(format!("COUNT(DISTINCT {})", column))
},
AggregateExpression::MeasureAggregate {
column,
function,
native,
..
} => {
#[allow(clippy::enum_glob_use)]
// Reason: glob import reduces noise in exhaustive match arms
use AggregateFunction::*;
// Native measure columns use quoted identifiers (no ::numeric cast needed)
let col_ref = if *native {
self.quote_identifier(column)
} else {
column.clone()
};
// Handle statistical functions with database-specific SQL
match function {
Stddev => Ok(self.generate_stddev_sql(&col_ref)),
Variance => Ok(self.generate_variance_sql(&col_ref)),
_ => Ok(format!("{}({})", function.sql_name(), col_ref)),
}
},
AggregateExpression::AdvancedAggregate {
column,
function,
delimiter,
order_by,
..
} => self.advanced_aggregate_to_sql(
column,
*function,
delimiter.as_deref(),
order_by.as_ref(),
),
AggregateExpression::BoolAggregate {
column, function, ..
} => Ok(self.generate_bool_agg_sql(column, *function)),
}
}
/// Generate SQL for advanced aggregates
pub(super) fn advanced_aggregate_to_sql(
&self,
column: &str,
function: AggregateFunction,
delimiter: Option<&str>,
order_by: Option<&Vec<OrderByClause>>,
) -> Result<String> {
#[allow(clippy::enum_glob_use)]
// Reason: glob import reduces noise in exhaustive match arms
use AggregateFunction::*;
match function {
ArrayAgg => Ok(self.generate_array_agg_sql(column, order_by)),
JsonAgg => Ok(self.generate_json_agg_sql(column, order_by)),
JsonbAgg => Ok(self.generate_jsonb_agg_sql(column, order_by)),
StringAgg => {
Ok(self.generate_string_agg_sql(column, delimiter.unwrap_or(","), order_by))
},
_ => Ok(format!("{}({})", function.sql_name(), column)),
}
}
/// Generate `ARRAY_AGG` SQL
pub(super) fn generate_array_agg_sql(
&self,
column: &str,
order_by: Option<&Vec<OrderByClause>>,
) -> String {
match self.database_type {
DatabaseType::PostgreSQL => {
if let Some(order) = order_by {
format!("ARRAY_AGG({} ORDER BY {})", column, self.order_by_to_sql(order))
} else {
format!("ARRAY_AGG({})", column)
}
},
}
}
/// Generate `JSON_AGG` SQL
pub(super) fn generate_json_agg_sql(
&self,
column: &str,
order_by: Option<&Vec<OrderByClause>>,
) -> String {
match self.database_type {
DatabaseType::PostgreSQL => {
if let Some(order) = order_by {
format!("JSON_AGG({} ORDER BY {})", column, self.order_by_to_sql(order))
} else {
format!("JSON_AGG({})", column)
}
},
}
}
/// Generate `JSONB_AGG` SQL (PostgreSQL-specific)
pub(super) fn generate_jsonb_agg_sql(
&self,
column: &str,
order_by: Option<&Vec<OrderByClause>>,
) -> String {
match self.database_type {
DatabaseType::PostgreSQL => {
if let Some(order) = order_by {
format!("JSONB_AGG({} ORDER BY {})", column, self.order_by_to_sql(order))
} else {
format!("JSONB_AGG({})", column)
}
},
}
}
/// Generate `STRING_AGG` SQL
pub(super) fn generate_string_agg_sql(
&self,
column: &str,
delimiter: &str,
order_by: Option<&Vec<OrderByClause>>,
) -> String {
// Escape the delimiter to prevent SQL injection via single-quote sequences.
// A delimiter like "O'Reilly" would otherwise break out of the string literal.
let safe_delimiter = self.escape_sql_string(delimiter);
match self.database_type {
DatabaseType::PostgreSQL => {
if let Some(order) = order_by {
format!(
"STRING_AGG({}, '{}' ORDER BY {})",
column,
safe_delimiter,
self.order_by_to_sql(order)
)
} else {
format!("STRING_AGG({}, '{}')", column, safe_delimiter)
}
},
}
}
/// Convert ORDER BY clauses to SQL
pub(super) fn order_by_to_sql(&self, order_by: &[OrderByClause]) -> String {
order_by
.iter()
.map(|clause| {
#[allow(clippy::match_same_arms)]
// Reason: non_exhaustive enum requires catch-all; explicit Asc arm documents intent
let direction = match clause.direction {
OrderDirection::Asc => "ASC",
OrderDirection::Desc => "DESC",
_ => "ASC",
};
format!("{} {}", self.quote_identifier(&clause.field), direction)
})
.collect::<Vec<_>>()
.join(", ")
}
/// Generate STDDEV SQL (database-specific)
///
/// Database support:
/// - PostgreSQL: `STDDEV_SAMP()` (default), `STDDEV_POP()` also available
/// - MySQL: `STDDEV_SAMP()` or `STD()`
/// - SQLite: Not natively supported (returns NULL or use custom function)
/// - SQL Server: `STDEV()`
pub(super) fn generate_stddev_sql(&self, column: &str) -> String {
match self.database_type {
DatabaseType::PostgreSQL => format!("STDDEV_SAMP({})", column),
}
}
/// Generate VARIANCE SQL (database-specific)
///
/// Database support:
/// - PostgreSQL: `VAR_SAMP()` (default), `VAR_POP()` also available
/// - MySQL: `VAR_SAMP()` or `VARIANCE()`
/// - SQLite: Not natively supported (returns NULL or use custom function)
/// - SQL Server: `VAR()`
pub(super) fn generate_variance_sql(&self, column: &str) -> String {
match self.database_type {
DatabaseType::PostgreSQL => format!("VAR_SAMP({})", column),
}
}
/// Generate `BOOL_AND/BOOL_OR` SQL
pub(super) fn generate_bool_agg_sql(
&self,
column: &str,
function: crate::compiler::aggregate_types::BoolAggregateFunction,
) -> String {
match self.database_type {
DatabaseType::PostgreSQL => {
// PostgreSQL has native BOOL_AND/BOOL_OR
format!("{}({})", function.sql_name(), column)
},
}
}
/// Build GROUP BY clause.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] if any GROUP BY expression cannot
/// be converted to SQL (e.g., unsupported temporal bucket on the current dialect).
pub(super) fn build_group_by_clause(
&self,
group_by_expressions: &[GroupByExpression],
) -> Result<String> {
let mut columns = Vec::new();
for expr in group_by_expressions {
let column = self.group_by_expression_to_sql(expr)?;
columns.push(column);
}
Ok(format!("GROUP BY {}", columns.join(", ")))
}
/// Build ORDER BY clause.
///
/// All ORDER BY fields are quoted via `quote_identifier`, which produces the correct
/// dialect syntax (double-quotes, backticks, or brackets). For native SQL columns,
/// this quoted identifier resolves to the SELECT alias emitted by `build_select_clause`,
/// so no JSONB path is ever generated in ORDER BY.
///
/// The `_native_aliases` parameter is accepted for documentation purposes: its presence
/// makes explicit that native-column aliases are handled correctly by the existing
/// `quote_identifier` path, and guards against future refactors accidentally introducing
/// JSONB path generation for ORDER BY fields.
///
/// # Errors
///
/// Currently infallible; reserved for future validation of column references
/// against the aggregation plan.
pub(super) fn build_order_by_clause(
&self,
order_by: &[OrderByClause],
_native_aliases: &std::collections::HashSet<&str>,
) -> Result<String> {
let clauses: Vec<String> = order_by
.iter()
.map(|clause| {
#[allow(clippy::match_same_arms)]
// Reason: non_exhaustive enum requires catch-all; explicit Asc arm documents intent
let direction = match clause.direction {
OrderDirection::Asc => "ASC",
OrderDirection::Desc => "DESC",
_ => "ASC",
};
format!("{} {}", self.quote_identifier(&clause.field), direction)
})
.collect();
Ok(format!("ORDER BY {}", clauses.join(", ")))
}
}