fraiseql-cli 2.19.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
//! Query/mutation structs: `IntermediateQuery`, `IntermediateMutation`,
//! `IntermediateArgument`, `IntermediateAutoParams`, `IntermediateQueryDefaults`.

use fraiseql_core::{
    db::types::ReadRouting,
    schema::{InputStyle, SourceKind},
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use super::types::IntermediateDeprecation;

/// Serde representation of the server-injected parameter map.
///
/// **The wire key is `inject_params` and it matches the compiled schema's key.** That is
/// the fix for #806, not a cosmetic choice: the intermediate format used to call this
/// `inject` while the compiled artifact called it `inject_params`, so every SDK author
/// who looked at a compiled schema to learn the name got it wrong. `TypeScript`, Go and
/// Java all did, independently, and `#[serde(default)]` with no `deny_unknown_fields`
/// turned each of their injection maps into an empty default — compiling a query with no
/// tenant predicate and printing `✓ Schema compiled successfully`. Two names for one
/// concept is what made that mistake available; one name retires it.
///
/// Both value shapes are accepted, because both are unambiguous and both are already in
/// use:
///
/// * nested — `{"tenant_id": {"source": "jwt", "claim": "org_id"}}`, what every SDK emits
/// * flat — `{"tenant_id": "jwt:org_id"}`, which is far pleasanter to hand-author
///
/// Serialization always emits the nested form, so a round-tripped intermediate schema is
/// byte-comparable with SDK output.
pub(super) mod inject_params_serde {
    use indexmap::IndexMap;
    use serde::{
        Deserialize, Deserializer, Serializer,
        de::Error as _,
        ser::{Error as _, SerializeMap as _},
    };

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Spec {
        /// `"jwt:org_id"`
        Flat(String),
        /// `{"source": "jwt", "claim": "org_id"}`
        Nested { source: String, claim: String },
    }

    /// Deserialize either accepted shape into the internal `"<source>:<claim>"` form.
    ///
    /// # Errors
    ///
    /// Returns an error for a flat value with no `<source>:` prefix. A malformed source
    /// must not become a silently-unfiltered query — the same reasoning as the key.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<IndexMap<String, String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        IndexMap::<String, Spec>::deserialize(deserializer)?
            .into_iter()
            .map(|(param, spec)| match spec {
                Spec::Flat(source) if source.contains(':') => Ok((param, source)),
                Spec::Flat(source) => Err(D::Error::custom(format!(
                    "inject_params['{param}'] must be \"<source>:<claim>\" (for example \
                     \"jwt:org_id\") or {{\"source\": \"jwt\", \"claim\": \"org_id\"}}, got \
                     \"{source}\""
                ))),
                Spec::Nested { source, claim } => Ok((param, format!("{source}:{claim}"))),
            })
            .collect()
    }

    /// Serialize as the nested form every SDK emits.
    ///
    /// # Errors
    ///
    /// Returns an error if an entry is not in `"<source>:<claim>"` form, which
    /// [`deserialize`] guarantees but a direct struct construction does not.
    pub fn serialize<S>(map: &IndexMap<String, String>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut out = serializer.serialize_map(Some(map.len()))?;
        for (param, spec) in map {
            let (source, claim) = spec.split_once(':').ok_or_else(|| {
                S::Error::custom(format!(
                    "inject_params['{param}'] is not in \"<source>:<claim>\" form: \"{spec}\""
                ))
            })?;
            out.serialize_entry(param, &serde_json::json!({"source": source, "claim": claim}))?;
        }
        out.end()
    }
}

/// Per-operation REST route override, in the shape every SDK emits.
///
/// The wire form is `"rest": {"path": "/api/v1/orders", "method": "GET"}` — verified
/// identical across the Python, Go, PHP, C#, Java, Elixir, F# and Rust SDKs. It had no
/// consumer: neither [`IntermediateQuery`] nor [`IntermediateMutation`] declared the
/// field and the intermediate schema has no `deny_unknown_fields`, so serde discarded
/// the block and the converter hardcoded `rest_path`/`rest_method` to `None`. An author
/// setting `rest_path` got a clean compile and a route that 404s — and `detect_conflicts`
/// told operators to "use `rest_path` override to resolve" a route collision, advice that
/// could not work (#846).
///
/// `deny_unknown_fields` here is deliberate. This block exists precisely because a
/// silently-dropped key shipped for two releases; a typo inside it must fail the compile
/// rather than quietly degrade to a path-only override.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateRest {
    /// Route path, replacing the derived one (e.g. `/api/v1/orders`).
    pub path: String,

    /// HTTP method. Absent means the derived default for the operation kind —
    /// `GET` for a query, `POST` for a mutation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
}

