es_entity/operation/
mod.rs

1//! Handle execution of database operations and transactions.
2
3pub mod hooks;
4mod with_time;
5
6use sqlx::{Acquire, PgPool, Postgres, Transaction};
7
8use crate::clock::ClockHandle;
9
10pub use with_time::*;
11
12/// Default return type of the derived EsRepo::begin_op().
13///
14/// Used as a wrapper of a [`sqlx::Transaction`] but can also cache the time at which the
15/// transaction is taking place.
16///
17/// When an artificial clock is provided, the transaction will automatically cache that
18/// clock's time, enabling deterministic testing. This cached time will be used in all
19/// time-dependent operations.
20pub struct DbOp<'c> {
21    tx: Transaction<'c, Postgres>,
22    clock: ClockHandle,
23    now: Option<chrono::DateTime<chrono::Utc>>,
24    commit_hooks: Option<hooks::CommitHooks>,
25}
26
27impl<'c> DbOp<'c> {
28    fn new(
29        tx: Transaction<'c, Postgres>,
30        clock: ClockHandle,
31        time: Option<chrono::DateTime<chrono::Utc>>,
32    ) -> Self {
33        Self {
34            tx,
35            clock,
36            now: time,
37            commit_hooks: Some(hooks::CommitHooks::new()),
38        }
39    }
40
41    /// Initializes a transaction using the global clock.
42    ///
43    /// Delegates to [`init_with_clock`](Self::init_with_clock) using the global clock handle.
44    pub async fn init(pool: &PgPool) -> Result<DbOp<'static>, sqlx::Error> {
45        Self::init_with_clock(pool, crate::clock::Clock::handle()).await
46    }
47
48    /// Initializes a transaction with the specified clock.
49    ///
50    /// If the clock is artificial, its current time will be cached in the transaction.
51    pub async fn init_with_clock(
52        pool: &PgPool,
53        clock: &ClockHandle,
54    ) -> Result<DbOp<'static>, sqlx::Error> {
55        let tx = pool.begin().await?;
56
57        // If an artificial clock is provided (and hasn't transitioned to realtime),
58        // cache its time for consistent timestamps within the transaction.
59        let time = clock.artificial_now();
60
61        Ok(DbOp::new(tx, clock.clone(), time))
62    }
63
64    /// Transitions to a [`DbOpWithTime`] with the given time cached.
65    pub fn with_time(self, time: chrono::DateTime<chrono::Utc>) -> DbOpWithTime<'c> {
66        DbOpWithTime::new(self, time)
67    }
68
69    /// Transitions to a [`DbOpWithTime`] using the clock.
70    ///
71    /// Uses cached time if present, otherwise uses the clock's current time.
72    pub fn with_clock_time(self) -> DbOpWithTime<'c> {
73        let time = self.now.unwrap_or_else(|| self.clock.now());
74        DbOpWithTime::new(self, time)
75    }
76
77    /// Transitions to a [`DbOpWithTime`] using the database time.
78    ///
79    /// Priority order:
80    /// 1. Cached time if present
81    /// 2. Artificial clock time if the clock is artificial (and hasn't transitioned)
82    /// 3. Database time via `SELECT NOW()`
83    pub async fn with_db_time(mut self) -> Result<DbOpWithTime<'c>, sqlx::Error> {
84        let time = if let Some(time) = self.now {
85            time
86        } else if let Some(artificial_time) = self.clock.artificial_now() {
87            artificial_time
88        } else {
89            let res = sqlx::query!("SELECT NOW()")
90                .fetch_one(&mut *self.tx)
91                .await?;
92            res.now.expect("could not fetch now")
93        };
94
95        Ok(DbOpWithTime::new(self, time))
96    }
97
98    /// Returns the optionally cached [`chrono::DateTime`]
99    pub fn maybe_now(&self) -> Option<chrono::DateTime<chrono::Utc>> {
100        self.now
101    }
102
103    /// Begins a nested transaction.
104    pub async fn begin(&mut self) -> Result<DbOp<'_>, sqlx::Error> {
105        Ok(DbOp::new(
106            self.tx.begin().await?,
107            self.clock.clone(),
108            self.now,
109        ))
110    }
111
112    /// Commits the inner transaction.
113    pub async fn commit(mut self) -> Result<(), sqlx::Error> {
114        let commit_hooks = self.commit_hooks.take().expect("no hooks");
115        let post_hooks = commit_hooks.execute_pre(&mut self).await?;
116        self.tx.commit().await?;
117        post_hooks.execute();
118        Ok(())
119    }
120
121    /// Gets a mutable handle to the inner transaction
122    pub fn tx_mut(&mut self) -> &mut Transaction<'c, Postgres> {
123        &mut self.tx
124    }
125}
126
127impl<'o> AtomicOperation for DbOp<'o> {
128    fn maybe_now(&self) -> Option<chrono::DateTime<chrono::Utc>> {
129        self.maybe_now()
130    }
131
132    fn clock(&self) -> &ClockHandle {
133        &self.clock
134    }
135
136    fn as_executor(&mut self) -> &mut sqlx::PgConnection {
137        self.tx.as_executor()
138    }
139
140    fn add_commit_hook<H: hooks::CommitHook>(&mut self, hook: H) -> Result<(), H> {
141        self.commit_hooks.as_mut().expect("no hooks").add(hook);
142        Ok(())
143    }
144}
145
146/// Equivileant of [`DbOp`] just that the time is guaranteed to be cached.
147///
148/// Used as a wrapper of a [`sqlx::Transaction`] with cached time of the transaction.
149pub struct DbOpWithTime<'c> {
150    inner: DbOp<'c>,
151    now: chrono::DateTime<chrono::Utc>,
152}
153
154impl<'c> DbOpWithTime<'c> {
155    fn new(mut inner: DbOp<'c>, time: chrono::DateTime<chrono::Utc>) -> Self {
156        inner.now = Some(time);
157        Self { inner, now: time }
158    }
159
160    /// The cached [`chrono::DateTime`]
161    pub fn now(&self) -> chrono::DateTime<chrono::Utc> {
162        self.now
163    }
164
165    /// Begins a nested transaction.
166    pub async fn begin(&mut self) -> Result<DbOpWithTime<'_>, sqlx::Error> {
167        Ok(DbOpWithTime::new(self.inner.begin().await?, self.now))
168    }
169
170    /// Commits the inner transaction.
171    pub async fn commit(self) -> Result<(), sqlx::Error> {
172        self.inner.commit().await
173    }
174
175    /// Gets a mutable handle to the inner transaction
176    pub fn tx_mut(&mut self) -> &mut Transaction<'c, Postgres> {
177        self.inner.tx_mut()
178    }
179}
180
181impl<'o> AtomicOperation for DbOpWithTime<'o> {
182    fn maybe_now(&self) -> Option<chrono::DateTime<chrono::Utc>> {
183        Some(self.now())
184    }
185
186    fn clock(&self) -> &ClockHandle {
187        self.inner.clock()
188    }
189
190    fn as_executor(&mut self) -> &mut sqlx::PgConnection {
191        self.inner.as_executor()
192    }
193
194    fn add_commit_hook<H: hooks::CommitHook>(&mut self, hook: H) -> Result<(), H> {
195        self.inner.add_commit_hook(hook)
196    }
197}
198
199impl<'o> AtomicOperationWithTime for DbOpWithTime<'o> {
200    fn now(&self) -> chrono::DateTime<chrono::Utc> {
201        self.now
202    }
203}
204
205/// Trait to signify we can make multiple consistent database roundtrips.
206///
207/// Its a stand in for [`&mut sqlx::Transaction<'_, DB>`](`sqlx::Transaction`).
208/// The reason for having a trait is to support custom types that wrap the inner
209/// transaction while providing additional functionality.
210///
211/// See [`DbOp`] or [`DbOpWithTime`].
212pub trait AtomicOperation: Send {
213    /// Function for querying when the operation is taking place - if it is cached.
214    fn maybe_now(&self) -> Option<chrono::DateTime<chrono::Utc>> {
215        None
216    }
217
218    /// Returns the clock handle for time operations.
219    ///
220    /// Default implementation returns the global clock handle.
221    fn clock(&self) -> &ClockHandle {
222        crate::clock::Clock::handle()
223    }
224
225    /// Returns the [`sqlx::Executor`] implementation.
226    /// The desired way to represent this would actually be as a GAT:
227    /// ```rust
228    /// trait AtomicOperation {
229    ///     type Executor<'c>: sqlx::PgExecutor<'c>
230    ///         where Self: 'c;
231    ///
232    ///     fn as_executor<'c>(&'c mut self) -> Self::Executor<'c>;
233    /// }
234    /// ```
235    ///
236    /// But GATs don't play well with `async_trait::async_trait` due to lifetime constraints
237    /// so we return the concrete [`&mut sqlx::PgConnection`](`sqlx::PgConnection`) instead as a work around.
238    ///
239    /// Since this trait is generally applied to types that wrap a [`sqlx::Transaction`]
240    /// there is no variance in the return type - so its fine.
241    fn as_executor(&mut self) -> &mut sqlx::PgConnection;
242
243    /// Registers a commit hook that will run pre_commit before and post_commit after the transaction commits.
244    /// Returns Ok(()) if the hook was registered, Err(hook) if hooks are not supported.
245    fn add_commit_hook<H: hooks::CommitHook>(&mut self, hook: H) -> Result<(), H> {
246        Err(hook)
247    }
248}
249
250impl<'c> AtomicOperation for sqlx::Transaction<'c, Postgres> {
251    fn as_executor(&mut self) -> &mut sqlx::PgConnection {
252        &mut *self
253    }
254}