Skip to main content

sqlive/
schema_cookie.rs

1//! SQLite's schema cookie as a transaction reads it. The connection compares
2//! the cookie with the one it saw when it prepared each app statement and
3//! read the tables' shapes, so a write checks it once for each app statement.
4//! A transaction that runs no DDL can't change the cookie, so while a
5//! transaction holds the cookie, the connection reads it from SQLite only
6//! once.
7
8use super::HostSql;
9use crate::authorization::Policy;
10use std::cell::Cell;
11
12/// The cookie as a transaction read it. The connection keeps the value until
13/// the last holder releases it.
14#[derive(Default)]
15pub(super) struct SchemaCookie {
16    holders: Cell<usize>,
17    value: Cell<Option<i64>>,
18}
19
20impl SchemaCookie {
21    pub(super) fn hold(&self) {
22        self.holders.set(self.holders.get() + 1);
23    }
24
25    pub(super) fn release(&self) {
26        let holders = self.holders.get().checked_sub(1).expect("a cookie release follows its hold");
27        self.holders.set(holders);
28        if holders == 0 {
29            self.value.set(None);
30        }
31    }
32}
33
34/// Holds the cookie for one transaction that runs no DDL. Dropping the last
35/// scope clears the stored cookie.
36pub struct CookieScope<'a>(&'a SchemaCookie);
37
38impl Drop for CookieScope<'_> {
39    fn drop(&mut self) {
40        self.0.release();
41    }
42}
43
44impl<P: Policy> HostSql<P> {
45    /// Read the schema cookie once until the returned scope drops. The
46    /// caller's transaction runs no DDL.
47    pub fn keep_schema_cookie(&self) -> CookieScope<'_> {
48        self.cookie.hold();
49        CookieScope(&self.cookie)
50    }
51
52    /// SQLite's count of changes to the main schema. The connection compares
53    /// it with the cookie it saw when it prepared each kept app statement and
54    /// read the tables' shapes.
55    pub(super) fn app_schema_cookie(&self) -> rusqlite::Result<i64> {
56        if let Some(cookie) = self.cookie.value.get() {
57            return Ok(cookie);
58        }
59        #[cfg(any(test, feature = "test-utils"))]
60        self.record_work(|work| work.cookie_reads += 1);
61        let cookie = self.schema_cookie()?;
62        if self.cookie.holders.get() > 0 {
63            self.cookie.value.set(Some(cookie));
64        }
65        Ok(cookie)
66    }
67}