fraiseql-cli 2.15.0

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! Unit tests for the pure mutation-contract logic (no database).

use fraiseql_core::schema::{
    ArgumentDefinition, CompiledSchema, FieldType, InjectedParamSource, InputFieldDefinition,
    InputObjectDefinition, MutationDefinition, MutationOperation,
};
use indexmap::IndexMap;

use super::*;
use crate::schema::pg_catalog::{OutColumn, PgFunction};

// ─── Fixtures ───────────────────────────────────────────────────────────────

fn single_input_arg(type_name: &str) -> ArgumentDefinition {
    ArgumentDefinition::new("input", FieldType::Input(type_name.to_string()))
}

fn input_type(name: &str, field_count: usize) -> InputObjectDefinition {
    let fields = (0..field_count)
        .map(|i| InputFieldDefinition::new(format!("f{i}"), "String"))
        .collect();
    InputObjectDefinition::new(name).with_fields(fields)
}

fn inject(keys: &[&str]) -> IndexMap<String, InjectedParamSource> {
    keys.iter()
        .map(|k| ((*k).to_string(), InjectedParamSource::Jwt((*k).to_string())))
        .collect()
}

fn col(name: &str, type_name: &str) -> OutColumn {
    OutColumn {
        name:      name.to_string(),
        type_name: type_name.to_string(),
        is_enum:   false,
    }
}

/// The canonical 13-column `mutation_response` result row.
fn full_response_columns() -> Vec<OutColumn> {
    vec![
        col("succeeded", "boolean"),
        col("state_changed", "boolean"),
        col("error_class", "text"),
        col("status_detail", "text"),
        col("http_status", "smallint"),
        col("message", "text"),
        col("entity_id", "uuid"),
        col("entity_type", "text"),
        col("entity", "jsonb"),
        col("updated_fields", "text[]"),
        col("cascade", "jsonb"),
        col("error_detail", "jsonb"),
        col("metadata", "jsonb"),
    ]
}

fn pg_function(in_types: &[&str], in_names: &[Option<&str>], out: Vec<OutColumn>) -> PgFunction {
    PgFunction {
        schema:      "public".to_string(),
        name:        "fn_test".to_string(),
        in_types:    in_types.iter().map(|s| (*s).to_string()).collect(),
        in_names:    in_names.iter().map(|n| n.map(str::to_string)).collect(),
        out_columns: out,
        returns_set: true,
        language:    "plpgsql".to_string(),
        source:      String::new(),
    }
}

// ─── expected_call: shape derivation ────────────────────────────────────────

#[test]
fn update_single_input_is_jsonb_payload_even_without_input_type_in_schema() {
    let mut m = MutationDefinition::new("updateUser", "UpdateUserResult");
    m.sql_source = Some("fn_update_user".to_string());
    m.operation = MutationOperation::Update {
        table: "tb_user".to_string(),
    };
    m.arguments = vec![single_input_arg("UpdateUserInput")];
    // No UpdateUserInput in the schema on purpose — the update path doesn't look it up.
    let schema = CompiledSchema::default();

    let ec = expected_call(&m, &schema).expect("update mutation is DB-backed");
    assert_eq!(ec.shape, CallShape::JsonbPayload);
    assert_eq!(ec.base_arity, 1);
    assert!(ec.first_is_jsonb_payload);
    assert_eq!(ec.total_arity(), 1);
}

#[test]
fn insert_single_input_flattens_input_type_fields() {
    let mut m = MutationDefinition::new("createUser", "CreateUserResult");
    m.sql_source = Some("fn_create_user".to_string());
    m.operation = MutationOperation::Insert {
        table: "tb_user".to_string(),
    };
    m.arguments = vec![single_input_arg("CreateUserInput")];
    let schema = CompiledSchema {
        input_types: vec![input_type("CreateUserInput", 3)],
        ..Default::default()
    };

    let ec = expected_call(&m, &schema).expect("insert mutation is DB-backed");
    assert_eq!(ec.shape, CallShape::FlattenedFields);
    assert_eq!(ec.base_arity, 3);
    assert!(!ec.first_is_jsonb_payload);
}

