1use 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
21pub struct Write(Kind);
42
43enum Kind {
44 Statement(Sql),
45 #[cfg(any(feature = "jobs", feature = "records"))]
46 Lent(LentWrite),
47 #[cfg(any(feature = "jobs", feature = "records"))]
50 Refused(Error),
51}
52
53impl Write {
54 #[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
98pub(super) struct Batch {
101 writes: Vec<Kind>,
102}
103
104pub(super) struct Ran {
107 done: Vec<Done>,
108 committed: Vec<Box<dyn FnOnce() + Send>>,
109 before_answer: Vec<Box<dyn FnOnce() + Send>>,
111}
112
113impl Ran {
114 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 #[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 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 #[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 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#[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#[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}