vantage-table 3.7.0

Table, Column, and operation traits for the Vantage data framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Lifecycle hooks attached to a [`Table`].
//!
//! Register them with [`Table::with_hook`] / [`Table::add_hook`]. Before-write
//! hooks run ahead of set-invariant enforcement, ordered by [`Phase`]; the
//! firing itself lives in the `table::sets` write paths.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use vantage_types::{EmptyEntity, Entity, Record};

use crate::table::Table;
use crate::traits::table_source::TableSource;
use crate::write_context::WriteContext;

/// Ordering band for before-write hooks. Hooks run in this order (and in
/// registration order within a band), ahead of set-invariant enforcement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Phase {
    /// Clean inputs (trim, default empties).
    Normalize,
    /// Set or compute fields (audit stamps, derived values). The default.
    Populate,
    /// Read-only checks, last — so they see the final record.
    Validate,
}

/// What a `before_delete` hook decided.
pub enum HookReturn {
    /// Carry out the underlying operation.
    Proceed,
    /// The hook already performed the operation (e.g. a soft-delete patch); skip
    /// the real one and report success.
    Handled,
}

/// The future a hook returns.
pub type BoxFuture<'r, X> = Pin<Box<dyn Future<Output = X> + Send + 'r>>;

/// What a before-write hook receives: the record about to be written (mutable),
/// the write's [`WriteContext`] if one is in scope, and the entity-erased table.
///
/// On an update (replace or patch), `id` is the row being written and
/// `stored` the row as the set holds it now, read once before the hooks
/// run; `stored` is `None` when the set doesn't hold the row. Both are
/// `None` on insert.
///
/// `patch` is true on a patch, whose `record` holds only the patched
/// fields: a hook judging the whole row reads the rest from `stored`. On a
/// replace, `record` is the whole new row and fields it lacks are dropped.
#[non_exhaustive]
pub struct BeforeCx<'r, T: TableSource> {
    pub record: &'r mut Record<T::Value>,
    pub id: Option<&'r T::Id>,
    pub stored: Option<&'r Record<T::Value>>,
    pub patch: bool,
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// What an after-commit hook receives. `record` is the committed row (the former
/// contents for a delete); `before` is the row as it was before an update, and
/// `None` for inserts and deletes.
#[non_exhaustive]
pub struct AfterCx<'r, T: TableSource> {
    pub id: &'r T::Id,
    pub record: &'r Record<T::Value>,
    pub before: Option<&'r Record<T::Value>>,
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// What a before-delete hook receives: the row id and its current contents.
#[non_exhaustive]
pub struct DeleteCx<'r, T: TableSource> {
    pub id: &'r T::Id,
    pub record: &'r Record<T::Value>,
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// What a bulk-delete hook receives: the table whose whole set is being
/// deleted. Its `conditions()` describe the set.
#[non_exhaustive]
pub struct DeleteAllCx<'r, T: TableSource> {
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// A bulk-delete hook, before (an `Err` cancels) or after `delete_all`.
pub type DeleteAllFn<T> = Arc<
    dyn for<'r> Fn(DeleteAllCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync,
>;

/// Build a [`DeleteAllFn`] from a closure.
pub fn delete_all_hook<T, F>(f: F) -> DeleteAllFn<T>
where
    T: TableSource,
    F: for<'r> Fn(DeleteAllCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// A before-write hook: mutate the record in place ahead of invariant
/// enforcement, returning `Err` to cancel the write.
pub type BeforeFn<T> =
    Arc<dyn for<'r> Fn(BeforeCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;

/// A before-delete hook: may `Err` to veto, or return [`HookReturn::Handled`]
/// to take over (soft-delete).
pub type BeforeDeleteFn<T> = Arc<
    dyn for<'r> Fn(DeleteCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<HookReturn>>
        + Send
        + Sync,
>;

/// An after-commit hook: side-effects on the committed row. Used for inserts,
/// updates, and deletes.
pub type AfterFn<T> =
    Arc<dyn for<'r> Fn(AfterCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;

/// Build a [`BeforeFn`] from a closure; the bound guides closure inference.
pub fn before_hook<T, F>(f: F) -> BeforeFn<T>
where
    T: TableSource,
    F: for<'r> Fn(BeforeCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// Build a [`BeforeDeleteFn`] from a closure.
