Skip to main content

sqlive/
write_with.rs

1//! A write in two phases on one transaction: the app's SQL, while the
2//! pre-update hook keeps each row operation on the recorded tables one at a
3//! time (ยง9.6), then the host's work under a session.
4
5use super::event_capture::{EventCapture, Operation};
6use super::stream_capture::{StreamCapture, StreamChanges};
7use super::transaction_capture::{ChangeCapture, SupplementalChanges};
8use super::write_transaction::WriteTransaction;
9use super::HostSql;
10use crate::authorization::Policy;
11use crate::net_changes::Captured;
12
13impl<P: Policy> HostSql<P> {
14    /// Run `app` while the pre-update hook keeps each operation on the
15    /// recorded tables, then `host` with those operations under a session,
16    /// judge the live queries, commit and tell the subscriptions. `app` gets
17    /// a call that returns the operations so far. `host` gets what `app`
18    /// returned.
19    pub fn write_with<A, T, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
20        &mut self,
21        app: impl FnOnce(&HostSql<P>, &dyn Fn() -> Vec<Operation>) -> Result<A, E>,
22        host: impl FnOnce(&HostSql<P>, &[Operation], A) -> Result<T, E>,
23    ) -> Result<T, E> {
24        let mut transaction = WriteTransaction::begin(self, false)?;
25        transaction.keep_schema_cookie();
26        let outcome = phases(&mut transaction, app, host);
27        transaction.commit(outcome)
28    }
29
30    /// A streamed transaction, as [`Self::stream_transaction`] runs one, in
31    /// which `stream` says whether `write_with`'s phases follow in the same
32    /// transaction. When they do, the app phase takes the hook the stream's
33    /// capture held, which has seen every change of `stream`; both commit, or
34    /// neither.
35    pub fn stream_then_write<S, A, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
36        &mut self,
37        stream: impl FnOnce(&HostSql<P>) -> Result<(S, bool), E>,
38        app: impl FnOnce(&HostSql<P>, &dyn Fn() -> Vec<Operation>) -> Result<A, E>,
39        host: impl FnOnce(&HostSql<P>, &[Operation], A) -> Result<(), E>,
40    ) -> Result<S, E> {
41        let mut transaction = WriteTransaction::begin(self, true)?;
42        let outcome = StreamCapture::begin(&mut transaction).map_err(E::from).and_then(|capture| {
43            let (result, writes) = transaction.within(|database| {
44                let ran = stream(database)?;
45                database.require_transaction()?;
46                Ok::<_, E>(ran)
47            })?;
48            let mut changes = match capture.changes() {
49                StreamChanges::Rows(rows) => rows,
50                StreamChanges::Tables(tables) => transaction
51                    .within(|database| crate::change_capture::table_changes(database, tables))?,
52            };
53            if writes {
54                transaction.stop_observing_operations()?;
55                transaction.keep_schema_cookie();
56                let ((), rows) = phases(&mut transaction, app, host)?;
57                changes.append(rows);
58            }
59            Ok((result, changes))
60        });
61        transaction.commit(outcome)
62    }
63}
64
65/// Runs the phases of a write on `transaction`, whose connection holds the
66/// transaction and whose hooks this sets. Returns the host's result and
67/// what the phases changed, which the commit sends to the live queries as
68/// each row's net change; `transaction` commits or rolls back with them.
69fn phases<P: Policy, A, T, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
70    transaction: &mut WriteTransaction<'_, P>,
71    app: impl FnOnce(&HostSql<P>, &dyn Fn() -> Vec<Operation>) -> Result<A, E>,
72    host: impl FnOnce(&HostSql<P>, &[Operation], A) -> Result<T, E>,
73) -> Result<(T, Captured), E> {
74    let recording = EventCapture::begin(transaction);
75    let begun = recording.map_err(E::from).and_then(|recording| {
76        transaction.within(|database| {
77            let begun = app(database, &|| recording.events())?;
78            database.require_transaction()?;
79            Ok((begun, recording))
80        })
81    });
82    // The app phase ends: a session observes the rest of the transaction.
83    let switched = match begun {
84        Ok(begun) => transaction
85            .stop_observing_operations()
86            .and_then(|()| SupplementalChanges::observe(transaction))
87            .map(|supplemental| (begun, supplemental))
88            .map_err(E::from),
89        Err(error) => Err(error),
90    };
91    switched.and_then(|((begun, recording), supplemental)| {
92        transaction.within(|database| {
93            let operations = recording.events();
94            let mut changes = recording.local_changes();
95            let mut capture = match &database.observation {
96                Some(_) => Some(ChangeCapture::begin(database, supplemental)?),
97                None => None,
98            };
99            let result = host(database, &operations, begun)?;
100            database.require_transaction()?;
101            if database.observation.is_some() {
102                let kept =
103                    database.handle.as_ref().map(crate::Handle::kept_columns).unwrap_or_default();
104                let mut app = crate::change_capture::event_changes(database, &operations, &kept)?;
105                app.append(changes);
106                changes = app;
107            } else {
108                changes = Captured::default();
109            }
110            if let Some(capture) = &mut capture {
111                changes.append(capture.take_changes()?);
112            }
113            Ok((result, changes))
114        })
115    })
116}