Skip to main content

fraiseql_cli/schema/intermediate/
operations.rs

1//! Query/mutation structs: `IntermediateQuery`, `IntermediateMutation`,
2//! `IntermediateArgument`, `IntermediateAutoParams`, `IntermediateQueryDefaults`.
3
4use fraiseql_core::{db::types::ReadRouting, schema::InputStyle};
5use indexmap::IndexMap;
6use serde::{Deserialize, Serialize};
7
8use super::types::IntermediateDeprecation;
9
10/// Serde representation of the server-injected parameter map.
11///
12/// **The wire key is `inject_params` and it matches the compiled schema's key.** That is
13/// the fix for #806, not a cosmetic choice: the intermediate format used to call this
14/// `inject` while the compiled artifact called it `inject_params`, so every SDK author
15/// who looked at a compiled schema to learn the name got it wrong. `TypeScript`, Go and
16/// Java all did, independently, and `#[serde(default)]` with no `deny_unknown_fields`
17/// turned each of their injection maps into an empty default — compiling a query with no
18/// tenant predicate and printing `✓ Schema compiled successfully`. Two names for one
19/// concept is what made that mistake available; one name retires it.
20///
21/// Both value shapes are accepted, because both are unambiguous and both are already in
22/// use:
23///
24/// * nested — `{"tenant_id": {"source": "jwt", "claim": "org_id"}}`, what every SDK emits
25/// * flat — `{"tenant_id": "jwt:org_id"}`, which is far pleasanter to hand-author
26///
27/// Serialization always emits the nested form, so a round-tripped intermediate schema is
28/// byte-comparable with SDK output.
29pub(super) mod inject_params_serde {
30    use indexmap::IndexMap;
31    use serde::{
32        Deserialize, Deserializer, Serializer,
33        de::Error as _,
34        ser::{Error as _, SerializeMap as _},
35    };
36
37    #[derive(Deserialize)]
38    #[serde(untagged)]
39    enum Spec {
40        /// `"jwt:org_id"`
41        Flat(String),
42        /// `{"source": "jwt", "claim": "org_id"}`
43        Nested { source: String, claim: String },
44    }
45
46    /// Deserialize either accepted shape into the internal `"<source>:<claim>"` form.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error for a flat value with no `<source>:` prefix. A malformed source
51    /// must not become a silently-unfiltered query — the same reasoning as the key.
52    pub fn deserialize<'de, D>(deserializer: D) -> Result<IndexMap<String, String>, D::Error>
53    where
54        D: Deserializer<'de>,
55    {
56        IndexMap::<String, Spec>::deserialize(deserializer)?
57            .into_iter()
58            .map(|(param, spec)| match spec {
59                Spec::Flat(source) if source.contains(':') => Ok((param, source)),
60                Spec::Flat(source) => Err(D::Error::custom(format!(
61                    "inject_params['{param}'] must be \"<source>:<claim>\" (for example \
62                     \"jwt:org_id\") or {{\"source\": \"jwt\", \"claim\": \"org_id\"}}, got \
63                     \"{source}\""
64                ))),
65                Spec::Nested { source, claim } => Ok((param, format!("{source}:{claim}"))),
66            })
67            .collect()
68    }
69
70    /// Serialize as the nested form every SDK emits.
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if an entry is not in `"<source>:<claim>"` form, which
75    /// [`deserialize`] guarantees but a direct struct construction does not.
76    pub fn serialize<S>(map: &IndexMap<String, String>, serializer: S) -> Result<S::Ok, S::Error>
77    where
78        S: Serializer,
79    {
80        let mut out = serializer.serialize_map(Some(map.len()))?;
81        for (param, spec) in map {
82            let (source, claim) = spec.split_once(':').ok_or_else(|| {
83                S::Error::custom(format!(
84                    "inject_params['{param}'] is not in \"<source>:<claim>\" form: \"{spec}\""
85                ))
86            })?;
87            out.serialize_entry(param, &serde_json::json!({"source": source, "claim": claim}))?;
88        }
89        out.end()
90    }
91}
92
93/// Per-operation REST route override, in the shape every SDK emits.
94///
95/// The wire form is `"rest": {"path": "/api/v1/orders", "method": "GET"}` — verified
96/// identical across the Python, Go, PHP, C#, Java, Elixir, F# and Rust SDKs. It had no
97/// consumer: neither [`IntermediateQuery`] nor [`IntermediateMutation`] declared the
98/// field and the intermediate schema has no `deny_unknown_fields`, so serde discarded
99/// the block and the converter hardcoded `rest_path`/`rest_method` to `None`. An author
100/// setting `rest_path` got a clean compile and a route that 404s — and `detect_conflicts`
101/// told operators to "use `rest_path` override to resolve" a route collision, advice that
102/// could not work (#846).
103///
104/// `deny_unknown_fields` here is deliberate. This block exists precisely because a
105/// silently-dropped key shipped for two releases; a typo inside it must fail the compile
106/// rather than quietly degrade to a path-only override.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(deny_unknown_fields)]
109pub struct IntermediateRest {
110    /// Route path, replacing the derived one (e.g. `/api/v1/orders`).
111    pub path: String,
112
113    /// HTTP method. Absent means the derived default for the operation kind —
114    /// `GET` for a query, `POST` for a mutation.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub method: Option<String>,
117}
118
119/// Project-wide default injected parameters, applied to operations that do not name them.
120///
121/// Seven SDKs — Python, Go, Java, PHP, C#, Elixir and F# — ship a `ConfigLoader` that
122/// parses `[inject_defaults]` from `fraiseql.toml` and emits this block as a top-level key.
123/// The compiler had never heard of it: `grep -rn inject_defaults crates/` returned nothing,
124/// so `fraiseql compile` accepted the key, exited 0, printed `✓ Schema compiled
125/// successfully`, and produced operations carrying no injection at all. An operator who
126/// wrote `[inject_defaults] tenant_id = "jwt:tenant_id"` to stamp every operation with the
127/// caller's tenant got a clean compile and **not one compiled operation with a tenant
128/// predicate** (#847). Seven separate implementations of a feature that had never done
129/// anything.
130///
131/// ## Ordering, and why it is not the one the issue suggested
132///
133/// `#847` proposed merging these in *before* `[fraiseql.tenancy]` validation. That is
134/// wrong, and the two features would have become mutually exclusive: tenancy auto-injects
135/// the annotated field when an operation's `inject_params` is empty and **fails the
136/// compile** when it is non-empty but lacks the field. A default supplying any unrelated
137/// key (`read_scope`, the example in the Python SDK's own docstring) would therefore have
138/// turned every tenancy-annotated query into a compile error.
139///
140/// Defaults are applied by the converter, which runs after tenancy validation. Precedence,
141/// most specific first:
142///
143/// 1. the operation's own `inject_params`
144/// 2. `[fraiseql.tenancy]` auto-injection
145/// 3. `[inject_defaults].queries` / `.mutations`
146/// 4. `[inject_defaults].base`
147#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct IntermediateInjectDefaults {
150    /// Applied to queries **and** mutations.
151    #[serde(
152        default,
153        with = "inject_params_serde",
154        skip_serializing_if = "IndexMap::is_empty"
155    )]
156    pub base: IndexMap<String, String>,
157
158    /// Applied to queries only, overriding a `base` entry of the same name.
159    #[serde(
160        default,
161        with = "inject_params_serde",
162        skip_serializing_if = "IndexMap::is_empty"
163    )]
164    pub queries: IndexMap<String, String>,
165
166    /// Applied to mutations only, overriding a `base` entry of the same name.
167    #[serde(
168        default,
169        with = "inject_params_serde",
170        skip_serializing_if = "IndexMap::is_empty"
171    )]
172    pub mutations: IndexMap<String, String>,
173}
174
175impl IntermediateInjectDefaults {
176    /// The defaults that apply to a query: `base`, then `queries` overriding it.
177    pub fn for_queries(&self) -> IndexMap<String, String> {
178        Self::layer(&self.base, &self.queries)
179    }
180
181    /// The defaults that apply to a mutation: `base`, then `mutations` overriding it.
182    pub fn for_mutations(&self) -> IndexMap<String, String> {
183        Self::layer(&self.base, &self.mutations)
184    }
185
186    /// `base` with `specific` layered on top.
187    fn layer(
188        base: &IndexMap<String, String>,
189        specific: &IndexMap<String, String>,
190    ) -> IndexMap<String, String> {
191        let mut merged = base.clone();
192        for (key, source) in specific {
193            merged.insert(key.clone(), source.clone());
194        }
195        merged
196    }
197
198    /// Fill in each default the operation does not already have, and return the keys added.
199    ///
200    /// A default is skipped when the operation:
201    ///
202    /// - names the same parameter — absent-only, never overwriting: an operation that names a
203    ///   parameter has made a more specific decision than a project-wide default;
204    /// - already injects the same **source** under another name (#1385) — a mutation whose function
205    ///   takes the tenant as `p_tenant_id` already receives it, and a second argument carrying the
206    ///   same claim would only break the function's arity;
207    /// - lists the key in `exclude_inject_defaults` (#1383) — global reference data (a country
208    ///   list, a catalogue) has no tenant to filter on, and the default is the fail-closed shape
209    ///   only if dropping it is expressible next to the operation.
210    ///
211    /// The returned keys are the default-supplied parameters — what the compiler names when
212    /// one of them does not fit the operation's function.
213    ///
214    /// # Errors
215    ///
216    /// An exclusion that no default supplies (stale, or a typo that would silently leave the
217    /// default applied), or one the operation also declares itself (a contradiction).
218    pub fn apply_to(
219        defaults: &IndexMap<String, String>,
220        inject: &mut IndexMap<String, String>,
221        excluded: &[String],
222        operation: &str,
223    ) -> anyhow::Result<Vec<String>> {
224        for key in excluded {
225            if inject.contains_key(key) {
226                anyhow::bail!(
227                    "Operation '{operation}' both declares inject_params['{key}'] and lists \
228                     '{key}' in exclude_inject_defaults. An exclusion drops a project default; \
229                     a parameter the operation declares itself is not a default. Keep one."
230                );
231            }
232            if !defaults.contains_key(key) {
233                anyhow::bail!(
234                    "Operation '{operation}' lists '{key}' in exclude_inject_defaults, but no \
235                     [inject_defaults] entry supplies '{key}' to it. Remove the exclusion, or fix \
236                     its spelling — an exclusion that matches nothing leaves every default applied."
237                );
238            }
239        }
240        let mut added = Vec::new();
241        for (key, source) in defaults {
242            let declared = inject.contains_key(key) || inject.values().any(|own| own == source);
243            if declared || excluded.contains(key) {
244                continue;
245            }
246            inject.insert(key.clone(), source.clone());
247            added.push(key.clone());
248        }
249        Ok(added)
250    }
251}
252
253/// Argument definition in intermediate format
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(deny_unknown_fields)]
256pub struct IntermediateArgument {
257    /// Argument name
258    pub name: String,
259
260    /// Argument type name
261    ///
262    /// **Language-agnostic**: Uses "type", not "`arg_type`"
263    #[serde(rename = "type")]
264    pub arg_type: String,
265
266    /// Is argument optional?
267    pub nullable: bool,
268
269    /// Default value (JSON)
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub default: Option<serde_json::Value>,
272
273    /// Argument description (from docstring or TOML `description`).
274    ///
275    /// The compiled `ArgumentDefinition` has always had a `description`, and the TOML
276    /// authoring surface has always accepted one — but there was no field here to carry it
277    /// between them, so the converter hard-coded `description: None` and every authored
278    /// argument description was dropped. Found while fixing `#756`; same seam, same shape.
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub description: Option<String>,
281
282    /// Deprecation info (from @deprecated directive)
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub deprecated: Option<IntermediateDeprecation>,
285}
286
287impl From<&crate::config::toml_schema::ArgumentDefinition> for IntermediateArgument {
288    /// Lower a TOML-declared argument into the intermediate form.
289    ///
290    /// **This conversion exists so the key names cannot drift.** `#756` was two
291    /// hand-written `json!` literals emitting `"args"` with a `"required"` flag while this
292    /// struct deserialized `"arguments"` with a `"nullable"` flag. Both sides carried
293    /// `#[serde(default)]`, so the mismatch bound to an empty vector and every
294    /// TOML-declared argument on every operation silently disappeared — compiling a query
295    /// whose declared `id` filter was never applied, and returning rows the author had
296    /// excluded.
297    ///
298    /// Producing the struct and serializing *it* means the wire keys come from the field
299    /// definitions above. There is no second spelling to keep in sync.
300    fn from(arg: &crate::config::toml_schema::ArgumentDefinition) -> Self {
301        Self {
302            name:        arg.name.clone(),
303            arg_type:    arg.arg_type.clone(),
304            // TOML says `required`; the intermediate and compiled schemas say `nullable`.
305            // The inversion happens here, once.
306            nullable:    !arg.required,
307            default:     arg.default.clone(),
308            description: arg.description.clone(),
309            deprecated:  None,
310        }
311    }
312}
313
314/// Query definition in intermediate format
315#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
316#[serde(deny_unknown_fields)]
317pub struct IntermediateQuery {
318    /// Query name (e.g., "users")
319    pub name: String,
320
321    /// Return type name (e.g., "User")
322    pub return_type: String,
323
324    /// Returns a list?
325    #[serde(default)]
326    pub returns_list: bool,
327
328    /// Result is nullable?
329    #[serde(default)]
330    pub nullable: bool,
331
332    /// Query arguments
333    #[serde(default)]
334    pub arguments: Vec<IntermediateArgument>,
335
336    /// Query description (from docstring)
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub description: Option<String>,
339
340    /// SQL source (table/view name)
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub sql_source: Option<String>,
343
344    /// Back this root field with a declared function instead of a relation (#1329).
345    ///
346    /// Names an entry in the `functions` section whose trigger is `request:query`.
347    /// Mutually exclusive with [`sql_source`](Self::sql_source) — a field resolves
348    /// one way, and a precedence rule would be one more thing to remember wrong.
349    ///
350    /// Everything that lowers into SQL is refused beside it rather than ignored:
351    /// `relay`, `count`, `pagination_order`, `inject_params`, `rest_stream`,
352    /// `jsonb_column`, a non-default `read_routing`, and an explicitly declared
353    /// `auto_params` flag. Each of those is a setting the compiler would otherwise
354    /// carry into an artifact where nothing reads it, and one of them
355    /// (`inject_params`) is a tenant-scoping control — a silently dropped security
356    /// setting is the failure this seam exists to refuse.
357    ///
358    /// Project-wide `[query_defaults]` are **not** refused, only defaulted away: an
359    /// author who set `limit = true` for the project did not declare it for this
360    /// query, and failing their compile over a default they never wrote here would
361    /// be refusing the wrong statement.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub function: Option<String>,
364
365    /// Auto-generated parameters config
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub auto_params: Option<IntermediateAutoParams>,
368
369    /// Deprecation info (from @deprecated directive)
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub deprecated: Option<IntermediateDeprecation>,
372
373    /// JSONB column name for extracting data (e.g., "data")
374    /// Used for tv_* (denormalized JSONB tables) pattern
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub jsonb_column: Option<String>,
377
378    /// Whether this is a Relay connection query.
379    /// When true, the compiler wraps results in `{ edges: [{ node, cursor }], pageInfo }`
380    /// and generates `first`/`after`/`last`/`before` arguments instead of `limit`/`offset`.
381    /// Requires `returns_list = true` and `sql_source` to be set.
382    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
383    pub relay: bool,
384
385    /// Emit a `<name>Count(where): Int!` sibling for this list query (#938).
386    ///
387    /// Opt-in rather than automatic: the count is a second `SELECT COUNT(*)` that
388    /// scans the whole filtered set, which is a real cost on a hot list endpoint
389    /// and is wasted on every list that is not rendered with page numbers.
390    ///
391    /// Requires `returns_list = true` and `sql_source`. Refused on `relay = true`
392    /// — a connection already carries `totalCount`.
393    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
394    pub count: bool,
395
396    /// Server-injected parameters: SQL column name → source expression (e.g. `"jwt:org_id"`).
397    /// Not exposed as GraphQL arguments.
398    ///
399    /// Wire key is `inject_params`, matching the compiled schema. The two names were
400    /// unified because the split is what let three SDKs emit a key that bound to
401    /// nothing (#806); see the `inject_params_serde` module for the full reasoning.
402    #[serde(
403        default,
404        rename = "inject_params",
405        with = "inject_params_serde",
406        skip_serializing_if = "IndexMap::is_empty"
407    )]
408    pub inject: IndexMap<String, String>,
409
410    /// Project `[inject_defaults]` keys this operation opts out of (#1383).
411    ///
412    /// Reviewable next to the operation it applies to: a catalogue query declares here
413    /// that the tenant default does not apply to it. Each key must name a default that
414    /// would otherwise apply, and must not also be declared in `inject_params`.
415    #[serde(default, skip_serializing_if = "Vec::is_empty")]
416    pub exclude_inject_defaults: Vec<String>,
417
418    /// Where this query's reads may be served from (#957).
419    ///
420    /// `any` (the default) follows server policy; `primary` refuses replicas —
421    /// and the result cache — for reads where staleness is a correctness problem;
422    /// `replica` opts out of the read-your-writes pin and may carry its own
423    /// `max_lag_ms`.
424    ///
425    /// FraiseQL defines the shape and enforces it; an authoring language emits
426    /// it — a `@reads_from(...)` directive is one spelling.
427    #[serde(default, skip_serializing_if = "ReadRouting::is_default")]
428    pub read_routing: ReadRouting,
429
430    /// Per-query result cache TTL in seconds. Overrides the global cache TTL for this query.
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub cache_ttl_seconds: Option<u64>,
433
434    /// Additional database views this query reads beyond the primary `sql_source`.
435    ///
436    /// Used for correct cache invalidation when a query JOINs or reads multiple views.
437    /// Each entry is validated as a safe SQL identifier at schema compile time.
438    #[serde(default, skip_serializing_if = "Vec::is_empty")]
439    pub additional_views: Vec<String>,
440
441    /// Role required to execute this query and see it in introspection.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub requires_role: Option<String>,
444
445    /// Actor classes permitted to execute this query — an allow-list (#966).
446    ///
447    /// Empty means unrestricted. Tokens are the `snake_case` `ActorType` names
448    /// (`human_user`, `service_account`, `ai_agent`, `system_job`); an
449    /// unrecognised one is a compile error rather than a silently-ignored
450    /// restriction, which is the difference between a typo and an open operation.
451    #[serde(default, skip_serializing_if = "Vec::is_empty")]
452    pub requires_actor: Vec<String>,
453
454    /// Relay cursor column type: `"uuid"` for UUID PKs, `"int64"` (or absent) for bigint PKs.
455    /// Only meaningful when `relay = true`.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub relay_cursor_type: Option<String>,
458
459    /// REST route override for this query. See [`IntermediateRest`].
460    #[serde(default, skip_serializing_if = "Option::is_none")]
461    pub rest: Option<IntermediateRest>,
462
463    /// Allow this query to be exported as a stream over REST (#958).
464    ///
465    /// Separate from [`rest`](Self::rest) rather than a key inside it, because
466    /// that block's `path` is mandatory: nesting the flag there would make every
467    /// author who wants an export also override the route.
468    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
469    pub rest_stream: bool,
470
471    /// Override the order this query's `LIMIT`/`OFFSET` pages are cut in (#1303).
472    ///
473    /// Two spellings, and absence is the third:
474    ///
475    /// * a **column name** — order pages by this column, which must be unique over `sql_source` or
476    ///   the pages still overlap;
477    /// * the literal **`"none"`** — emit no default ordering. This is how a view that carries its
478    ///   own `ORDER BY` keeps it: the compiler cannot read a view's body, so the opt-out is
479    ///   declared rather than inferred, and declaring it also silences the compile warning about
480    ///   non-deterministic pages, because the author answered it.
481    /// * **absent** — the compiler derives the entity identity, which is what almost every query
482    ///   wants.
483    ///
484    /// `"none"` is therefore not usable as a column name here. A relation column
485    /// actually called `none` must be ordered by through the SQL view instead.
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub pagination_order: Option<String>,
488}
489
490/// Mutation definition in intermediate format
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
492#[serde(deny_unknown_fields)]
493pub struct IntermediateMutation {
494    /// Mutation name (e.g., "createUser")
495    pub name: String,
496
497    /// Return type name (e.g., "User")
498    pub return_type: String,
499
500    /// Returns a list?
501    #[serde(default)]
502    pub returns_list: bool,
503
504    /// Result is nullable?
505    #[serde(default)]
506    pub nullable: bool,
507
508    /// Mutation arguments
509    #[serde(default)]
510    pub arguments: Vec<IntermediateArgument>,
511
512    /// Mutation description (from docstring)
513    #[serde(skip_serializing_if = "Option::is_none")]
514    pub description: Option<String>,
515
516    /// SQL source (function name)
517    #[serde(skip_serializing_if = "Option::is_none")]
518    pub sql_source: Option<String>,
519
520    /// Operation type (CREATE, UPDATE, DELETE, CUSTOM)
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub operation: Option<String>,
523
524    /// Deprecation info (from @deprecated directive)
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub deprecated: Option<IntermediateDeprecation>,
527
528    /// Server-injected parameters: SQL parameter name → source expression (e.g. `"jwt:org_id"`).
529    /// Not exposed as GraphQL arguments.
530    ///
531    /// Wire key is `inject_params`, matching the compiled schema. The two names were
532    /// unified because the split is what let three SDKs emit a key that bound to
533    /// nothing (#806); see the `inject_params_serde` module for the full reasoning.
534    #[serde(
535        default,
536        rename = "inject_params",
537        with = "inject_params_serde",
538        skip_serializing_if = "IndexMap::is_empty"
539    )]
540    pub inject: IndexMap<String, String>,
541
542    /// Project `[inject_defaults]` keys this operation opts out of (#1383).
543    ///
544    /// Reviewable next to the operation it applies to: a catalogue query declares here
545    /// that the tenant default does not apply to it. Each key must name a default that
546    /// would otherwise apply, and must not also be declared in `inject_params`.
547    #[serde(default, skip_serializing_if = "Vec::is_empty")]
548    pub exclude_inject_defaults: Vec<String>,
549
550    /// Role required to execute this mutation and see it in introspection.
551    ///
552    /// Mirrors [`IntermediateQuery::requires_role`]. Enforced at runtime with the same
553    /// enumeration-hiding "not found" response as the query gate — a principal lacking
554    /// the role cannot distinguish a forbidden mutation from a nonexistent one.
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    pub requires_role: Option<String>,
557
558    /// Actor classes permitted to execute this mutation — an allow-list (#966).
559    ///
560    /// Mirrors [`IntermediateQuery::requires_actor`].
561    #[serde(default, skip_serializing_if = "Vec::is_empty")]
562    pub requires_actor: Vec<String>,
563
564    /// Fact tables whose version counter should be bumped after this mutation succeeds.
565    ///
566    /// Used for correct invalidation of analytic/aggregate cache entries.
567    #[serde(default, skip_serializing_if = "Vec::is_empty")]
568    pub invalidates_fact_tables: Vec<String>,
569
570    /// View names whose cached query results should be invalidated after this
571    /// mutation succeeds.
572    #[serde(default, skip_serializing_if = "Vec::is_empty")]
573    pub invalidates_views: Vec<String>,
574
575    /// Whether this mutation writes a Change-Spine change-log row (default `true`).
576    ///
577    /// Set `false` (via the authoring SDK's `@fraiseql.mutation(changelog=False)`)
578    /// to opt a single mutation out of the in-transaction change-log outbox while
579    /// the rest of the schema keeps logging. Defaults to `true` so a schema
580    /// authored before this field existed keeps logging.
581    #[serde(default = "default_changelog")]
582    pub changelog: bool,
583
584    /// How the GraphQL `input` argument is passed to the SQL function:
585    /// `"flatten"` (positional columns, the default) or `"jsonb"` (the whole
586    /// input as one `jsonb` arg). See [`InputStyle`].
587    ///
588    /// Orthogonal to [`operation`](IntermediateMutation::operation): set
589    /// `"jsonb"` (via the authoring SDK's
590    /// `@fraiseql.mutation(input_style="jsonb")`) so a backend using the
591    /// single-`jsonb`-wrapper convention can register the real DML verb and
592    /// still receive the whole input as one argument. Defaults to `"flatten"`,
593    /// byte-identical to a schema authored before this field existed.
594    #[serde(default, skip_serializing_if = "InputStyle::is_flatten")]
595    pub input_style: InputStyle,
596
597    /// Whether a successful, state-changing run of this mutation also records the
598    /// changed entity's pre-image (before-state) into the Change-Spine
599    /// `object_data_before` column, sourced from an optional `entity_before` on the
600    /// mutation's `app.mutation_response`.
601    ///
602    /// Set `true` (via the authoring SDK's
603    /// `@fraiseql.mutation(changelog_pre_image=True)` or TOML
604    /// `changelog_pre_image = true`) to opt an audit-sensitive mutation into an
605    /// inline Debezium-style `{before, after}`. Defaults to `false`,
606    /// byte-identical to a schema authored before this field existed.
607    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
608    pub changelog_pre_image: bool,
609
610    /// Whether this mutation exposes the typed graphql-cascade `cascade` field
611    /// on its success payload.
612    ///
613    /// Set `true` via the authoring SDK's `@fraiseql.type(crud=True,
614    /// cascade=True)` / `@fraiseql.mutation(cascade=True)`, or TOML
615    /// `cascade = true`. Defaults to `false`, byte-identical to a schema
616    /// authored before this field existed. Before this field, the compiler
617    /// silently dropped the SDK flag.
618    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
619    pub cascade: bool,
620
621    /// REST route override for this mutation. See [`IntermediateRest`].
622    #[serde(default, skip_serializing_if = "Option::is_none")]
623    pub rest: Option<IntermediateRest>,
624}
625
626impl Default for IntermediateMutation {
627    /// Hand-written so `changelog` defaults to `true` (matching the serde default),
628    /// not `bool`'s `false`. A `#[derive(Default)]` would silently opt
629    /// `..Default::default()`-built mutations out of the change log.
630    fn default() -> Self {
631        Self {
632            name:                    String::new(),
633            return_type:             String::new(),
634            returns_list:            false,
635            nullable:                false,
636            arguments:               Vec::new(),
637            description:             None,
638            sql_source:              None,
639            operation:               None,
640            deprecated:              None,
641            inject:                  IndexMap::new(),
642            exclude_inject_defaults: Vec::new(),
643            requires_actor:          Vec::new(),
644            requires_role:           None,
645            invalidates_fact_tables: Vec::new(),
646            invalidates_views:       Vec::new(),
647            changelog:               default_changelog(),
648            input_style:             InputStyle::Flatten,
649            changelog_pre_image:     false,
650            cascade:                 false,
651            rest:                    None,
652        }
653    }
654}
655
656/// Serde default for [`IntermediateMutation::changelog`]: log by default (opt-out).
657const fn default_changelog() -> bool {
658    true
659}
660
661/// Auto-params configuration in intermediate format.
662///
663/// Each field is `Option<bool>`: `None` means "not specified — inherit from
664/// `[query_defaults]`"; `Some(v)` means explicitly set by the authoring-language decorator.
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
666#[serde(deny_unknown_fields)]
667pub struct IntermediateAutoParams {
668    /// Enable automatic limit parameter (None = inherit from query_defaults)
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub limit:        Option<bool>,
671    /// Enable automatic offset parameter (None = inherit from query_defaults)
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub offset:       Option<bool>,
674    /// Enable automatic where clause parameter (None = inherit from query_defaults)
675    #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")]
676    pub where_clause: Option<bool>,
677    /// Enable automatic order_by parameter (None = inherit from query_defaults)
678    #[serde(default, skip_serializing_if = "Option::is_none")]
679    pub order_by:     Option<bool>,
680}
681
682/// Global auto-param defaults for list queries (injected from TOML by the merger).
683///
684/// Never present in `schema.json` — set only at compile time via `[query_defaults]`
685/// in `fraiseql.toml`.
686///
687/// The `Default` implementation returns all-`true`, matching the historical behaviour
688/// when no `[query_defaults]` section is present in TOML.
689#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
690#[serde(deny_unknown_fields)]
691pub struct IntermediateQueryDefaults {
692    /// Default for `where` parameter
693    pub where_clause:     bool,
694    /// Default for `order_by` parameter
695    pub order_by:         bool,
696    /// Default for `limit` parameter
697    pub limit:            bool,
698    /// Default for `offset` parameter
699    pub offset:           bool,
700    /// Deployment-wide posture on the order paginated pages are cut in (#1303).
701    pub pagination_order: crate::config::toml_schema::PaginationPosture,
702}
703
704impl Default for IntermediateQueryDefaults {
705    fn default() -> Self {
706        Self {
707            where_clause:     true,
708            order_by:         true,
709            limit:            true,
710            offset:           true,
711            pagination_order: crate::config::toml_schema::PaginationPosture::Identity,
712        }
713    }
714}