/// Project-wide default injected parameters, applied to operations that do not name them.
///
/// Seven SDKs — Python, Go, Java, PHP, C#, Elixir and F# — ship a `ConfigLoader` that
/// parses `[inject_defaults]` from `fraiseql.toml` and emits this block as a top-level key.
/// The compiler had never heard of it: `grep -rn inject_defaults crates/` returned nothing,
/// so `fraiseql compile` accepted the key, exited 0, printed `✓ Schema compiled
/// successfully`, and produced operations carrying no injection at all. An operator who
/// wrote `[inject_defaults] tenant_id = "jwt:tenant_id"` to stamp every operation with the
/// caller's tenant got a clean compile and **not one compiled operation with a tenant
/// predicate** (#847). Seven separate implementations of a feature that had never done
/// anything.
///
/// ## Ordering, and why it is not the one the issue suggested
///
/// `#847` proposed merging these in *before* `[fraiseql.tenancy]` validation. That is
/// wrong, and the two features would have become mutually exclusive: tenancy auto-injects
/// the annotated field when an operation's `inject_params` is empty and **fails the
/// compile** when it is non-empty but lacks the field. A default supplying any unrelated
/// key (`read_scope`, the example in the Python SDK's own docstring) would therefore have
/// turned every tenancy-annotated query into a compile error.
///
/// Defaults are applied by the converter, which runs after tenancy validation. Precedence,
/// most specific first:
///
/// 1. the operation's own `inject_params`
/// 2. `[fraiseql.tenancy]` auto-injection
/// 3. `[inject_defaults].queries` / `.mutations`
/// 4. `[inject_defaults].base`
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateInjectDefaults {
    /// Applied to queries **and** mutations.
    #[serde(
        default,
        with = "inject_params_serde",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub base: IndexMap<String, String>,

    /// Applied to queries only, overriding a `base` entry of the same name.
    #[serde(
        default,
        with = "inject_params_serde",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub queries: IndexMap<String, String>,

    /// Applied to mutations only, overriding a `base` entry of the same name.
    #[serde(
        default,
        with = "inject_params_serde",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub mutations: IndexMap<String, String>,
}

impl IntermediateInjectDefaults {
    /// The defaults that apply to a query: `base`, then `queries` overriding it.
    pub fn for_queries(&self) -> IndexMap<String, String> {
        Self::layer(&self.base, &self.queries)
    }

    /// The defaults that apply to a mutation: `base`, then `mutations` overriding it.
    pub fn for_mutations(&self) -> IndexMap<String, String> {
        Self::layer(&self.base, &self.mutations)
    }

    /// `base` with `specific` layered on top.
    fn layer(
        base: &IndexMap<String, String>,
        specific: &IndexMap<String, String>,
    ) -> IndexMap<String, String> {
        let mut merged = base.clone();
        for (key, source) in specific {
            merged.insert(key.clone(), source.clone());
        }
        merged
    }

    /// Fill in each default the operation does not already have, and return the keys added.
    ///
    /// A default is skipped when the operation:
    ///
    /// - names the same parameter — absent-only, never overwriting: an operation that names a
    ///   parameter has made a more specific decision than a project-wide default;
    /// - already injects the same **source** under another name (#1385) — a mutation whose function
    ///   takes the tenant as `p_tenant_id` already receives it, and a second argument carrying the
    ///   same claim would only break the function's arity;
    /// - lists the key in `exclude_inject_defaults` (#1383) — global reference data (a country
    ///   list, a catalogue) has no tenant to filter on, and the default is the fail-closed shape
    ///   only if dropping it is expressible next to the operation.
    ///
    /// The returned keys are the default-supplied parameters — what the compiler names when
    /// one of them does not fit the operation's function.
    ///
    /// # Errors
    ///
    /// An exclusion that no default supplies (stale, or a typo that would silently leave the
    /// default applied), or one the operation also declares itself (a contradiction).
    pub fn apply_to(
        defaults: &IndexMap<String, String>,
        inject: &mut IndexMap<String, String>,
        excluded: &[String],
        operation: &str,
    ) -> anyhow::Result<Vec<String>> {
        for key in excluded {
            if inject.contains_key(key) {
                anyhow::bail!(
                    "Operation '{operation}' both declares inject_params['{key}'] and lists \
                     '{key}' in exclude_inject_defaults. An exclusion drops a project default; \
                     a parameter the operation declares itself is not a default. Keep one."
                );
            }
            if !defaults.contains_key(key) {
                anyhow::bail!(
                    "Operation '{operation}' lists '{key}' in exclude_inject_defaults, but no \
                     [inject_defaults] entry supplies '{key}' to it. Remove the exclusion, or fix \
                     its spelling — an exclusion that matches nothing leaves every default applied."
                );
            }
        }
        let mut added = Vec::new();
        for (key, source) in defaults {
            let declared = inject.contains_key(key) || inject.values().any(|own| own == source);
            if declared || excluded.contains(key) {
                continue;
            }
            inject.insert(key.clone(), source.clone());
            added.push(key.clone());
        }
        Ok(added)
    }
}

