Skip to main content

coven_database/
before_commit.rs

1//! The app's before-commit function (§9.4): app Rust that coven runs last in
2//! each transaction that changes the app's rows, whether this device wrote
3//! them, applied another device's or loaded a snapshot, so the app can store
4//! what its own rules compute from them in the same transaction. Like a local
5//! trigger, it writes device-local tables only.
6
7use crate::sqlite::StoreSql;
8use crate::DbError;
9use sqlive::rusqlite::{Params, Row};
10use std::cell::Cell;
11
12/// App SQL inside the app's before-commit function: it reads any table app
13/// SQL reads, the transaction's changes included, and writes device-local
14/// tables only. A statement that would write a synced table, itself or
15/// through a trigger or foreign-key action, fails with
16/// `SyncedTableBeforeCommit`. Returning an error rolls back the transaction
17/// the function runs in.
18pub struct CommitSql<'a> {
19    database: &'a StoreSql,
20    /// Whether one of the function's statements failed, which fails the
21    /// transaction even if the function goes on (§4).
22    failed: Cell<bool>,
23}
24
25impl CommitSql<'_> {
26    /// Execute one app statement with parameters.
27    pub fn execute<P: Params>(&self, sql: &str, params: P) -> sqlive::rusqlite::Result<usize> {
28        self.statement(|| self.database.app_execute(sql, params))
29    }
30
31    /// Execute app statements within the transaction.
32    pub fn execute_batch(&self, sql: &str) -> sqlive::rusqlite::Result<()> {
33        self.statement(|| self.database.app_batch(sql))
34    }
35
36    /// Map one app row, including the transaction's changes.
37    pub fn query_row<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<T>
38    where
39        P: Params,
40        F: FnOnce(&Row<'_>) -> sqlive::rusqlite::Result<T>,
41    {
42        self.statement(|| self.database.app_query_row(sqlive::Recorded::No, sql, params, map))
43    }
44
45    /// Map all app rows a query produces, including the transaction's
46    /// changes.
47    pub fn query<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<Vec<T>>
48    where
49        P: Params,
50        F: FnMut(&Row<'_>) -> sqlive::rusqlite::Result<T>,
51    {
52        self.statement(|| self.database.app_query(sqlive::Recorded::No, sql, params, map))
53    }
54
55    /// Run one statement. One SQLite fails may have kept part of its change,
56    /// so it fails the transaction even if the function goes on. An answer
57    /// with no row, or the function's own mapping of a row, is no failure of
58    /// the statement.
59    fn statement<T>(
60        &self,
61        run: impl FnOnce() -> sqlive::rusqlite::Result<T>,
62    ) -> sqlive::rusqlite::Result<T> {
63        let result = run();
64        if matches!(result, Err(sqlive::rusqlite::Error::SqliteFailure(..))) {
65            self.failed.set(true);
66        }
67        result
68    }
69}
70
71impl crate::SqlRead for CommitSql<'_> {
72    fn query_row<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<T>
73    where
74        P: Params,
75        F: FnOnce(&Row<'_>) -> sqlive::rusqlite::Result<T>,
76    {
77        CommitSql::query_row(self, sql, params, map)
78    }
79
80    fn query<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<Vec<T>>
81    where
82        P: Params,
83        F: FnMut(&Row<'_>) -> sqlive::rusqlite::Result<T>,
84    {
85        CommitSql::query(self, sql, params, map)
86    }
87}
88
89/// The app's before-commit function, as the database keeps it.
90pub(crate) type BeforeCommit = dyn Fn(&CommitSql<'_>) -> Result<(), DbError> + Send + Sync;
91
92/// Run the app's before-commit function, if it registered one, as the last
93/// step of the transaction `database` holds. Its error, or a statement of it
94/// that failed, fails the transaction.
95pub(crate) fn run(database: &StoreSql, function: Option<&BeforeCommit>) -> Result<(), DbError> {
96    let Some(function) = function else {
97        return Ok(());
98    };
99    let _scope = database.local_scope();
100    let sql = CommitSql { database, failed: Cell::new(false) };
101    function(&sql)?;
102    // SQLite ending the transaction says more than the statement that
103    // ended it.
104    database.require_transaction().map_err(DbError::from)?;
105    if sql.failed.get() {
106        return Err(DbError::StatementFailed);
107    }
108    Ok(())
109}
110
111#[cfg(test)]
112#[path = "before_commit_tests.rs"]
113mod tests;