fraiseql-cli 2.18.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
#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics acceptable
//! Compiler → runtime contract gate (audit coverage-gap §2).
//!
//! `fraiseql-cli` emits `schema.compiled.json`; the server/core parse it back with
//! serde. A field added on one side and silently defaulted (or refused) on the other
//! passes each crate's own lens — this class has caused two production REDs
//! (`token_revocation: null` boot-refusal; serde-default divergences). These tests
//! compile real fixtures with the CLI binary and assert that:
//!
//! 1. `RuntimeConfig::from_compiled_schema` — the server's boot-time config seam — accepts the
//!    compiler's output (it must not refuse valid compiler output), and
//! 2. an enterprise security toggle set in `fraiseql.toml` survives the full emit → parse →
//!    runtime-config-derivation chain (proving the field is *consumed*, not silently dropped or
//!    defaulted), and
//! 3. every field the compiler emits is preserved through `from_json` (parse drops nothing) —
//!    caught by a non-null-leaf round-trip superset check.

use std::{collections::BTreeSet, fs, process::Command};

use fraiseql_core::{runtime::RuntimeConfig, schema::CompiledSchema};
use tempfile::TempDir;

/// Compile `fraiseql.toml` + `types.json` with the real CLI binary, returning the
/// compiled JSON string. Panics with the CLI's stderr on failure.
fn compile(types_json: &str, toml_config: &str) -> String {
    let temp_dir = TempDir::new().unwrap();
    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");
    fs::write(&types_path, types_json).unwrap();
    fs::write(&toml_path, toml_config).unwrap();

    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output()
        .expect("failed to run fraiseql-cli");
    assert!(
        output.status.success(),
        "CLI compile failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    fs::read_to_string(&output_path).expect("compiled schema missing")
}

const TYPES_JSON: &str = r#"
{
  "types": [
    {
      "name": "Order",
      "sql_source": "v_order",
      "fields": [
        {"name": "id",     "type": "ID",     "nullable": false},
        {"name": "amount", "type": "Float",  "nullable": false}
      ]
    }
  ],
  "queries": [
    {
      "name": "orders",
      "return_type": "Order",
      "returns_list": true,
      "nullable": false,
      "sql_source": "v_order",
      "cache_ttl_seconds": 300,
      "inject_params": {"tenant_id": "jwt:tenant_id"}
    }
  ],
  "mutations": [
    {
      "name": "createOrder",
      "return_type": "Order",
      "sql_source": "fn_create_order",
      "invalidates_views": ["v_order"]
    }
  ]
}
"#;

/// The boot seam (`RuntimeConfig::from_compiled_schema`) must accept the compiler's
/// output, AND an enterprise toggle set in TOML must survive emit → parse → derive.
/// This is the exact chain the `token_revocation: null` / audit-default incidents
/// broke: the compiler emitted a config the server then refused or silently dropped.
#[test]
fn enterprise_audit_toggle_survives_emit_parse_runtime() {
    let toml = r#"
[schema]
name = "contract_audit"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = true
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false)
        .expect("core must parse CLI-produced schema");

    // The boot seam must not refuse valid compiler output.
    let runtime = RuntimeConfig::from_compiled_schema(&schema)
        .expect("RuntimeConfig::from_compiled_schema must accept compiler output");

    // `audit_logging_enabled = true` in TOML must reach the server's runtime config.
    assert!(
        runtime.audit_mutations,
        "audit_logging_enabled=true must survive emit→parse→runtime (it was consumed)"
    );
}

/// With the toggle off, the derived runtime config must reflect that (proving the
/// value is read, not hardcoded). Guards against a regression where the seam ignores
/// the compiled value entirely.
#[test]
fn enterprise_audit_toggle_off_is_respected() {
    let toml = r#"
[schema]
name = "contract_audit_off"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
    let runtime = RuntimeConfig::from_compiled_schema(&schema).unwrap();
    assert!(!runtime.audit_mutations, "audit_logging_enabled=false must be respected");
}