pub fn before_delete_hook<T, F>(f: F) -> BeforeDeleteFn<T>
where
    T: TableSource,
    F: for<'r> Fn(DeleteCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<HookReturn>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// Build a [`BeforeFn`] from a synchronous closure over the record and the
/// write's context; an `Err` cancels the write. For callers with nothing to
/// await, such as a script evaluated in place.
pub fn before_hook_sync<T: TableSource>(
    f: impl Fn(&mut Record<T::Value>, Option<&WriteContext>) -> vantage_core::Result<()>
    + Send
    + Sync
    + 'static,
) -> BeforeFn<T> {
    Arc::new(move |cx: BeforeCx<'_, T>| {
        let outcome = f(cx.record, cx.context);
        Box::pin(std::future::ready(outcome))
    })
}

/// Build a [`BeforeFn`] from a synchronous closure over the whole
/// [`BeforeCx`]: the record, and on an update the id and the stored row.
pub fn before_hook_sync_cx<T: TableSource>(
    f: impl for<'r> Fn(BeforeCx<'r, T>) -> vantage_core::Result<()> + Send + Sync + 'static,
) -> BeforeFn<T> {
    Arc::new(move |cx: BeforeCx<'_, T>| Box::pin(std::future::ready(f(cx))))
}

/// Build a [`BeforeDeleteFn`] from a synchronous closure over the row id and
/// the write's context: `Ok` proceeds with the delete, an `Err` vetoes it.
pub fn before_delete_hook_sync<T: TableSource>(
    f: impl Fn(&T::Id, Option<&WriteContext>) -> vantage_core::Result<()> + Send + Sync + 'static,
) -> BeforeDeleteFn<T> {
    Arc::new(move |cx: DeleteCx<'_, T>| {
        let outcome = f(cx.id, cx.context).map(|()| HookReturn::Proceed);
        Box::pin(std::future::ready(outcome))
    })
}

/// Build an [`AfterFn`] from a closure.
pub fn after_hook<T, F>(f: F) -> AfterFn<T>
where
    T: TableSource,
    F: for<'r> Fn(AfterCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// What a read hook receives: the table about to be read (its conditions
/// describe the set) and the [`WriteContext`] in scope, if any — the same
/// task-local a write sees, so one scope covers a request's reads and writes.
#[non_exhaustive]
pub struct SelectCx<'r, T: TableSource> {
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// A read hook: an `Err` refuses the read.
pub type SelectFn<T> =
    Arc<dyn for<'r> Fn(SelectCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;

/// Build a [`SelectFn`] from a closure.
pub fn select_hook<T, F>(f: F) -> SelectFn<T>
where
    T: TableSource,
    F: for<'r> Fn(SelectCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// What an after-load hook receives: one row as it was read (mutable), its
/// id, the [`WriteContext`] in scope and the table.
#[non_exhaustive]
pub struct LoadCx<'r, T: TableSource> {
    pub id: &'r T::Id,
    pub record: &'r mut Record<T::Value>,
    pub context: Option<&'r WriteContext>,
    pub table: &'r Table<T, EmptyEntity>,
}

/// An after-load hook: rewrite the row in place; an `Err` fails the read.
pub type AfterLoadFn<T> =
    Arc<dyn for<'r> Fn(LoadCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;

/// Build an [`AfterLoadFn`] from a closure.
pub fn after_load_hook<T, F>(f: F) -> AfterLoadFn<T>
where
    T: TableSource,
    F: for<'r> Fn(LoadCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync + 'static,
{
    Arc::new(f)
}

/// Build an [`AfterLoadFn`] from a synchronous closure over the row and the
/// context in scope.
pub fn after_load_hook_sync<T: TableSource>(
    f: impl Fn(&mut Record<T::Value>, Option<&WriteContext>) -> vantage_core::Result<()>
    + Send
    + Sync
    + 'static,
) -> AfterLoadFn<T> {
    Arc::new(move |cx: LoadCx<'_, T>| {
        let outcome = f(cx.record, cx.context);
        Box::pin(std::future::ready(outcome))
    })
}

