mongo-graphql 0.0.1

Dynamic GraphQL schema generation from MongoDB collections, optimized for AWS Lambda
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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use std::collections::{HashMap, HashSet};

use async_graphql::dynamic::ResolverContext;
use mongodb::bson::{doc, oid::ObjectId, Bson, Document};
use mongodb::{Client, Database};

use crate::error::GraphQLError;
use crate::helpers::serialization::{document_to_graphql_value, input_doc_to_mongo};
use crate::resolvers::query::transform_id_filter;
use crate::schema::definition::{CollectionDef, FieldType, JunctionDef, RelationKind, SchemaDefinition};

pub async fn resolve_create(
    ctx: ResolverContext<'_>,
    collection_def: &CollectionDef,
    client: &Client,
    db: &Database,
) -> Result<Option<serde_json::Value>, GraphQLError> {
    let definition = ctx.data::<SchemaDefinition>()?;
    let collection = db.collection::<Document>(&collection_def.collection);

    let mut input: Document = ctx
        .args
        .try_get("input")?
        .deserialize()
        .map_err(|err| GraphQLError::Internal(err.message))?;

    let oid = ObjectId::new();

    with_transaction!(client, session, {
        let fk_values = extract_relation_fields(
            &mut input, collection_def, definition, db, &mut session, &HashMap::new(), oid, 1,
        )
        .await?;

        let mut doc = input_doc_to_mongo(input, collection_def);
        for (mongo_name, value) in fk_values {
            doc.insert(mongo_name, value);
        }
        doc.insert("_id", oid);
        doc.insert("id", oid);

        collection.insert_one(&doc).session(&mut session).await.map_err(|err| {
            if is_duplicate_key_error(&err) {
                GraphQLError::DuplicateKey {
                    message: format!("Duplicate key in collection '{}'", collection_def.collection),
                }
            } else {
                GraphQLError::from(err)
            }
        })?;

        Ok(Some(document_to_graphql_value(&doc, collection_def)))
    })
}

pub async fn resolve_update(
    ctx: ResolverContext<'_>,
    collection_def: &CollectionDef,
    client: &Client,
    db: &Database,
) -> Result<Option<serde_json::Value>, GraphQLError> {
    let definition = ctx.data::<SchemaDefinition>()?;
    let collection = db.collection::<Document>(&collection_def.collection);

    let where_input: Document = ctx
        .args
        .try_get("where")?
        .deserialize()
        .map_err(|err| GraphQLError::Internal(err.message))?;
    let mut update_input: Document = ctx
        .args
        .try_get("input")?
        .deserialize()
        .map_err(|err| GraphQLError::Internal(err.message))?;

    let filter = transform_id_filter(where_input)?;

    with_transaction!(client, session, {
        let existing = collection
            .find_one(filter.clone())
            .session(&mut session)
            .await?
            .ok_or_else(|| GraphQLError::NotFound {
                message: format!(
                    "Document not found in '{}' for update",
                    collection_def.collection
                ),
            })?;

        let source_oid = existing
            .get_object_id("_id")
            .map_err(|_| GraphQLError::Internal("Existing document missing _id".into()))?;
        let current_fks = build_current_fk_map(&existing, collection_def);

        let fk_values = extract_relation_fields(
            &mut update_input, collection_def, definition, db, &mut session, &current_fks, source_oid, 1,
        )
        .await?;

        let mut update_doc = input_doc_to_mongo(update_input, collection_def);
        if update_doc.contains_key("_id") || update_doc.contains_key("id") {
            return Err(GraphQLError::Internal(
                "Updating the id field is not allowed".into(),
            ));
        }

        for (mongo_name, value) in fk_values {
            update_doc.insert(mongo_name, value);
        }

        collection.update_one(filter, doc! { "$set": &update_doc })
            .session(&mut session)
            .await
            .map_err(GraphQLError::from)?;

        let mut merged = existing;
        for (key, value) in &update_doc {
            merged.insert(key.clone(), value.clone());
        }
        Ok(Some(document_to_graphql_value(&merged, collection_def)))
    })
}