#[test]
fn insert_single_input_takes_jsonb_path_when_type_missing() {
    let mut m = MutationDefinition::new("createUser", "CreateUserResult");
    m.sql_source = Some("fn_create_user".to_string());
    m.operation = MutationOperation::Insert {
        table: String::new(),
    };
    m.arguments = vec![single_input_arg("CreateUserInput")];
    // CreateUserInput absent → the runtime can't flatten an unknown type, so it
    // forwards the whole input as one jsonb arg (`!known_input_type`, mirroring
    // mutation/mod.rs:500). The gate must agree: JsonbPayload(1), arg-1 is jsonb.
    let schema = CompiledSchema::default();

    let ec = expected_call(&m, &schema).expect("DB-backed");
    assert_eq!(ec.shape, CallShape::JsonbPayload);
    assert_eq!(ec.base_arity, 1);
    assert!(ec.first_is_jsonb_payload);
}

#[test]
fn flat_args_count_each_argument() {
    let mut m = MutationDefinition::new("archive", "ArchiveResult");
    m.sql_source = Some("fn_archive".to_string());
    m.arguments = vec![
        ArgumentDefinition::new("id", FieldType::Uuid),
        ArgumentDefinition::new("reason", FieldType::String),
    ];
    let schema = CompiledSchema::default();

    let ec = expected_call(&m, &schema).expect("DB-backed");
    assert_eq!(ec.shape, CallShape::FlatArgs);
    assert_eq!(ec.base_arity, 2);
}

#[test]
fn single_input_with_non_input_type_is_flat() {
    let mut m = MutationDefinition::new("touch", "TouchResult");
    m.sql_source = Some("fn_touch".to_string());
    // arg is named "input" but typed as a scalar, not an Input object.
    m.arguments = vec![ArgumentDefinition::new("input", FieldType::String)];
    let schema = CompiledSchema::default();

    let ec = expected_call(&m, &schema).expect("DB-backed");
    assert_eq!(ec.shape, CallShape::FlatArgs);
    assert_eq!(ec.base_arity, 1);
}

#[test]
fn inject_params_extend_total_arity_in_order() {
    let mut m = MutationDefinition::new("updateUser", "UpdateUserResult");
    m.sql_source = Some("fn_update_user".to_string());
    m.operation = MutationOperation::Update {
        table: "tb_user".to_string(),
    };
    m.arguments = vec![single_input_arg("UpdateUserInput")];
    m.inject_params = inject(&["tenant_id", "sub"]);
    let schema = CompiledSchema::default();

    let ec = expected_call(&m, &schema).expect("DB-backed");
    assert_eq!(ec.base_arity, 1);
    assert_eq!(ec.inject_names, vec!["tenant_id".to_string(), "sub".to_string()]);
    assert_eq!(ec.total_arity(), 3);
}

#[test]
fn non_db_backed_mutation_is_skipped() {
    let mut m = MutationDefinition::new("notifyExternal", "NotifyResult");
    // No sql_source, Custom operation (no table) → not DB-backed.
    m.operation = MutationOperation::Custom;
    let schema = CompiledSchema::default();
    assert!(expected_call(&m, &schema).is_none());
}

#[test]
fn falls_back_to_operation_table_when_sql_source_absent() {
    let mut m = MutationDefinition::new("createUser", "CreateUserResult");
    m.operation = MutationOperation::Insert {
        table: "fn_create_user".to_string(),
    };
    let schema = CompiledSchema::default();
    let ec = expected_call(&m, &schema).expect("table fallback is DB-backed");
    assert_eq!(ec.sql_source, "fn_create_user");
}

// ─── #484: single-JSONB arity mirror (input_style == Jsonb) ──────────────────
//
// The contract gate must mirror the runtime predicate
// (`mutation/mod.rs:499-500`): a single structured `input` arg is passed as ONE
// jsonb payload when the op is Update, OR `input_style == Jsonb`, OR the input
// type is unknown. Before the fix the gate only routed `Update` to JsonbPayload,
// so every single-JSONB Insert/Delete/Custom false-failed with ArityMismatch.

/// End-to-end: derive the expected call from the schema, then check it against
/// the candidate functions — exactly what `doctor`/`validate --against-db` do.
fn check(
    m: &MutationDefinition,
    schema: &CompiledSchema,
    candidates: &[PgFunction],
) -> Vec<ContractViolation> {
    check_mutation(&expected_call(m, schema).expect("DB-backed mutation"), candidates)
}

