Skip to main content

sqlive/
event_capture.rs

1//! A local write's app phase, observed one SQLite row operation at a time.
2//!
3//! Sessions record only net changes. A write's steps need each operation, in
4//! order (ยง9.6, D5). A connection has one pre-update hook, which a session
5//! would otherwise own, so the app phase records through this hook and no
6//! session runs until it ends. The capture keeps every operation on a
7//! recorded table, and keeps only what live queries need from any other
8//! table.
9
10use super::pre_update_changes::{new_value, old_value, ImageColumns};
11use super::write_transaction::WriteTransaction;
12use crate::authorization::Policy;
13use crate::authorization::PolicyError;
14use crate::SqlValue;
15use panic_as_error::locks::lock_unpoisoned;
16use rusqlite::hooks::{Action, PreUpdateCase};
17use std::sync::{Arc, Mutex};
18
19/// One row operation of the app phase.
20#[derive(Clone, Debug, PartialEq)]
21pub struct Operation {
22    /// The table, as SQLite names it.
23    pub table: String,
24    /// Insert, update or delete.
25    pub action: Action,
26    /// Every column before the operation, in declaration order; `None` for a
27    /// virtual generated column, which keeps no value. Empty for an insert.
28    pub old: Vec<Option<SqlValue>>,
29    /// Every column after the operation; empty for a delete.
30    pub new: Vec<Option<SqlValue>>,
31    /// The rowid before and after, meaningful only for rowid tables.
32    pub rowids: (i64, i64),
33}
34
35struct CapturedEvents {
36    operations: Vec<(i32, Operation)>,
37    local: super::pre_update_changes::PreUpdateChanges,
38}
39
40/// A panic in the hook fails the transaction it observes before it commits
41/// (`write_transaction.rs`), so what a panicking hook call left half-recorded
42/// is never committed: the capture's lock is taken as it is.
43pub(super) struct EventCapture {
44    shapes: Arc<super::table_shapes::TableShapes>,
45    events: Arc<Mutex<CapturedEvents>>,
46}
47
48impl EventCapture {
49    /// Record `transaction`'s row operations until it stops observing them.
50    pub(super) fn begin<P: Policy>(
51        transaction: &mut WriteTransaction<'_, P>,
52    ) -> Result<Self, PolicyError<P>> {
53        let (tables, recorded, scoped) = transaction.within(|database| {
54            let recorded = Arc::clone(
55                &database
56                    .observation
57                    .as_ref()
58                    .ok_or(crate::Error::Invariant {
59                        what: "a local write's writer serves its handle",
60                    })?
61                    .recorded,
62            );
63            let tables = database.table_shapes()?;
64            let scoped = match &database.handle {
65                Some(handle) => ImageColumns::kept(&tables, &handle.kept_columns()),
66                None => std::collections::HashMap::new(),
67            };
68            Ok::<_, PolicyError<P>>((tables, recorded, scoped))
69        })?;
70        let events = Arc::new(Mutex::new(CapturedEvents {
71            operations: Vec::new(),
72            local: super::pre_update_changes::PreUpdateChanges::new(scoped),
73        }));
74        let captured = Arc::clone(&events);
75        let shapes = Arc::clone(&tables);
76        transaction.observe_operations(
77            move |action: Action, schema: &str, table: &str, case: &PreUpdateCase| {
78                if schema != "main" {
79                    return Ok(());
80                }
81                match tables.position(table) {
82                    Some(position) if recorded.contains(&tables.shape(position).name) => {}
83                    Some(position) => {
84                        return lock_unpoisoned(&captured).local.record(&tables, position, case);
85                    }
86                    None => {
87                        lock_unpoisoned(&captured).local.unshaped(table);
88                        return Ok(());
89                    }
90                }
91                let depth = match case {
92                    PreUpdateCase::Insert(a) => a.get_query_depth(),
93                    PreUpdateCase::Delete(a) => a.get_query_depth(),
94                    PreUpdateCase::Update { new_value_accessor, .. } => {
95                        new_value_accessor.get_query_depth()
96                    }
97                    PreUpdateCase::Unknown => return Ok(()),
98                };
99                let count = |columns: i32| 0..usize::try_from(columns).unwrap_or(0);
100                let old = |accessor: &rusqlite::hooks::PreUpdateOldValueAccessor| {
101                    count(accessor.get_column_count())
102                        .map(|i| Ok(old_value(accessor, i)?.map(SqlValue::from)))
103                        .collect::<Result<Vec<_>, PolicyError<P>>>()
104                };
105                let new = |accessor: &rusqlite::hooks::PreUpdateNewValueAccessor| {
106                    count(accessor.get_column_count())
107                        .map(|i| Ok(new_value(accessor, i)?.map(SqlValue::from)))
108                        .collect::<Result<Vec<_>, PolicyError<P>>>()
109                };
110                let event = match case {
111                    PreUpdateCase::Insert(accessor) => Operation {
112                        table: table.to_owned(),
113                        action,
114                        old: Vec::new(),
115                        new: new(accessor)?,
116                        rowids: (accessor.get_new_row_id(), accessor.get_new_row_id()),
117                    },
118                    PreUpdateCase::Delete(accessor) => Operation {
119                        table: table.to_owned(),
120                        action,
121                        old: old(accessor)?,
122                        new: Vec::new(),
123                        rowids: (accessor.get_old_row_id(), accessor.get_old_row_id()),
124                    },
125                    PreUpdateCase::Update { old_value_accessor, new_value_accessor } => Operation {
126                        table: table.to_owned(),
127                        action,
128                        old: old(old_value_accessor)?,
129                        new: new(new_value_accessor)?,
130                        rowids: (
131                            old_value_accessor.get_old_row_id(),
132                            new_value_accessor.get_new_row_id(),
133                        ),
134                    },
135                    PreUpdateCase::Unknown => return Ok(()),
136                };
137                lock_unpoisoned(&captured).operations.push((depth, event));
138                Ok(())
139            },
140        )?;
141        Ok(Self { shapes, events })
142    }
143
144    /// The device-local tables' changes, as live queries read them.
145    pub(super) fn local_changes(&self) -> crate::net_changes::Captured {
146        std::mem::take(&mut lock_unpoisoned(&self.events).local).finish(&self.shapes)
147    }
148
149    /// The recorded tables' operations so far, in order.
150    pub(super) fn events(&self) -> Vec<Operation> {
151        lock_unpoisoned(&self.events).operations.iter().map(|(_, event)| event.clone()).collect()
152    }
153}
154
155#[cfg(test)]
156#[path = "event_capture_tests.rs"]
157mod tests;