pub async fn resolve_delete(
    ctx: ResolverContext<'_>,
    collection_def: &CollectionDef,
    client: &Client,
    db: &Database,
) -> Result<Option<serde_json::Value>, GraphQLError> {
    let collection = db.collection::<Document>(&collection_def.collection);

    let where_input: Document = ctx
        .args
        .try_get("where")?
        .deserialize()
        .map_err(|err| GraphQLError::Internal(err.message))?;

    let id = where_input
        .get_str("id")
        .map(|s| s.to_owned())
        .or_else(|_| {
            where_input
                .get_object_id("id")
                .map(|oid| oid.to_hex())
        })
        .map_err(|_| GraphQLError::Internal("where.id is required for delete".into()))?;

    let filter = transform_id_filter(where_input)?;

    with_transaction!(client, session, {
        let result = collection
            .delete_one(filter)
            .session(&mut session)
            .await
            .map_err(GraphQLError::from)?;

        if result.deleted_count == 0 {
            return Err(GraphQLError::NotFound {
                message: format!(
                    "Document not found in '{}' for delete",
                    collection_def.collection
                ),
            });
        }

        Ok(Some(serde_json::json!({
            "success": true,
            "deletedId": &id,
        })))
    })
}

fn check_depth(depth: u8) -> Result<(), GraphQLError> {
    if depth >= 3 {
        return Err(GraphQLError::Internal(
            "Maximum nested mutation depth (3) exceeded".into(),
        ));
    }
    Ok(())
}

fn validate_single_operation(nested: &Document) -> Result<(), GraphQLError> {
    let ops = ["connect", "create", "disconnect", "delete", "update"];
    if ops.iter().filter(|op| nested.contains_key(*op)).count() > 1 {
        return Err(GraphQLError::Internal(
            "Only one of create, connect, disconnect, delete, or update can be specified per relation field"
                .into(),
        ));
    }
    Ok(())
}

