fraiseql-core 2.2.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
//! Integration tests for aggregation queries.
//!
//! These tests verify the end-to-end aggregation pipeline:
//! - JSON query parsing
//! - Execution plan generation
//! - SQL generation
//! - Result projection
//!
//! To run unit tests:
//!   cargo test -p fraiseql-core --test `aggregation_integration`
//!
//! For database integration tests:
//!   1. Start test database: docker compose -f docker-compose.test.yml up -d
//!   2. Run tests: cargo test -p fraiseql-core --features test-postgres --test
//!      `aggregation_integration`

#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::match_wildcard_for_single_variants)] // Reason: test match uses wildcard arm for forward-compatibility
use fraiseql_core::{
    compiler::{
        aggregate_types::{AggregateFunction, TemporalBucket},
        aggregation::{AggregateSelection, AggregationRequest, GroupBySelection},
        fact_table::{
            CalendarBucket, CalendarDimension, CalendarGranularity, DimensionColumn, DimensionPath,
            FactTableMetadata, FilterColumn, MeasureColumn, SqlType,
        },
    },
    runtime::{AggregateQueryParser, AggregationProjector, AggregationSqlGenerator},
};
use serde_json::json;

/// Helper to create test fact table metadata for `tf_sales`
fn create_test_metadata() -> FactTableMetadata {
    FactTableMetadata {
        table_name:           "tf_sales".to_string(),
        measures:             vec![
            MeasureColumn {
                name:     "revenue".to_string(),
                sql_type: SqlType::Decimal,
                nullable: false,
            },
            MeasureColumn {
                name:     "quantity".to_string(),
                sql_type: SqlType::Int,
                nullable: false,
            },
        ],
        dimensions:           DimensionColumn {
            name:  "data".to_string(),
            paths: vec![
                DimensionPath {
                    name:      "category".to_string(),
                    json_path: "data->>'category'".to_string(),
                    data_type: "text".to_string(),
                },
                DimensionPath {
                    name:      "product".to_string(),
                    json_path: "data->>'product'".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![CalendarDimension {
            source_column: "occurred_at".to_string(),
            granularities: vec![CalendarGranularity {
                column_name: "date_info".to_string(),
                buckets:     vec![
                    CalendarBucket {
                        json_key:    "day".to_string(),
                        bucket_type: TemporalBucket::Day,
                        data_type:   "date".to_string(),
                    },
                    CalendarBucket {
                        json_key:    "month".to_string(),
                        bucket_type: TemporalBucket::Month,
                        data_type:   "integer".to_string(),
                    },
                ],
            }],
        }],
    }
}

// ============================================================================
// Query Parsing Tests
// ============================================================================

#[test]
fn test_parse_simple_aggregate_query() {
    let metadata = create_test_metadata();
    let query = json!({
        "table": "tf_sales",
        "aggregates": [
            {"count": {}}
        ]
    });

    let request =
        AggregateQueryParser::parse(&query, &metadata, &std::collections::HashMap::new()).unwrap();

    assert_eq!(request.table_name, "tf_sales");
    assert_eq!(request.aggregates.len(), 1);
    assert_eq!(request.aggregates[0].alias(), "count");
}

#[test]
fn test_parse_group_by_with_aggregates() {
    let metadata = create_test_metadata();
    let query = json!({
        "table": "tf_sales",
        "groupBy": {
            "category": true,
            "occurred_at_day": true
        },
        "aggregates": [
            {"count": {}},
            {"revenue_sum": {}},
            {"revenue_avg": {}}
        ]
    });

    let request =
        AggregateQueryParser::parse(&query, &metadata, &std::collections::HashMap::new()).unwrap();

    assert_eq!(request.group_by.len(), 2);
    assert_eq!(request.aggregates.len(), 3);

    // Verify GROUP BY selections
    match &request.group_by[0] {
        GroupBySelection::Dimension { path, alias } => {
            assert_eq!(path, "category");
            assert_eq!(alias, "category");
        },
        _ => panic!("Expected Dimension selection"),
    }

    // Parser prefers CalendarDimension over TemporalBucket when calendar dimensions are defined
    match &request.group_by[1] {
        GroupBySelection::CalendarDimension {
            source_column,
            calendar_column,
            json_key,
            bucket,
            alias,
        } => {
            assert_eq!(source_column, "occurred_at");
            assert_eq!(calendar_column, "date_info");
            assert_eq!(json_key, "day");
            assert_eq!(*bucket, TemporalBucket::Day);
            assert_eq!(alias, "occurred_at_day");
        },
        GroupBySelection::TemporalBucket {
            column,
            bucket,
            alias,
        } => {
            // Fallback if no calendar dimension (shouldn't happen in this test)
            assert_eq!(column, "occurred_at");
            assert_eq!(*bucket, TemporalBucket::Day);
            assert_eq!(alias, "occurred_at_day");
        },
        _ => panic!("Expected CalendarDimension or TemporalBucket selection"),
    }
}

// ============================================================================
// SQL Generation Tests
// ============================================================================

#[test]
fn test_sql_generation_postgres() {
    use fraiseql_core::{compiler::aggregation::AggregationPlanner, db::types::DatabaseType};

    let metadata = create_test_metadata();
    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,
    };

    // Generate execution plan
    let plan = AggregationPlanner::plan(request, metadata).unwrap();

    // Generate SQL
    let sql_generator = AggregationSqlGenerator::new(DatabaseType::PostgreSQL);
    let sql = sql_generator.generate_parameterized(&plan).unwrap();

    // Verify SQL contains expected clauses
    assert!(sql.sql.contains("data->>'category'"));
    assert!(sql.sql.contains("COUNT(*)"));
    assert!(sql.sql.contains("SUM(revenue)"));
    assert!(sql.sql.contains("GROUP BY"));
    assert!(sql.sql.contains("FROM tf_sales"));
}

#[test]
fn test_temporal_bucket_sql_generation() {
    use fraiseql_core::{compiler::aggregation::AggregationPlanner, db::types::DatabaseType};

    let metadata = create_test_metadata();
    let request = AggregationRequest {
        table_name:   "tf_sales".to_string(),
        where_clause: None,
        group_by:     vec![GroupBySelection::TemporalBucket {
            column: "occurred_at".to_string(),
            bucket: TemporalBucket::Day,
            alias:  "day".to_string(),
        }],
        aggregates:   vec![AggregateSelection::Count {
            alias: "count".to_string(),
        }],
        having:       vec![],
        order_by:     vec![],
        limit:        None,
        offset:       None,
    };

    let plan = AggregationPlanner::plan(request, metadata).unwrap();

    // Test PostgreSQL SQL generation
    let pg_generator = AggregationSqlGenerator::new(DatabaseType::PostgreSQL);
    let pg_sql = pg_generator.generate_parameterized(&plan).unwrap();
    assert!(pg_sql.sql.contains("DATE_TRUNC('day', occurred_at)"));

    // Test MySQL SQL generation
    let mysql_generator = AggregationSqlGenerator::new(DatabaseType::MySQL);
    let mysql_sql = mysql_generator.generate_parameterized(&plan).unwrap();
    assert!(mysql_sql.sql.contains("DATE_FORMAT(occurred_at"));

    // Test SQLite SQL generation
    let sqlite_generator = AggregationSqlGenerator::new(DatabaseType::SQLite);
    let sqlite_sql = sqlite_generator.generate_parameterized(&plan).unwrap();
    assert!(sqlite_sql.sql.contains("strftime"));

    // Test SQL Server SQL generation
    let sqlserver_generator = AggregationSqlGenerator::new(DatabaseType::SQLServer);
    let sqlserver_sql = sqlserver_generator.generate_parameterized(&plan).unwrap();
    assert!(sqlserver_sql.sql.contains("CAST(occurred_at AS DATE)"));
}

// ============================================================================
// Result Projection Tests
// ============================================================================

#[test]
fn test_result_projection() {
    use std::collections::HashMap;

    use fraiseql_core::compiler::aggregation::{
        AggregateExpression, AggregationPlan, GroupByExpression,
    };

    let metadata = create_test_metadata();
    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(),
        }],
        having:       vec![],
        order_by:     vec![],
        limit:        None,
        offset:       None,
    };

    let plan = 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(),
        }],
        having_conditions: vec![],
    };

    // Mock SQL results
    let rows = vec![
        {
            let mut row = HashMap::new();
            row.insert("category".to_string(), json!("Electronics"));
            row.insert("count".to_string(), json!(42));
            row
        },
        {
            let mut row = HashMap::new();
            row.insert("category".to_string(), json!("Books"));
            row.insert("count".to_string(), json!(15));
            row
        },
    ];

    // Project results
    let projected = AggregationProjector::project(rows, &plan).unwrap();

    // Verify projection
    assert!(projected.is_array());
    let arr = projected.as_array().unwrap();
    assert_eq!(arr.len(), 2);
    assert_eq!(arr[0]["category"], "Electronics");
    assert_eq!(arr[0]["count"], 42);
    assert_eq!(arr[1]["category"], "Books");
    assert_eq!(arr[1]["count"], 15);
}