/// Argument definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateArgument {
    /// Argument name
    pub name: String,

    /// Argument type name
    ///
    /// **Language-agnostic**: Uses "type", not "`arg_type`"
    #[serde(rename = "type")]
    pub arg_type: String,

    /// Is argument optional?
    pub nullable: bool,

    /// Default value (JSON)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,

    /// Argument description (from docstring or TOML `description`).
    ///
    /// The compiled `ArgumentDefinition` has always had a `description`, and the TOML
    /// authoring surface has always accepted one — but there was no field here to carry it
    /// between them, so the converter hard-coded `description: None` and every authored
    /// argument description was dropped. Found while fixing `#756`; same seam, same shape.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,

    /// A localized `String` (#1513): written as a label, translations or a locale map, and
    /// received by the SQL function as the map.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub localized: bool,
}

impl From<&crate::config::toml_schema::ArgumentDefinition> for IntermediateArgument {
    /// Lower a TOML-declared argument into the intermediate form.
    ///
    /// **This conversion exists so the key names cannot drift.** `#756` was two
    /// hand-written `json!` literals emitting `"args"` with a `"required"` flag while this
    /// struct deserialized `"arguments"` with a `"nullable"` flag. Both sides carried
    /// `#[serde(default)]`, so the mismatch bound to an empty vector and every
    /// TOML-declared argument on every operation silently disappeared — compiling a query
    /// whose declared `id` filter was never applied, and returning rows the author had
    /// excluded.
    ///
    /// Producing the struct and serializing *it* means the wire keys come from the field
    /// definitions above. There is no second spelling to keep in sync.
    fn from(arg: &crate::config::toml_schema::ArgumentDefinition) -> Self {
        Self {
            name:        arg.name.clone(),
            arg_type:    arg.arg_type.clone(),
            // TOML says `required`; the intermediate and compiled schemas say `nullable`.
            // The inversion happens here, once.
            nullable:    !arg.required,
            default:     arg.default.clone(),
            description: arg.description.clone(),
            deprecated:  None,
            localized:   false,
        }
    }
}

