Skip to main content

sqlive/
bulk_write.rs

1//! A bulk write: the app's SQL on device-local tables alone, run as plain
2//! SQLite, with no pre-update hook watching it (ยง4).
3//!
4//! A local write's hook records each row operation, which also keeps SQLite
5//! from emptying a table in one step. The policy refuses any statement in a
6//! bulk write that writes a table whose changes the host records, so no write
7//! record holds anything a bulk write does. For live queries, sqlive knows
8//! only which tables a bulk write changed, from what the authorizer saw as
9//! SQLite prepared each statement, triggers and foreign-key actions
10//! included.
11
12use super::HostSql;
13use crate::authorization::Policy;
14
15impl<P: Policy> HostSql<P> {
16    /// Run `sql`, the app's bulk write, in a write transaction with no
17    /// pre-update hook. The policy judges its statements in the bulk scope,
18    /// and live queries learn only which tables it changed.
19    pub fn bulk_write<F, R, E>(&mut self, sql: F) -> Result<R, E>
20    where
21        E: crate::RollbackJoin<P::Failure, P::Refusal>,
22        F: FnOnce(&Self) -> Result<R, E>,
23    {
24        self.with_profile(|db| db.bulk_transaction(sql))
25    }
26
27    fn bulk_transaction<F, R, E>(&mut self, sql: F) -> Result<R, E>
28    where
29        E: crate::RollbackJoin<P::Failure, P::Refusal>,
30        F: FnOnce(&Self) -> Result<R, E>,
31    {
32        let transaction = super::write_transaction::WriteTransaction::begin(self, false)?;
33        let outcome = transaction.within(|database| {
34            let scope = database.authorization.bulk();
35            let result = sql(database)?;
36            database.require_transaction()?;
37            let changed = scope.changed();
38            drop(scope);
39            let changes = crate::change_capture::table_changes(database, changed)?;
40            Ok((result, changes))
41        });
42        transaction.commit(outcome)
43    }
44}
45
46#[cfg(test)]
47#[path = "bulk_write_tests.rs"]
48mod tests;