es_entity/
operation.rs

1use sqlx::{PgPool, Postgres, Transaction};
2
3pub struct DbOp<'t> {
4    tx: Transaction<'t, Postgres>,
5    now: chrono::DateTime<chrono::Utc>,
6}
7
8impl<'t> DbOp<'t> {
9    pub fn new(tx: Transaction<'t, Postgres>, time: chrono::DateTime<chrono::Utc>) -> Self {
10        Self { tx, now: time }
11    }
12
13    pub async fn init(pool: &PgPool) -> Result<Self, sqlx::Error> {
14        #[cfg(feature = "sim-time")]
15        let res = {
16            let tx = pool.begin().await?;
17            let now = sim_time::now();
18            Self { tx, now }
19        };
20
21        #[cfg(not(feature = "sim-time"))]
22        let res = {
23            let mut tx = pool.begin().await?;
24            let now = sqlx::query!("SELECT NOW()")
25                .fetch_one(&mut *tx)
26                .await?
27                .now
28                .expect("NOW() is not NULL");
29            Self { tx, now }
30        };
31
32        Ok(res)
33    }
34
35    pub fn now(&self) -> chrono::DateTime<chrono::Utc> {
36        self.now
37    }
38
39    pub fn tx(&mut self) -> &mut Transaction<'t, Postgres> {
40        &mut self.tx
41    }
42
43    pub fn into_tx(self) -> Transaction<'t, Postgres> {
44        self.tx
45    }
46
47    pub async fn commit(self) -> Result<(), sqlx::Error> {
48        self.tx.commit().await?;
49        Ok(())
50    }
51}