fraiseql_core/runtime/executor/mutation.rs
1//! Mutation execution — thin wrappers on `Executor<A>`.
2//!
3//! The core mutation logic lives in
4//! [`runners::mutation::execute_mutation_impl`](super::runners::mutation::execute_mutation_impl).
5//! This module contains:
6//!
7//! - The compile-time-enforced public API ([`Executor::execute_mutation`], bounded on
8//! [`SupportsMutations`]).
9//! - The runtime-guarded internal dispatch entry point (`Executor::execute_mutation_query`, bounded
10//! only on [`DatabaseAdapter`]).
11//! - Convenience wrappers used by the REST transport ([`execute_mutation_with_security`],
12//! [`execute_mutation_batch`], [`execute_bulk_by_filter`]).
13
14use super::{Executor, runners};
15use crate::{
16 db::traits::{DatabaseAdapter, SupportsMutations},
17 error::{FraiseQLError, Result},
18 graphql::FieldSelection,
19 security::SecurityContext,
20};
21
22/// Compile-time enforcement: `SqliteAdapter` must NOT implement `SupportsMutations`.
23///
24/// Calling `execute_mutation` on an `Executor<SqliteAdapter>` must not compile
25/// because `SqliteAdapter` does not implement the `SupportsMutations` marker trait.
26///
27/// ```compile_fail
28/// use fraiseql_core::runtime::Executor;
29/// use fraiseql_core::db::sqlite::SqliteAdapter;
30/// use fraiseql_core::schema::CompiledSchema;
31/// use std::sync::Arc;
32/// async fn _wont_compile() {
33/// let adapter = Arc::new(SqliteAdapter::new_in_memory().await.unwrap());
34/// let executor = Executor::new(CompiledSchema::new(), adapter);
35/// executor.execute_mutation("createUser", None, &[]).await.unwrap();
36/// }
37/// ```
38impl<A: DatabaseAdapter + SupportsMutations> Executor<A> {
39 /// Construct a mutation runner on demand.
40 ///
41 /// Zero-cost: `Arc::clone` is one atomic increment, no allocation.
42 fn mutation_runner(&self) -> runners::mutation::MutationRunner<A> {
43 runners::mutation::MutationRunner::new(std::sync::Arc::clone(&self.ctx))
44 }
45
46 /// Execute a GraphQL mutation directly, with compile-time capability enforcement.
47 ///
48 /// Unlike `execute()` (which accepts raw GraphQL strings and performs a runtime
49 /// `supports_mutations()` check), this method is only available on adapters that
50 /// implement [`SupportsMutations`]. The capability is enforced at **compile time**:
51 /// attempting to call this method with `SqliteAdapter` results in a compiler error.
52 ///
53 /// # Arguments
54 ///
55 /// * `mutation_name` - The GraphQL mutation field name (e.g. `"createUser"`)
56 /// * `variables` - Optional JSON object of GraphQL variable values
57 /// * `selections` - The result selection set (inline fragments intact) used to project the
58 /// response; pass `&[]` for no field filtering.
59 ///
60 /// # Returns
61 ///
62 /// A JSON-encoded GraphQL response value on success.
63 ///
64 /// # Errors
65 ///
66 /// Same as `execute_mutation_query`, minus the adapter
67 /// capability check.
68 pub async fn execute_mutation(
69 &self,
70 mutation_name: &str,
71 variables: Option<&serde_json::Value>,
72 selections: &[FieldSelection],
73 ) -> Result<serde_json::Value> {
74 // No runtime supports_mutations() check: the SupportsMutations bound
75 // guarantees at compile time that this adapter supports mutations.
76 self.mutation_runner()
77 .execute_mutation(mutation_name, variables, selections)
78 .await
79 }
80}
81
82impl<A: DatabaseAdapter> Executor<A> {
83 /// Execute a GraphQL mutation by calling the configured database function.
84 ///
85 /// This is the **runtime-guarded** entry point called from [`execute_internal`] when the
86 /// query is classified as a mutation. It checks `adapter.supports_mutations()` at runtime
87 /// (because `execute_internal` is bounded only on `DatabaseAdapter`) and delegates to the
88 /// shared [`execute_mutation_impl`](runners::mutation::execute_mutation_impl) function.
89 ///
90 /// # Errors
91 ///
92 /// * [`FraiseQLError::Validation`] — the adapter does not support mutations, mutation name not
93 /// found in the compiled schema, no `sql_source` configured, or the database function
94 /// returned no rows.
95 /// * [`FraiseQLError::Database`] — the adapter's `execute_function_call` returned an error.
96 ///
97 /// # Example
98 ///
99 /// ```no_run
100 /// // Requires: live database adapter with SupportsMutations implementation.
101 /// // See: tests/integration/ for runnable examples.
102 /// # use fraiseql_core::db::postgres::PostgresAdapter;
103 /// # use fraiseql_core::schema::CompiledSchema;
104 /// # use fraiseql_core::runtime::Executor;
105 /// # use std::sync::Arc;
106 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
107 /// # let schema: CompiledSchema = panic!("example");
108 /// # let adapter = PostgresAdapter::new("postgresql://localhost/mydb").await?;
109 /// # let executor = Executor::new(schema, Arc::new(adapter));
110 /// let vars = serde_json::json!({ "name": "Alice", "email": "alice@example.com" });
111 /// // Returns {"data":{"createUser":{"id":"...", "name":"Alice"}}}
112 /// // or {"data":{"createUser":{"__typename":"UserAlreadyExistsError", "email":"..."}}}
113 /// let result = executor.execute_mutation("createUser", Some(&vars), &[]).await?;
114 /// # Ok(())
115 /// # }
116 /// ```
117 pub(super) async fn execute_mutation_query(
118 &self,
119 mutation_name: &str,
120 variables: Option<&serde_json::Value>,
121 selections: &[FieldSelection],
122 ) -> Result<serde_json::Value> {
123 // Runtime guard: verify this adapter supports mutations.
124 // Note: this is a runtime check, not compile-time enforcement.
125 // The common execute() entry point accepts raw GraphQL strings and
126 // determines the operation type at runtime, which precludes compile-time
127 // mutation gating. The direct execute_mutation() API provides compile-time
128 // enforcement via the SupportsMutations bound on MutationRunner.
129 if !self.ctx.adapter.supports_mutations() {
130 return Err(FraiseQLError::Validation {
131 message: format!(
132 "Mutation '{mutation_name}' cannot be executed: the configured database \
133 adapter does not support mutations. Use PostgresAdapter, MySqlAdapter, \
134 or SqlServerAdapter for mutation operations."
135 ),
136 path: None,
137 });
138 }
139 runners::mutation::execute_mutation_impl(
140 &self.ctx,
141 mutation_name,
142 variables,
143 None,
144 selections,
145 )
146 .await
147 }
148
149 /// Execute a mutation with security context for REST transport.
150 ///
151 /// Delegates to the standard mutation execution path with RLS enforcement.
152 ///
153 /// # Errors
154 ///
155 /// Returns `FraiseQLError::Database` if the adapter returns an error.
156 /// Returns `FraiseQLError::Validation` if inject params require a missing security context.
157 pub async fn execute_mutation_with_security(
158 &self,
159 mutation_name: &str,
160 arguments: &serde_json::Value,
161 security_context: Option<&SecurityContext>,
162 ) -> crate::error::Result<serde_json::Value> {
163 // Build a synthetic GraphQL mutation query and delegate to execute()
164 let args_str = if let Some(obj) = arguments.as_object() {
165 obj.iter().map(|(k, v)| format!("{k}: {v}")).collect::<Vec<_>>().join(", ")
166 } else {
167 String::new()
168 };
169 let query = if args_str.is_empty() {
170 format!("mutation {{ {mutation_name} {{ status entity_id message }} }}")
171 } else {
172 format!("mutation {{ {mutation_name}({args_str}) {{ status entity_id message }} }}")
173 };
174
175 if let Some(ctx) = security_context {
176 self.execute_with_security(&query, None, ctx).await
177 } else {
178 self.execute(&query, None).await
179 }
180 }
181
182 /// Execute a batch of mutations (for REST bulk insert).
183 ///
184 /// Executes each mutation individually and collects results into a `BulkResult`.
185 ///
186 /// # Errors
187 ///
188 /// Returns the first error encountered during batch execution.
189 pub async fn execute_mutation_batch(
190 &self,
191 mutation_name: &str,
192 items: &[serde_json::Value],
193 security_context: Option<&SecurityContext>,
194 ) -> crate::error::Result<crate::runtime::BulkResult> {
195 let mut entities = Vec::with_capacity(items.len());
196 for item in items {
197 let result = self
198 .execute_mutation_with_security(mutation_name, item, security_context)
199 .await?;
200 entities.push(result);
201 }
202 Ok(crate::runtime::BulkResult {
203 affected_rows: entities.len() as u64,
204 entities: Some(entities),
205 })
206 }
207
208 /// Execute a bulk operation (collection-level PATCH/DELETE) by filter.
209 ///
210 /// # Errors
211 ///
212 /// Returns `FraiseQLError::Database` if the adapter returns an error.
213 pub async fn execute_bulk_by_filter(
214 &self,
215 query_match: &crate::runtime::matcher::QueryMatch,
216 mutation_name: &str,
217 body: Option<&serde_json::Value>,
218 _id_field: &str,
219 _max_affected: u64,
220 security_context: Option<&SecurityContext>,
221 ) -> crate::error::Result<crate::runtime::BulkResult> {
222 // Execute the filter query to find matching rows.
223 let filter_result = self
224 .query_runner()
225 .execute_query_direct(query_match, None, security_context)
226 .await?;
227
228 let args = body.cloned().unwrap_or(serde_json::json!({}));
229 let result = self
230 .execute_mutation_with_security(mutation_name, &args, security_context)
231 .await?;
232
233 let count = filter_result
234 .get("data")
235 .and_then(|d| d.as_object())
236 .and_then(|o| o.values().next())
237 .and_then(|v| v.as_array())
238 .map_or(1, |a| a.len() as u64);
239
240 Ok(crate::runtime::BulkResult {
241 affected_rows: count,
242 entities: Some(vec![result]),
243 })
244 }
245}