#[test]
fn test_wrap_in_graphql_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_eq!(response["data"]["sales_aggregate"][0]["category"], "Electronics");
}

// ============================================================================
// Database Integration Tests
// ============================================================================

#[cfg(feature = "test-postgres")]
#[tokio::test]
async fn test_end_to_end_aggregate_query() {
    use std::sync::Arc;

    use fraiseql_core::{db::postgres::PostgresAdapter, runtime::Executor, schema::CompiledSchema};

    const TEST_DB_URL: &str =
        "postgresql://fraiseql_test:fraiseql_test_password@localhost:5433/test_fraiseql";

    // Setup test database
    let adapter = Arc::new(
        PostgresAdapter::new(TEST_DB_URL)
            .await
            .expect("Failed to connect to test database"),
    );

    // Create test schema
    let schema = CompiledSchema::new();
    let executor = Executor::new(schema, adapter);

    // Create test fact table metadata
    let metadata = create_test_metadata();

    // Create aggregate query
    let query_json = json!({
        "table": "tf_sales",
        "groupBy": {
            "category": true
        },
        "aggregates": [
            {"count": {}},
            {"revenue_sum": {}}
        ],
        "limit": 10
    });

    // Execute aggregate query
    let result = executor
        .execute_aggregate_query(&query_json, "sales_aggregate", &metadata)
        .await
        .expect("Failed to execute aggregate query");

    // Parse response
    let response = result;

    // Verify response structure
    assert!(response.get("data").is_some());
    assert!(response["data"].get("sales_aggregate").is_some());
    assert!(response["data"]["sales_aggregate"].is_array());

    println!("Aggregate query result: {}", serde_json::to_string_pretty(&response).unwrap());
}