fraiseql-core 2.13.1

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
//! Cross-subgraph mutation coordination.

#![allow(clippy::unwrap_used, clippy::panic, clippy::print_stderr)] // Reason: test code, panics + skip notes acceptable
use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};
use serde_json::json;

use super::common;

#[tokio::test]
async fn test_mutation_coordinate_two_subgraph_updates() {
    // Coordinate mutations across two subgraphs
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![
            FederatedType {
                name:                "Order".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["order_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          false,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
            FederatedType {
                name:                "OrderItem".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["item_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          true,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
        ],
        remote_subscription_fields: std::collections::HashMap::new(),
    };

    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("order", &["order_id text", "status text"])])
            .await
    else {
        eprintln!("SKIP test_mutation_coordinate_two_subgraph_updates: no postgres");
        return;
    };

    // Update order (subgraph 1, local). Seed the row first so the read-back
    // UPDATE matches an existing entity (#430).
    let order_vars = json!({"order_id": "order123", "status": "confirmed"});
    executor
        .execute_local_mutation("Order", "createOrder", &order_vars)
        .await
        .unwrap_or_else(|e| panic!("seed createOrder failed: {e}"));
    executor
        .execute_local_mutation("Order", "updateOrder", &order_vars)
        .await
        .unwrap_or_else(|e| panic!("execute_local_mutation(Order/updateOrder) failed: {e}"));

    // Update order items (subgraph 2, extended)
    let item_vars = json!({"item_id": "item1", "quantity": 2});
    executor
        .execute_extended_mutation("OrderItem", "updateQuantity", &item_vars)
        .await
        .unwrap_or_else(|e| {
            panic!("execute_extended_mutation(OrderItem/updateQuantity) failed: {e}")
        });
}

#[tokio::test]
async fn test_mutation_coordinate_three_subgraph_updates() {
    // Coordinate mutations across three subgraphs
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![
            FederatedType {
                name:                "User".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["id".to_string()],
                    resolvable: true,
                }],
                is_extends:          false,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
            FederatedType {
                name:                "Order".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["order_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          true,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
            FederatedType {
                name:                "Payment".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["payment_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          true,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
        ],
        remote_subscription_fields: std::collections::HashMap::new(),
    };

    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("user", &["id text", "status text"])]).await
    else {
        eprintln!("SKIP test_mutation_coordinate_three_subgraph_updates: no postgres");
        return;
    };

    // Update user in subgraph 1 (local). Seed the row, then update it and verify
    // the response is read back from the database, not echoed from input (#430).
    executor
        .execute_local_mutation("User", "createUser", &json!({"id": "user123", "status": "new"}))
        .await
        .unwrap_or_else(|e| panic!("seed createUser failed: {e}"));
    let user_vars = json!({"id": "user123", "status": "verified"});
    let updated = executor
        .execute_local_mutation("User", "updateUser", &user_vars)
        .await
        .unwrap_or_else(|e| panic!("execute_local_mutation(User/updateUser) failed: {e}"));
    assert_eq!(updated["__typename"], "User");
    assert_eq!(updated["status"], "verified", "read-back must reflect the updated DB row");

    // Update order in subgraph 2 (extended)
    let order_vars = json!({"order_id": "order123", "status": "processing"});
    executor
        .execute_extended_mutation("Order", "updateOrder", &order_vars)
        .await
        .unwrap_or_else(|e| panic!("execute_extended_mutation(Order/updateOrder) failed: {e}"));

    // Update payment in subgraph 3 (extended)
    let payment_vars = json!({"payment_id": "pay123", "status": "processed"});
    executor
        .execute_extended_mutation("Payment", "processPayment", &payment_vars)
        .await
        .unwrap_or_else(|e| {
            panic!("execute_extended_mutation(Payment/processPayment) failed: {e}")
        });
}

#[tokio::test]
async fn test_mutation_reference_update_propagation() {
    // Reference update propagation across subgraphs (extended only)
    let metadata = common::metadata_extended_type("Review", "review_id", &["product_id"], &[]);
    let Some((_pg, executor)) = common::pg_mutation_executor(metadata, &[]).await else {
        eprintln!("SKIP test_mutation_reference_update_propagation: no postgres");
        return;
    };

    let variables = json!({
        "review_id": "review123",
        "product_id": "product456",
        "rating": 5
    });

    executor
        .execute_extended_mutation("Review", "updateReview", &variables)
        .await
        .unwrap_or_else(|e| panic!("execute_extended_mutation(Review/updateReview) failed: {e}"));
}

#[tokio::test]
async fn test_mutation_circular_reference_handling() {
    // Circular reference handling in mutations
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![
            FederatedType {
                name:                "Author".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["author_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          false,
                external_fields:     vec![],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
            FederatedType {
                name:                "Book".to_string(),
                keys:                vec![KeyDirective {
                    fields:     vec!["book_id".to_string()],
                    resolvable: true,
                }],
                is_extends:          true,
                external_fields:     vec!["author_id".to_string()],
                shareable_fields:    vec![],
                inaccessible_fields: vec![],
                field_directives:    std::collections::HashMap::new(),
                type_shareable:      false,
            },
        ],
        remote_subscription_fields: std::collections::HashMap::new(),
    };

    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("author", &["author_id text", "name text"])])
            .await
    else {
        eprintln!("SKIP test_mutation_circular_reference_handling: no postgres");
        return;
    };

    // Update author (local). Seed first so the read-back UPDATE matches (#430).
    let author_vars = json!({"author_id": "author1", "name": "Updated Author"});
    executor
        .execute_local_mutation("Author", "createAuthor", &author_vars)
        .await
        .unwrap_or_else(|e| panic!("seed createAuthor failed: {e}"));
    executor
        .execute_local_mutation("Author", "updateAuthor", &author_vars)
        .await
        .unwrap_or_else(|e| panic!("execute_local_mutation(Author/updateAuthor) failed: {e}"));

    // Update book referencing author (circular, extended)
    let book_vars = json!({"book_id": "book1", "author_id": "author1", "title": "Updated Book"});
    executor
        .execute_extended_mutation("Book", "updateBook", &book_vars)
        .await
        .unwrap_or_else(|e| panic!("execute_extended_mutation(Book/updateBook) failed: {e}"));
}

