fraiseql-core 2.3.2

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
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
//! End-to-End Tests: Cross-Database Federation Chains
//!
//! This test suite validates federation behavior across multiple database backends
//! and cross-database entity resolution chains.
//!
//! Test scenarios:
//! 1. PostgreSQL → PostgreSQL entity chain
//! 2. PostgreSQL → MySQL entity chain
//! 3. PostgreSQL → SQLite entity chain
//! 4. MySQL → PostgreSQL → SQLite chain (3 databases)
//! 5. Entity resolution with type conversion across databases
//! 6. Key field mapping across database types
//! 7. Field selection from different database backends
//! 8. Error handling for cross-database mismatches

#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::needless_collect)] // Reason: intermediate collect is needed before assert_eq! consumes the iterator
#![allow(clippy::used_underscore_binding)] // Reason: test helper results prefixed with _ to suppress unused warnings
use std::collections::HashMap;

use fraiseql_core::federation::types::{
    EntityRepresentation, FederatedType, FederationMetadata, KeyDirective,
};
use serde_json::json;

// ============================================================================
// Test: Basic Single-Database Federation
// ============================================================================

#[test]
fn test_single_database_federation_postgresql() {
    // TEST: Single PostgreSQL instance serving federation
    // SCHEMA:
    //   Users table in PostgreSQL (source of truth)
    //   Orders table in PostgreSQL (references Users)
    //
    // WHEN: Entity resolution from PostgreSQL
    // THEN: Should resolve entities correctly

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type, order_type],
        remote_subscription_fields: HashMap::new(),
    };

    assert_eq!(metadata.types.len(), 2);
    assert_eq!(metadata.types[0].keys.len(), 1);
}

// ============================================================================
// Test: Cross-Database Entity Chains
// ============================================================================

#[test]
fn test_postgres_to_mysql_entity_chain() {
    // TEST: Entity resolution chain: PostgreSQL → MySQL
    // ARCHITECTURE:
    //   Users subgraph (PostgreSQL) - owns User entity
    //   Orders subgraph (MySQL)     - references User from PostgreSQL
    //
    // FLOW: Router requests User.orders → Orders MySQL → references User from PostgreSQL
    // WHEN: Entity is resolved across databases
    // THEN: Should handle type conversions transparently

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type, order_type],
        remote_subscription_fields: HashMap::new(),
    };

    // Simulate: User resolved from PostgreSQL
    let mut pg_user_fields = HashMap::new();
    pg_user_fields.insert("id".to_string(), json!("user-pg-123"));
    pg_user_fields.insert("name".to_string(), json!("Alice"));

    let pg_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-pg-123"));
            m
        },
        all_fields: pg_user_fields,
    };

    // Simulate: Order resolved from MySQL references the User
    let mut mysql_order_fields = HashMap::new();
    mysql_order_fields.insert("id".to_string(), json!("order-mysql-456"));
    mysql_order_fields.insert("user_id".to_string(), json!("user-pg-123"));
    mysql_order_fields.insert("total".to_string(), json!(99.99));

    let mysql_order = EntityRepresentation {
        typename:   "Order".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("order-mysql-456"));
            m
        },
        all_fields: mysql_order_fields,
    };

    // Both should be resolvable
    assert_eq!(pg_user.typename, "User");
    assert_eq!(mysql_order.typename, "Order");
    assert!(!metadata.types.is_empty());
}

#[test]
fn test_postgres_sqlite_entity_chain() {
    // TEST: Entity resolution: PostgreSQL → SQLite
    // SCENARIO:
    //   Users in PostgreSQL (primary production database)
    //   Local cache in SQLite (for offline support)
    //
    // WHEN: Entity requested, could come from either source
    // THEN: Should resolve correctly regardless of source

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type],
        remote_subscription_fields: HashMap::new(),
    };

    // PostgreSQL source
    let mut pg_user_fields = HashMap::new();
    pg_user_fields.insert("id".to_string(), json!("user-123"));
    pg_user_fields.insert("email".to_string(), json!("alice@example.com"));

    let pg_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: pg_user_fields,
    };

    // SQLite source (same user, different database)
    let mut sqlite_user_fields = HashMap::new();
    sqlite_user_fields.insert("id".to_string(), json!("user-123"));
    sqlite_user_fields.insert("email".to_string(), json!("alice@example.com"));

    let sqlite_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: sqlite_user_fields,
    };

    // Both sources should produce same logical entity
    assert_eq!(pg_user.key_fields, sqlite_user.key_fields);
    assert_eq!(metadata.types[0].name, "User");
}

// ============================================================================
// Test: Multi-Database Chains (3+ Databases)
// ============================================================================