/// `createOrder` with a single 6-field `input`, given operation + input style.
fn order_mutation(
    op: MutationOperation,
    style: fraiseql_core::schema::InputStyle,
) -> MutationDefinition {
    let mut m = MutationDefinition::new("createOrder", "CreateOrderResult");
    m.sql_source = Some("fn_create_order".to_string());
    m.operation = op;
    m.input_style = style;
    m.arguments = vec![single_input_arg("CreateOrderInput")];
    m
}

fn schema_with_order_input(fields: usize) -> CompiledSchema {
    CompiledSchema {
        input_types: vec![input_type("CreateOrderInput", fields)],
        ..Default::default()
    }
}

#[test]
fn jsonb_insert_single_input_no_false_arity_mismatch() {
    use fraiseql_core::schema::InputStyle;
    // input_style = jsonb + a single-jsonb function → the runtime sends one jsonb
    // arg, so the gate must NOT expect the 6 flattened fields. (Today: ArityMismatch{6}.)
    let m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Jsonb,
    );
    let schema = schema_with_order_input(6);
    let candidates = vec![pg_function(
        &["jsonb"],
        &[Some("p_input")],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "single-jsonb insert must be clean");
}

#[test]
fn jsonb_insert_with_inject_param_no_violations() {
    use fraiseql_core::schema::InputStyle;
    let mut m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Jsonb,
    );
    m.inject_params = inject(&["tenant_id"]);
    let schema = schema_with_order_input(6);
    let candidates = vec![pg_function(
        &["jsonb", "uuid"],
        &[Some("p_input"), Some("tenant_id")],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "jsonb + inject must be clean");
}

#[test]
fn jsonb_insert_against_flattened_function_is_arity_mismatch() {
    use fraiseql_core::schema::InputStyle;
    // input_style = jsonb but the function actually flattens 6 args → genuinely
    // wrong: the runtime sends 1 jsonb, the function wants 6. Still caught.
    let m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Jsonb,
    );
    let schema = schema_with_order_input(6);
    let candidates = vec![pg_function(
        &["int4", "int4", "int4", "int4", "int4", "int4"],
        &[None, None, None, None, None, None],
        full_response_columns(),
    )];
    assert_eq!(
        check(&m, &schema, &candidates),
        vec![ContractViolation::ArityMismatch {
            expected: 1,
            found:    vec![6],
        }],
    );
}

#[test]
fn flatten_insert_is_unchanged() {
    use fraiseql_core::schema::InputStyle;
    // Flatten style with a known 6-field input → still flattens to 6 args.
    let m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Flatten,
    );
    let schema = schema_with_order_input(6);
    let candidates = vec![pg_function(
        &["text", "text", "text", "text", "text", "text"],
        &[None, None, None, None, None, None],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "flatten path unchanged");
}

#[test]
fn update_with_flatten_style_still_takes_jsonb_path() {
    use fraiseql_core::schema::InputStyle;
    // Update always uses the single-JSONB path regardless of input_style.
    let m = order_mutation(
        MutationOperation::Update {
            table: "tb_order".to_string(),
        },
        InputStyle::Flatten,
    );
    let schema = schema_with_order_input(6);
    let candidates = vec![pg_function(
        &["jsonb"],
        &[Some("p_input")],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "update→jsonb preserved");
}

#[test]
fn jsonb_payload_wrong_type_is_flagged() {
    use fraiseql_core::schema::InputStyle;
    let m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Jsonb,
    );
    let schema = schema_with_order_input(6);
    // Right arity (1) but arg-1 is text, not jsonb → the new path still asserts jsonb.
    let candidates = vec![pg_function(
        &["text"],
        &[Some("p_input")],
        full_response_columns(),
    )];
    assert!(
        check(&m, &schema, &candidates).contains(&ContractViolation::PayloadNotJsonb {
            actual: "text".to_string(),
        }),
        "single-jsonb path must assert arg-1 is jsonb",
    );
}

