use std::cell::RefCell;
use std::fmt;
#[cfg(any(feature = "kv", feature = "jobs"))]
use std::sync::Arc;
#[cfg(any(feature = "kv", feature = "jobs"))]
use crate::Store;
#[cfg(any(feature = "kv", feature = "jobs"))]
use crate::sqlite::{Begun, Committed, Mark};
use crate::sqlite::{File, Left, Tx as SqlTx, refuse_when_rolled_back, sql_error};
use crate::{Error, Result};
const SAVEPOINT: &str = "savepoint call";
const RELEASE: &str = "release call";
const ROLLBACK_TO: &str = "rollback to call";
#[cfg(any(feature = "kv", feature = "jobs"))]
impl Store {
pub fn tx<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
self.refuse_when_closed("a transaction")?;
let files = self.engine_files();
Transaction::of_store(&files, |transaction| work(&Tx { transaction }))
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
pub struct Tx<'a> {
transaction: &'a Transaction<'a>,
}
#[cfg(any(feature = "kv", feature = "jobs"))]
impl Tx<'_> {
pub fn with<'h, H: TxHandle>(&'h self, handle: &'h H) -> H::InTx<'h> {
handle.in_tx(self.transaction)
}
#[cfg(all(feature = "wire", feature = "jobs"))]
pub(crate) fn transaction(&self) -> &Transaction<'_> {
self.transaction
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
impl fmt::Debug for Tx<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Tx")
}
}
pub struct Transaction<'t> {
writer: &'t dyn Writer,
bound: Option<&'t dyn Fn() -> Result<()>>,
#[cfg_attr(not(feature = "jobs"), expect(dead_code, reason = "only a queue asks for what runs once it ends"))]
ended: &'t Ended,
}
impl Transaction<'_> {
#[cfg(feature = "sql")]
pub(crate) fn run<T, E: From<Error>>(
file: &File,
owner: &str,
bound: Option<&dyn Fn() -> Result<()>>,
work: impl FnOnce(&Transaction<'_>) -> Result<T, E>,
) -> Result<T, E> {
if file.is_copy() {
return Err(crate::sqlite::a_copy_takes_no_transaction(owner).into());
}
let ended = Ended::default();
let outcome = file.transaction(|raw| {
let writer = OneFile { raw, file, owner };
let transaction = Transaction { writer: &writer, bound, ended: &ended };
let value = work(&transaction)?;
transaction.within_bound()?;
Ok(value)
});
ended.finish(outcome.is_ok());
outcome
}
#[cfg(any(feature = "kv", feature = "jobs"))]
fn of_store<T, E: From<Error>>(
files: &[Arc<File>],
work: impl FnOnce(&Transaction<'_>) -> Result<T, E>,
) -> Result<T, E> {
let ended = Ended::default();
let outcome = (|| {
let marks = files.iter().map(|file| file.mark()).collect::<Result<Vec<_>>>()?;
let writer = OfStore { files, begun: RefCell::new(None), marks, early: Committed::default() };
let value = work(&Transaction { writer: &writer, bound: None, ended: &ended })?;
writer.commit()?;
Ok(value)
})();
ended.finish(outcome.is_ok());
outcome
}
pub(crate) fn call<T>(&self, work: impl FnOnce(&SqlTx<'_>) -> Result<T>) -> Result<T> {
self.within_bound()?;
let (mut work, mut value) = (Some(work), None);
self.writer.on(&mut |raw| {
let work = work.take().ok_or_else(|| Error::internal("a transaction's call ran twice"))?;
refuse_when_rolled_back(raw)?;
value = Some(in_savepoint(raw, || {
let value = work(raw)?;
raw.settle(Left::Here)?;
Ok(value)
})?);
Ok(())
})?;
value.ok_or_else(|| Error::internal("a transaction's call did not run"))
}
#[cfg(feature = "channels")]
pub(crate) fn after_commit(&self, hook: Box<dyn FnOnce()>) {
self.writer.after_commit(hook);
}
#[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
pub(crate) fn takes(&self, file: &File, place: &str) -> Result<()> {
self.writer.takes(file, place)
}
#[cfg(feature = "jobs")]
pub(crate) fn after(&self, hook: impl FnOnce(bool) + 'static) {
self.ended.0.borrow_mut().push(Box::new(hook));
}
pub(crate) fn within_bound(&self) -> Result<()> {
self.bound.map_or(Ok(()), |bound| bound())
}
}
impl fmt::Debug for Transaction<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Transaction")
}
}
trait Writer {
#[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
fn takes(&self, file: &File, place: &str) -> Result<()>;
fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()>;
#[cfg(feature = "channels")]
fn after_commit(&self, hook: Box<dyn FnOnce()>);
}
#[cfg(feature = "sql")]
struct OneFile<'t> {
raw: &'t SqlTx<'t>,
#[cfg_attr(
not(any(feature = "kv", feature = "jobs", feature = "search")),
expect(dead_code, reason = "only kv's, jobs' and search's handles ask whether they are kept in a file")
)]
file: &'t File,
#[cfg_attr(
not(any(feature = "kv", feature = "jobs", feature = "search")),
expect(dead_code, reason = "only kv's, jobs' and search's handles ask whether they are kept in a file")
)]
owner: &'t str,
}
#[cfg(feature = "sql")]
impl Writer for OneFile<'_> {
#[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
fn takes(&self, file: &File, place: &str) -> Result<()> {
if std::ptr::eq(self.file, file) {
return Ok(());
}
Err(Error::invalid(format!("kept in {place}, outside this transaction of {}", self.owner)))
}
fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()> {
work(self.raw)
}
#[cfg(feature = "channels")]
fn after_commit(&self, hook: Box<dyn FnOnce()>) {
self.raw.after_commit(hook);
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
struct OfStore<'f> {
files: &'f [Arc<File>],
begun: RefCell<Option<(Begun<'f>, String)>>,
marks: Vec<Mark>,
early: Committed,
}
#[cfg(any(feature = "kv", feature = "jobs"))]
impl OfStore<'_> {
fn commit(&self) -> Result<()> {
match self.begun.borrow_mut().take() {
Some((begun, _)) => begun.commit(),
None => {
self.early.run();
Ok(())
}
}
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
impl Writer for OfStore<'_> {
fn takes(&self, file: &File, place: &str) -> Result<()> {
let mut begun = self.begun.borrow_mut();
if let Some((held, owner)) = begun.as_ref() {
if std::ptr::eq(held.file(), file) {
return Ok(());
}
return Err(Error::invalid(format!("kept in {place}, outside this transaction of {owner}")));
}
let Some(at) = self.files.iter().position(|own| std::ptr::eq(&**own, file)) else {
return Err(Error::invalid(format!(
"kept in {place}, which this store's transaction does not hold: a database's handle joins its db.tx"
)));
};
let began = self.files[at].begin(&self.marks[at])?;
#[cfg(feature = "channels")]
began.tx().committed().append(self.early.take());
*begun = Some((began, place.to_owned()));
Ok(())
}
fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()> {
let begun = self.begun.borrow();
let Some((begun, _)) = begun.as_ref() else {
return Err(Error::internal("a call in a transaction that took no handle in"));
};
work(&begun.tx())
}
#[cfg(feature = "channels")]
fn after_commit(&self, hook: Box<dyn FnOnce()>) {
match self.begun.borrow().as_ref() {
Some((begun, _)) => begun.tx().after_commit(hook),
None => self.early.push(hook),
}
}
}
fn in_savepoint<T>(raw: &SqlTx<'_>, work: impl FnOnce() -> Result<T>) -> Result<T> {
let failed = |error| sql_error("a call's savepoint", error);
raw.execute_batch(SAVEPOINT).map_err(failed)?;
let mark = raw.committed().mark();
let outcome = work();
if raw.is_autocommit() {
raw.committed().take_back(mark);
return outcome.and_then(|value| refuse_when_rolled_back(raw).map(|()| value));
}
match outcome {
Ok(value) => raw.execute_batch(RELEASE).map_err(failed).map(|()| value),
Err(error) => {
raw.committed().take_back(mark);
match raw.execute_batch(ROLLBACK_TO).and_then(|()| raw.execute_batch(RELEASE)) {
Ok(()) => Err(error),
Err(rollback) => Err(error.within(format!("a savepoint not rolled back ({rollback})"))),
}
}
}
}
type Hook = Box<dyn FnOnce(bool)>;
#[derive(Default)]
struct Ended(RefCell<Vec<Hook>>);
impl Ended {
fn finish(&self, committed: bool) {
let hooks = std::mem::take(&mut *self.0.borrow_mut());
for hook in hooks {
hook(committed);
}
}
}
impl Drop for Ended {
fn drop(&mut self) {
self.finish(false);
}
}
pub trait TxHandle: sealed::Sealed {
type InTx<'t>
where
Self: 't;
#[doc(hidden)]
fn in_tx<'t>(&'t self, tx: &'t Transaction<'t>) -> Self::InTx<'t>;
}
impl<H: TxHandle + ?Sized> TxHandle for &H {
type InTx<'t>
= H::InTx<'t>
where
Self: 't;
fn in_tx<'t>(&'t self, tx: &'t Transaction<'t>) -> H::InTx<'t> {
(**self).in_tx(tx)
}
}
pub(crate) mod sealed {
pub trait Sealed {}
impl<H: Sealed + ?Sized> Sealed for &H {}
}
#[cfg(test)]
#[path = "transaction_tests.rs"]
mod tests;