/// Query definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateQuery {
    /// Query name (e.g., "users")
    pub name: String,

    /// Return type name (e.g., "User")
    pub return_type: String,

    /// Returns a list?
    #[serde(default)]
    pub returns_list: bool,

    /// Result is nullable?
    #[serde(default)]
    pub nullable: bool,

    /// Query arguments
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Query description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// SQL source (table/view name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sql_source: Option<String>,

    /// What [`sql_source`](Self::sql_source) names: `"relation"` (the default) or
    /// `"function"`, a `STABLE` set-returning function the query reads from.
    ///
    /// The function is called with the query's own arguments, in declaration order and
    /// auto-params left out, then its `inject_params`; its rows are filtered, ordered and
    /// paged like a view's. A Relay connection, a count sibling and a streamed export are
    /// refused beside it: each reads the relation's rows by a statement of its own.
    #[serde(default, skip_serializing_if = "SourceKind::is_relation")]
    pub sql_source_kind: SourceKind,

    /// Back this root field with a declared function instead of a relation (#1329).
    ///
    /// Names an entry in the `functions` section whose trigger is `request:query`.
    /// Mutually exclusive with [`sql_source`](Self::sql_source) — a field resolves
    /// one way, and a precedence rule would be one more thing to remember wrong.
    ///
    /// Everything that lowers into SQL is refused beside it rather than ignored:
    /// `relay`, `count`, `pagination_order`, `inject_params`, `rest_stream`,
    /// `jsonb_column`, a non-default `read_routing`, and an explicitly declared
    /// `auto_params` flag. Each of those is a setting the compiler would otherwise
    /// carry into an artifact where nothing reads it, and one of them
    /// (`inject_params`) is a tenant-scoping control — a silently dropped security
    /// setting is the failure this seam exists to refuse.
    ///
    /// Project-wide `[query_defaults]` are **not** refused, only defaulted away: an
    /// author who set `limit = true` for the project did not declare it for this
    /// query, and failing their compile over a default they never wrote here would
    /// be refusing the wrong statement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub function: Option<String>,

    /// Auto-generated parameters config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_params: Option<IntermediateAutoParams>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,

    /// JSONB column name for extracting data (e.g., "data")
    /// Used for tv_* (denormalized JSONB tables) pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jsonb_column: Option<String>,

    /// Whether this is a Relay connection query.
    /// When true, the compiler wraps results in `{ edges: [{ node, cursor }], pageInfo }`
    /// and generates `first`/`after`/`last`/`before` arguments instead of `limit`/`offset`.
    /// Requires `returns_list = true` and `sql_source` to be set.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub relay: bool,

    /// Emit a `<name>Count(where): Int!` sibling for this list query (#938).
    ///
    /// Opt-in rather than automatic: the count is a second `SELECT COUNT(*)` that
    /// scans the whole filtered set, which is a real cost on a hot list endpoint
    /// and is wasted on every list that is not rendered with page numbers.
    ///
    /// Requires `returns_list = true` and `sql_source`. Refused on `relay = true`
    /// — a connection already carries `totalCount`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub count: bool,

    /// Server-injected parameters: SQL column name → source expression (e.g. `"jwt:org_id"`).
    /// Not exposed as GraphQL arguments.
    ///
    /// Wire key is `inject_params`, matching the compiled schema. The two names were
    /// unified because the split is what let three SDKs emit a key that bound to
    /// nothing (#806); see the `inject_params_serde` module for the full reasoning.
    #[serde(
        default,
        rename = "inject_params",
        with = "inject_params_serde",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub inject: IndexMap<String, String>,

    /// Project `[inject_defaults]` keys this operation opts out of (#1383).
    ///
    /// Reviewable next to the operation it applies to: a catalogue query declares here
    /// that the tenant default does not apply to it. Each key must name a default that
    /// would otherwise apply, and must not also be declared in `inject_params`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude_inject_defaults: Vec<String>,

    /// Where this query's reads may be served from (#957).
    ///
    /// `any` (the default) follows server policy; `primary` refuses replicas —
    /// and the result cache — for reads where staleness is a correctness problem;
    /// `replica` opts out of the read-your-writes pin and may carry its own
    /// `max_lag_ms`.
    ///
    /// FraiseQL defines the shape and enforces it; an authoring language emits
    /// it — a `@reads_from(...)` directive is one spelling.
    #[serde(default, skip_serializing_if = "ReadRouting::is_default")]
    pub read_routing: ReadRouting,

    /// Per-query result cache TTL in seconds. Overrides the global cache TTL for this query.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_ttl_seconds: Option<u64>,

    /// Additional database views this query reads beyond the primary `sql_source`.
    ///
    /// Used for correct cache invalidation when a query JOINs or reads multiple views.
    /// Each entry is validated as a safe SQL identifier at schema compile time.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub additional_views: Vec<String>,

    /// Role required to execute this query and see it in introspection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requires_role: Option<String>,

    /// Actor classes permitted to execute this query — an allow-list (#966).
    ///
    /// Empty means unrestricted. Tokens are the `snake_case` `ActorType` names
    /// (`human_user`, `service_account`, `ai_agent`, `system_job`); an
    /// unrecognised one is a compile error rather than a silently-ignored
    /// restriction, which is the difference between a typo and an open operation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_actor: Vec<String>,

    /// Relay cursor column type: `"uuid"` for UUID PKs, `"int64"` (or absent) for bigint PKs.
    /// Only meaningful when `relay = true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relay_cursor_type: Option<String>,

    /// REST route override for this query. See [`IntermediateRest`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rest: Option<IntermediateRest>,

    /// Allow this query to be exported as a stream over REST (#958).
    ///
    /// Separate from [`rest`](Self::rest) rather than a key inside it, because
    /// that block's `path` is mandatory: nesting the flag there would make every
    /// author who wants an export also override the route.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub rest_stream: bool,

    /// Override the order this query's `LIMIT`/`OFFSET` pages are cut in (#1303).
    ///
    /// Two spellings, and absence is the third:
    ///
    /// * a **column name** — order pages by this column, which must be unique over `sql_source` or
    ///   the pages still overlap;
    /// * the literal **`"none"`** — emit no default ordering. This is how a view that carries its
    ///   own `ORDER BY` keeps it: the compiler cannot read a view's body, so the opt-out is
    ///   declared rather than inferred, and declaring it also silences the compile warning about
    ///   non-deterministic pages, because the author answered it.
    /// * **absent** — the compiler derives the entity identity, which is what almost every query
    ///   wants.
    ///
    /// `"none"` is therefore not usable as a column name here. A relation column
    /// actually called `none` must be ordered by through the SQL view instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pagination_order: Option<String>,
}