#[tokio::test]
async fn test_mutation_multi_subgraph_transaction() {
    // Multi-subgraph transaction handling
    let metadata = common::metadata_single_key("Account", "account_id");
    let Some((_pg, executor)) = common::pg_mutation_executor(
        metadata,
        &[("account", &["account_id text", "balance numeric"])],
    )
    .await
    else {
        eprintln!("SKIP test_mutation_multi_subgraph_transaction: no postgres");
        return;
    };

    let variables = json!({
        "account_id": "acc123",
        "balance": 1000.00
    });

    // Seed first so the read-back UPDATE matches an existing account (#430).
    executor
        .execute_local_mutation("Account", "createAccount", &variables)
        .await
        .unwrap_or_else(|e| panic!("seed createAccount failed: {e}"));
    executor
        .execute_local_mutation("Account", "updateAccount", &variables)
        .await
        .unwrap_or_else(|e| panic!("execute_local_mutation(Account/updateAccount) failed: {e}"));
}

#[tokio::test]
async fn test_mutation_absent_local_entity_fails_loud() {
    // A local UPDATE against a row that does not exist must fail loud with a
    // not-found error (0-row read-back), not silently "succeed" by echoing the
    // input — the failure semantics a cross-subgraph coordinator relies on to
    // roll back (#430).
    let metadata = common::metadata_single_key("Transaction", "txn_id");
    let Some((_pg, executor)) = common::pg_mutation_executor(
        metadata,
        &[("transaction", &["txn_id text", "amount numeric"])],
    )
    .await
    else {
        eprintln!("SKIP test_mutation_absent_local_entity_fails_loud: no postgres");
        return;
    };

    // The `transaction` table is empty — this UPDATE matches no row.
    let variables = json!({
        "txn_id": "txn123",
        "amount": 100.00
    });

    let err = executor
        .execute_local_mutation("Transaction", "updateTransaction", &variables)
        .await
        .expect_err("an UPDATE matching no row must error, not fabricate success");
    assert!(
        err.to_string().contains("not found"),
        "0-row UPDATE must be a not-found error, got: {err}"
    );
}

#[tokio::test]
async fn test_mutation_subgraph_timeout_handling() {
    // Subgraph timeout handling (extended only)
    let metadata = common::metadata_extended_type("AsyncJob", "job_id", &[], &[]);
    let Some((_pg, executor)) = common::pg_mutation_executor(metadata, &[]).await else {
        eprintln!("SKIP test_mutation_subgraph_timeout_handling: no postgres");
        return;
    };

    let variables = json!({
        "job_id": "job123",
        "status": "processing"
    });

    executor
        .execute_extended_mutation("AsyncJob", "updateJob", &variables)
        .await
        .unwrap_or_else(|e| panic!("execute_extended_mutation(AsyncJob/updateJob) failed: {e}"));
}

