vantage_table/table/sets/
hooks.rs1use 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
28impl<T: TableSource, E: Entity<T::Value>> Table<T, E>
32where
33 T::Value: InvariantValue,
34{
35 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 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 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 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 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
122pub(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
138pub(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
163pub(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
185pub(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
203fn 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 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
265pub(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}