#[test]
fn custom_op_jsonb_style_is_not_update_only() {
    use fraiseql_core::schema::{InputStyle, MutationOperation as Op};
    // The gap is NOT update-only: a Custom (non-DML) op with jsonb style also
    // takes the single-JSONB path. (Today: ArityMismatch{3}.)
    let mut m = MutationDefinition::new("archiveOrder", "ArchiveOrderResult");
    m.sql_source = Some("fn_archive_order".to_string());
    m.operation = Op::Custom;
    m.input_style = InputStyle::Jsonb;
    m.arguments = vec![single_input_arg("ArchiveOrderInput")];
    let schema = CompiledSchema {
        input_types: vec![input_type("ArchiveOrderInput", 3)],
        ..Default::default()
    };
    let candidates = vec![pg_function(
        &["jsonb"],
        &[Some("p_input")],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "custom + jsonb must be clean");
}

#[test]
fn two_scalar_args_with_jsonb_style_stay_flat() {
    use fraiseql_core::schema::InputStyle;
    // No single structured `input` → input_arg_is_structured is false, so the
    // jsonb arm must NOT fire even with input_style = jsonb. Stays FlatArgs(2).
    let mut m = MutationDefinition::new("createOrder", "CreateOrderResult");
    m.sql_source = Some("fn_create_order".to_string());
    m.operation = MutationOperation::Insert {
        table: "tb_order".to_string(),
    };
    m.input_style = InputStyle::Jsonb;
    m.arguments = vec![
        ArgumentDefinition::new("a", FieldType::Int),
        ArgumentDefinition::new("b", FieldType::Int),
    ];
    let schema = CompiledSchema::default();
    let candidates = vec![pg_function(
        &["int4", "int4"],
        &[None, None],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "two scalar args stay FlatArgs(2)");
}

#[test]
fn preserve_naming_jsonb_single_input_holds() {
    use fraiseql_core::schema::{InputStyle, NamingConvention};
    let m = order_mutation(
        MutationOperation::Insert {
            table: "tb_order".to_string(),
        },
        InputStyle::Jsonb,
    );
    let schema = CompiledSchema {
        input_types: vec![input_type("CreateOrderInput", 6)],
        naming_convention: NamingConvention::Preserve,
        ..Default::default()
    };
    let candidates = vec![pg_function(
        &["jsonb"],
        &[Some("p_input")],
        full_response_columns(),
    )];
    assert_eq!(check(&m, &schema, &candidates), vec![], "arg-1-is-jsonb holds under Preserve");
}

// ─── check_mutation: call binding ───────────────────────────────────────────

fn jsonb_update_call() -> ExpectedCall {
    ExpectedCall {
        sql_source:             "fn_update_user".to_string(),
        shape:                  CallShape::JsonbPayload,
        base_arity:             1,
        inject_names:           vec!["tenant_id".to_string()],
        first_is_jsonb_payload: true,
        payload_keys:           vec![],
        stamps:                 None,
    }
}

#[test]
fn missing_function_when_no_candidates() {
    let v = check_mutation(&jsonb_update_call(), &[]);
    assert_eq!(v, vec![ContractViolation::MissingFunction]);
}

#[test]
fn arity_mismatch_reports_found_arities() {
    let candidates = vec![pg_function(
        &["jsonb"],
        &[Some("input")],
        full_response_columns(),
    )];
    // expects 2 (1 payload + 1 inject) but the candidate takes 1.
    let v = check_mutation(&jsonb_update_call(), &candidates);
    assert_eq!(
        v,
        vec![ContractViolation::ArityMismatch {
            expected: 2,
            found:    vec![1],
        }]
    );
}

#[test]
fn ambiguous_when_two_overloads_match_arity() {
    let f = || {
        pg_function(
            &["jsonb", "uuid"],
            &[Some("input"), Some("tenant_id")],
            full_response_columns(),
        )
    };
    let v = check_mutation(&jsonb_update_call(), &[f(), f()]);
    assert_eq!(v, vec![ContractViolation::AmbiguousFunction { arity: 2, count: 2 }]);
}

#[test]
fn payload_not_jsonb_flagged() {
    let candidates = vec![pg_function(
        &["text", "uuid"],
        &[Some("input"), Some("tenant_id")],
        full_response_columns(),
    )];
    let v = check_mutation(&jsonb_update_call(), &candidates);
    assert!(v.contains(&ContractViolation::PayloadNotJsonb {
        actual: "text".to_string(),
    }));
}

#[test]
fn happy_path_has_no_violations() {
    let candidates = vec![pg_function(
        &["jsonb", "uuid"],
        &[Some("input"), Some("tenant_id")],
        full_response_columns(),
    )];
    let v = check_mutation(&jsonb_update_call(), &candidates);
    assert!(v.is_empty(), "expected no violations, got {v:?}");
}

#[test]
fn inject_name_mismatch_is_a_warning() {
    let candidates = vec![pg_function(
        &["jsonb", "uuid"],
        &[Some("input"), Some("org_id")], // server binds inject `tenant_id` here
        full_response_columns(),
    )];
    let v = check_mutation(&jsonb_update_call(), &candidates);
    let mismatch = v
        .iter()
        .find(|x| matches!(x, ContractViolation::InjectNameMismatch { .. }))
        .expect("inject name mismatch reported");
    assert_eq!(mismatch.severity(), Severity::Warn);
}

#[test]
fn unnamed_inject_param_position_is_not_flagged() {
    // Function with no parameter names → can't verify inject names → no warning.
    let candidates = vec![pg_function(
        &["jsonb", "uuid"],
        &[None, None],
        full_response_columns(),
    )];
    let v = check_mutation(&jsonb_update_call(), &candidates);
    assert!(
        !v.iter().any(|x| matches!(x, ContractViolation::InjectNameMismatch { .. })),
        "unnamed params should not trigger an inject-name mismatch: {v:?}"
    );
}

// ─── check_mutation: response shape ─────────────────────────────────────────

fn flat_call() -> ExpectedCall {
    ExpectedCall {
        sql_source:             "fn_create".to_string(),
        shape:                  CallShape::FlatArgs,
        base_arity:             1,
        inject_names:           vec![],
        first_is_jsonb_payload: false,
        payload_keys:           vec![],
        stamps:                 None,
    }
}

#[test]
fn missing_succeeded_column_is_an_error() {
    let mut cols = full_response_columns();
    cols.retain(|c| c.name != "succeeded");
    let candidates = vec![pg_function(&["jsonb"], &[Some("input")], cols)];
    let v = check_mutation(&flat_call(), &candidates);
    let missing = v
        .iter()
        .find(|x| {
            matches!(
                x,
                ContractViolation::MissingRequiredColumn {
                    column: "succeeded",
                }
            )
        })
        .expect("missing succeeded reported");
    assert_eq!(missing.severity(), Severity::Error);
}

#[test]
fn wrong_succeeded_type_is_an_error() {
    let mut cols = full_response_columns();
    cols[0] = col("succeeded", "text");
    let candidates = vec![pg_function(&["jsonb"], &[Some("input")], cols)];
    let v = check_mutation(&flat_call(), &candidates);
    assert!(v.contains(&ContractViolation::RequiredColumnWrongType {
        column: "succeeded",
        actual: "text".to_string(),
    }));
}

#[test]
fn optional_column_wrong_type_is_a_warning() {
    let mut cols = full_response_columns();
    // entity declared as text instead of jsonb.
    if let Some(c) = cols.iter_mut().find(|c| c.name == "entity") {
        c.type_name = "text".to_string();
    }
    let candidates = vec![pg_function(&["jsonb"], &[Some("input")], cols)];
    let v = check_mutation(&flat_call(), &candidates);
    let warn = v
        .iter()
        .find(|x| {
            matches!(
                x,
                ContractViolation::OptionalColumnWrongType {
                    column: "entity",
                    ..
                }
            )
        })
        .expect("entity type warning reported");
    assert_eq!(warn.severity(), Severity::Warn);
}

#[test]
fn error_class_enum_is_accepted() {
    let mut cols = full_response_columns();
    if let Some(c) = cols.iter_mut().find(|c| c.name == "error_class") {
        c.type_name = "app.mutation_error_class".to_string();
        c.is_enum = true;
    }
    let candidates = vec![pg_function(&["jsonb"], &[Some("input")], cols)];
    let v = check_mutation(&flat_call(), &candidates);
    assert!(
        !v.iter().any(|x| matches!(
            x,
            ContractViolation::OptionalColumnWrongType {
                column: "error_class",
                ..
            }
        )),
        "enum error_class must be accepted: {v:?}"
    );
}

#[test]
fn scalar_return_is_unverifiable() {
    let candidates = vec![pg_function(&["jsonb"], &[Some("input")], vec![])];
    let v = check_mutation(&flat_call(), &candidates);
    let unverifiable = v
        .iter()
        .find(|x| matches!(x, ContractViolation::ResponseShapeUnverifiable))
        .expect("unverifiable reported");
    assert_eq!(unverifiable.severity(), Severity::Warn);
}

// ─── Report aggregation ─────────────────────────────────────────────────────

#[test]
fn report_counts_split_by_severity() {
    let mut report = ContractReport {
        checked:   2,
        skipped:   1,
        mutations: vec![],
    };
    report.mutations.push(MutationReport {
        mutation:   "updateUser".to_string(),
        sql_source: "fn_update_user".to_string(),
        violations: vec![
            ContractViolation::MissingRequiredColumn {
                column: "succeeded",
            }, // error
            ContractViolation::ResponseShapeUnverifiable, // warn
        ],
    });
    assert_eq!(report.error_count(), 1);
    assert_eq!(report.warn_count(), 1);
    let json = report.to_json();
    assert_eq!(json["errors"], 1);
    assert_eq!(json["warnings"], 1);
    assert_eq!(json["checked"], 2);
    assert_eq!(json["skipped"], 1);
}

// ─── check_mutation: payload-key consumption (#384 category 2) ──────────────

/// A `JsonbPayload` call whose keys the scan should probe.
fn payload_call(keys: &[&str]) -> ExpectedCall {
    ExpectedCall {
        sql_source:             "fn_update_thing".to_string(),
        shape:                  CallShape::JsonbPayload,
        base_arity:             1,
        inject_names:           vec![],
        first_is_jsonb_payload: true,
        payload_keys:           keys.iter().map(ToString::to_string).collect(),
        stamps:                 None,
    }
}

/// A jsonb-taking plpgsql function with the given body and a full response row.
fn payload_function(body: &str) -> PgFunction {
    let mut f = pg_function(&["jsonb"], &[Some("payload")], full_response_columns());
    f.source = body.to_string();
    f
}

#[test]
fn payload_keys_referenced_in_body_are_clean() {
    let candidates = vec![payload_function(
        "BEGIN PERFORM payload->>'author'; PERFORM payload->>'title'; END",
    )];
    let v = check_mutation(&payload_call(&["author", "title"]), &candidates);
    assert_eq!(v, vec![], "keys the body extracts must not be flagged");
}

#[test]
fn unreferenced_payload_key_is_flagged() {
    // The body extracts `author` but never `ownerId` (in either casing) — the
    // silently-dropped-input shape from the issue comment.
    let candidates = vec![payload_function("BEGIN PERFORM payload->>'author'; END")];
    let v = check_mutation(&payload_call(&["author", "ownerId"]), &candidates);
    assert_eq!(
        v,
        vec![ContractViolation::PayloadKeyUnreferenced {
            field:     "ownerId".to_string(),
            snake_key: "owner_id".to_string(),
        }]
    );
}

#[test]
fn snake_case_reference_satisfies_a_camel_case_field() {
    // The runtime re-cases payload keys to stored names, so a body reading the
    // snake form consumes the camelCase-declared field.
    let candidates = vec![payload_function("BEGIN PERFORM payload->>'owner_id'; END")];
    let v = check_mutation(&payload_call(&["ownerId"]), &candidates);
    assert_eq!(v, vec![]);
}

#[test]
fn whole_payload_consumer_skips_the_scan() {
    // `jsonb_populate_record` reads every key without naming any.
    let candidates = vec![payload_function(
        "BEGIN INSERT INTO tb_thing SELECT * FROM jsonb_populate_record(NULL::tb_thing, payload); \
         PERFORM payload->>'author'; END",
    )];
    let v = check_mutation(&payload_call(&["author", "ownerId"]), &candidates);
    assert_eq!(v, vec![]);
}

#[test]
fn non_sql_language_skips_the_scan() {
    // For a C function `prosrc` is a symbol name, not scannable source.
    let mut f = payload_function("thing_update_impl");
    f.language = "c".to_string();
    let v = check_mutation(&payload_call(&["author"]), &[f]);
    assert_eq!(v, vec![]);
}

#[test]
fn forwarding_body_without_extraction_skips_the_scan() {
    // A body that never extracts any key forwards the payload to a helper —
    // per-key scanning would flag every field of a correct function.
    let candidates = vec![payload_function(
        "BEGIN PERFORM app.do_update(payload); END",
    )];
    let v = check_mutation(&payload_call(&["author", "ownerId"]), &candidates);
    assert_eq!(v, vec![]);
}

#[test]
fn expected_call_populates_payload_keys_for_known_update_input() {
    let mut m = MutationDefinition::new("updateThing", "UpdateThingResult");
    m.sql_source = Some("fn_update_thing".to_string());
    m.operation = MutationOperation::Update {
        table: "tb_thing".to_string(),
    };
    m.arguments = vec![single_input_arg("UpdateThingInput")];
    let schema = CompiledSchema {
        input_types: vec![input_type("UpdateThingInput", 2)],
        ..CompiledSchema::new()
    };
    let call = expected_call(&m, &schema).expect("DB-backed mutation");
    assert_eq!(call.payload_keys, vec!["f0".to_string(), "f1".to_string()]);
}

#[test]
fn expected_call_has_no_payload_keys_for_unknown_input_type() {
    // Unknown input type → the payload keys cannot be enumerated; the scan
    // must not fire on guesses.
    let mut m = MutationDefinition::new("updateThing", "UpdateThingResult");
    m.sql_source = Some("fn_update_thing".to_string());
    m.operation = MutationOperation::Update {
        table: "tb_thing".to_string(),
    };
    m.arguments = vec![single_input_arg("NotInSchema")];
    let call = expected_call(&m, &CompiledSchema::new()).expect("DB-backed mutation");
    assert!(call.payload_keys.is_empty());
}

// ─── check_mutation: literal entity_type stamps (rulings AA 1, AJ 2) ────────

/// `createUser: CreateUserResult = User | DuplicateEmailError | ValidationError`, backed by
/// `fn_create_user()`; `Admin` is a type of the schema no outcome of this mutation can be.
fn stamp_schema() -> (CompiledSchema, MutationDefinition) {
    use fraiseql_core::schema::{TypeDefinition, UnionDefinition};
    let error = |name: &str| {
        let mut t = TypeDefinition::new(name, "v_error");
        t.is_error = true;
        t
    };
    let schema = CompiledSchema {
        types: vec![
            TypeDefinition::new("User", "v_user"),
            TypeDefinition::new("Admin", "v_admin"),
            error("DuplicateEmailError"),
            error("ValidationError"),
        ],
        unions: vec![UnionDefinition::new("CreateUserResult").with_members(vec![
            "User".to_string(),
            "DuplicateEmailError".to_string(),
            "ValidationError".to_string(),
        ])],
        ..CompiledSchema::new()
    };
    let mut m = MutationDefinition::new("createUser", "CreateUserResult");
    m.sql_source = Some("fn_create_user".to_string());
    (schema, m)
}

/// The Error-grade findings `check_mutation` reports for `fn_create_user` with `body`.
fn stamp_errors(body: &str) -> Vec<String> {
    let (schema, m) = stamp_schema();
    let call = expected_call(&m, &schema).expect("DB-backed mutation");
    let mut f = pg_function(&[], &[], full_response_columns());
    f.source = body.to_string();
    check_mutation(&call, &[f])
        .iter()
        .filter(|v| v.severity() == Severity::Error)
        .map(ToString::to_string)
        .collect()
}

// A success stamped with a type the mutation cannot return: the server refuses the write
// (a contract error, rolled back); the lint says so before it ships.
#[test]
fn a_literal_success_stamp_outside_the_contract_is_an_error() {
    let errors = stamp_errors(
        "BEGIN RETURN fraiseql.mutation_ok(to_jsonb(v_user), v_user.id, \
         p_entity_type => 'Admin'); END",
    );
    assert!(errors.iter().any(|e| e.contains("'Admin'")), "{errors:?}");
}

// A failure stamped, by position, with the success type — the #465-era habit AG 3 made a
// contract error.
#[test]
fn a_literal_error_stamp_outside_the_contract_is_an_error() {
    let errors = stamp_errors(
        "BEGIN RETURN fraiseql.mutation_err('conflict', 'Email taken', NULL, 409, 'User'); END",
    );
    assert!(errors.iter().any(|e| e.contains("'User'")), "{errors:?}");
}

// A stamp assigned to the result record names no type of the schema at all.
#[test]
fn an_assigned_stamp_outside_the_contract_is_an_error() {
    let errors = stamp_errors("BEGIN result.entity_type := 'tb_user'; RETURN result; END");
    assert!(errors.iter().any(|e| e.contains("'tb_user'")), "{errors:?}");
}

// Pins (pass before and after): what the lint must never judge.
#[test]
fn stamps_inside_the_contract_and_what_is_not_a_literal_stamp_are_clean() {
    for body in [
        // In the contract, each arm and the assignment.
        "BEGIN RETURN fraiseql.mutation_ok(to_jsonb(v), v.id, p_entity_type => 'User'); END",
        "BEGIN RETURN mutation_err('conflict', 'x', p_entity_type => 'DuplicateEmailError'); END",
        "BEGIN RETURN fraiseql.mutation_err('invalid', 'x', NULL, 422, 'ValidationError'); END",
        "BEGIN result.entity_type := 'User'; RETURN result; END",
        // Not literals: the runtime is the backstop.
        "BEGIN RETURN fraiseql.mutation_ok(to_jsonb(v), v.id, p_entity_type => v_type); END",
        "BEGIN RETURN fraiseql.mutation_ok(to_jsonb(v), v.id, NULL); END",
        // A comparison, not an assignment.
        "BEGIN PERFORM 1 FROM audit a WHERE a.entity_type = 'Admin'; RETURN r; END",
        // Commented out.
        "BEGIN\n-- RETURN fraiseql.mutation_ok(e, i, 'Admin');\nRETURN r; END",
        "BEGIN -- p_entity_type => 'Admin'\n /* result.entity_type := 'Admin'; */ RETURN r; END",
        // A helper's name inside a string, its parenthesis closed outside it: not a call.
        "BEGIN PERFORM app.log('mutation_ok(', e, 'Admin'); RETURN r; END",
        // Another function's stamp argument.
        "BEGIN PERFORM app.log_event(p_entity_type => 'Admin'); RETURN r; END",
    ] {
        assert_eq!(stamp_errors(body), Vec::<String>::new(), "{body}");
    }
}

// The finding names the outcome, the stamp and exactly the set that outcome allows — the
// runtime's own contract (`StampContract`); an assignment is judged against both outcomes.
#[test]
fn an_off_contract_stamp_names_its_outcome_and_the_set_it_allows() {
    let (schema, m) = stamp_schema();
    let call = expected_call(&m, &schema).expect("DB-backed mutation");
    let run = |body: &str| {
        let mut f = pg_function(&[], &[], full_response_columns());
        f.source = body.to_string();
        check_mutation(&call, &[f])
    };
    let errors = || {
        vec![
            "DuplicateEmailError".to_string(),
            "ValidationError".to_string(),
        ]
    };
    assert_eq!(
        run("BEGIN RETURN fraiseql.mutation_ok(to_jsonb(v), v.id, p_entity_type => 'Admin'); END"),
        vec![ContractViolation::OffContractStamp {
            arm:     StampArm::Success,
            stamp:   "Admin".to_string(),
            allowed: vec!["User".to_string()],
        }]
    );
    assert_eq!(
        run("BEGIN RETURN fraiseql.mutation_err('conflict', 'x', NULL, 409, 'User'); END"),
        vec![ContractViolation::OffContractStamp {
            arm:     StampArm::Error,
            stamp:   "User".to_string(),
            allowed: errors(),
        }]
    );
    let mut either = vec!["User".to_string()];
    either.extend(errors());
    assert_eq!(
        run("BEGIN r.entity_type := 'it''s'; RETURN r; END"),
        vec![ContractViolation::OffContractStamp {
            arm:     StampArm::Either,
            stamp:   "it's".to_string(),
            allowed: either,
        }]
    );
    // Upper-case helper names and a `::text` cast are the same call and the same literal; a
    // stamp repeated in one body is reported once.
    assert_eq!(
        run("BEGIN IF x THEN RETURN FRAISEQL.MUTATION_OK(e, i, 'Admin'::text); END IF; \
             RETURN fraiseql.mutation_ok(e, i, p_entity_type := 'Admin'); END")
        .len(),
        1
    );
    // A string that merely contains a call is not code.
    assert_eq!(
        run("BEGIN EXECUTE 'SELECT fraiseql.mutation_ok(e, i, ''Admin'')'; RETURN r; END"),
        vec![]
    );
    // A function in another language: its source is a symbol, not SQL.
    let mut c = pg_function(&[], &[], full_response_columns());
    c.source = "mutation_ok(e, i, 'Admin')".to_string();
    c.language = "c".to_string();
    assert_eq!(check_mutation(&call, &[c]), vec![]);
}