#[test]
fn test_three_database_chain_mysql_postgres_sqlite() {
    // TEST: Complex chain: MySQL → PostgreSQL → SQLite
    // ARCHITECTURE:
    //   Subgraph 1: Users in MySQL
    //   Subgraph 2: Orders in PostgreSQL (references Users)
    //   Subgraph 3: Inventory in SQLite (references Orders)
    //
    // FLOW: Router requests Order.inventory → PostgreSQL → SQLite
    //                                              ↓
    //                                    references User in MySQL
    //
    // WHEN: Full chain is executed
    // THEN: All 3 databases should coordinate correctly

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let mut inventory_type = FederatedType::new("Inventory".to_string());
    inventory_type.keys.push(KeyDirective {
        fields:     vec!["order_id".to_string()],
        resolvable: true,
    });

    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type, order_type, inventory_type],
        remote_subscription_fields: HashMap::new(),
    };

    // MySQL User
    let mut mysql_user_fields = HashMap::new();
    mysql_user_fields.insert("id".to_string(), json!("user-mysql-1"));

    let _mysql_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-mysql-1"));
            m
        },
        all_fields: mysql_user_fields,
    };

    // PostgreSQL Order (references MySQL User)
    let mut pg_order_fields = HashMap::new();
    pg_order_fields.insert("id".to_string(), json!("order-pg-100"));
    pg_order_fields.insert("user_id".to_string(), json!("user-mysql-1"));

    let pg_order = EntityRepresentation {
        typename:   "Order".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("order-pg-100"));
            m
        },
        all_fields: pg_order_fields,
    };

    // SQLite Inventory (references PostgreSQL Order)
    let mut sqlite_inventory_fields = HashMap::new();
    sqlite_inventory_fields.insert("order_id".to_string(), json!("order-pg-100"));
    sqlite_inventory_fields.insert("status".to_string(), json!("in_stock"));

    let sqlite_inventory = EntityRepresentation {
        typename:   "Inventory".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("order_id".to_string(), json!("order-pg-100"));
            m
        },
        all_fields: sqlite_inventory_fields,
    };

    // All entities should be resolvable
    assert!(pg_order.key_fields.contains_key("id"));
    assert!(sqlite_inventory.key_fields.contains_key("order_id"));
    assert_eq!(metadata.types.len(), 3);
}

// ============================================================================
// Test: Key Field Mapping Across Databases
// ============================================================================

#[test]
fn test_key_field_type_conversion_string_int() {
    // TEST: Key field type conversion: String (PostgreSQL) ↔ INT (MySQL)
    // SCENARIO:
    //   PostgreSQL stores user_id as TEXT
    //   MySQL stores user_id as INT
    //
    // WHEN: Entity resolution across these databases
    // THEN: Should handle type conversion (string to int and back)

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type],
        remote_subscription_fields: HashMap::new(),
    };

    // PostgreSQL: TEXT id
    let mut pg_user_fields = HashMap::new();
    pg_user_fields.insert("id".to_string(), json!("12345"));

    let pg_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("12345"));
            m
        },
        all_fields: pg_user_fields,
    };

    // MySQL: INT id (same logical value)
    let mut mysql_user_fields = HashMap::new();
    mysql_user_fields.insert("id".to_string(), json!(12345));

    let mysql_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!(12345));
            m
        },
        all_fields: mysql_user_fields,
    };

    // Both should be valid entities (even with different JSON types)
    assert_eq!(pg_user.typename, mysql_user.typename);
    assert_eq!(metadata.types[0].name, "User");
}

// ============================================================================
// Test: Field Selection from Different Databases
// ============================================================================

#[test]
fn test_field_selection_across_databases() {
    // TEST: Select different fields from different databases
    // SCENARIO:
    //   User.id comes from PostgreSQL
    //   User.profile comes from MySQL
    //
    // WHEN: Resolving user with fields from multiple sources
    // THEN: Should aggregate fields correctly

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let _metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type],
        remote_subscription_fields: HashMap::new(),
    };

    // PostgreSQL provides: id, created_at
    let mut pg_user_fields = HashMap::new();
    pg_user_fields.insert("id".to_string(), json!("user-123"));
    pg_user_fields.insert("created_at".to_string(), json!("2024-01-01"));

    let pg_partial_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: pg_user_fields,
    };

    // MySQL provides: id, profile
    let mut mysql_user_fields = HashMap::new();
    mysql_user_fields.insert("id".to_string(), json!("user-123"));
    mysql_user_fields.insert("profile".to_string(), json!({"bio": "Engineer"}));

    let mysql_partial_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: mysql_user_fields,
    };

    // Both have different fields but same key
    assert_eq!(pg_partial_user.key_fields, mysql_partial_user.key_fields);
    assert!(pg_partial_user.has_field("created_at"));
    assert!(mysql_partial_user.has_field("profile"));
}

// ============================================================================
// Test: Consistency Across Database Boundaries
// ============================================================================

