Skip to main content

sqlive/
rolled_back.rs

1//! A connection's transactions that end by rolling back: a read of one
2//! snapshot, and checks whose scratch writes are discarded.
3
4use super::HostSql;
5use crate::authorization::Policy;
6use crate::authorization::PolicyError;
7
8impl<P: Policy> HostSql<P> {
9    /// A one-shot read of one snapshot. Nothing runs it again, so it records
10    /// nothing of what it reads, and narrows nothing (§4).
11    pub fn read_snapshot<F, R, E>(&self, read: F) -> Result<R, E>
12    where
13        F: FnOnce(&Self) -> Result<R, E>,
14        E: From<PolicyError<P>>,
15    {
16        self.read_transaction(|| {
17            let _reading = self.authorization.reading();
18            read(self)
19        })
20    }
21
22    /// Run `read` in a read transaction, which rolls back however `read`
23    /// ends.
24    pub fn read_transaction<R, E: From<PolicyError<P>>>(
25        &self,
26        read: impl FnOnce() -> Result<R, E>,
27    ) -> Result<R, E> {
28        self.batch("BEGIN DEFERRED")?;
29        let mut guard = SqlTransaction { database: self, active: true };
30        // A read runs no DDL.
31        let cookie = self.keep_schema_cookie();
32        // BEGIN alone does not fix a WAL snapshot. Pin it before invoking a
33        // consumer that can wait while a writer commits. Reading the schema
34        // table also brings this connection's copy of the schema, and the
35        // planner's statistics SQLite loads with it, up to the snapshot's,
36        // before the read prepares a statement. No commit runs between the
37        // pin and taking the host's values, so the read sees both as of one
38        // moment (`snapshot_values.rs`).
39        let result = (|| {
40            {
41                let _ordered = self.commit_order.reading();
42                self.query_row("SELECT count(*) FROM main.sqlite_schema", [], |r| {
43                    r.get::<_, i64>(0)
44                })?;
45                self.snapshot_values.take();
46            }
47            read()
48        })();
49        drop(cookie);
50        guard.active = false;
51        match self.roll_back() {
52            Ok(()) => result,
53            // A failed read keeps its own cause; the handle now refuses calls.
54            Err(rollback) => Err(match result {
55                Ok(_) => crate::Error::from(rollback).into(),
56                Err(error) => {
57                    tracing::error!(%rollback, "ending a failed read's snapshot failed");
58                    error
59                }
60            }),
61        }
62    }
63
64    /// Run checks that write scratch state, such as temporary tables, in a
65    /// transaction that always rolls back, so nothing they write is kept or
66    /// observed. It takes no write lock until something writes the main schema.
67    pub fn discarded_transaction<T, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
68        &self,
69        run: impl FnOnce(&Self) -> Result<T, E>,
70    ) -> Result<T, E> {
71        self.discarded("BEGIN DEFERRED", run)
72    }
73
74    /// A discarded transaction, as [`Self::discarded_transaction`] runs,
75    /// that takes the write lock as it begins, for a test's check that
76    /// writes the main schema after reading it. SQLite never waits for the
77    /// write lock a transaction already reading asks for: it fails at once
78    /// with `SQLITE_BUSY` if another connection holds it even for a moment,
79    /// where `BEGIN IMMEDIATE` waits out the busy timeout.
80    #[cfg(any(test, feature = "test-utils"))]
81    pub fn discarded_write_transaction<T, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
82        &self,
83        run: impl FnOnce(&Self) -> Result<T, E>,
84    ) -> Result<T, E> {
85        self.discarded("BEGIN IMMEDIATE", run)
86    }
87
88    fn discarded<T, E: crate::RollbackJoin<P::Failure, P::Refusal>>(
89        &self,
90        begin: &str,
91        run: impl FnOnce(&Self) -> Result<T, E>,
92    ) -> Result<T, E> {
93        self.batch(begin)?;
94        let mut guard = SqlTransaction { database: self, active: true };
95        let result = run(self);
96        guard.active = false;
97        match self.roll_back() {
98            Ok(()) => result,
99            Err(rollback) => Err(match result {
100                Ok(_) => E::from(crate::Error::from(rollback)),
101                Err(error) => error.with_rollback(rollback),
102            }),
103        }
104    }
105
106    /// Roll back the open transaction unless SQLite already ended it. When
107    /// ROLLBACK fails, this connection may still be inside the transaction: a
108    /// writer would treat its uncommitted changes as committed and a reader
109    /// would keep reading its old snapshot, so the handle refuses every later
110    /// call until the host opens the database again (§4).
111    pub(super) fn roll_back(&self) -> rusqlite::Result<()> {
112        self.snapshot_values.forget();
113        if self.connection.is_autocommit() {
114            return Ok(());
115        }
116        let result = {
117            let _scope = self.authorization.internal();
118            self.connection.execute_batch("ROLLBACK")
119        };
120        if result.is_err() {
121            if let Some(handle) = &self.handle {
122                handle.fail_engine(crate::EngineFailure::Rollback);
123            }
124        }
125        result
126    }
127}
128
129/// A read or a discarded transaction, rolled back if its callback panics.
130struct SqlTransaction<'a, P: Policy> {
131    database: &'a HostSql<P>,
132    active: bool,
133}
134
135// Still active only while a callback's panic unwinds, when a second panic
136// would abort the process. The panic propagates; a failed rollback is logged
137// and fails the handle, so every later call reports it.
138impl<P: Policy> Drop for SqlTransaction<'_, P> {
139    fn drop(&mut self) {
140        if self.active {
141            if let Err(rollback) = self.database.roll_back() {
142                tracing::error!(%rollback, "rolling back a panicking transaction failed");
143            }
144        }
145    }
146}