Skip to main content

tinystore/sql/
batch.rs

1//! A database's batch: writes known before they run, in one savepoint of the
2//! next shared commit, all of them or none. A write is a statement, a
3//! queue's add for a queue kept in the database's file, or a stream's append
4//! for a stream opened from the database, so that a job or an event commits
5//! with the rows it is about and still shares the commit with every other
6//! write of the file, where `db.tx` holds the writer and pays a sync of its
7//! own.
8
9use std::fmt;
10
11use super::database::Done;
12use super::run;
13use super::statement::Sql;
14use crate::Result;
15#[cfg(any(feature = "jobs", feature = "records"))]
16use crate::engine::LentWrite;
17use crate::sqlite::{File, Tx as SqlTx};
18#[cfg(any(feature = "jobs", feature = "records"))]
19use crate::{Error, ErrorKind};
20
21/// A write of a batch: a statement, a job's add of a queue opened from the
22/// database, `queue.adding(&job)`, or an event's append of a stream opened
23/// from it, `audit.appending(name, &fields)`. A statement becomes one by
24/// `into`:
25///
26/// ```no_run
27/// # #[derive(serde::Serialize, serde::Deserialize)]
28/// # struct Index { note: i64 }
29/// # fn main() -> tinystore::Result<()> {
30/// # let store = tinystore::Store::open("data", Default::default())?;
31/// # let (body, note) = ("milk", 7);
32/// let db = store.database("app").open()?;
33/// let indexing = db.queue::<Index>("indexing").open()?;
34/// db.batch([
35///     tinystore::sql!("update notes set body = ? where id = ?", body, note).into(),
36///     indexing.adding(&Index { note }), // committed with the row, or not at all
37/// ])?;
38/// # Ok(())
39/// # }
40/// ```
41pub struct Write(Kind);
42
43enum Kind {
44    Statement(Sql),
45    #[cfg(any(feature = "jobs", feature = "records"))]
46    Lent(LentWrite),
47    /// What made the write could not: its batch fails with it, and runs
48    /// nothing.
49    #[cfg(any(feature = "jobs", feature = "records"))]
50    Refused(Error),
51}
52
53impl Write {
54    /// A write of a handle kept in a file another engine lends, or why it
55    /// could not be made.
56    #[cfg(any(feature = "jobs", feature = "records"))]
57    pub(crate) fn lent(made: Result<LentWrite>) -> Write {
58        Write(made.map_or_else(Kind::Refused, Kind::Lent))
59    }
60}
61
62impl From<Sql> for Write {
63    fn from(statement: Sql) -> Write {
64        Write(Kind::Statement(statement))
65    }
66}
67
68impl From<&str> for Write {
69    fn from(text: &str) -> Write {
70        Write::from(Sql::from(text))
71    }
72}
73
74impl From<String> for Write {
75    fn from(text: String) -> Write {
76        Write::from(Sql::from(text))
77    }
78}
79
80impl From<&String> for Write {
81    fn from(text: &String) -> Write {
82        Write::from(Sql::from(text))
83    }
84}
85
86impl fmt::Debug for Write {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match &self.0 {
89            Kind::Statement(statement) => f.debug_tuple("Write").field(statement).finish(),
90            #[cfg(any(feature = "jobs", feature = "records"))]
91            Kind::Lent(lent) => f.debug_tuple("Write").field(lent).finish(),
92            #[cfg(any(feature = "jobs", feature = "records"))]
93            Kind::Refused(error) => f.debug_tuple("Write").field(error).finish(),
94        }
95    }
96}
97
98/// A batch's writes, checked against the file it runs on before it waits
99/// for the writer.
100pub(super) struct Batch {
101    writes: Vec<Kind>,
102}
103
104/// What a batch did: a `Done` a write, in their order, and what runs once
105/// its commit is durable.
106pub(super) struct Ran {
107    done: Vec<Done>,
108    committed: Vec<Box<dyn FnOnce() + Send>>,
109    /// What runs before the batch answers, and may wait for another file.
110    before_answer: Vec<Box<dyn FnOnce() + Send>>,
111}
112
113impl Ran {
114    /// What each write did, once what waited for the commit ran, on this
115    /// thread, which may wait.
116    pub(super) fn finish(self) -> Vec<Done> {
117        for committed in self.committed {
118            committed();
119        }
120        for before_answer in self.before_answer {
121            before_answer();
122        }
123        self.done
124    }
125
126    /// Whether finishing the batch waits for another file, which the thread
127    /// that committed it must not: the commits after it would wait too.
128    #[cfg(all(feature = "records", any(feature = "wire", feature = "async")))]
129    pub(super) fn waits(&self) -> bool {
130        !self.before_answer.is_empty()
131    }
132}
133
134impl Batch {
135    /// The writes of a batch on `file`, which `owner` names: a write that
136    /// could not be made, or one of a handle kept in another file, fails it.
137    /// A copy passes statements on to its file's home, and refuses the rest,
138    /// which the home's own batch runs.
139    pub(super) fn checked(writes: Vec<Write>, file: &File, owner: &str) -> Result<Batch> {
140        let writes = writes.into_iter().map(|Write(write)| kept_in(write, file, owner));
141        Ok(Batch { writes: writes.collect::<Result<_>>()? })
142    }
143
144    /// The batch's statements, every write being one: what a copy passes on.
145    #[cfg(feature = "replication")]
146    pub(super) fn statements(self) -> Vec<Sql> {
147        let mut statements = Vec::with_capacity(self.writes.len());
148        for write in self.writes {
149            match write {
150                Kind::Statement(statement) => statements.push(statement),
151                #[cfg(any(feature = "jobs", feature = "records"))]
152                Kind::Lent(_) | Kind::Refused(_) => {}
153            }
154        }
155        statements
156    }
157
158    /// What the batch weighs in its commit, and its write: every write in
159    /// order, a failure naming its own.
160    pub(super) fn write(self) -> (usize, impl FnOnce(&SqlTx<'_>) -> Result<Ran> + Send + 'static) {
161        let weight = self.writes.iter().map(weight_of).sum();
162        let writes = self.writes;
163        let write = move |tx: &SqlTx<'_>| {
164            let mut ran =
165                Ran { done: Vec::with_capacity(writes.len()), committed: Vec::new(), before_answer: Vec::new() };
166            for write in writes {
167                match write {
168                    Kind::Statement(statement) => {
169                        let done = run::exec(tx, &statement).map_err(|error| error.within(statement.describe()))?;
170                        ran.done.push(done);
171                    }
172                    #[cfg(any(feature = "jobs", feature = "records"))]
173                    Kind::Lent(lent) => {
174                        let describe = lent.describe;
175                        let wrote = (lent.write)(tx).map_err(|error| error.within(describe))?;
176                        ran.done.push(Done { changes: wrote.changes, last_insert_rowid: 0 });
177                        ran.committed.extend(wrote.committed);
178                        ran.before_answer.extend(wrote.before_answer);
179                    }
180                    #[cfg(any(feature = "jobs", feature = "records"))]
181                    Kind::Refused(error) => return Err(error),
182                }
183            }
184            Ok(ran)
185        };
186        (weight, write)
187    }
188}
189
190/// A write a batch on `file` can run: a statement, or a lent write of a
191/// handle kept in `file` while `file` is not a copy.
192#[cfg(any(feature = "jobs", feature = "records"))]
193fn kept_in(write: Kind, file: &File, owner: &str) -> Result<Kind> {
194    match write {
195        Kind::Refused(error) => Err(error),
196        Kind::Lent(lent) if !std::ptr::eq(&*lent.file, file) => {
197            let why = format!("kept in {}, outside this batch of {owner}", lent.place);
198            Err(Error::invalid(why).within(lent.describe))
199        }
200        Kind::Lent(lent) if file.is_copy() => {
201            let why = "a batch that writes a job or an event runs at its file's home, which this copy is not";
202            Err(Error::new(ErrorKind::Unavailable, why).within(lent.describe))
203        }
204        write => Ok(write),
205    }
206}
207
208/// Without jobs and records a batch holds statements alone, which any file
209/// runs.
210#[cfg(not(any(feature = "jobs", feature = "records")))]
211fn kept_in(write: Kind, _file: &File, _owner: &str) -> Result<Kind> {
212    Ok(write)
213}
214
215fn weight_of(write: &Kind) -> usize {
216    match write {
217        Kind::Statement(statement) => statement.weight(),
218        #[cfg(any(feature = "jobs", feature = "records"))]
219        Kind::Lent(lent) => lent.weight,
220        #[cfg(any(feature = "jobs", feature = "records"))]
221        Kind::Refused(_) => 0,
222    }
223}