/// A lifecycle hook attached to a table via [`Table::with_hook`]. Each variant
/// carries a closure receiving exactly the references available at that stage.
/// `BeforeSave`/`AfterSave` are sugar that register for both insert and update.
#[non_exhaustive]
pub enum Hook<T: TableSource> {
    /// Before every read that returns rows or facts about rows: list, get,
    /// get-some, streams (before the first item), count and the aggregates
    /// (sum/max/min). An `Err` refuses the read. Vista shells that read the
    /// source directly call [`Table::check_read`] first.
    ///
    /// It does **not** run when the table is embedded in another query —
    /// `related_in_condition`, `column_table_values_expr`, `get_*_query` and
    /// `get_expr_*` build expressions or subqueries, not reads of this table.
    /// Rules that must hold inside a subquery belong in the table's
    /// conditions, added when it is built.
    ///
    /// Reads a write makes run it too, so a refusing `BeforeSelect` also
    /// refuses: an update when before- or after-update hooks exist (the
    /// stored row is read first), a delete when delete hooks exist (the row is read for
    /// them), and a write whose backend reads the row back. A Dio serves
    /// reads from its cache, filled by its own loader, so reads through a
    /// Dio don't run the master table's `BeforeSelect`.
    BeforeSelect(SelectFn<T>),
    /// On each row a list, get, get-some or stream returns, before the lazy
    /// expressions: the hook may rewrite the row callers see. Counts and the
    /// aggregates don't run it, and conditions, search and order still match
    /// the stored values. It must be idempotent, as a row it rewrote and
    /// saved back is read through it again. Vista shells that read the
    /// source directly call [`Table::finish_read`] on each row.
    AfterLoad(AfterLoadFn<T>),
    BeforeInsert(Phase, BeforeFn<T>),
    BeforeUpdate(Phase, BeforeFn<T>),
    BeforeSave(Phase, BeforeFn<T>),
    BeforeDelete(BeforeDeleteFn<T>),
    AfterInsert(AfterFn<T>),
    AfterUpdate(AfterFn<T>),
    AfterSave(AfterFn<T>),
    AfterDelete(AfterFn<T>),
    /// Before `delete_all`, once for the whole set. Without a
    /// [`Hook::BeforeDelete`] the set goes in one statement and the per-row
    /// delete hooks don't run; with one, `delete_all` deletes row by row.
    BeforeDeleteAll(DeleteAllFn<T>),
    AfterDeleteAll(DeleteAllFn<T>),
}

/// A table's registered lifecycle hooks, split by placement. The before-write
/// bands are kept ordered by [`Phase`]. Populated via [`Table::with_hook`].
#[derive(Clone)]
pub struct Hooks<T: TableSource> {
    pub(crate) before_select: Vec<SelectFn<T>>,
    pub(crate) after_load: Vec<AfterLoadFn<T>>,
    pub(crate) before_insert: Vec<(Phase, BeforeFn<T>)>,
    pub(crate) before_update: Vec<(Phase, BeforeFn<T>)>,
    pub(crate) before_delete: Vec<BeforeDeleteFn<T>>,
    pub(crate) after_insert: Vec<AfterFn<T>>,
    pub(crate) after_update: Vec<AfterFn<T>>,
    pub(crate) after_delete: Vec<AfterFn<T>>,
    pub(crate) before_delete_all: Vec<DeleteAllFn<T>>,
    pub(crate) after_delete_all: Vec<DeleteAllFn<T>>,
}

impl<T: TableSource> Default for Hooks<T> {
    fn default() -> Self {
        Self {
            before_select: Vec::new(),
            after_load: Vec::new(),
            before_insert: Vec::new(),
            before_update: Vec::new(),
            before_delete: Vec::new(),
            after_insert: Vec::new(),
            after_update: Vec::new(),
            after_delete: Vec::new(),
            before_delete_all: Vec::new(),
            after_delete_all: Vec::new(),
        }
    }
}

impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
    pub(crate) fn before_insert_hooks(&self) -> &[(Phase, BeforeFn<T>)] {
        &self.hooks.before_insert
    }
    pub(crate) fn before_update_hooks(&self) -> &[(Phase, BeforeFn<T>)] {
        &self.hooks.before_update
    }
    pub(crate) fn before_delete_hooks(&self) -> &[BeforeDeleteFn<T>] {
        &self.hooks.before_delete
    }
    pub(crate) fn after_insert_hooks(&self) -> &[AfterFn<T>] {
        &self.hooks.after_insert
    }
    pub(crate) fn after_update_hooks(&self) -> &[AfterFn<T>] {
        &self.hooks.after_update
    }
    pub(crate) fn after_delete_hooks(&self) -> &[AfterFn<T>] {
        &self.hooks.after_delete
    }
    pub(crate) fn before_delete_all_hooks(&self) -> &[DeleteAllFn<T>] {
        &self.hooks.before_delete_all
    }
    pub(crate) fn after_delete_all_hooks(&self) -> &[DeleteAllFn<T>] {
        &self.hooks.after_delete_all
    }

    /// Register a lifecycle [`Hook`]. Before-write hooks are kept ordered by
    /// [`Phase`] (then registration order); `BeforeSave`/`AfterSave` register
    /// for both insert and update.
    pub fn add_hook(&mut self, hook: Hook<T>) {
        let hooks = &mut self.hooks;
        match hook {
            Hook::BeforeSelect(f) => hooks.before_select.push(f),
            Hook::AfterLoad(f) => hooks.after_load.push(f),
            Hook::BeforeInsert(phase, f) => push_phased(&mut hooks.before_insert, phase, f),
            Hook::BeforeUpdate(phase, f) => push_phased(&mut hooks.before_update, phase, f),
            Hook::BeforeSave(phase, f) => {
                push_phased(&mut hooks.before_insert, phase, f.clone());
                push_phased(&mut hooks.before_update, phase, f);
            }
            Hook::BeforeDelete(f) => hooks.before_delete.push(f),
            Hook::AfterInsert(f) => hooks.after_insert.push(f),
            Hook::AfterUpdate(f) => hooks.after_update.push(f),
            Hook::AfterSave(f) => {
                hooks.after_insert.push(f.clone());
                hooks.after_update.push(f);
            }
            Hook::AfterDelete(f) => hooks.after_delete.push(f),
            Hook::BeforeDeleteAll(f) => hooks.before_delete_all.push(f),
            Hook::AfterDeleteAll(f) => hooks.after_delete_all.push(f),
        }
    }

    /// Builder form of [`Self::add_hook`].
    pub fn with_hook(mut self, hook: Hook<T>) -> Self {
        self.add_hook(hook);
        self
    }

    /// Run the [`Hook::BeforeSelect`] hooks; an `Err` means the read is
    /// refused. Every `Table` read path calls this. Code that reads through
    /// the table's data source directly (a vista shell's count or window)
    /// must call it first.
    pub async fn check_read(&self) -> vantage_core::Result<()> {
        if self.hooks.before_select.is_empty() {
            return Ok(());
        }
        let context = WriteContext::current();
        let table = self.as_entity_erased();
        for hook in &self.hooks.before_select {
            hook(SelectCx {
                context: context.as_ref(),
                table,
            })
            .await?;
        }
        Ok(())
    }

    /// Run the [`Hook::AfterLoad`] hooks on a row as read, then its lazy
    /// expressions. Every `Table` row read calls this; code that reads rows
    /// through the data source directly must call it on each row.
    pub async fn finish_read(
        &self,
        id: &T::Id,
        record: &mut Record<T::Value>,
    ) -> vantage_core::Result<()> {
        self.run_after_load(id, record).await?;
        self.apply_lazy_expressions(record).await
    }

    pub(crate) async fn run_after_load(
        &self,
        id: &T::Id,
        record: &mut Record<T::Value>,
    ) -> vantage_core::Result<()> {
        if self.hooks.after_load.is_empty() {
            return Ok(());
        }
        let context = WriteContext::current();
        let table = self.as_entity_erased();
        for hook in &self.hooks.after_load {
            hook(LoadCx {
                id,
                record: &mut *record,
                context: context.as_ref(),
                table,
            })
            .await?;
        }
        Ok(())
    }

    pub(crate) fn reads_rewrite_rows(&self) -> bool {
        !self.hooks.after_load.is_empty() || !self.lazy_expressions.is_empty()
    }
}

/// Append a before-write hook and keep the vector ordered by phase (stable, so
/// registration order is preserved within a phase).
fn push_phased<T: TableSource>(
    hooks: &mut Vec<(Phase, BeforeFn<T>)>,
    phase: Phase,
    f: BeforeFn<T>,
) {
    hooks.push((phase, f));
    hooks.sort_by_key(|(p, _)| *p);
}