Skip to main content

fraiseql_db/traits/
mutations.rs

1//! The write capability: [`Writer`], one method, [`Writer::execute_write`] (ruling AA 6), and
2//! its batch form, [`Writer::execute_writes`] (#1574).
3
4use async_trait::async_trait;
5use fraiseql_error::{FraiseQLError, Result};
6
7use super::{BatchRowGate, ChangeLogWrite, DatabaseAdapter, MutationRowGate};
8
9/// Whether a write commits.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum WriteMode {
13    /// Commit once the gate admits the rows the function returned.
14    Commit,
15    /// Everything [`Commit`](Self::Commit) does — session variables, the change-log outbox
16    /// row, the timing stamp, the gate — then roll back: a dry run exercises exactly the
17    /// write it stands in for, and nothing persists.
18    DryRun,
19}
20
21/// The rows `pg_tviews` reports a write's transaction changed, asked for before the commit
22/// (#1391).
23///
24/// The adapter calls `tviews.pg_tviews_flush_and_report(max_entities, false, true)` after
25/// the function, then reads the reported rows of each type in `views` from that type's view,
26/// one statement per type (`WHERE id = ANY(…)`), on the write's own connection (so its session
27/// variables and row security apply), and attaches the result to the first row under
28/// [`DERIVED_CASCADE_KEY`]:
29///
30/// `{"updated": [{"__typename", "id", "operation", "entity"}], "deleted": [{"__typename",
31/// "id", "deletedAt"}], "truncated": bool, "invalidated_types": [...]}`
32///
33/// `entity` is `null` for a row the view did not return (not visible to this caller) or a
34/// type `views` does not name. Only on a row that succeeded.
35#[derive(Debug, Clone, Copy)]
36#[non_exhaustive]
37pub struct DerivedCascade<'a> {
38    /// The most rows `pg_tviews` reports before truncating.
39    pub max_entities: i32,
40    /// GraphQL type name → the relation its rows are read from (`id`, `data`). A type left
41    /// out is not read: its rows come back with `entity: null`.
42    pub views:        &'a [(&'a str, &'a str)],
43}
44
45impl<'a> DerivedCascade<'a> {
46    /// Report at most `max_entities` rows, reading each from the view `views` names for its
47    /// type.
48    #[must_use]
49    pub const fn new(max_entities: i32, views: &'a [(&'a str, &'a str)]) -> Self {
50        Self {
51            max_entities,
52            views,
53        }
54    }
55}
56
57/// The key a [`DerivedCascade`] report is attached under, on the first returned row.
58pub const DERIVED_CASCADE_KEY: &str = "__fraiseql_derived_cascade";
59
60/// The key the report of the rows a write changed is attached under, on the first returned
61/// row, when its request asked for one ([`WriteRequest::with_changes_reported`], #1576).
62///
63/// `pg_tviews`' report, as `tviews.pg_tviews_flush_and_report(max_entities, false, true)`
64/// returns it after the function: `{"updated": [{"__typename", "id"}], "deleted": [...],
65/// "invalidated_types": [...], "collections": {"Comment.fk_post": [...]}}` (`collections`
66/// only for rows written with `pg_tviews.publish_changes = 'rows'`). No row is read. Read it
67/// with [`ChangedRows::from_report`].
68pub const CHANGED_ROWS_KEY: &str = "__fraiseql_changed_rows";
69
70/// Parent ids, as text, by collection: `<child type>.<reference column>`, as `pg_tviews`
71/// names it (`Comment.fk_post`).
72pub type ChangedCollections =
73    std::collections::BTreeMap<String, std::collections::BTreeSet<String>>;
74
75/// The TVIEW rows a committed write changed, by GraphQL type and public id, as `pg_tviews`
76/// reported them (#1576). Cascaded rows are included: `pg_tviews` journals every row it
77/// refreshes.
78///
79/// The default is a write that changed nothing: no row, no type, no collection.
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct ChangedRows {
83    /// Rows inserted, updated or deleted: public ids, as text, by type.
84    pub rows:        std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
85    /// Types whose rows are not all listed (the report was truncated): every row of each may
86    /// have changed, and every collection of each (#1603).
87    pub types:       std::collections::BTreeSet<String>,
88    /// The collections whose members changed: the parents whose child lists the rows left,
89    /// joined or changed in (#1603). `None` when the report captured none (the rows were
90    /// written without `pg_tviews.publish_changes = 'rows'`): which changed is then unknown.
91    pub collections: Option<ChangedCollections>,
92}
93
94impl Default for ChangedRows {
95    fn default() -> Self {
96        Self {
97            rows:        std::collections::BTreeMap::new(),
98            types:       std::collections::BTreeSet::new(),
99            collections: Some(ChangedCollections::new()),
100        }
101    }
102}
103
104impl ChangedRows {
105    /// Read a `pg_tviews` report (see [`CHANGED_ROWS_KEY`]). `None` when `report` is not one:
106    /// what changed is then unknown. An entry whose id is neither text nor a number names
107    /// its type as wholly changed, and a collection's parent likewise its child type. A
108    /// report without `collections`, or with a key that is not `<type>.<column>`, captured
109    /// none ([`collections`](Self::collections) is `None`).
110    #[must_use]
111    pub fn from_report(report: &serde_json::Value) -> Option<Self> {
112        let report = report.as_object()?;
113        let mut changed = Self {
114            collections: None,
115            ..Self::default()
116        };
117        for arm in ["updated", "deleted"] {
118            let entries = match report.get(arm) {
119                None => continue,
120                Some(entries) => entries.as_array()?,
121            };
122            for entry in entries {
123                let typename = entry.get("__typename")?.as_str()?;
124                match entry.get("id") {
125                    Some(serde_json::Value::String(id)) => {
126                        changed.rows.entry(typename.to_string()).or_default().insert(id.clone());
127                    },
128                    Some(serde_json::Value::Number(id)) => {
129                        changed
130                            .rows
131                            .entry(typename.to_string())
132                            .or_default()
133                            .insert(id.to_string());
134                    },
135                    _ => {
136                        changed.types.insert(typename.to_string());
137                    },
138                }
139            }
140        }
141        if let Some(types) = report.get("invalidated_types") {
142            for typename in types.as_array()? {
143                changed.types.insert(typename.as_str()?.to_string());
144            }
145        }
146        if let Some(collections) = report.get("collections") {
147            let mut read = ChangedCollections::new();
148            let mut readable = true;
149            for (key, parents) in collections.as_object()? {
150                let Some((child_type, _)) = key
151                    .split_once('.')
152                    .filter(|(child_type, column)| !child_type.is_empty() && !column.is_empty())
153                else {
154                    readable = false;
155                    continue;
156                };
157                for parent in parents.as_array()? {
158                    match parent {
159                        serde_json::Value::String(id) => {
160                            read.entry(key.clone()).or_default().insert(id.clone());
161                        },
162                        serde_json::Value::Number(id) => {
163                            read.entry(key.clone()).or_default().insert(id.to_string());
164                        },
165                        _ => {
166                            changed.types.insert(child_type.to_string());
167                        },
168                    }
169                }
170            }
171            changed.collections = readable.then_some(read);
172        }
173        Some(changed)
174    }
175
176    /// Also the rows, types and collections of `other`, committed in the same transaction.
177    /// When either captured no collections, which changed is unknown.
178    pub fn absorb(&mut self, other: Self) {
179        for (typename, ids) in other.rows {
180            self.rows.entry(typename).or_default().extend(ids);
181        }
182        self.types.extend(other.types);
183        match (self.collections.as_mut(), other.collections) {
184            (Some(mine), Some(theirs)) => {
185                for (key, parents) in theirs {
186                    mine.entry(key).or_default().extend(parents);
187                }
188            },
189            _ => self.collections = None,
190        }
191    }
192
193    /// Every type named, by a row or wholly.
194    pub fn type_names(&self) -> impl Iterator<Item = &str> {
195        self.rows.keys().chain(&self.types).map(String::as_str)
196    }
197}
198
199/// One call of a write function.
200///
201/// `#[non_exhaustive]`: build it with [`WriteRequest::new`] and the `with_*` builders, so a
202/// field added later breaks no adapter and no caller.
203#[derive(Debug, Clone, Copy)]
204#[non_exhaustive]
205pub struct WriteRequest<'a> {
206    /// The function to call.
207    pub function:        &'a str,
208    /// Its arguments, positionally.
209    pub args:            &'a [serde_json::Value],
210    /// Transaction-local settings applied before the call (`set_config(.., true)`).
211    pub session_vars:    &'a [(&'a str, &'a str)],
212    /// The change-log outbox row to write in the same transaction, if any.
213    pub changelog:       Option<&'a ChangeLogWrite<'a>>,
214    /// Whether the write commits.
215    pub mode:            WriteMode,
216    /// The `pg_tviews` report to attach before the gate, if any (#1391).
217    pub derived_cascade: Option<&'a DerivedCascade<'a>>,
218    /// Report the rows the call changed, at most this many (#1576): see
219    /// [`CHANGED_ROWS_KEY`]. A call with a [`DerivedCascade`] carries its report there
220    /// instead.
221    pub report_changes:  Option<i32>,
222}
223
224impl<'a> WriteRequest<'a> {
225    /// A committing call of `function` with `args`, no session variables and no outbox row.
226    #[must_use]
227    pub const fn new(function: &'a str, args: &'a [serde_json::Value]) -> Self {
228        Self {
229            function,
230            args,
231            session_vars: &[],
232            changelog: None,
233            mode: WriteMode::Commit,
234            derived_cascade: None,
235            report_changes: None,
236        }
237    }
238
239    /// Reporting the rows the call changes, at most `max_entities` (#1576).
240    #[must_use]
241    pub const fn with_changes_reported(mut self, max_entities: Option<i32>) -> Self {
242        self.report_changes = max_entities;
243        self
244    }
245
246    /// With the `pg_tviews` report attached before the gate (#1391).
247    #[must_use]
248    pub const fn with_derived_cascade(
249        mut self,
250        derived_cascade: Option<&'a DerivedCascade<'a>>,
251    ) -> Self {
252        self.derived_cascade = derived_cascade;
253        self
254    }
255
256    /// With these transaction-local session variables.
257    #[must_use]
258    pub const fn with_session_vars(mut self, session_vars: &'a [(&'a str, &'a str)]) -> Self {
259        self.session_vars = session_vars;
260        self
261    }
262
263    /// With this change-log outbox row, written in the write's transaction.
264    #[must_use]
265    pub const fn with_changelog(mut self, changelog: Option<&'a ChangeLogWrite<'a>>) -> Self {
266        self.changelog = changelog;
267        self
268    }
269
270    /// In `mode`.
271    #[must_use]
272    pub const fn with_mode(mut self, mode: WriteMode) -> Self {
273        self.mode = mode;
274        self
275    }
276}
277
278/// A database adapter that writes.
279///
280/// Implementing [`execute_write`](Self::execute_write) **is** the capability: there is no
281/// flag to set beside it and no default to override, so an adapter cannot be write-capable
282/// to the type system and read-only at run time, or the other way round. A write-capable
283/// `Executor` is constructed only from a `Writer` (`Executor::new`, `Executor::with_config`);
284/// `Executor::read_only` takes any adapter.
285///
286/// # Which adapters implement this?
287///
288/// | Adapter | Implements |
289/// |---------|-----------|
290/// | `PostgresAdapter` | ✅ Yes |
291/// | `FraiseWireAdapter` | ❌ No — read-only wire protocol |
292/// | `CachedDatabaseAdapter<A>` | ✅ When `A: Writer` |
293///
294/// # Contract
295///
296/// In ONE transaction: apply `session_vars` transaction-locally, run the function (and write
297/// the change-log outbox row when `changelog` is `Some`), call `gate` on the rows it returned
298/// **before** the transaction ends, then roll back and return the gate's error verbatim if it
299/// errs; otherwise commit in [`WriteMode::Commit`] and roll back in [`WriteMode::DryRun`], and
300/// return the rows. An adapter that cannot hold a transaction open for the gate must not
301/// implement this trait: it stays read-only.
302// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
303#[async_trait]
304pub trait Writer: DatabaseAdapter {
305    /// Run `request` under `gate` (see the trait's contract).
306    ///
307    /// # Errors
308    ///
309    /// The gate's error, verbatim, after the rollback; a database error from any step.
310    async fn execute_write(
311        &self,
312        request: &WriteRequest<'_>,
313        gate: MutationRowGate<'_>,
314    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
315
316    /// Run every request in `requests` in **one** transaction, under `gate` (#1574).
317    ///
318    /// The contract of [`execute_write`](Self::execute_write), over several calls: in one
319    /// transaction, each call in order with its own `session_vars`, outbox row and derived
320    /// cascade, `gate` called with each call's index and rows before the transaction ends.
321    /// The first database error or gate error rolls everything back and is returned: a
322    /// database error names its call ([`FraiseQLError::in_batch_item`]), a gate error is
323    /// returned verbatim. Otherwise every call commits, or none does: the requests must
324    /// share one [`WriteMode`]. Returns each call's rows, in order.
325    ///
326    /// Provided: refuses. An adapter that cannot hold several calls in one transaction must
327    /// not fall back to one transaction per call, which would commit a batch in part.
328    ///
329    /// # Errors
330    ///
331    /// [`FraiseQLError::Unsupported`] unless the adapter overrides it; otherwise as above.
332    async fn execute_writes(
333        &self,
334        _requests: &[WriteRequest<'_>],
335        _gate: BatchRowGate<'_>,
336    ) -> Result<Vec<Vec<std::collections::HashMap<String, serde_json::Value>>>> {
337        Err(FraiseQLError::Unsupported {
338            message: "this database adapter cannot run a batch of writes in one transaction"
339                .to_string(),
340        })
341    }
342
343    /// Bump the version counters of `tables` after a committed write that changed them, so
344    /// cached aggregates over them are invalidated by version key.
345    ///
346    /// Provided: nothing to bump for an adapter with no aggregate cache. The cache wrapper
347    /// overrides it, bumping through [`execute_write`](Self::execute_write).
348    ///
349    /// # Errors
350    ///
351    /// A database error from the bump.
352    async fn bump_fact_table_versions(&self, _tables: &[String]) -> Result<()> {
353        Ok(())
354    }
355}