#[tokio::test]
async fn test_mutation_concurrent_request_handling() {
    let metadata = common::metadata_single_key("User", "id");
    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("user", &["id text", "name text"])]).await
    else {
        eprintln!("SKIP test_mutation_concurrent_request_handling: no postgres");
        return;
    };

    // Spawn concurrent mutation requests sharing the executor (and its pool).
    let handles: Vec<_> = (0..5)
        .map(|i| {
            let exec = executor.clone();
            tokio::spawn(async move {
                let variables = json!({
                    "id": format!("user{}", i),
                    "name": format!("Updated User {}", i)
                });
                // Seed each row so the read-back UPDATE matches (#430).
                exec.execute_local_mutation("User", "createUser", &variables).await?;
                exec.execute_local_mutation("User", "updateUser", &variables).await
            })
        })
        .collect();

    // All mutations should complete successfully
    for handle in handles {
        let join_result = handle.await.unwrap_or_else(|e| panic!("task panicked: {e:?}"));
        join_result
            .unwrap_or_else(|e| panic!("execute_local_mutation(User/updateUser) failed: {e}"));
    }
}

// ── #430 read-back acceptance ─────────────────────────────────────────────────

#[tokio::test]
async fn local_update_reads_back_db_row_not_input_echo() {
    // The `version` column has a DB default and is never present in the input;
    // its appearance in the response proves the row is read back from the
    // database (RETURNING *), not echoed from the input variables.
    let metadata = common::metadata_single_key("Widget", "id");
    let Some((_pg, executor)) = common::pg_mutation_executor(
        metadata,
        &[("widget", &["id text", "status text", "version int not null default 7"])],
    )
    .await
    else {
        eprintln!("SKIP local_update_reads_back_db_row_not_input_echo: no postgres");
        return;
    };

    executor
        .execute_local_mutation("Widget", "createWidget", &json!({"id": "w1", "status": "new"}))
        .await
        .unwrap_or_else(|e| panic!("seed createWidget failed: {e}"));
    let resp = executor
        .execute_local_mutation("Widget", "updateWidget", &json!({"id": "w1", "status": "active"}))
        .await
        .unwrap_or_else(|e| panic!("updateWidget failed: {e}"));

    assert_eq!(resp["__typename"], "Widget");
    assert_eq!(resp["status"], "active", "read-back reflects the updated value");
    assert_eq!(
        resp["version"], 7,
        "the DB-default column must come from RETURNING *, not the input echo"
    );
}

#[tokio::test]
async fn local_delete_absent_row_is_not_found() {
    let metadata = common::metadata_single_key("Widget", "id");
    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("widget", &["id text"])]).await
    else {
        eprintln!("SKIP local_delete_absent_row_is_not_found: no postgres");
        return;
    };

    let err = executor
        .execute_local_mutation("Widget", "deleteWidget", &json!({"id": "ghost"}))
        .await
        .expect_err("a DELETE matching no row must error");
    assert!(
        err.to_string().contains("not found"),
        "0-row DELETE must be a not-found error, got: {err}"
    );
}

#[tokio::test]
async fn local_delete_returns_the_deleted_row() {
    let metadata = common::metadata_single_key("Widget", "id");
    let Some((_pg, executor)) =
        common::pg_mutation_executor(metadata, &[("widget", &["id text", "status text"])]).await
    else {
        eprintln!("SKIP local_delete_returns_the_deleted_row: no postgres");
        return;
    };

    executor
        .execute_local_mutation("Widget", "createWidget", &json!({"id": "w9", "status": "live"}))
        .await
        .unwrap_or_else(|e| panic!("seed createWidget failed: {e}"));
    let resp = executor
        .execute_local_mutation("Widget", "deleteWidget", &json!({"id": "w9"}))
        .await
        .unwrap_or_else(|e| panic!("deleteWidget failed: {e}"));

    assert_eq!(resp["__typename"], "Widget");
    assert_eq!(resp["id"], "w9", "DELETE ... RETURNING * returns the removed row");
    assert_eq!(resp["status"], "live");
}