/// Every field the compiler emits must be consumed by the core parse: parse the
/// compiled JSON, re-serialize the parsed model, and assert no non-null field present
/// in the compiler output is missing from the re-serialized model. A field the parse
/// model doesn't know is silently dropped by serde — this check fails when that
/// happens. (`_content_hash` is a CLI-added envelope field, not a schema field.)
#[test]
fn every_emitted_field_survives_parse_roundtrip() {
    let toml = r#"
[schema]
name = "contract_roundtrip"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[queries.getOrder]
return_type = "Order"
return_array = false
sql_source = "v_order"

[[queries.getOrder.args]]
name = "orderId"
type = "ID"
required = true

[security]

# Note: [[security.rules]] / [[security.policies]] / [security] default_policy are
# intentionally absent — declared-but-unenforced authorization is rejected
# (#612 item 4 / #626 / #983). The emit↔parse contract this test guards is exercised
# by the remaining security fields (enterprise).

[security.enterprise]
rate_limiting_enabled = true
audit_logging_enabled = true
"#;
    let compiled_json = compile(TYPES_JSON, toml);

    let emitted: serde_json::Value = serde_json::from_str(&compiled_json).unwrap();
    let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
    let reparsed = serde_json::to_value(&schema).unwrap();

    let mut emitted_paths = BTreeSet::new();
    collect_nonnull_paths(&emitted, "", &mut emitted_paths);
    let mut reparsed_paths = BTreeSet::new();
    collect_nonnull_paths(&reparsed, "", &mut reparsed_paths);

    // `_content_hash` is the CLI's integrity envelope, not a CompiledSchema field.
    let dropped: Vec<&String> = emitted_paths
        .iter()
        .filter(|p| !p.starts_with("/_content_hash"))
        .filter(|p| !reparsed_paths.contains(*p))
        .collect();

    assert!(
        dropped.is_empty(),
        "core parse silently dropped {} compiler-emitted field(s); the emit↔parse \
         contract has drifted (a field added to the compiler is not consumed by \
         CompiledSchema). Dropped paths:\n  {}",
        dropped.len(),
        dropped.iter().map(|p| p.as_str()).collect::<Vec<_>>().join("\n  ")
    );
}

/// #379: `[security] persisted_queries_only = true` must survive emit → parse into
/// the **typed** `SecurityConfig::persisted_queries_only` field the server reads in
/// `trusted_docs_from_schema` (#977) — a rename on either side is now a compile or
/// load error, never a silently-disabled flag.
#[test]
fn persisted_queries_only_survives_emit_parse() {
    let toml = r#"
[schema]
name = "contract_pqo"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]
persisted_queries_only = true
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false)
        .expect("core must parse CLI-produced schema");
    let security = schema.security.expect("security must be present");
    assert!(
        security.persisted_queries_only,
        "persisted_queries_only=true must survive emit→parse into the typed field"
    );
}

/// Omitting the flag must compile to `persisted_queries_only = false` — never
/// silently strict — so a schema without the flag leaves the server permissive.
#[test]
fn persisted_queries_only_defaults_false() {
    let toml = r#"
[schema]
name = "contract_pqo_off"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
    let security = schema.security.expect("security must be present");
    assert!(
        !security.persisted_queries_only,
        "omitting the flag must compile to false, not strict-by-default"
    );
}

/// #379: `[security.cost_budget]` must survive emit → parse into the **typed**
/// `SecurityConfig::cost_budget` field the executor and tenant registry read —
/// not into the untyped `additional` map, where a key rename would silently
/// disable the ceiling.
#[test]
fn cost_budget_survives_emit_parse_into_typed_field() {
    let toml = r#"
[schema]
name = "contract_cost_budget"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]

[security.cost_budget]
per_request_max = 50
per_tenant_per_minute_default = 1000
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false)
        .expect("core must parse CLI-produced schema");
    let security = schema.security.expect("security must be present");
    let budget = security.cost_budget.expect("cost_budget must land in the typed field");
    assert_eq!(budget.per_request_max, Some(50));
    assert_eq!(budget.per_tenant_per_minute_default, Some(1000));
    // The untyped `additional` map is gone (#977): `SecurityConfig` denies
    // unknown fields, so "falls through to a catch-all" is unrepresentable.
}