/// Mutation definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateMutation {
    /// Mutation name (e.g., "createUser")
    pub name: String,

    /// Return type name (e.g., "User")
    pub return_type: String,

    /// Returns a list?
    #[serde(default)]
    pub returns_list: bool,

    /// Result is nullable?
    #[serde(default)]
    pub nullable: bool,

    /// Mutation arguments
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Mutation description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// SQL source (function name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sql_source: Option<String>,

    /// Operation type (CREATE, UPDATE, DELETE, CUSTOM)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,

    /// Server-injected parameters: SQL parameter name → source expression (e.g. `"jwt:org_id"`).
    /// Not exposed as GraphQL arguments.
    ///
    /// Wire key is `inject_params`, matching the compiled schema. The two names were
    /// unified because the split is what let three SDKs emit a key that bound to
    /// nothing (#806); see the `inject_params_serde` module for the full reasoning.
    #[serde(
        default,
        rename = "inject_params",
        with = "inject_params_serde",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub inject: IndexMap<String, String>,

    /// Project `[inject_defaults]` keys this operation opts out of (#1383).
    ///
    /// Reviewable next to the operation it applies to: a catalogue query declares here
    /// that the tenant default does not apply to it. Each key must name a default that
    /// would otherwise apply, and must not also be declared in `inject_params`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude_inject_defaults: Vec<String>,

    /// Role required to execute this mutation and see it in introspection.
    ///
    /// Mirrors [`IntermediateQuery::requires_role`]. Enforced at runtime with the same
    /// enumeration-hiding "not found" response as the query gate — a principal lacking
    /// the role cannot distinguish a forbidden mutation from a nonexistent one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requires_role: Option<String>,

    /// Actor classes permitted to execute this mutation — an allow-list (#966).
    ///
    /// Mirrors [`IntermediateQuery::requires_actor`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_actor: Vec<String>,

    /// Fact tables whose version counter should be bumped after this mutation succeeds.
    ///
    /// Used for correct invalidation of analytic/aggregate cache entries.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invalidates_fact_tables: Vec<String>,

    /// View names whose cached query results should be invalidated after this
    /// mutation succeeds.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invalidates_views: Vec<String>,

    /// Whether this mutation writes a Change-Spine change-log row (default `true`).
    ///
    /// Set `false` (via the authoring SDK's `@fraiseql.mutation(changelog=False)`)
    /// to opt a single mutation out of the in-transaction change-log outbox while
    /// the rest of the schema keeps logging. Defaults to `true` so a schema
    /// authored before this field existed keeps logging.
    #[serde(default = "default_changelog")]
    pub changelog: bool,

    /// How the GraphQL `input` argument is passed to the SQL function:
    /// `"flatten"` (positional columns, the default) or `"jsonb"` (the whole
    /// input as one `jsonb` arg). See [`InputStyle`].
    ///
    /// Orthogonal to [`operation`](IntermediateMutation::operation): set
    /// `"jsonb"` (via the authoring SDK's
    /// `@fraiseql.mutation(input_style="jsonb")`) so a backend using the
    /// single-`jsonb`-wrapper convention can register the real DML verb and
    /// still receive the whole input as one argument. Defaults to `"flatten"`,
    /// byte-identical to a schema authored before this field existed.
    #[serde(default, skip_serializing_if = "InputStyle::is_flatten")]
    pub input_style: InputStyle,

    /// Whether a successful, state-changing run of this mutation also records the
    /// changed entity's pre-image (before-state) into the Change-Spine
    /// `object_data_before` column, sourced from an optional `entity_before` on the
    /// mutation's `app.mutation_response`.
    ///
    /// Set `true` (via the authoring SDK's
    /// `@fraiseql.mutation(changelog_pre_image=True)` or TOML
    /// `changelog_pre_image = true`) to opt an audit-sensitive mutation into an
    /// inline Debezium-style `{before, after}`. Defaults to `false`,
    /// byte-identical to a schema authored before this field existed.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub changelog_pre_image: bool,

    /// Whether this mutation exposes the typed graphql-cascade `cascade` field
    /// on its success payload.
    ///
    /// Set `true` via the authoring SDK's `@fraiseql.type(crud=True,
    /// cascade=True)` / `@fraiseql.mutation(cascade=True)`, or TOML
    /// `cascade = true`. Defaults to `false`, byte-identical to a schema
    /// authored before this field existed. Before this field, the compiler
    /// silently dropped the SDK flag.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub cascade: bool,

    /// Typed facts about the operation, served on the cascade payload (#1397): the
    /// function returns them in its response row's `result jsonb` column. Only on a `cascade`
    /// mutation, only leaf types (a scalar or an enum).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub success_fields: Vec<super::IntermediateField>,

    /// Where the cascade comes from (#1391): `"function"` (the default) or `"pg_tviews"`,
    /// which also merges the TVIEW rows `pg_tviews` reports the transaction changed. Only on a
    /// `cascade` mutation.
    #[serde(
        default,
        skip_serializing_if = "fraiseql_core::schema::CascadeSource::is_function"
    )]
    pub cascade_source: fraiseql_core::schema::CascadeSource,

    /// REST route override for this mutation. See [`IntermediateRest`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rest: Option<IntermediateRest>,
}

