Skip to main content

vantage_table/table/sets/
hooks.rs

1//! Fire a table's lifecycle hooks around a write.
2//!
3//! Before-write hooks run on the record about to be written, in phase order,
4//! just ahead of set-invariant enforcement, with the source typing the
5//! record between the Populate and Validate bands; an error cancels the
6//! operation.
7//! `before_delete` hooks may instead return [`HookReturn::Handled`] to take over
8//! (soft-delete). After-commit hooks run for their side-effects: at once, or,
9//! when the table's datasource is in a transaction, after it commits. Hooks
10//! receive the entity-erased table for relation/datasource access.
11
12use std::future::Future;
13
14use indexmap::IndexMap;
15
16use vantage_core::Result;
17use vantage_types::{EmptyEntity, Entity, InvariantValue, Record};
18use vantage_vista::{Capability, Transaction};
19
20use super::invariants::enforce_invariants;
21use crate::table::{
22    AfterCx, AfterFn, BeforeCx, BeforeDeleteFn, BeforeFn, DeleteAllCx, DeleteAllFn, DeleteCx,
23    HookReturn, Phase, Table,
24};
25use crate::traits::table_source::TableSource;
26use crate::write_context::WriteContext;
27
28/// The two halves of a single-record insert that surround the driver's write.
29/// A driver's bulk path calls them around its batch so that it stays
30/// equivalent to inserting the records one by one.
31impl<T: TableSource, E: Entity<T::Value>> Table<T, E>
32where
33    T::Value: InvariantValue,
34{
35    /// Everything a single insert does to `record` before the driver write:
36    /// the denial and confined-writes checks, before-insert hooks, dropping
37    /// read-only imported and expression columns, and conforming to the
38    /// set's invariants. Returns the record to store.
39    pub async fn prepare_insert(&self, record: &Record<T::Value>) -> Result<Record<T::Value>> {
40        self.require_allowed(Capability::Insert)?;
41        self.require_confined_writes("insert")?;
42        let mut record = record.clone();
43        self.before_write(self.before_insert_hooks(), &mut record, None)
44            .await?;
45        enforce_invariants(&mut record, &self.typed_invariants())?;
46        Ok(record)
47    }
48
49    /// Run the after-insert hooks for a record stored under `id`, as a single
50    /// insert does once the driver write has succeeded. Inside a transaction
51    /// they are held until it commits.
52    pub async fn finish_insert(&self, id: &T::Id, record: &Record<T::Value>) -> Result<()> {
53        run_after(
54            self.after_insert_hooks(),
55            id,
56            record,
57            None,
58            self.as_entity_erased(),
59        )
60        .await
61    }
62}
63
64impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
65    /// What every insert, replace and patch does to `record` before the
66    /// set's invariants: the Normalize and Populate hooks, dropping imported
67    /// and expression columns, typing the declared columns through the
68    /// source, then the Validate hooks, which so see the record as stored.
69    pub(crate) async fn before_write(
70        &self,
71        hooks: &[(Phase, BeforeFn<T>)],
72        record: &mut Record<T::Value>,
73        update: Option<UpdateOf<'_, T>>,
74    ) -> Result<()> {
75        let (shaping, validating) =
76            hooks.split_at(hooks.partition_point(|(phase, _)| *phase < Phase::Validate));
77        let erased = self.as_entity_erased();
78        run_before(shaping, record, update, erased).await?;
79        self.strip_imported_columns(record);
80        self.strip_expression_columns(record);
81        self.coerce_record(record)?;
82        run_before(validating, record, update, erased).await
83    }
84
85    /// Each declared column of `record` other than the id, as the source
86    /// stores it ([`TableSource::coerce_column_value`]).
87    fn coerce_record(&self, record: &mut Record<T::Value>) -> Result<()> {
88        let id_field = self.id_field_name();
89        for (name, value) in record.iter_mut() {
90            if *name == id_field || !self.columns().contains_key(name) {
91                continue;
92            }
93            *value = self
94                .data_source()
95                .coerce_column_value(self, name, value.clone())?;
96        }
97        Ok(())
98    }
99
100    /// The set's invariants as the source stores their columns, so they
101    /// compare with and stamp typed record values. A condition value is
102    /// often loose text (`price = "5"`); one that doesn't fit its column
103    /// stays as given and the comparison decides.
104    pub(crate) fn typed_invariants(&self) -> IndexMap<String, T::Value> {
105        let id_field = self.id_field_name();
106        self.invariants()
107            .iter()
108            .map(|(name, value)| {
109                let typed = if *name == id_field || !self.columns().contains_key(name) {
110                    value.clone()
111                } else {
112                    self.data_source()
113                        .coerce_column_value(self, name, value.clone())
114                        .unwrap_or_else(|_| value.clone())
115                };
116                (name.clone(), typed)
117            })
118            .collect()
119    }
120}
121
122/// The row an update writes, the row as the set holds it, and whether the
123/// update is a patch (its record holds only the patched fields).
124pub(crate) struct UpdateOf<'a, T: TableSource> {
125    pub id: &'a T::Id,
126    pub stored: Option<&'a Record<T::Value>>,
127    pub patch: bool,
128}
129
130impl<T: TableSource> Clone for UpdateOf<'_, T> {
131    fn clone(&self) -> Self {
132        *self
133    }
134}
135
136impl<T: TableSource> Copy for UpdateOf<'_, T> {}
137
138/// `update` is `None` on insert.
139pub(crate) async fn run_before<T: TableSource>(
140    hooks: &[(Phase, BeforeFn<T>)],
141    record: &mut Record<T::Value>,
142    update: Option<UpdateOf<'_, T>>,
143    table: &Table<T, EmptyEntity>,
144) -> Result<()> {
145    if hooks.is_empty() {
146        return Ok(());
147    }
148    let context = WriteContext::current();
149    for (_phase, hook) in hooks {
150        hook(BeforeCx {
151            record: &mut *record,
152            id: update.as_ref().map(|u| u.id),
153            stored: update.as_ref().and_then(|u| u.stored),
154            patch: update.as_ref().is_some_and(|u| u.patch),
155            context: context.as_ref(),
156            table,
157        })
158        .await?;
159    }
160    Ok(())
161}
162
163/// Inside a transaction the hooks are held until it commits.
164pub(crate) async fn run_after<T: TableSource>(
165    hooks: &[AfterFn<T>],
166    id: &T::Id,
167    record: &Record<T::Value>,
168    before: Option<&Record<T::Value>>,
169    table: &Table<T, EmptyEntity>,
170) -> Result<()> {
171    if hooks.is_empty() {
172        return Ok(());
173    }
174    let Some(tx) = table.data_source().transaction() else {
175        return run_after_now(hooks, id, record, before, table).await;
176    };
177    let hooks = hooks.to_vec();
178    let (id, record, before) = (id.clone(), record.clone(), before.cloned());
179    after_commit(&tx, table, move |table| async move {
180        run_after_now(&hooks, &id, &record, before.as_ref(), &table).await
181    });
182    Ok(())
183}
184
185/// Inside a transaction the hooks are held until it commits.
186pub(crate) async fn run_after_delete_all<T: TableSource>(
187    hooks: &[DeleteAllFn<T>],
188    table: &Table<T, EmptyEntity>,
189) -> Result<()> {
190    if hooks.is_empty() {
191        return Ok(());
192    }
193    let Some(tx) = table.data_source().transaction() else {
194        return run_delete_all(hooks, table).await;
195    };
196    let hooks = hooks.to_vec();
197    after_commit(&tx, table, move |table| async move {
198        run_delete_all(&hooks, &table).await
199    });
200    Ok(())
201}
202
203/// Hold `work` until `tx` commits; a rollback drops it. It runs on a copy of
204/// `table` back on its pool, the transaction being gone by then, under the
205/// writer's [`WriteContext`].
206fn after_commit<T, F, Fut>(tx: &Transaction, table: &Table<T, EmptyEntity>, work: F)
207where
208    T: TableSource,
209    F: FnOnce(Table<T, EmptyEntity>) -> Fut + Send + 'static,
210    Fut: Future<Output = Result<()>> + Send + 'static,
211{
212    let mut outside = table.with_data_source(table.data_source().without_transaction());
213    // Out of the transaction a locked read would wait on other writers' row locks.
214    outside.lock = false;
215    let context = WriteContext::current();
216    tx.defer(Box::new(move || {
217        Box::pin(async move {
218            match context {
219                Some(context) => context.scope(work(outside)).await,
220                None => work(outside).await,
221            }
222        })
223    }));
224}
225
226async fn run_after_now<T: TableSource>(
227    hooks: &[AfterFn<T>],
228    id: &T::Id,
229    record: &Record<T::Value>,
230    before: Option<&Record<T::Value>>,
231    table: &Table<T, EmptyEntity>,
232) -> Result<()> {
233    let context = WriteContext::current();
234    for hook in hooks {
235        hook(AfterCx {
236            id,
237            record,
238            before,
239            context: context.as_ref(),
240            table,
241        })
242        .await?;
243    }
244    Ok(())
245}
246
247pub(crate) async fn run_delete_all<T: TableSource>(
248    hooks: &[DeleteAllFn<T>],
249    table: &Table<T, EmptyEntity>,
250) -> Result<()> {
251    if hooks.is_empty() {
252        return Ok(());
253    }
254    let context = WriteContext::current();
255    for hook in hooks {
256        hook(DeleteAllCx {
257            context: context.as_ref(),
258            table,
259        })
260        .await?;
261    }
262    Ok(())
263}
264
265/// Run before-delete hooks; the first `Handled` short-circuits and signals the
266/// caller to skip the underlying delete.
267pub(crate) async fn run_before_delete<T: TableSource>(
268    hooks: &[BeforeDeleteFn<T>],
269    id: &T::Id,
270    record: &Record<T::Value>,
271    table: &Table<T, EmptyEntity>,
272) -> Result<HookReturn> {
273    let context = WriteContext::current();
274    for hook in hooks {
275        let cx = DeleteCx {
276            id,
277            record,
278            context: context.as_ref(),
279            table,
280        };
281        if let HookReturn::Handled = hook(cx).await? {
282            return Ok(HookReturn::Handled);
283        }
284    }
285    Ok(HookReturn::Proceed)
286}