/// Omitting `[security.cost_budget]` must compile to no budget — never a
/// surprise default ceiling.
#[test]
fn cost_budget_defaults_to_absent() {
    let toml = r#"
[schema]
name = "contract_cost_budget_off"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]
"#;
    let compiled_json = compile(TYPES_JSON, toml);
    let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
    let security = schema.security.expect("security must be present");
    assert!(
        security.cost_budget.is_none(),
        "omitting [security.cost_budget] must mean no budget, got {:?}",
        security.cost_budget
    );
}

/// Collect the set of JSON paths whose value is a non-null scalar or a container,
/// so a field present in one document but absent in the other is detectable.
fn collect_nonnull_paths(value: &serde_json::Value, prefix: &str, out: &mut BTreeSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            for (k, v) in map {
                let path = format!("{prefix}/{k}");
                if !v.is_null() {
                    out.insert(path.clone());
                }
                collect_nonnull_paths(v, &path, out);
            }
        },
        serde_json::Value::Array(items) => {
            for (i, v) in items.iter().enumerate() {
                let path = format!("{prefix}/{i}");
                if !v.is_null() {
                    out.insert(path.clone());
                }
                collect_nonnull_paths(v, &path, out);
            }
        },
        _ => {},
    }
}

// ── #623: [[caching.rules]] lower onto the compiled per-query TTL and
//    per-mutation invalidates_views — the fields the runtime already consumes ──

/// Fixture with a TTL-less query, a second query, and a mutation, so the rules
/// (not SDK annotations) are what the assertions observe.
const CACHING_TYPES_JSON: &str = r#"
{
  "types": [
    {
      "name": "Order",
      "sql_source": "v_order",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false}
      ]
    },
    {
      "name": "Inventory",
      "sql_source": "v_inventory",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false}
      ]
    }
  ],
  "queries": [
    {
      "name": "orders",
      "return_type": "Order",
      "returns_list": true,
      "nullable": false,
      "sql_source": "v_order"
    },
    {
      "name": "inventory",
      "return_type": "Inventory",
      "returns_list": true,
      "nullable": false,
      "sql_source": "v_inventory"
    }
  ],
  "mutations": [
    {
      "name": "createOrder",
      "return_type": "Order",
      "sql_source": "fn_create_order"
    }
  ]
}
"#;

const CACHING_TOML_HEAD: &str = r#"
[schema]
name = "contract_caching"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"
"#;

/// A `[[caching.rules]]` entry lowers its TTL onto the named query's
/// `cache_ttl_seconds` and appends the query's view to each trigger mutation's
/// `invalidates_views` — the two compiled fields the P12-tested runtime
/// (per-view TTL map + mutation-driven invalidation) actually consumes.
#[test]
fn caching_rule_lowers_ttl_and_invalidation_triggers() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = true

[[caching.rules]]
query = "inventory"
ttl_seconds = 120
invalidation_triggers = ["createOrder"]
"#
    );
    let compiled_json = compile(CACHING_TYPES_JSON, &toml);
    let schema = CompiledSchema::from_json(&compiled_json, false)
        .expect("core must parse CLI-produced schema");

    let query = schema
        .queries
        .iter()
        .find(|q| q.name == "inventory")
        .expect("inventory query present");
    assert_eq!(query.cache_ttl_seconds, Some(120), "rule TTL must land on the query");

    let mutation = schema
        .mutations
        .iter()
        .find(|m| m.name == "createOrder")
        .expect("createOrder mutation present");
    assert!(
        mutation.invalidates_views.iter().any(|v| v == "v_inventory"),
        "the trigger mutation must gain the rule query's view in invalidates_views, got {:?}",
        mutation.invalidates_views
    );
}