#[test]
fn test_entity_consistency_across_databases() {
    // TEST: Entity should be consistent when resolved from different databases
    // SCENARIO:
    //   User exists in both PostgreSQL and MySQL (replicated)
    //
    // WHEN: User resolved from either database
    // THEN: Key fields should be identical

    let _user_type = FederatedType::new("User".to_string());

    // PostgreSQL version
    let mut pg_fields = HashMap::new();
    pg_fields.insert("id".to_string(), json!("user-123"));
    pg_fields.insert("email".to_string(), json!("alice@example.com"));
    pg_fields.insert("name".to_string(), json!("Alice Smith"));

    let pg_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: pg_fields,
    };

    // MySQL version (same data)
    let mut mysql_fields = HashMap::new();
    mysql_fields.insert("id".to_string(), json!("user-123"));
    mysql_fields.insert("email".to_string(), json!("alice@example.com"));
    mysql_fields.insert("name".to_string(), json!("Alice Smith"));

    let mysql_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-123"));
            m
        },
        all_fields: mysql_fields,
    };

    // Key fields must be identical
    assert_eq!(pg_user.key_fields, mysql_user.key_fields);
    assert_eq!(pg_user.typename, mysql_user.typename);
}

// ============================================================================
// Test: Error Handling for Database Mismatches
// ============================================================================

#[test]
fn test_missing_entity_in_secondary_database() {
    // TEST: Handle case where entity exists in one DB but not other
    // SCENARIO:
    //   User exists in PostgreSQL
    //   User doesn't exist in MySQL
    //
    // WHEN: Requested from MySQL
    // THEN: Should return None/error appropriately

    let user_type = FederatedType::new("User".to_string());

    let _metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![user_type],
        remote_subscription_fields: HashMap::new(),
    };

    // PostgreSQL has this user
    let mut pg_fields = HashMap::new();
    pg_fields.insert("id".to_string(), json!("user-999"));

    let _pg_user = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: {
            let mut m = HashMap::new();
            m.insert("id".to_string(), json!("user-999"));
            m
        },
        all_fields: pg_fields,
    };

    // MySQL doesn't have this user (would be None/empty)
    let mysql_user: Option<EntityRepresentation> = None;

    // Verify that not all sources might have the entity
    assert!(mysql_user.is_none());
}

#[test]
fn test_database_type_mismatch_in_keys() {
    // TEST: Handle key type mismatch across databases
    // SCENARIO:
    //   Entity key in PostgreSQL: STRING
    //   Entity key in MySQL: INTEGER
    //   Same logical entity but different types
    //
    // WHEN: Trying to match keys
    // THEN: Should handle type coercion or return error

    let _user_type = FederatedType::new("User".to_string());

    // PostgreSQL: key as string
    let pg_key_fields = {
        let mut m = HashMap::new();
        m.insert("id".to_string(), json!("12345"));
        m
    };

    // MySQL: key as int
    let mysql_key_fields = {
        let mut m = HashMap::new();
        m.insert("id".to_string(), json!(12345));
        m
    };

    // Keys are logically equivalent but have different JSON types
    assert_ne!(pg_key_fields, mysql_key_fields);
}

// ============================================================================
// Test: Performance Considerations
// ============================================================================

#[test]
fn test_batch_entity_resolution_multiple_databases() {
    // TEST: Batch resolution across multiple databases
    // SCENARIO:
    //   Resolve 100 orders, each might come from different database
    //
    // WHEN: Batching entities across databases
    // THEN: Should handle efficiently

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    let _metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![order_type],
        remote_subscription_fields: HashMap::new(),
    };

    // Simulate 50 orders from PostgreSQL
    let _pg_orders: Vec<EntityRepresentation> = (0..50)
        .map(|i| EntityRepresentation {
            typename:   "Order".to_string(),
            key_fields: {
                let mut m = HashMap::new();
                m.insert("id".to_string(), json!(format!("pg-order-{}", i)));
                m
            },
            all_fields: {
                let mut m = HashMap::new();
                m.insert("id".to_string(), json!(format!("pg-order-{}", i)));
                m.insert("total".to_string(), json!(99.99 + f64::from(i)));
                m
            },
        })
        .collect();

    // Simulate 50 orders from MySQL
    let _mysql_orders: Vec<EntityRepresentation> = (50..100)
        .map(|i| EntityRepresentation {
            typename:   "Order".to_string(),
            key_fields: {
                let mut m = HashMap::new();
                m.insert("id".to_string(), json!(format!("mysql-order-{}", i)));
                m
            },
            all_fields: {
                let mut m = HashMap::new();
                m.insert("id".to_string(), json!(format!("mysql-order-{}", i)));
                m.insert("total".to_string(), json!(49.99 + f64::from(i - 50)));
                m
            },
        })
        .collect();

    // Verify batch can be processed
    assert_eq!(_pg_orders.len(), 50);
    assert_eq!(_mysql_orders.len(), 50);
}