/// Process a forward to-one nested input (CreateOneInput / UpdateOneInput).
/// Returns Some(ObjectId) for connect/create, None for disconnect/delete (sets FK to null).
async fn process_nested_one_input(
    nested: &Document,
    target_collection_def: &CollectionDef,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    current_fk: Option<&Bson>,
    depth: u8,
) -> Result<Option<Bson>, GraphQLError> {
    check_depth(depth)?;
    validate_single_operation(nested)?;

    if let Some(hex) = nested
        .get("connect")
        .and_then(|v| v.as_document())
        .and_then(|d| d.get_str("id").ok())
    {
        let oid = ObjectId::parse_str(hex)
            .map_err(|_| GraphQLError::Internal(format!("Invalid ObjectId in connect: {}", hex)))?;
        return Ok(Some(Bson::ObjectId(oid)));
    }

    if let Some(create_doc) = nested.get("create").and_then(|v| v.as_document()) {
        let oid = create_nested_document(
            create_doc, target_collection_def, definition, db, session, None, depth,
        )
        .await?;
        return Ok(Some(Bson::ObjectId(oid)));
    }

    if nested.get("disconnect") == Some(&Bson::Boolean(true)) {
        return Ok(None);
    }

    if nested.get("delete") == Some(&Bson::Boolean(true)) {
        if let Some(fk_oid) = current_fk.and_then(|v| v.as_object_id()) {
            db.collection::<Document>(&target_collection_def.collection)
                .delete_one(doc! { "_id": fk_oid })
                .session(session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(None);
    }

    if let Some(update_data) = nested.get("update").and_then(|v| v.as_document()) {
        if let Some(fk_oid) = current_fk.and_then(|v| v.as_object_id()) {
            apply_nested_update(
                doc! { "_id": fk_oid }, update_data, target_collection_def, db, session,
            )
            .await?;
        }
        return Ok(current_fk.cloned());
    }

    Ok(None)
}

/// Scan a mutation input for relation fields and dispatch to the appropriate handler.
/// Returns (mongo_field_name, Bson_value) pairs to merge into the MongoDB document.
///
/// `current_fks` is populated for updates (maps GraphQL name → current FK value),
/// `source_oid` is the _id of the document being created/updated,
/// `depth` tracks nesting level (max 3).
async fn extract_relation_fields(
    input: &mut Document,
    collection_def: &CollectionDef,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    current_fks: &HashMap<String, Option<Bson>>,
    source_oid: ObjectId,
    depth: u8,
) -> Result<Vec<(String, Bson)>, GraphQLError> {
    let mut fk_values: Vec<(String, Bson)> = Vec::new();
    let relation_field_keys: HashSet<String> = collection_def
        .fields
        .iter()
        .filter(|field| matches!(field.field_type, FieldType::Relation(_)))
        .map(|field| field.graphql_name())
        .collect();

    for field_name in &relation_field_keys {
        let field_def = collection_def
            .fields
            .iter()
            .find(|field| field.graphql_name() == *field_name)
            .unwrap();

        let relation = match &field_def.field_type {
            FieldType::Relation(relation) => relation,
            _ => continue,
        };

        let target_def = definition.collection_by_name(&relation.collection).ok_or_else(|| {
            GraphQLError::Internal(format!(
                "Target collection '{}' not found in schema definition",
                relation.collection
            ))
        })?;

        let value = match input.remove(field_def.graphql_name().as_str()) {
            Some(Bson::Document(nested)) => nested,
            Some(_) => {
                return Err(GraphQLError::Internal(format!(
                    "Expected a nested input object for relation field '{}'",
                    field_name
                )));
            }
            None => continue,
        };

        match relation.kind {
            RelationKind::OneToMany | RelationKind::OneToOne => {
                let current_fk = current_fks.get(field_name).and_then(|v| v.as_ref());
                let processed = process_nested_one_input(
                    &value, target_def, definition, db, session, current_fk, depth,
                )
                .await?;
                let bson = processed.unwrap_or(Bson::Null);
                fk_values.push((field_def.name.clone(), bson));
            }
            RelationKind::ManyToMany => {
                let junction = relation.junction.as_ref().ok_or_else(|| {
                    GraphQLError::Internal(
                        "ManyToMany relation missing junction definition".into(),
                    )
                })?;
                process_nested_many_to_many_input(
                    &value, junction, target_def, source_oid, definition, db, session, depth,
                )
                .await?;
            }
        }
    }

    let remaining_keys: Vec<String> = input.keys().cloned().collect();
    for key in remaining_keys {
        if relation_field_keys.contains(&key) {
            continue;
        }

        let (target_collection, fk_field, kind) = match find_reverse_field(definition, collection_def, &key) {
            Some(info) => info,
            None => continue,
        };

        let value = match input.remove(&key) {
            Some(Bson::Document(nested)) => nested,
            Some(_) => {
                return Err(GraphQLError::Internal(format!(
                    "Expected a nested input object for reverse field '{}'",
                    key
                )));
            }
            None => continue,
        };

        match kind {
            RelationKind::OneToMany => {
                process_nested_many_input(
                    &value, target_collection, &fk_field, source_oid, definition, db, session, depth,
                )
                .await?;
            }
            RelationKind::OneToOne => {
                process_reverse_one_to_one_input(
                    &value, target_collection, fk_field.as_str(), source_oid, definition, db, session,
                    depth,
                )
                .await?;
            }
            _ => unreachable!(),
        }
    }

    Ok(fk_values)
}

/// Find a OneToMany or OneToOne relation in `definition` where the reverse field
/// matches `key` on `collection_def`. Returns (target_collection, fk_field_name, kind).
fn find_reverse_field<'a>(
    definition: &'a SchemaDefinition,
    collection_def: &CollectionDef,
    key: &str,
) -> Option<(&'a CollectionDef, String, RelationKind)> {
    for other in &definition.collections {
        if other.collection == collection_def.collection {
            continue;
        }
        for field in &other.fields {
            if let FieldType::Relation(relation) = &field.field_type {
                if relation.collection != collection_def.collection {
                    continue;
                }
                let match_result: Option<RelationKind> = match relation.kind {
                    RelationKind::OneToMany => {
                        let name = relation
                            .reverse_name
                            .clone()
                            .unwrap_or_else(|| other.plural_name());
                        if name == key { Some(RelationKind::OneToMany) } else { None }
                    }
                    RelationKind::OneToOne => {
                        let name = relation
                            .reverse_name
                            .clone()
                            .unwrap_or_else(|| other.singular_name());
                        if name == key { Some(RelationKind::OneToOne) } else { None }
                    }
                    _ => None,
                };
                if let Some(kind) = match_result {
                    return Some((other, field.name.clone(), kind));
                }
            }
        }
    }
    None
}

async fn process_nested_many_input(
    nested: &Document,
    target_collection_def: &CollectionDef,
    fk_field: &str,
    source_oid: ObjectId,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    depth: u8,
) -> Result<(), GraphQLError> {
    check_depth(depth)?;
    validate_single_operation(nested)?;

    let target_collection = db.collection::<Document>(&target_collection_def.collection);

    if let Some(ids) = nested.get("connect").and_then(|v| v.as_array()) {
        for oid in &parse_id_array(ids)? {
            target_collection
                .update_one(
                    doc! { "_id": oid },
                    doc! { "$set": { fk_field: source_oid } },
                )
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(elems) = nested.get("create").and_then(|v| v.as_array()) {
        for create_val in elems {
            let create_doc = create_val.as_document().ok_or_else(|| {
                GraphQLError::Internal("create entries must be objects".into())
            })?;
            create_nested_document(
                create_doc, target_collection_def, definition, db, session,
                Some((fk_field, source_oid)), depth,
            )
            .await?;
        }
        return Ok(());
    }

    if let Some(ids) = nested.get("disconnect").and_then(|v| v.as_array()) {
        for oid in &parse_id_array(ids)? {
            target_collection
                .update_one(
                    doc! { "_id": oid, fk_field: source_oid },
                    doc! { "$set": { fk_field: Bson::Null } },
                )
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(ids) = nested.get("delete").and_then(|v| v.as_array()) {
        for oid in &parse_id_array(ids)? {
            target_collection
                .delete_one(doc! { "_id": oid, fk_field: source_oid })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(updates) = nested.get("update").and_then(|v| v.as_array()) {
        return process_nested_many_update(updates, target_collection_def, db, session).await;
    }

    Ok(())
}

async fn process_nested_many_to_many_input(
    nested: &Document,
    junction: &JunctionDef,
    target_collection_def: &CollectionDef,
    source_oid: ObjectId,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    depth: u8,
) -> Result<(), GraphQLError> {
    check_depth(depth)?;
    validate_single_operation(nested)?;

    let junction_collection = db.collection::<Document>(&junction.collection);

    if let Some(ids) = nested.get("connect").and_then(|v| v.as_array()) {
        for oid in &parse_id_array(ids)? {
            junction_collection
                .insert_one(&doc! {
                    &junction.local_field: source_oid,
                    &junction.foreign_field: oid,
                })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(elems) = nested.get("create").and_then(|v| v.as_array()) {
        for create_val in elems {
            let create_doc = create_val.as_document().ok_or_else(|| {
                GraphQLError::Internal("create entries must be objects".into())
            })?;
            let oid = create_nested_document(
                create_doc, target_collection_def, definition, db, session, None, depth,
            )
            .await?;

            junction_collection
                .insert_one(&doc! {
                    &junction.local_field: source_oid,
                    &junction.foreign_field: oid,
                })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(ids) = nested.get("disconnect").and_then(|v| v.as_array()) {
        for oid in &parse_id_array(ids)? {
            junction_collection
                .delete_one(doc! {
                    &junction.local_field: source_oid,
                    &junction.foreign_field: oid,
                })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(ids) = nested.get("delete").and_then(|v| v.as_array()) {
        let target_collection = db.collection::<Document>(&target_collection_def.collection);
        for oid in &parse_id_array(ids)? {
            junction_collection
                .delete_one(doc! {
                    &junction.local_field: source_oid,
                    &junction.foreign_field: oid,
                })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
            target_collection
                .delete_one(doc! { "_id": oid })
                .session(&mut *session)
                .await
                .map_err(GraphQLError::from)?;
        }
        return Ok(());
    }

    if let Some(updates) = nested.get("update").and_then(|v| v.as_array()) {
        return process_nested_many_update(updates, target_collection_def, db, session).await;
    }

    Ok(())
}

async fn process_reverse_one_to_one_input(
    nested: &Document,
    target_collection_def: &CollectionDef,
    fk_field: &str,
    source_oid: ObjectId,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    depth: u8,
) -> Result<(), GraphQLError> {
    check_depth(depth)?;
    validate_single_operation(nested)?;

    let target_collection = db.collection::<Document>(&target_collection_def.collection);

    if let Some(hex) = nested
        .get("connect")
        .and_then(|v| v.as_document())
        .and_then(|d| d.get_str("id").ok())
    {
        let target_oid = ObjectId::parse_str(hex)
            .map_err(|_| GraphQLError::Internal("Invalid connect id".into()))?;
        target_collection
            .update_one(
                doc! { "_id": target_oid },
                doc! { "$set": { fk_field: source_oid } },
            )
            .session(&mut *session)
            .await
            .map_err(|err| {
                GraphQLError::Internal(format!("Reverse OneToOne connect failed: {}", err))
            })?;
    }

    if let Some(create_doc) = nested.get("create").and_then(|v| v.as_document()) {
        create_nested_document(
            create_doc, target_collection_def, definition, db, session,
            Some((fk_field, source_oid)), depth,
        )
        .await?;
    }

    if nested.get("disconnect") == Some(&Bson::Boolean(true)) {
        target_collection
            .update_many(
                doc! { fk_field: source_oid },
                doc! { "$unset": { fk_field: "" } },
            )
            .session(&mut *session)
            .await
            .map_err(|err| {
                GraphQLError::Internal(format!("Reverse OneToOne disconnect failed: {}", err))
            })?;
    }

    if nested.get("delete") == Some(&Bson::Boolean(true)) {
        target_collection
            .delete_many(doc! { fk_field: source_oid })
            .session(&mut *session)
            .await
            .map_err(|err| {
                GraphQLError::Internal(format!("Reverse OneToOne delete failed: {}", err))
            })?;
    }

    if let Some(update_data) = nested.get("update").and_then(|v| v.as_document()) {
        apply_nested_update(
            doc! { fk_field: source_oid }, update_data, target_collection_def, db, session,
        )
        .await?;
    }

    Ok(())
}

async fn create_nested_document(
    create_doc: &Document,
    target_collection_def: &CollectionDef,
    definition: &SchemaDefinition,
    db: &Database,
    session: &mut mongodb::ClientSession,
    fk_field: Option<(&str, ObjectId)>,
    depth: u8,
) -> Result<ObjectId, GraphQLError> {
    let mut target_doc = input_doc_to_mongo(create_doc.clone(), target_collection_def);
    let oid = ObjectId::new();
    target_doc.insert("_id", oid);
    target_doc.insert("id", oid);

    if let Some((field_name, value)) = fk_field {
        target_doc.insert(field_name, value);
    }

    let next_depth = depth + 1;
    if next_depth < 3 {
        let mut create_doc_mut = create_doc.clone();
        let nested_fk_values = Box::pin(extract_relation_fields(
            &mut create_doc_mut,
            target_collection_def,
            definition,
            db,
            session,
            &HashMap::new(),
            oid,
            next_depth,
        ))
        .await?;
        for (mongo_name, value) in nested_fk_values {
            target_doc.insert(mongo_name, value);
        }
    }

    let target_collection = db.collection::<Document>(&target_collection_def.collection);
    target_collection
        .insert_one(&target_doc)
        .session(&mut *session)
        .await
        .map_err(|err| {
            if is_duplicate_key_error(&err) {
                GraphQLError::DuplicateKey {
                    message: format!(
                        "Duplicate key in nested create for collection '{}'",
                        target_collection_def.collection
                    ),
                }
            } else {
                GraphQLError::from(err)
            }
        })?;

    Ok(oid)
}

/// Apply scalar field updates to an existing document found by `filter`.
async fn apply_nested_update(
    filter: Document,
    update_data: &Document,
    target_collection_def: &CollectionDef,
    db: &Database,
    session: &mut mongodb::ClientSession,
) -> Result<(), GraphQLError> {
    let update_doc = input_doc_to_mongo(update_data.clone(), target_collection_def);
    if update_doc.is_empty() {
        return Ok(());
    }
    let target_collection = db.collection::<Document>(&target_collection_def.collection);
    target_collection
        .update_one(filter, doc! { "$set": &update_doc })
        .session(&mut *session)
        .await
        .map_err(GraphQLError::from)?;
    Ok(())
}

/// Process a to-many `update` array: `[{ where: …, data: … }]`.
/// Used by both reverse to-many and ManyToMany nested update handlers.
async fn process_nested_many_update(
    updates: &mongodb::bson::Array,
    target_collection_def: &CollectionDef,
    db: &Database,
    session: &mut mongodb::ClientSession,
) -> Result<(), GraphQLError> {
    for entry in updates {
        let entry_doc = entry.as_document().ok_or_else(|| {
            GraphQLError::Internal("update entries must be objects".into())
        })?;
        let where_clause = entry_doc.get_document("where").map_err(|_| {
            GraphQLError::Internal("update entry must have a 'where' field".into())
        })?;
        let data = entry_doc.get_document("data").map_err(|_| {
            GraphQLError::Internal("update entry must have a 'data' field".into())
        })?;
        let filter = transform_id_filter(where_clause.clone())?;
        apply_nested_update(filter, data, target_collection_def, db, session).await?;
    }
    Ok(())
}

fn build_current_fk_map(
    existing: &Document,
    collection_def: &CollectionDef,
) -> HashMap<String, Option<Bson>> {
    collection_def
        .fields
        .iter()
        .filter(|field| matches!(field.field_type, FieldType::Relation(_)))
        .map(|field| (field.graphql_name(), existing.get(&field.name).cloned()))
        .collect()
}

fn parse_id_array(
    arr: &mongodb::bson::Array,
) -> Result<Vec<ObjectId>, GraphQLError> {
    arr.iter()
        .map(|entry| {
            let doc = entry.as_document().ok_or_else(|| {
                GraphQLError::Internal(
                    "Each entry must be an object with an id field".into(),
                )
            })?;
            let hex = doc.get_str("id").map_err(|_| {
                GraphQLError::Internal("Each entry must have an 'id' field".into())
            })?;
            ObjectId::parse_str(hex)
                .map_err(|_| GraphQLError::Internal("Invalid ObjectId in entry".into()))
        })
        .collect()
}

macro_rules! with_transaction {
    ($client:expr, $session:ident, $body:block) => {{
        let mut $session = $client.start_session().await?;
        $session.start_transaction().await.map_err(|err| {
            GraphQLError::Internal(format!("Failed to start transaction: {}", err))
        })?;
        let __result: Result<_, GraphQLError> = (|| async { $body })().await;
        match &__result {
            Ok(_) => {
                $session.commit_transaction().await.map_err(|err| {
                    GraphQLError::Internal(format!("Failed to commit transaction: {}", err))
                })?;
            }
            Err(_) => {
                let _ = $session.abort_transaction().await;
            }
        }
        __result
    }};
}
use with_transaction;

fn is_duplicate_key_error(error: &mongodb::error::Error) -> bool {
    match &*error.kind {
        mongodb::error::ErrorKind::Write(write_failure) => match write_failure {
            mongodb::error::WriteFailure::WriteError(write_error) => {
                write_error.code == 11000 || write_error.code == 11001
            }
            mongodb::error::WriteFailure::WriteConcernError(write_concern_error) => {
                write_concern_error.code == 11000 || write_concern_error.code == 11001
            }
            _ => false,
        },
        mongodb::error::ErrorKind::BulkWrite(bulk_failure) => {
            bulk_failure
                .write_errors
                .iter()
                .any(|(_, write_error)| write_error.code == 11000 || write_error.code == 11001)
        }
        _ => false,
    }
}