/// A rule naming a query that does not exist must fail the compile loudly —
/// a cache rule that silently matches nothing is the #612 config-honesty bug
/// this section was rejected over.
#[test]
fn caching_rule_with_unknown_query_fails_compile() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = true

[[caching.rules]]
query = "no_such_query"
ttl_seconds = 60
invalidation_triggers = []
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &toml);
    assert!(err.contains("no_such_query"), "the error must name the unknown query: {err}");
}

/// A trigger naming a mutation that does not exist must fail the compile.
#[test]
fn caching_rule_with_unknown_trigger_fails_compile() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = true

[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = ["no_such_mutation"]
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &toml);
    assert!(
        err.contains("no_such_mutation"),
        "the error must name the unknown trigger mutation: {err}"
    );
}

/// A rule targeting a query that already carries an SDK-authored
/// `cache_ttl_seconds` must fail: two authoring sources for the same TTL must
/// not silently last-write-win.
#[test]
fn caching_rule_conflicting_with_sdk_ttl_fails_compile() {
    // TYPES_JSON's `orders` already declares cache_ttl_seconds = 300.
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = true

[[caching.rules]]
query = "orders"
ttl_seconds = 60
invalidation_triggers = []
"#
    );
    let err = compile_err(TYPES_JSON, &toml);
    assert!(
        err.contains("orders") && err.contains("cache_ttl_seconds"),
        "the error must name the doubly-declared query and field: {err}"
    );
}

/// `enabled = false` with rules, `enabled = true` with no rules, a non-memory
/// backend, and a set `redis_url` are each refused: every one is a
/// configuration that silently does nothing (or claims a backend that does
/// not exist — there is no Redis result cache anywhere in the runtime).
#[test]
fn caching_dishonest_configurations_fail_compile() {
    let disabled_with_rules = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = false

[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = []
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &disabled_with_rules);
    assert!(err.contains("enabled"), "disabled-with-rules must be refused: {err}");

    let enabled_without_rules = format!(
        r"{CACHING_TOML_HEAD}
[caching]
enabled = true
"
    );
    let err = compile_err(CACHING_TYPES_JSON, &enabled_without_rules);
    assert!(
        err.contains("rules"),
        "enabled-without-rules does nothing and must be refused: {err}"
    );

    let redis_backend = format!(
        r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
backend = "redis"

[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = []
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &redis_backend);
    assert!(
        err.contains("redis"),
        "a backend with no runtime counterpart must be refused: {err}"
    );
}

/// Compile expecting failure; returns combined stdout+stderr.
fn compile_err(types_json: &str, toml_config: &str) -> String {
    let temp_dir = TempDir::new().unwrap();
    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");
    fs::write(&types_path, types_json).unwrap();
    fs::write(&toml_path, toml_config).unwrap();

    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output()
        .expect("failed to run fraiseql-cli");
    assert!(
        !output.status.success(),
        "compile must fail for this configuration; stdout: {} stderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

// ── #624: [[analytics.queries]] lower onto plain compiled QueryDefinitions —
//    operator-authored sql_source, compiled SELECT list, no new runtime path ──

/// An `[[analytics.queries]]` entry becomes a served, view-backed query:
/// compile-validated `sql_source`, `returns_list = true`, SELECT list from the
/// compiled return type. No client-supplied identifier can reach FROM or the
/// SELECT list because neither exists on this path at request time.
#[test]
fn analytics_query_lowers_to_a_served_query() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true

[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily_orders"
description = "orders rolled up by day"
"#
    );
    let compiled_json = compile(CACHING_TYPES_JSON, &toml);
    let schema = CompiledSchema::from_json(&compiled_json, false)
        .expect("core must parse CLI-produced schema");
    let query = schema
        .queries
        .iter()
        .find(|q| q.name == "daily_orders")
        .expect("analytics query must be compiled as a query");
    assert_eq!(query.sql_source.as_deref(), Some("v_daily_orders"));
    assert_eq!(query.return_type, "Order");
    assert!(query.returns_list, "analytics queries return row sets");
}

/// A return type that is not a declared type is a compile error — the SELECT
/// list comes from the type, so an unknown type has no servable projection.
#[test]
fn analytics_query_with_unknown_return_type_fails_compile() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true

[[analytics.queries]]
name = "daily_orders"
return_type = "NoSuchType"
sql_source = "v_daily_orders"
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &toml);
    assert!(err.contains("NoSuchType"), "must name the unknown type: {err}");
}