impl Default for IntermediateMutation {
    /// Hand-written so `changelog` defaults to `true` (matching the serde default),
    /// not `bool`'s `false`. A `#[derive(Default)]` would silently opt
    /// `..Default::default()`-built mutations out of the change log.
    fn default() -> Self {
        Self {
            name:                    String::new(),
            return_type:             String::new(),
            returns_list:            false,
            nullable:                false,
            arguments:               Vec::new(),
            description:             None,
            sql_source:              None,
            operation:               None,
            deprecated:              None,
            inject:                  IndexMap::new(),
            exclude_inject_defaults: Vec::new(),
            requires_actor:          Vec::new(),
            requires_role:           None,
            invalidates_fact_tables: Vec::new(),
            invalidates_views:       Vec::new(),
            changelog:               default_changelog(),
            input_style:             InputStyle::Flatten,
            changelog_pre_image:     false,
            cascade:                 false,
            success_fields:          Vec::new(),
            cascade_source:          fraiseql_core::schema::CascadeSource::Function,
            rest:                    None,
        }
    }
}

/// Serde default for [`IntermediateMutation::changelog`]: log by default (opt-out).
const fn default_changelog() -> bool {
    true
}

/// Auto-params configuration in intermediate format.
///
/// Each field is `Option<bool>`: `None` means "not specified — inherit from
/// `[query_defaults]`"; `Some(v)` means explicitly set by the authoring-language decorator.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateAutoParams {
    /// Enable automatic limit parameter (None = inherit from query_defaults)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit:        Option<bool>,
    /// Enable automatic offset parameter (None = inherit from query_defaults)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset:       Option<bool>,
    /// Enable automatic where clause parameter (None = inherit from query_defaults)
    #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")]
    pub where_clause: Option<bool>,
    /// Enable automatic order_by parameter (None = inherit from query_defaults)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order_by:     Option<bool>,
}

/// Global auto-param defaults for list queries (injected from TOML by the merger).
///
/// Never present in `schema.json` — set only at compile time via `[query_defaults]`
/// in `fraiseql.toml`.
///
/// The `Default` implementation returns all-`true`, matching the historical behaviour
/// when no `[query_defaults]` section is present in TOML.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IntermediateQueryDefaults {
    /// Default for `where` parameter
    pub where_clause:     bool,
    /// Default for `order_by` parameter
    pub order_by:         bool,
    /// Default for `limit` parameter
    pub limit:            bool,
    /// Default for `offset` parameter
    pub offset:           bool,
    /// Deployment-wide posture on the order paginated pages are cut in (#1303).
    pub pagination_order: crate::config::toml_schema::PaginationPosture,
}

impl Default for IntermediateQueryDefaults {
    fn default() -> Self {
        Self {
            where_clause:     true,
            order_by:         true,
            limit:            true,
            offset:           true,
            pagination_order: crate::config::toml_schema::PaginationPosture::Identity,
        }
    }
}