/// A name colliding with an existing query, or ending in the `_aggregate` /
/// `_window` suffixes the executor's classifier hijacks before query
/// resolution, would be silently unreachable or ambiguous — compile error.
#[test]
fn analytics_query_reserved_or_colliding_names_fail_compile() {
    let colliding = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true

[[analytics.queries]]
name = "orders"
return_type = "Order"
sql_source = "v_daily_orders"
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &colliding);
    assert!(err.contains("orders"), "must name the colliding query: {err}");

    let reserved = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true

[[analytics.queries]]
name = "sales_aggregate"
return_type = "Order"
sql_source = "v_sales"
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &reserved);
    assert!(err.contains("_aggregate"), "must explain the reserved suffix: {err}");
}

/// An `sql_source` that is not a valid SQL identifier is refused by the same
/// compile-time validator every query goes through (the P01 posture: reject,
/// never escape).
#[test]
fn analytics_query_with_injection_shaped_sql_source_fails_compile() {
    let toml = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true

[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily; DROP TABLE tb_user --"
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &toml);
    assert!(
        err.to_lowercase().contains("identifier") || err.contains("sql_source"),
        "must be refused as an invalid identifier: {err}"
    );
}

/// `enabled = false` with queries, and `enabled = true` without queries, are
/// each refused — the same no-silent-no-op rule as [caching].
#[test]
fn analytics_dishonest_configurations_fail_compile() {
    let disabled_with_queries = format!(
        r#"{CACHING_TOML_HEAD}
[analytics]
enabled = false

[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily_orders"
"#
    );
    let err = compile_err(CACHING_TYPES_JSON, &disabled_with_queries);
    assert!(err.contains("enabled"), "disabled-with-queries must be refused: {err}");

    let enabled_without_queries = format!(
        r"{CACHING_TOML_HEAD}
[analytics]
enabled = true
"
    );
    let err = compile_err(CACHING_TYPES_JSON, &enabled_without_queries);
    assert!(
        err.contains("queries"),
        "enabled-without-queries does nothing and must be refused: {err}"
    );
}

/// #1304: the artifact the compiler writes names the build that wrote it, and this
/// runtime accepts it *because* of that — not incidentally.
///
/// The second half is what makes the first mean something. Every other test here
/// asserts the seam accepts compiler output, which would stay green if the stamp
/// were never written and the check never ran; stripping the key and requiring the
/// same artifact to be refused pins that the acceptance was the check passing.
#[test]
fn the_compiler_stamps_its_own_build_and_the_seam_requires_it() {
    let toml = r#"
[schema]
name = "contract_producer_version"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"
"#;
    let compiled_json = compile(TYPES_JSON, toml);

    let emitted: serde_json::Value = serde_json::from_str(&compiled_json).unwrap();
    assert_eq!(
        emitted.get("fraiseql_version").and_then(serde_json::Value::as_str),
        Some(env!("CARGO_PKG_VERSION")),
        "the compiler must stamp the build it is part of into the artifact it writes"
    );

    let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
    RuntimeConfig::from_compiled_schema(&schema)
        .expect("this build must accept the artifact this build compiled");

    // The same artifact with the stamp removed — what an earlier release wrote.
    let mut stripped = emitted;
    stripped.as_object_mut().unwrap().remove("fraiseql_version");
    let stripped = CompiledSchema::from_json(&stripped.to_string(), false)
        .expect("it must still parse, so the operator meets the build refusal");

    let err = RuntimeConfig::from_compiled_schema(&stripped)
        .expect_err("an artifact naming no build must be refused");
    assert!(err.contains("Recompile"), "{err}");
}